Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧴 fix: Strip LangChain URLs From Provider Errors (#15421)
Danny Avila982a9a5141bb
diff --git a/.codex b/.codexnew file mode 100644index 0000000000..e69de29bb2diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex e290563b3e..9dab458650 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -279,6 +279,14 @@ jest.mock('@librechat/api', () => ({hasModelBoundContentProtection: mockHasModelBoundContentProtection,isContentFilterError: jest.fn((error) => error?.code === 'content_filter_block'),getSafeErrorMetadata: mockGetSafeErrorMetadata,+ /** Mirrors the real helper's contract: generic copy under content protection, otherwise the+ * provider's own message. Stripping of LangChain's docs URL is covered in its own unit test. */+ getUserFacingProviderError: (error, protectionEnabled) => {+ if (protectionEnabled) {+ return 'An error occurred while processing the request';+ }+ return error instanceof Error ? error.message : 'An error occurred';+ },contentFilterBlockResponse: jest.fn().mockReturnValue({error: 'content_filter_block',message: 'Submitted content was blocked.',diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex 198b3f9f4d..7570cd6c8e 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -313,6 +313,14 @@ jest.mock('@librechat/api', () => ({hasModelBoundContentProtection: mockHasModelBoundContentProtection,isContentFilterError: jest.fn((error) => error?.code === 'content_filter_block'),getSafeErrorMetadata: mockGetSafeErrorMetadata,+ /** Mirrors the real helper's contract: generic copy under content protection, otherwise the+ * provider's own message. Stripping of LangChain's docs URL is covered in its own unit test. */+ getUserFacingProviderError: (error, protectionEnabled) => {+ if (protectionEnabled) {+ return 'An error occurred while processing the request';+ }+ return error instanceof Error ? error.message : 'An error occurred';+ },contentFilterBlockResponse: jest.fn().mockReturnValue({error: 'content_filter_block',message: 'Submitted content was blocked.',diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 9a90f46a1a..efcf38ed83 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -117,6 +117,7 @@ const {hasYouTubeVideoParts,appendYouTubeVideoParts,resolveGoogleVideoError,+ resolveLangChainError,resolveYouTubeInjectionConfig,decrementPendingRequest,maybePrewarmCodeSandbox,@@ -160,6 +161,7 @@ const {isAgentsEndpoint,isEphemeralAgentId,removeNullishValues,+ stripLangChainTroubleshootingUrl,DEFAULT_MEMORY_MAX_INPUT_TOKENS,} = require('librechat-data-provider');const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');@@ -234,6 +236,12 @@ function getLatestEventActorSummary(contentParts) {return undefined;}+/**+ * User-visible text for a failed run. LangChain classifies provider errors by mutating+ * `error.message` with a docs URL, so a classified failure becomes typed copy the client localizes+ * and everything else keeps the provider's own wording with that URL removed. The untouched error+ * still reaches the logs through `getSafeErrorMetadata`.+ */function getUserFacingRequestError(baseMessage, error, appConfig) {const protectionEnabled = hasModelBoundContentProtection(appConfig?.filters,@@ -242,7 +250,15 @@ function getUserFacingRequestError(baseMessage, error, appConfig) {if (protectionEnabled || !error?.message) {return baseMessage;}- return `${baseMessage}: ${error.message}`;+ const typedError = resolveLangChainError(error);+ if (typedError != null) {+ return typedError;+ }+ const message = stripLangChainTroubleshootingUrl(error.message);+ if (!message) {+ return baseMessage;+ }+ return `${baseMessage}: ${message}`;}class AgentClient extends BaseClient {diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex 5a48d5d999..c327ce7f98 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -53,6 +53,7 @@ const {hasModelBoundContentProtection,isContentFilterError,getSafeErrorMetadata,+ getUserFacingProviderError,getRemoteAgentPermissions,createToolExecuteHandler,buildNonStreamingResponse,@@ -98,14 +99,6 @@ const db = require('~/models');const filterFilesByRemoteAgentAccess = (params) =>filterFilesByAgentAccess({ ...params, resourceType: ResourceType.REMOTE_AGENT });-const GENERIC_PROVIDER_ERROR = 'An error occurred while processing the request';--function getUserFacingProviderError(error, protectionEnabled) {- if (protectionEnabled) {- return GENERIC_PROVIDER_ERROR;- }- return error instanceof Error ? error.message : 'An error occurred';-}/*** Creates a tool loader function for the agent.diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 8256cb6e3f..9abc9d22b6 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -51,6 +51,7 @@ const {hasModelBoundContentProtection,isContentFilterError,getSafeErrorMetadata,+ getUserFacingProviderError,createToolExecuteHandler,getRemoteAgentPermissions,resolveAgentScopedSkillIds,@@ -113,14 +114,6 @@ const db = require('~/models');const filterFilesByRemoteAgentAccess = (params) =>filterFilesByAgentAccess({ ...params, resourceType: ResourceType.REMOTE_AGENT });-const GENERIC_PROVIDER_ERROR = 'An error occurred while processing the request';--function getUserFacingProviderError(error, protectionEnabled) {- if (protectionEnabled) {- return GENERIC_PROVIDER_ERROR;- }- return error instanceof Error ? error.message : 'An error occurred';-}function handleExecutionError({ error, res, appConfig }) {logger.error('[Responses API] Error:', getSafeErrorMetadata(error));diff --git a/client/src/components/Messages/Content/Error.tsx b/client/src/components/Messages/Content/Error.tsxindex 974d54e8af..d282fd399e 100644--- a/client/src/components/Messages/Content/Error.tsx+++ b/client/src/components/Messages/Content/Error.tsx@@ -1,12 +1,33 @@// file deepcode ignore HardcodedNonCryptoSecret: No hardcoded secrets-import { ViolationTypes, ErrorTypes, alternateName } from 'librechat-data-provider';+import {+ ErrorTypes,+ alternateName,+ ViolationTypes,+ parseLangChainErrorCode,+ stripLangChainTroubleshootingUrl,+} from 'librechat-data-provider';import type { LocalizeFunction } from '~/common';+import type { TranslationKeys } from '~/hooks';import { formatJSON, extractJson, isJson } from '~/utils/json';import { useLocalize } from '~/hooks';import CodeBlock from './CodeBlock';const localizedErrorPrefix = 'com_error';-const langChainModelNotFoundUrl = /langchain\.com\/.*\/MODEL_NOT_FOUND(?:\/|\b)/i;++/**+ * The server converts classified LangChain failures into typed payloads, but messages persisted+ * before it did still carry the docs URL, so the code is read back out of the text to localize+ * those the same way. Codes without copy fall through to the provider text, stripped of the URL.+ */+const langChainErrorKeys: Record<string, TranslationKeys> = {+ MODEL_NOT_FOUND: 'com_error_model_not_found',+ MODEL_RATE_LIMIT: 'com_error_model_rate_limit',+};++function getLangChainErrorKey(text: string): TranslationKeys | undefined {+ const code = parseLangChainErrorCode(text);+ return code == null ? undefined : langChainErrorKeys[code];+}type TConcurrent = {limit: number;@@ -79,6 +100,8 @@ const errorMessages = {[ErrorTypes.GOOGLE_VIDEO_UNPROCESSABLE]: 'com_error_google_video_unprocessable',[ErrorTypes.RESOURCE_RECOVERY_REQUIRED]: 'com_error_resource_recovery_required',[ErrorTypes.STREAM_EXPIRED]: 'com_error_stream_expired',+ [ErrorTypes.MODEL_NOT_FOUND]: langChainErrorKeys.MODEL_NOT_FOUND,+ [ErrorTypes.MODEL_RATE_LIMIT]: langChainErrorKeys.MODEL_RATE_LIMIT,[ViolationTypes.BAN]:'Your account has been temporarily banned due to violations of our service.',[ViolationTypes.ILLEGAL_MODEL_REQUEST]: (json: TGenericError, localize: LocalizeFunction) => {@@ -134,11 +157,14 @@ const errorMessages = {const Error = ({ text }: { text: string }) => {const localize = useLocalize();const jsonString = extractJson(text);- const errorMessage = text.length > 512 && !jsonString ? text.slice(0, 512) + '...' : text;+ const providerText = stripLangChainTroubleshootingUrl(text);+ const errorMessage =+ providerText.length > 512 && !jsonString ? providerText.slice(0, 512) + '...' : providerText;const defaultResponse = `Something went wrong. Here's the specific error message we encountered: ${errorMessage}`;- if (langChainModelNotFoundUrl.test(text)) {- return localize('com_error_model_not_found');+ const langChainErrorKey = getLangChainErrorKey(text);+ if (langChainErrorKey != null) {+ return localize(langChainErrorKey);}if (!isJson(jsonString)) {diff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsxindex 5e2bc1ce76..3c6e3069dc 100644--- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx+++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx@@ -30,12 +30,32 @@ describe('Error — typed provider errors', () => {expect(catalog.com_error_google_video_unprocessable).toMatch(/too long/i);});- it('replaces LangChain model-not-found attribution with localized guidance', () => {+ it.each([+ ['MODEL_NOT_FOUND', 'com_error_model_not_found'],+ ['MODEL_RATE_LIMIT', 'com_error_model_rate_limit'],+ ])('replaces LangChain %s attribution with localized guidance', (code, key) => {+ const raw = `An error occurred while processing the request: 404 404 page not found Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${code}/`;+ render(<Error text={raw} />);++ expect(screen.getByText(catalog[key])).toBeInTheDocument();+ expect(screen.queryByText(/langchain\.com/i)).not.toBeInTheDocument();+ });++ it.each([+ [ErrorTypes.MODEL_NOT_FOUND, 'com_error_model_not_found'],+ [ErrorTypes.MODEL_RATE_LIMIT, 'com_error_model_rate_limit'],+ ])('localizes the typed %s payload the server now emits', (type, key) => {+ render(<Error text={JSON.stringify({ type })} />);++ expect(screen.getByText(catalog[key])).toBeInTheDocument();+ });++ it('keeps the provider message for a LangChain code without localized copy, minus the URL', () => {const raw =- 'An error occurred while processing the request: 404 404 page not found Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/MODEL_NOT_FOUND/';+ 'An error occurred while processing the request: could not parse output\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/OUTPUT_PARSING_FAILURE/\n';render(<Error text={raw} />);- expect(screen.getByText(catalog.com_error_model_not_found)).toBeInTheDocument();+ expect(screen.getByText(/could not parse output/)).toBeInTheDocument();expect(screen.queryByText(/langchain\.com/i)).not.toBeInTheDocument();});diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex fa36e7c78e..39c1f6a6ca 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -396,6 +396,7 @@"com_error_invalid_user_key": "Invalid key provided. Please provide a valid key and try again.","com_error_missing_model": "No model selected for {{0}}. Please select a model and try again.","com_error_model_not_found": "The selected model is unavailable from this provider. Select a different model or ask an administrator to verify the provider configuration.",+ "com_error_model_rate_limit": "The provider declined this request for exceeding a rate or spending limit. Wait a moment and try again, or ask an administrator to review the provider's limits.","com_error_models_not_loaded": "Models configuration could not be loaded. Please refresh the page and try again.","com_error_moderation": "It appears that the content submitted has been flagged by our moderation system for not aligning with our community guidelines. We're unable to proceed with this specific topic. If you have any other questions or topics you'd like to explore, please edit your message, or create a new conversation.","com_error_no_base_url": "No base URL found. Please provide one and try again.",diff --git a/packages/api/src/agents/errors.spec.ts b/packages/api/src/agents/errors.spec.tsindex e75982b3af..8eb490912e 100644--- a/packages/api/src/agents/errors.spec.ts+++ b/packages/api/src/agents/errors.spec.ts@@ -1,5 +1,12 @@import { ErrorTypes } from 'librechat-data-provider';-import { AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE, isFatalAgentInitializationError } from './errors';+import {+ GENERIC_PROVIDER_ERROR,+ getLangChainErrorCode,+ resolveLangChainError,+ getUserFacingProviderError,+ isFatalAgentInitializationError,+ AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE,+} from './errors';describe('isFatalAgentInitializationError', () => {it.each([@@ -27,3 +34,75 @@ describe('isFatalAgentInitializationError', () => {},);});++describe('LangChain provider error text', () => {+ /** The exact tail `addLangChainErrorFields` appends to `error.message`. */+ const troubleshooting = (code: string) =>+ `\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${code}/\n`;++ describe('getLangChainErrorCode', () => {+ it('prefers the field LangChain stamps on the error', () => {+ const error = Object.assign(new Error('429 budget exceeded'), {+ lc_error_code: 'MODEL_RATE_LIMIT',+ });+ expect(getLangChainErrorCode(error)).toBe('MODEL_RATE_LIMIT');+ });++ it('recovers the code from the message when the field did not survive', () => {+ const error = new Error(`404 page not found${troubleshooting('MODEL_NOT_FOUND')}`);+ expect(getLangChainErrorCode(error)).toBe('MODEL_NOT_FOUND');+ });++ it.each([undefined, null, 'plain text', new Error('429 Too Many Requests')])(+ 'returns undefined for an unclassified error',+ (error) => {+ expect(getLangChainErrorCode(error)).toBeUndefined();+ },+ );++ it('survives an error-like object whose message is not a string', () => {+ expect(getLangChainErrorCode({ message: { error: 'rate limited' } })).toBeUndefined();+ });+ });++ describe('resolveLangChainError', () => {+ it.each([+ ['MODEL_RATE_LIMIT', ErrorTypes.MODEL_RATE_LIMIT],+ ['MODEL_NOT_FOUND', ErrorTypes.MODEL_NOT_FOUND],+ ])('maps %s to the typed payload the client localizes', (code, type) => {+ const error = Object.assign(new Error('failed'), { lc_error_code: code });+ expect(resolveLangChainError(error)).toBe(JSON.stringify({ type }));+ });++ it('leaves codes without localized copy to the provider message', () => {+ const error = Object.assign(new Error('failed'), { lc_error_code: 'OUTPUT_PARSING_FAILURE' });+ expect(resolveLangChainError(error)).toBeUndefined();+ });+ });++ describe('getUserFacingProviderError', () => {+ it('strips the docs URL from the forwarded provider message', () => {+ const error = new Error(`429 budget exceeded${troubleshooting('MODEL_RATE_LIMIT')}`);+ expect(getUserFacingProviderError(error, false)).toBe('429 budget exceeded');+ });++ it('withholds provider text when content protection is enabled', () => {+ const error = new Error(`429 budget exceeded${troubleshooting('MODEL_RATE_LIMIT')}`);+ expect(getUserFacingProviderError(error, true)).toBe(GENERIC_PROVIDER_ERROR);+ });++ it('falls back when stripping leaves nothing behind', () => {+ const error = new Error(troubleshooting('MODEL_RATE_LIMIT').trim());+ expect(getUserFacingProviderError(error, false)).toBe(GENERIC_PROVIDER_ERROR);+ });++ it('does not attempt to read a message off a non-Error rejection', () => {+ expect(getUserFacingProviderError('boom', false)).toBe('An error occurred');+ });++ it('coerces an Error whose message was overwritten with an object', () => {+ const error = Object.assign(new Error('replaced'), { message: { error: 'rate limited' } });+ expect(getUserFacingProviderError(error, false)).toBe('[object Object]');+ });+ });+});diff --git a/packages/api/src/agents/errors.ts b/packages/api/src/agents/errors.tsindex bb3e6aef49..1cb6a7bc6a 100644--- a/packages/api/src/agents/errors.ts+++ b/packages/api/src/agents/errors.ts@@ -1,4 +1,8 @@-import { ErrorTypes } from 'librechat-data-provider';+import {+ ErrorTypes,+ parseLangChainErrorCode,+ stripLangChainTroubleshootingUrl,+} from 'librechat-data-provider';export const AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE = 'AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE';@@ -46,3 +50,54 @@ export function isFatalAgentInitializationError((code === AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE && options.allowExpectedMCPFallback !== true));}++/** Fallback shown when provider error text must not reach the user. */+export const GENERIC_PROVIDER_ERROR = 'An error occurred while processing the request';++/**+ * LangChain error codes we answer with localized copy. Codes absent here keep the provider's own+ * message (minus the docs URL), which is more specific than any generic string we could write.+ */+const LANGCHAIN_ERROR_TYPES: Record<string, ErrorTypes> = {+ MODEL_NOT_FOUND: ErrorTypes.MODEL_NOT_FOUND,+ MODEL_RATE_LIMIT: ErrorTypes.MODEL_RATE_LIMIT,+};++/**+ * Reads LangChain's classification off the error, falling back to the docs URL it stamps into the+ * message so a re-thrown or serialized error still classifies.+ */+export function getLangChainErrorCode(error: unknown): string | undefined {+ if (error == null || typeof error !== 'object') {+ return parseLangChainErrorCode(error);+ }+ const { lc_error_code: code, message } = error as { lc_error_code?: unknown; message?: unknown };+ if (typeof code === 'string' && code.length > 0) {+ return code.toUpperCase();+ }+ return parseLangChainErrorCode(message);+}++/**+ * Typed payload the client localizes for a classified LangChain failure, or `undefined` when the+ * code has no localized copy and the provider's own message should be shown instead.+ */+export function resolveLangChainError(error: unknown): string | undefined {+ const code = getLangChainErrorCode(error);+ const type = code == null ? undefined : LANGCHAIN_ERROR_TYPES[code];+ return type == null ? undefined : JSON.stringify({ type });+}++/**+ * Provider failure text for OpenAI-compatible responses, which carry raw strings rather than the+ * typed payloads the LibreChat client localizes.+ */+export function getUserFacingProviderError(error: unknown, protectionEnabled: boolean): string {+ if (protectionEnabled) {+ return GENERIC_PROVIDER_ERROR;+ }+ if (!(error instanceof Error)) {+ return 'An error occurred';+ }+ return stripLangChainTroubleshootingUrl(error.message) || GENERIC_PROVIDER_ERROR;+}diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.tsindex 11cce34216..f8f5b01bed 100644--- a/packages/api/src/agents/openai/service.ts+++ b/packages/api/src/agents/openai/service.ts@@ -71,19 +71,11 @@ import {import { contentFilterBlockResponse, isContentFilterError } from '~/middleware/contentFilter';import { contentFilterUninspectableResponse } from '~/protection/files';import { createMCPRuntimeRequestBody } from '~/mcp/request';+import { getUserFacingProviderError } from '../errors';import { collectReachableAgents } from '../traversal';import { getDynamicToolContexts } from '../hitl';import { createSafeUser } from '~/utils';-const GENERIC_PROVIDER_ERROR = 'An error occurred while processing the request';--function getUserFacingProviderError(error: unknown, protectionEnabled: boolean): string {- if (protectionEnabled) {- return GENERIC_PROVIDER_ERROR;- }- return error instanceof Error ? error.message : 'An error occurred';-}-/*** Dependencies for the chat completion service*/diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 42e39f10e5..8f4bab1609 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -3090,6 +3090,14 @@ export enum ErrorTypes {* SSE stream 404 — job completed, expired, or was deleted before the subscriber connected*/STREAM_EXPIRED = 'stream_expired',+ /**+ * Provider does not serve the requested model+ */+ MODEL_NOT_FOUND = 'model_not_found',+ /**+ * Provider throttled or refused the request for exceeding a rate/spend allowance+ */+ MODEL_RATE_LIMIT = 'model_rate_limit',}/**diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.tsindex 7c3e1651bc..6b5e3e5fe2 100644--- a/packages/data-provider/src/index.ts+++ b/packages/data-provider/src/index.ts@@ -3,6 +3,7 @@ export * from './azure';export * from './bedrock';export * from './balance';export * from './config';+export * from './langchain';export * from './filters';export * from './file-config';/* messages */diff --git a/packages/data-provider/src/langchain.spec.ts b/packages/data-provider/src/langchain.spec.tsnew file mode 100644index 0000000000..839083f571--- /dev/null+++ b/packages/data-provider/src/langchain.spec.ts@@ -0,0 +1,48 @@+import { stripLangChainTroubleshootingUrl, parseLangChainErrorCode } from './langchain';++/** The exact tail `addLangChainErrorFields` appends to `error.message`. */+const troubleshooting = (code: string) =>+ `\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${code}/\n`;++describe('stripLangChainTroubleshootingUrl', () => {+ it('removes the docs URL and the whitespace that framed it', () => {+ expect(+ stripLangChainTroubleshootingUrl(`429 budget exceeded${troubleshooting('MODEL_RATE_LIMIT')}`),+ ).toBe('429 budget exceeded');+ });++ it('removes every occurrence when a wrapped error carries more than one', () => {+ const message = `outer${troubleshooting('MODEL_RATE_LIMIT')}inner${troubleshooting('MODEL_NOT_FOUND')}`;+ expect(stripLangChainTroubleshootingUrl(message)).toBe('outer inner');+ });++ it('leaves provider text without the tail untouched', () => {+ const message = '400 Bad Request\nRequest contains an invalid argument';+ expect(stripLangChainTroubleshootingUrl(message)).toBe(message);+ });++ it('coerces a non-string message the way string interpolation would', () => {+ expect(stripLangChainTroubleshootingUrl({ error: 'rate limited' })).toBe('[object Object]');+ expect(stripLangChainTroubleshootingUrl(429)).toBe('429');+ });++ it.each([undefined, null])('treats an absent message as empty', (message) => {+ expect(stripLangChainTroubleshootingUrl(message)).toBe('');+ });+});++describe('parseLangChainErrorCode', () => {+ it.each(['MODEL_RATE_LIMIT', 'MODEL_NOT_FOUND', 'OUTPUT_PARSING_FAILURE'])(+ 'reads %s back out of the appended URL',+ (code) => {+ expect(parseLangChainErrorCode(`failed${troubleshooting(code)}`)).toBe(code);+ },+ );++ it.each(['429 Too Many Requests', '', undefined, { message: 'nested' }])(+ 'returns undefined when the text carries no classification',+ (message) => {+ expect(parseLangChainErrorCode(message)).toBeUndefined();+ },+ );+});diff --git a/packages/data-provider/src/langchain.ts b/packages/data-provider/src/langchain.tsnew file mode 100644index 0000000000..df4a0c6889--- /dev/null+++ b/packages/data-provider/src/langchain.ts@@ -0,0 +1,28 @@+/**+ * LangChain classifies a provider failure by mutating the error: it stamps `lc_error_code` and+ * appends `\n\nTroubleshooting URL: <docs url>\n` to the message. Both halves are handled here+ * because the server strips the URL before persisting the message, while the client still reads the+ * code back out of messages persisted before it did.+ */+const TROUBLESHOOTING_URL =+ /\s*Troubleshooting URL:\s*https?:\/\/\S*langchain\S*\/errors\/[A-Za-z_]+\/?\s*/g;++const ERROR_CODE_URL = /langchain\S*\/errors\/([A-Za-z_]+)/i;++/** Provider errors cross untyped boundaries, so a `message` is not guaranteed to be a string. */+function toMessageText(message: unknown): string {+ if (typeof message === 'string') {+ return message;+ }+ return message == null ? '' : String(message);+}++/** Removes LangChain's appended docs URL so provider text carries no third-party attribution. */+export function stripLangChainTroubleshootingUrl(message: unknown): string {+ return toMessageText(message).replace(TROUBLESHOOTING_URL, ' ').trim();+}++/** The classification LangChain encoded in the docs URL it appended, when the text carries one. */+export function parseLangChainErrorCode(message: unknown): string | undefined {+ return toMessageText(message).match(ERROR_CODE_URL)?.[1]?.toUpperCase();+}