🤯 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: stop router fallback for invalid requests (#14285)
YuTengjingd0e99aada42e
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.tsindex 905c654f215..5e6be3c488a 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts@@ -504,6 +504,79 @@ describe('createRouterRuntime', () => {expect(mockChatSuccess).not.toHaveBeenCalled();});+ it('should not retry when the upstream rejects the request payload', async () => {+ const invalidRequestError = {+ errorType: AgentRuntimeErrorType.ProviderBizError,+ error: {+ body: { httpStatusCode: 400 },+ message: 'This model maximum input length is 128000 tokens. Please reduce your input.',+ type: 'invalid_request_error',+ },+ provider: 'test',+ };++ const mockChatFail = vi.fn().mockRejectedValue(invalidRequestError);++ class FailRuntime implements LobeRuntimeAI {+ chat = mockChatFail;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: FailRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await expect(+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),+ ).rejects.toEqual(invalidRequestError);++ expect(mockChatFail).toHaveBeenCalledTimes(1);+ });++ it('should not retry when the response_format schema is invalid', async () => {+ const invalidSchemaError = {+ errorType: AgentRuntimeErrorType.ProviderBizError,+ error: {+ message:+ "Invalid schema for response_format 'json_schema': schema must be a JSON Schema.",+ },+ provider: 'test',+ };++ const mockChatFail = vi.fn().mockRejectedValue(invalidSchemaError);++ class FailRuntime implements LobeRuntimeAI {+ chat = mockChatFail;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: FailRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await expect(+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),+ ).rejects.toEqual(invalidSchemaError);++ expect(mockChatFail).toHaveBeenCalledTimes(1);+ });+it('should not retry when shouldStopFallback returns true', async () => {const moderationError = {errorType: AgentRuntimeErrorType.ProviderBizError,@@ -589,6 +662,40 @@ describe('createRouterRuntime', () => {expect(mockChatFail).toHaveBeenCalledTimes(2);});+ it('should still retry on channel-specific auth errors even when status is 400', async () => {+ const invalidKeyError = {+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,+ error: { message: 'Unauthorized: invalid API key' },+ provider: 'test',+ status: 400,+ };++ const mockChatFail = vi.fn().mockRejectedValue(invalidKeyError);++ class FailRuntime implements LobeRuntimeAI {+ chat = mockChatFail;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [+ {+ apiType: 'openai',+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],+ runtime: FailRuntime as any,+ models: ['gpt-4'],+ },+ ],+ });++ const runtime = new Runtime();+ await expect(+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),+ ).rejects.toEqual(invalidKeyError);++ expect(mockChatFail).toHaveBeenCalledTimes(2);+ });+it('should use apiType from option item when specified for fallback', async () => {const constructorCalls: any[] = [];diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex 3b1faa56043..6c7ed23d0c7 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -2,7 +2,7 @@* @see https://github.com/lobehub/lobe-chat/discussions/6563*/import type { GoogleGenAIOptions } from '@google/genai';-import { AgentRuntimeErrorType, type ChatModelCard } from '@lobechat/types';+import type { ChatModelCard } from '@lobechat/types';import debug from 'debug';import type { ClientOptions } from 'openai';import type OpenAI from 'openai';@@ -30,6 +30,7 @@ import type {ILobeAgentRuntimeErrorType,TextToSpeechPayload,} from '../../types';+import { isNonRetryableRequestError } from '../../utils/isNonRetryableRequestError';import { postProcessModelList } from '../../utils/postProcessModelList';import { safeParseJSON } from '../../utils/safeParseJSON';import type { LobeRuntimeAI } from '../BaseAI';@@ -404,11 +405,7 @@ export const createRouterRuntime = ({log('onRouteAttempt callback error: %O', e);});- // Non-retryable errors: the request itself is invalid, retrying with another channel won't help- if (- (error as ChatCompletionErrorPayload)?.errorType ===- AgentRuntimeErrorType.ExceededContextWindow- ) {+ if (isNonRetryableRequestError(error)) {throw error;}diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.tsnew file mode 100644index 00000000000..6183c800392--- /dev/null+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest';++import { AgentRuntimeErrorType } from '../types/error';+import { isNonRetryableRequestError } from './isNonRetryableRequestError';++describe('isNonRetryableRequestError', () => {+ it('returns true for ExceededContextWindow errors', () => {+ expect(+ isNonRetryableRequestError({+ error: { message: 'Too many input tokens' },+ errorType: AgentRuntimeErrorType.ExceededContextWindow,+ }),+ ).toBe(true);+ });++ it('returns true for invalid request payload errors', () => {+ expect(+ isNonRetryableRequestError({+ error: {+ body: { httpStatusCode: 400 },+ message: 'This model maximum input length is 128000 tokens. Please reduce your input.',+ type: 'invalid_request_error',+ },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ }),+ ).toBe(true);+ });++ it('returns true for invalid response_format schema errors', () => {+ expect(+ isNonRetryableRequestError({+ error: {+ message:+ "Invalid schema for response_format 'json_schema': schema must be a JSON Schema.",+ },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ }),+ ).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('returns false for retryable rate limit and quota errors', () => {+ expect(+ isNonRetryableRequestError({+ error: { code: 'rate_limit_exceeded', message: 'Rate limit reached for requests' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ status: 429,+ }),+ ).toBe(false);++ expect(+ isNonRetryableRequestError({+ error: { code: 'insufficient_quota', message: 'You exceeded your current quota' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ status: 429,+ }),+ ).toBe(false);+ });++ it('returns false for channel-specific auth and model errors', () => {+ expect(+ isNonRetryableRequestError({+ error: { message: 'Unauthorized: invalid API key' },+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,+ status: 400,+ }),+ ).toBe(false);++ expect(+ isNonRetryableRequestError({+ error: { code: 'DeploymentNotFound', message: 'The deployment does not exist.' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ status: 404,+ }),+ ).toBe(false);+ });+});diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.tsnew file mode 100644index 00000000000..8e079002d66--- /dev/null+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts@@ -0,0 +1,160 @@+import { AgentRuntimeErrorType } from '../types/error';++const NON_RETRYABLE_ERROR_TYPES = new Set<string>([AgentRuntimeErrorType.ExceededContextWindow]);+const RETRYABLE_STATUS_CODES = new Set([401, 403, 404, 408, 409, 423, 425, 429]);+const RETRYABLE_ERROR_CODES = new Set([+ 'accountdeactivated',+ 'deploymentnotfound',+ 'invalid_api_key',+ 'invalidapikey',+ 'invalidproviderapikey',+ 'insufficient_quota',+ 'model_not_found',+ 'quota_exceeded',+ 'rate_limit_exceeded',+]);+const NON_RETRYABLE_ERROR_CODES = new Set([+ 'context_length_exceeded',+ 'invalid_request_error',+ 'invalid_schema',+ 'invalid_type',+ 'invalid_value',+ 'json_schema_validation_error',+ 'string_above_max_length',+]);++const RETRYABLE_MESSAGE_PATTERNS = [+ 'api key',+ 'billing',+ 'capacity',+ 'deploymentnotfound',+ 'forbidden',+ 'insufficient quota',+ 'invalid api key',+ 'invalidapikey',+ 'invalidproviderapikey',+ 'model not found',+ 'overloaded',+ 'permission denied',+ 'quota',+ 'rate limit',+ 'temporarily unavailable',+ 'timeout',+ 'timed out',+ 'too many requests',+ 'unauthorized',+];++const NON_RETRYABLE_MESSAGE_PATTERNS = [+ 'context length exceeded',+ 'context_length_exceeded',+ 'expected a string',+ 'input is too long',+ 'input tokens exceed',+ 'invalid input',+ 'invalid request',+ 'invalid schema',+ 'invalid schema for response_format',+ 'invalid type for',+ 'maximum allowed number of input tokens',+ 'maximum context length',+ 'maximum input length',+ 'messages with role',+ 'missing required parameter',+ 'prompt is too long',+ 'request too large for model',+ 'response_format',+ 'schema validation error',+ 'string_above_max_length',+ 'tool_choice',+ 'tool_calls',+ 'too many input tokens',+ 'unsupported parameter',+ 'unrecognized request argument',+];++const toRecord = (value: unknown): Record<string, unknown> | undefined =>+ value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;++const collectErrorStrings = (+ value: unknown,+ visited = new WeakSet<object>(),+ depth = 0,+): string[] => {+ if (depth > 4 || value === undefined || value === null) return [];+ if (typeof value === 'string') return [value];+ if (typeof value === 'number' || typeof value === 'boolean') return [String(value)];++ if (value instanceof Error) {+ return [+ value.name,+ value.message,+ ...collectErrorStrings(value.cause, visited, depth + 1),+ ].filter(Boolean);+ }++ const objectValue = toRecord(value);+ if (!objectValue) return [];+ if (visited.has(objectValue)) return [];+ visited.add(objectValue);++ const result: string[] = [];+ for (const [key, nestedValue] of Object.entries(objectValue)) {+ if (key === 'stack' || key === 'headers') continue;+ result.push(...collectErrorStrings(nestedValue, visited, depth + 1));+ }++ return result;+};++const collectStatusCodes = (+ value: unknown,+ visited = new WeakSet<object>(),+ depth = 0,+): number[] => {+ if (depth > 4 || value === undefined || value === null) return [];+ const objectValue = toRecord(value);+ if (!objectValue) return [];+ if (visited.has(objectValue)) return [];+ visited.add(objectValue);++ const result: number[] = [];+ for (const [key, nestedValue] of Object.entries(objectValue)) {+ const normalizedKey = key.toLowerCase();+ if (+ (normalizedKey === 'status' ||+ normalizedKey === 'statuscode' ||+ normalizedKey === 'httpstatuscode') &&+ typeof nestedValue === 'number'+ ) {+ result.push(nestedValue);+ continue;+ }++ result.push(...collectStatusCodes(nestedValue, visited, depth + 1));+ }++ return result;+};++export const isNonRetryableRequestError = (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 (normalizedStrings.some((value) => RETRYABLE_ERROR_CODES.has(value))) return false;+ if (normalizedStrings.some((value) => NON_RETRYABLE_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;++ const statusCodes = collectStatusCodes(error);+ if (statusCodes.some((statusCode) => RETRYABLE_STATUS_CODES.has(statusCode))) return false;++ return false;+};