๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
๐ fix(router): fallback on remote media download timeouts (#19601)
YuTengjing6af887cdb95b
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 1d13f3af871..25d04cad93e 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -88,6 +88,13 @@ vi.mock('@lobechat/model-runtime', async () => {// implementation instead of a drifting stub.const { resolveEffectiveReasoningChatConfig } =await import('../../../../../../packages/model-runtime/src/utils/modelExtendParams');+ const errorCodeSpecs = {+ RemoteMediaDownloadTimeout: {+ code: 'RemoteMediaDownloadTimeout',+ retryable: false,+ },+ };+return {// The executor resolves extend params via this helper; an empty result keeps// the runtime payload unchanged, matching this suite's pre-existing behavior.@@ -96,11 +103,12 @@ vi.mock('@lobechat/model-runtime', async () => {}),resolveEffectiveReasoningChatConfig,consumeStreamUntilDone: vi.fn().mockResolvedValue(undefined),- // `llmErrorClassification.ts` reads these at module-load time; an empty- // spec map is fine here because this suite never exercises the runtime- // retry classifier path.- ERROR_CODE_SPECS: {},- getErrorCodeSpec: () => undefined,+ // `llmErrorClassification.ts` reads these at module-load time. Keep the+ // terminal media-timeout transport contract available to the executor test below.+ ERROR_CODE_SPECS: errorCodeSpecs,+ getErrorCodeSpec: (code: string) =>+ errorCodeSpecs[code as keyof typeof errorCodeSpecs] as+ (typeof errorCodeSpecs)[keyof typeof errorCodeSpecs] | undefined,isDeepSeekThinkingEligibleModel: (model: string) =>typeof model === 'string' &&(model.toLowerCase().includes('deepseek-reasoner') ||@@ -5560,6 +5568,54 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {).toBe(false);});+ it.each(['lobehub', 'azure'])(+ 'should not retry a %s remote media download timeout after routing ends',+ async (provider) => {+ const mediaDownloadTimeout = {+ error: {+ code: 'invalid_value',+ error: {+ code: 'invalid_value',+ message:+ 'Unable to download content from the provided URL before the timeout. Check that the URL is publicly accessible and responds promptly, or upload the file and provide a file_id instead.',+ param: 'url',+ type: 'invalid_request_error',+ },+ param: 'url',+ status: 400,+ type: 'invalid_request_error',+ },+ errorType: 'RemoteMediaDownloadTimeout',+ provider: 'azure',+ };+ const mockChat = vi.fn().mockRejectedValue(mediaDownloadTimeout);++ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);++ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();+ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-6-astra',+ parentMessageId: 'parent-msg-123',+ provider,+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await expect(executors.call_llm!(instruction, state)).rejects.toEqual(mediaDownloadTimeout);++ expect(mockChat).toHaveBeenCalledTimes(1);+ expect(+ mockStreamManager.publishStreamEvent.mock.calls.some(+ ([, event]: [string, { type: string }]) => event.type === 'stream_retry',+ ),+ ).toBe(false);+ },+ );+it('should retry a no-usage empty completion caused by a network error once', async () => {vi.useFakeTimers();diff --git a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.tsindex d2ba2612925..dbf736db885 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts@@ -76,6 +76,7 @@ describe('classifyLLMError', () => {['ExceededToolLimit', 'tools array exceeds limit'],['ModelEmptyCompletion', 'model returned an empty completion'],['ModelRefusal', 'model declined to answer'],+ ['RemoteMediaDownloadTimeout', 'provider timed out downloading remote media'],])('classifies %s as stop (no HTTP status)', (errorType, message) => {expect(classifyLLMError({ errorType, message }).kind).toBe('stop');});diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.jsonindex 4cd7484e9a7..abf32e54a30 100644--- a/locales/en-US/modelRuntime.json+++ b/locales/en-US/modelRuntime.json@@ -43,6 +43,7 @@"ProviderServiceUnavailable": "The provider is temporarily overloaded or unavailable. Please try again shortly.","QuotaLimitReached": "Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.","RateLimitExceeded": "Sorry, the token usage or request count has reached the rate limit for this key. Please try again later or increase the key's quota.",+ "RemoteMediaDownloadTimeout": "The provider timed out while downloading an attached image or file. Please try again.","RequestBodyTooLarge": "This request is too large for the model provider. Compact the conversation or reduce attached content, then try again.","StateStorePersistError": "A temporary issue with the conversation state store interrupted this operation. Please try again; if it persists, contact support.","StateStoreReadError": "This operation could not be resumed because its session state was unavailable. Please reopen the conversation to continue; if it persists, contact support.",diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.jsonindex 14d4b555e04..dc94129458c 100644--- a/locales/zh-CN/modelRuntime.json+++ b/locales/zh-CN/modelRuntime.json@@ -43,6 +43,7 @@"ProviderServiceUnavailable": "ๆไพๅๆๆถ่ฟ่ฝฝๆไธๅฏ็จใ่ฏท็จๅ้่ฏใ","QuotaLimitReached": "ๆฑๆญ๏ผๆญคๅฏ้ฅ็ไปค็ไฝฟ็จ้ๆ่ฏทๆฑๆฌกๆฐๅทฒ่พพๅฐ้ ้ข้ๅถใ่ฏทๅขๅ ๅฏ้ฅ้ ้ขๆ็จๅ้่ฏใ","RateLimitExceeded": "ๆฑๆญ๏ผๆญคๅฏ้ฅ็ไปค็ไฝฟ็จ้ๆ่ฏทๆฑๆฌกๆฐๅทฒ่พพๅฐ้็้ๅถใ่ฏท็จๅ้่ฏๆๅขๅ ๅฏ้ฅ้ ้ขใ",+ "RemoteMediaDownloadTimeout": "ๆไพๅไธ่ฝฝ้ๅ ็ๅพ็ๆๆไปถๆถ่ถ ๆถใ่ฏท้่ฏใ","RequestBodyTooLarge": "่ฟๆฌก่ฏทๆฑ่ถ ่ฟๆจกๅๆไพๅๅ ่ฎธ็ๅคงๅฐใ่ฏทๅ็ผฉๅฏน่ฏๆๅๅฐ้ๅ ๅ ๅฎนๅ้่ฏใ","StateStorePersistError": "ๅฏน่ฏ็ถๆๅญๅจ็ไธดๆถ้ฎ้ขไธญๆญไบๆญคๆไฝใ่ฏท้่ฏ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏท่็ณปๆฏๆใ","StateStoreReadError": "ๆญคๆไฝๆ ๆณ็ปง็ปญ๏ผๅ ไธบไผ่ฏ็ถๆไธๅฏ็จใ่ฏท้ๆฐๆๅผๅฏน่ฏไปฅ็ปง็ปญ๏ผๅฆๆ้ฎ้ขไป็ถๅญๅจ๏ผ่ฏท่็ณปๆฏๆไบบๅใ",diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.tsindex 90eae7d6f05..6ddc9b6eb60 100644--- a/packages/locales/src/default/modelRuntime.ts+++ b/packages/locales/src/default/modelRuntime.ts@@ -79,6 +79,8 @@ export default {'Connection to the provider timed out or was dropped. Please check your network and try again.','ProviderNoImageGenerated':'The provider returned no image for this request. Try rephrasing the request, or choose a model that supports image generation.',+ 'RemoteMediaDownloadTimeout':+ 'The provider timed out while downloading an attached image or file. Please try again.','ProviderServiceUnavailable':'The provider is temporarily overloaded or unavailable. Please try again shortly.','QuotaLimitReached':diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 70f333cdb32..22f79c150e0 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -954,6 +954,54 @@ describe('createRouterRuntime', () => {expect(attemptedKeys).toEqual(['key-1', 'key-2']);});+ it('should fallback after a structured remote media download timeout', async () => {+ const attemptedKeys: string[] = [];++ class RemoteMediaRuntime implements LobeRuntimeAI {+ private readonly apiKey: string;++ constructor(options: { apiKey: string }) {+ this.apiKey = options.apiKey;+ }++ chat = vi.fn().mockImplementation(async () => {+ attemptedKeys.push(this.apiKey);++ if (this.apiKey === 'key-1') {+ throw {+ error: {+ code: 'invalid_value',+ message: 'Unable to download content from the provided URL before the timeout.',+ param: 'url',+ type: 'invalid_request_error',+ },+ errorType: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ provider: 'azure',+ status: 400,+ };+ }++ return 'success';+ });+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ models: ['gpt-4o'],+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: RemoteMediaRuntime as any,+ },+ ],+ });++ const runtime = new Runtime();+ await expect(runtime.chat({ model: 'gpt-4o', messages: [] })).resolves.toBe('success');+ expect(attemptedKeys).toEqual(['key-1', 'key-2']);+ });+it('should throw error when options array is empty', async () => {const Runtime = createRouterRuntime({id: 'test-runtime',diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex bcd505a57d4..f849732a07d 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -39,12 +39,9 @@ import type {TextToSpeechPayload,} from '../../types';import { AgentRuntimeError } from '../../utils/createError';-import {- isImageDecodingRequestError,- isNonRetryableRequestError,-} from '../../utils/isNonRetryableRequestError';import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import { postProcessModelList } from '../../utils/postProcessModelList';+import { isImageDecodingRequestError, shouldStopFallbackForError } from '../../utils/routeFallback';import { safeParseJSON } from '../../utils/safeParseJSON';import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';import type { LobeRuntimeAI } from '../BaseAI';@@ -814,9 +811,9 @@ export const createRouterRuntime = ({);}- const nonRetryable = isNonRetryableRequestError(error);+ const shouldStopFallback = shouldStopFallbackForError(error);const nonRetryableReason =- nonRetryable && isImageDecodingRequestError(error)+ shouldStopFallback && isImageDecodingRequestError(error)? ('imageDecode' as const): undefined;@@ -828,7 +825,7 @@ export const createRouterRuntime = ({error,metadata,model,- nonRetryable,+ nonRetryable: shouldStopFallback,nonRetryableReason,optionIndex: index,providerId: id,@@ -841,7 +838,7 @@ export const createRouterRuntime = ({log('onRouteAttempt callback error: %O', e);});- if (nonRetryable) {+ if (shouldStopFallback) {throw error;}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex d8f6a241d6a..6fba2f65072 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -1377,6 +1377,41 @@ describe('LobeOpenAICompatibleFactory', () => {});});+ it('should classify a remote media download timeout as retryable', async () => {+ const message =+ 'Unable to download content from the provided URL before the timeout. Check that the URL is publicly accessible and responds promptly, or upload the file and provide a file_id instead.';+ const apiError = new OpenAI.APIError(+ 400,+ {+ code: 'invalid_value',+ error: {+ code: 'invalid_value',+ message,+ param: 'url',+ type: 'invalid_request_error',+ },+ param: 'url',+ status: 400,+ type: 'invalid_request_error',+ },+ message,+ new Headers(),+ );++ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);++ await expect(+ instance.chat({+ messages: [{ content: 'Describe this image', role: 'user' }],+ model: 'gpt-4o',+ temperature: 0,+ }),+ ).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ provider,+ });+ });+it('should classify an HTML 413 response as RequestBodyTooLarge', async () => {const apiError = new OpenAI.APIError(413,diff --git a/packages/model-runtime/src/errors/match.test.ts b/packages/model-runtime/src/errors/match.test.tsindex 033abbb7b2b..fb9fe2f3f49 100644--- a/packages/model-runtime/src/errors/match.test.ts+++ b/packages/model-runtime/src/errors/match.test.ts@@ -347,6 +347,10 @@ describe('matchErrorPattern โ second residue convergence round', () => {AgentRuntimeErrorType.InsufficientQuota,],['fetch failed', AgentRuntimeErrorType.ProviderNetworkError],+ [+ 'Unable to download content from the provided URL before the timeout.',+ AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ ],['404 page not found', AgentRuntimeErrorType.UserConfigError],['{"errors":[{"code":7003,"message":"No route for that URI"}]}',diff --git a/packages/model-runtime/src/errors/patterns.ts b/packages/model-runtime/src/errors/patterns.tsindex 7195aa887ab..1d60398dd05 100644--- a/packages/model-runtime/src/errors/patterns.ts+++ b/packages/model-runtime/src/errors/patterns.ts@@ -578,6 +578,17 @@ export const ERROR_PATTERNS: ErrorPattern[] = [note: 'Aggregator proxies wrap a transient upstream outage in a bare 500.',},+ // โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ // RemoteMediaDownloadTimeout โ provider-side remote media fetch+ // โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ {+ code: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ match: sub('Unable to download content from the provided URL before the timeout', {+ caseInsensitive: true,+ }),+ note: 'OpenAI-compatible remote media fetch timed out before inference.',+ },+// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ// ProviderNetworkError โ connection / timeout// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdiff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.tsindex d6116aa05e3..21a350a6096 100644--- a/packages/model-runtime/src/errors/specs.ts+++ b/packages/model-runtime/src/errors/specs.ts@@ -51,6 +51,9 @@ export interface ErrorCodeSpec {/** Whether transport-level retry is allowed. */retryable: boolean;+ /** Whether RouterRuntime may continue with a different route option. */+ routeFallback?: boolean;+severity: ErrorSeverity;}@@ -282,6 +285,7 @@ export const ERROR_CODE_SPECS: SpecMap = {attribution: 'user',httpStatus: 400,retryable: false,+ routeFallback: false,countAsFailure: false,description: 'Prompt + tool payload exceeds the model context window.',},@@ -315,6 +319,7 @@ export const ERROR_CODE_SPECS: SpecMap = {attribution: 'user',httpStatus: 400,retryable: false,+ routeFallback: false,countAsFailure: false,description: 'Upstream rejected the request as malformed (bad JSON / schema / parameters).',},@@ -326,6 +331,7 @@ export const ERROR_CODE_SPECS: SpecMap = {attribution: 'user',httpStatus: 400,retryable: false,+ routeFallback: false,countAsFailure: false,description: 'Upstream rejected the serialized request body as too large.',},@@ -367,6 +373,18 @@ export const ERROR_CODE_SPECS: SpecMap = {countAsFailure: false,description: 'Connection timeout / network drop talking to the provider.',},+ [AgentRuntimeErrorType.RemoteMediaDownloadTimeout]: {+ code: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ numericId: 6002,+ category: 'network',+ severity: 'warning',+ attribution: 'system',+ httpStatus: 504,+ retryable: false,+ routeFallback: true,+ countAsFailure: false,+ description: 'Provider timed out while downloading a remote image or file URL.',+ },// โโโ 7xxx Stream / Runtime โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ[AgentRuntimeErrorType.StreamChunkError]: {@@ -503,6 +521,7 @@ export const ERROR_CODE_SPECS: SpecMap = {attribution: 'provider',httpStatus: 471,retryable: false,+ routeFallback: false,countAsFailure: true,description: 'Image-generation provider returned no image.',},@@ -580,6 +599,7 @@ export const ERROR_CODE_SPECS: SpecMap = {attribution: 'user',httpStatus: 471,retryable: false,+ routeFallback: false,countAsFailure: false,description: 'Provider blocked the request or generated output due to content policy.',},diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.tsindex 36c9c54f71e..11f5fb93ef9 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as nonStreamToStreamModule from '../../core/openaiCompatibleFactory/nonStreamToStream';import * as streamsModule from '../../core/streams';+import { AgentRuntimeErrorType } from '../../types/error';import * as debugStreamModule from '../../utils/debugStream';import * as getModelPricingModule from '../../utils/getModelPricing';import { LobeAzureOpenAI } from './index';@@ -378,6 +379,41 @@ describe('LobeAzureOpenAI', () => {});describe('Error', () => {+ it('should classify a Responses API remote media download timeout as retryable', async () => {+ const message =+ 'Unable to download content from the provided URL before the timeout. Check that the URL is publicly accessible and responds promptly, or upload the file and provide a file_id instead.';+ const apiError = new OpenAI.APIError(+ 400,+ {+ code: 'invalid_value',+ error: {+ code: 'invalid_value',+ message,+ param: 'url',+ type: 'invalid_request_error',+ },+ param: 'url',+ status: 400,+ type: 'invalid_request_error',+ },+ message,+ new Headers(),+ );++ (instance['client'].responses.create as Mock).mockRejectedValue(apiError);++ await expect(+ instance.chat({+ messages: [{ content: 'Describe this image', role: 'user' }],+ model: 'gpt-5.4-mini',+ temperature: 0,+ }),+ ).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ provider: 'azure',+ });+ });+it('should return AzureBizError with DeploymentNotFound error', async () => {// Arrangeconst error = {diff --git a/packages/model-runtime/src/providers/azureOpenai/index.ts b/packages/model-runtime/src/providers/azureOpenai/index.tsindex 5228fc28a07..25b798024fd 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.ts@@ -4,6 +4,7 @@ import type OpenAI from 'openai';import { pruneReasoningPayload } from '../../core/contextBuilders/openai';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';+import { refineErrorCode } from '../../errors';import type { ChatMethodOptions, ChatStreamPayload } from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import type { CreateImagePayload } from '../../types/image';@@ -309,12 +310,24 @@ export class LobeAzureOpenAI extends BaseAzureOpenAI {};}+ const fallbackErrorType = normalizedError.code+ ? AgentRuntimeErrorType.ProviderBizError+ : AgentRuntimeErrorType.AgentRuntimeError;+ const errorMessage =+ typeof normalizedError.error?.message === 'string'+ ? normalizedError.error.message+ : normalizedError.message;+ const refinedErrorType = refineErrorCode({+ errorType: fallbackErrorType,+ httpStatus: normalizedError.status,+ message: errorMessage,+ provider: ModelProvider.Azure,+ });+return AgentRuntimeError.chat({endpoint: maskSensitiveUrl(this.baseURL),error: sanitizeError(normalizedError),- errorType: normalizedError.code- ? AgentRuntimeErrorType.ProviderBizError- : AgentRuntimeErrorType.AgentRuntimeError,+ errorType: refinedErrorType ?? fallbackErrorType,provider: ModelProvider.Azure,});}diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts b/packages/model-runtime/src/utils/routeFallback.test.tssimilarity index 63%rename from packages/model-runtime/src/utils/isNonRetryableRequestError.test.tsrename to packages/model-runtime/src/utils/routeFallback.test.tsindex 581a39a691d..54a80695dca 100644--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts+++ b/packages/model-runtime/src/utils/routeFallback.test.ts@@ -1,49 +1,46 @@import { describe, expect, it } from 'vitest';import { AgentRuntimeErrorType } from '../types/error';-import {- isImageDecodingRequestError,- isNonRetryableRequestError,-} from './isNonRetryableRequestError';+import { isImageDecodingRequestError, shouldStopFallbackForError } from './routeFallback';-describe('isNonRetryableRequestError', () => {- it('returns true for ExceededContextWindow errors', () => {+describe('shouldStopFallbackForError', () => {+ it('stops fallback for ExceededContextWindow errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: 'Too many input tokens' },errorType: AgentRuntimeErrorType.ExceededContextWindow,}),).toBe(true);});- it('does not retry an oversized upstream request body on another channel', () => {+ it('stops fallback for an oversized upstream request body', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: '<html>413 Request Entity Too Large</html>', status: 413 },errorType: AgentRuntimeErrorType.RequestBodyTooLarge,}),).toBe(true);});- it('returns true for terminal image generation errors', () => {+ it('stops fallback for terminal image generation errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: 'Google image generation was blocked by content policy.' },errorType: AgentRuntimeErrorType.ProviderContentPolicyViolation,}),).toBe(true);expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: 'The provider did not return an image.' },errorType: AgentRuntimeErrorType.ProviderNoImageGenerated,}),).toBe(true);});- it('returns true for provider image decoding request errors', () => {+ it('stops fallback for provider image decoding request errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {message:'400 INVALID_ARGUMENT: Failed to decode image data. Please make sure the image is valid.',@@ -54,7 +51,7 @@ describe('isNonRetryableRequestError', () => {).toBe(true);expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: 'Unable to process input image' },errorType: AgentRuntimeErrorType.ProviderBizError,status: 400,@@ -70,9 +67,9 @@ describe('isNonRetryableRequestError', () => {expect(isImageDecodingRequestError({ message: 'Invalid request payload' })).toBe(false);});- it('returns true for invalid request payload errors', () => {+ it('stops fallback for invalid request payload errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {body: { httpStatusCode: 400 },message: 'This model maximum input length is 128000 tokens. Please reduce your input.',@@ -83,9 +80,45 @@ describe('isNonRetryableRequestError', () => {).toBe(true);});- it('returns true for provider request-body-too-large context errors', () => {+ it('allows fallback for a structured remote media download timeout', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({+ error: {+ code: 'invalid_value',+ error: {+ code: 'invalid_value',+ message:+ 'Unable to download content from the provided URL before the timeout. Check that the URL is publicly accessible and responds promptly, or upload the file and provide a file_id instead.',+ param: 'url',+ type: 'invalid_request_error',+ },+ param: 'url',+ status: 400,+ type: 'invalid_request_error',+ },+ errorType: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,+ provider: 'azure',+ }),+ ).toBe(false);+ });++ it('does not infer remote media timeout semantics from raw provider text', () => {+ expect(+ shouldStopFallbackForError({+ error: {+ code: 'invalid_value',+ message: 'Unable to download content from the provided URL before the timeout.',+ type: 'invalid_request_error',+ },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ status: 400,+ }),+ ).toBe(true);+ });++ it('stops fallback for provider request-body-too-large context errors', () => {+ expect(+ shouldStopFallbackForError({error: {message: 'Request body too large for gpt-4o model',type: 'invalid_request_error',@@ -102,16 +135,16 @@ describe('isNonRetryableRequestError', () => {// OpenAI-compatible providers can return content filter rejections as 400// responses with `code`, `type`, or `finish_reason` set to// "content_filter" instead of a structured runtime error type. If the- // router treats that raw provider payload as retryable, one blocked prompt+ // router treats that raw provider payload as fallback-eligible, one blocked prompt// can fan out across fallback channels.//// Before the fix, this returned false because `content_filter` was not in- // the non-retryable code set.+ // the terminal error code set.//// We fixed this by treating provider moderation signals as terminal request- // errors at the model-runtime retry gate.+ // errors at the Router fallback gate.expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {code: 'content_filter',message: 'The provider blocked this prompt.',@@ -123,7 +156,7 @@ describe('isNonRetryableRequestError', () => {).toBe(true);expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {choices: [{ finish_reason: 'content_policy_violation' }],message: 'The provider blocked this prompt.',@@ -134,9 +167,9 @@ describe('isNonRetryableRequestError', () => {).toBe(true);});- it('returns true for invalid response_format schema errors', () => {+ it('stops fallback for invalid response_format schema errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {message:"Invalid schema for response_format 'json_schema': schema must be a JSON Schema.",@@ -146,9 +179,9 @@ describe('isNonRetryableRequestError', () => {).toBe(true);});- it('returns true for unsupported model parameter errors', () => {+ it('stops fallback for unsupported model parameter errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {error: {code: 'bad_response_status_code',@@ -163,9 +196,9 @@ describe('isNonRetryableRequestError', () => {).toBe(true);});- it('returns true for assistant prefill request-shape errors', () => {+ it('stops fallback for assistant prefill request-shape errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {body: { httpStatusCode: 400 },message:@@ -177,15 +210,15 @@ describe('isNonRetryableRequestError', () => {).toBe(true);});- it('returns false for bare 400/413/422 request errors', () => {- expect(isNonRetryableRequestError({ errorType: 'ProviderBizError', status: 400 })).toBe(false);- expect(isNonRetryableRequestError({ errorType: 'ProviderBizError', status: 413 })).toBe(false);- expect(isNonRetryableRequestError({ errorType: 'ProviderBizError', status: 422 })).toBe(false);+ it('allows fallback for bare 400/413/422 request errors', () => {+ expect(shouldStopFallbackForError({ errorType: 'ProviderBizError', status: 400 })).toBe(false);+ expect(shouldStopFallbackForError({ errorType: 'ProviderBizError', status: 413 })).toBe(false);+ expect(shouldStopFallbackForError({ errorType: 'ProviderBizError', status: 422 })).toBe(false);});- it('returns false for retryable rate limit and quota errors', () => {+ it('allows fallback for rate limit and quota errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: 'Unable to process input image' },errorType: AgentRuntimeErrorType.ProviderBizError,status: 429,@@ -193,7 +226,7 @@ describe('isNonRetryableRequestError', () => {).toBe(false);expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { code: 'rate_limit_exceeded', message: 'Rate limit reached for requests' },errorType: AgentRuntimeErrorType.ProviderBizError,status: 429,@@ -201,7 +234,7 @@ describe('isNonRetryableRequestError', () => {).toBe(false);expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { code: 'insufficient_quota', message: 'You exceeded your current quota' },errorType: AgentRuntimeErrorType.ProviderBizError,status: 429,@@ -209,9 +242,9 @@ describe('isNonRetryableRequestError', () => {).toBe(false);});- it('returns false for standardized provider account balance errors', () => {+ it('allows fallback for standardized provider account balance errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: {code: 'invalid_request_error',message: 'Insufficient Balance',@@ -223,9 +256,9 @@ describe('isNonRetryableRequestError', () => {).toBe(false);});- it('returns false for channel-specific auth and model errors', () => {+ it('allows fallback for channel-specific auth and model errors', () => {expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { message: 'Unauthorized: invalid API key' },errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,status: 400,@@ -233,7 +266,7 @@ describe('isNonRetryableRequestError', () => {).toBe(false);expect(- isNonRetryableRequestError({+ shouldStopFallbackForError({error: { code: 'DeploymentNotFound', message: 'The deployment does not exist.' },errorType: AgentRuntimeErrorType.ProviderBizError,status: 404,diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/routeFallback.tssimilarity index 78%rename from packages/model-runtime/src/utils/isNonRetryableRequestError.tsrename to packages/model-runtime/src/utils/routeFallback.tsindex 1a31f1968e9..691cde487e7 100644--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts+++ b/packages/model-runtime/src/utils/routeFallback.ts@@ -1,18 +1,11 @@import { toRecord } from '@lobechat/utils';+import { getErrorCodeSpec } from '../errors/specs';import { AgentRuntimeErrorType } from '../types/error';import { isErrorCausedByContentFilter } from './isErrorCausedByContentFilter';-const NON_RETRYABLE_ERROR_TYPES = new Set<string>([- AgentRuntimeErrorType.ExceededContextWindow,- AgentRuntimeErrorType.InvalidRequestFormat,- AgentRuntimeErrorType.ProviderContentPolicyViolation,- AgentRuntimeErrorType.ProviderNoImageGenerated,- // Avoid amplifying an oversized payload across channels, accepting that proxy limits can differ.- AgentRuntimeErrorType.RequestBodyTooLarge,-]);-const RETRYABLE_STATUS_CODES = new Set([401, 403, 404, 408, 409, 423, 425, 429]);-const RETRYABLE_ERROR_CODES = new Set([+const FALLBACK_STATUS_CODES = new Set([401, 403, 404, 408, 409, 423, 425, 429]);+const FALLBACK_ERROR_CODES = new Set(['accountdeactivated','deploymentnotfound','invalid_api_key',@@ -24,7 +17,7 @@ const RETRYABLE_ERROR_CODES = new Set(['quota_exceeded','rate_limit_exceeded',]);-const NON_RETRYABLE_ERROR_CODES = new Set([+const TERMINAL_ERROR_CODES = new Set(['context_length_exceeded','invalid_request_error','invalid_schema',@@ -34,7 +27,7 @@ const NON_RETRYABLE_ERROR_CODES = new Set(['string_above_max_length',]);-const RETRYABLE_MESSAGE_PATTERNS = [+const FALLBACK_MESSAGE_PATTERNS = ['api key','billing','capacity',@@ -61,7 +54,7 @@ const IMAGE_DECODING_MESSAGE_PATTERNS = ['unable to process input image',];-const NON_RETRYABLE_MESSAGE_PATTERNS = [+const TERMINAL_MESSAGE_PATTERNS = ['assistant message prefill','conversation must end with a user message','context length exceeded',@@ -177,29 +170,33 @@ export const isImageDecodingRequestError = (error: unknown): boolean => {return IMAGE_DECODING_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern));};-export const isNonRetryableRequestError = (error: unknown): boolean => {+export const shouldStopFallbackForError = (error: unknown): boolean => {const errorStrings = collectErrorStrings(error);const normalizedStrings = errorStrings.map((value) => value.toLowerCase());if (error && typeof error === 'object') {const errorType = (error as { errorType?: unknown }).errorType;- if (typeof errorType === 'string' && NON_RETRYABLE_ERROR_TYPES.has(errorType)) return true;+ if (typeof errorType === 'string') {+ const routeFallback = getErrorCodeSpec(errorType)?.routeFallback;+ if (routeFallback !== undefined) return !routeFallback;+ }}if (isErrorCausedByContentFilter(error)) return true;- // Explicitly retryable HTTP statuses represent route or channel conditions.+ // Explicitly fallback-eligible HTTP statuses represent route or channel conditions.// They take precedence over provider body text, which can reuse terminal// request phrases such as "unable to process input image" for a 429 response.const statusCodes = collectStatusCodes(error);- if (statusCodes.some((statusCode) => RETRYABLE_STATUS_CODES.has(statusCode))) return false;+ if (statusCodes.some((statusCode) => FALLBACK_STATUS_CODES.has(statusCode))) return false;++ if (normalizedStrings.some((value) => FALLBACK_ERROR_CODES.has(value))) return false;- if (normalizedStrings.some((value) => RETRYABLE_ERROR_CODES.has(value))) return false;- if (normalizedStrings.some((value) => NON_RETRYABLE_ERROR_CODES.has(value))) return true;+ if (normalizedStrings.some((value) => TERMINAL_ERROR_CODES.has(value))) return true;const combined = normalizedStrings.join('\n');- if (RETRYABLE_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern))) return false;- if (NON_RETRYABLE_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern))) return true;+ if (FALLBACK_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern))) return false;+ if (TERMINAL_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern))) return true;return false;};diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex bac6bed171f..0ffa98cb93f 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -192,6 +192,8 @@ export const AgentRuntimeErrorType = {ProviderServiceUnavailable: 'ProviderServiceUnavailable',/** Network timeout / connection drop talking to the provider. */ProviderNetworkError: 'ProviderNetworkError',+ /** Provider timed out while downloading a remote image or file URL. */+ RemoteMediaDownloadTimeout: 'RemoteMediaDownloadTimeout',/** Proxy/router has no channel for the requested model (key pool exhausted, no upstream). */NoAvailableChannel: 'NoAvailableChannel',/** Upstream content-moderation / safety filter rejected the input or output. */