Skip to content

๐Ÿคฏ 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.

๐Ÿ› fix: classify oversized model requests (#19568)

YuTengjing81dd84cebb35
diff --git a/locales/en-US/modelRuntime.json b/locales/en-US/modelRuntime.json
index 7261621c290..1995977780a 100644
--- a/locales/en-US/modelRuntime.json
+++ b/locales/en-US/modelRuntime.json
@@ -38,6 +38,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.",
+ "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.",
"StreamChunkError": "Error parsing the message chunk of the streaming request. Please check if the current API interface complies with the standard specifications, or contact your API provider for assistance.",
diff --git a/locales/zh-CN/modelRuntime.json b/locales/zh-CN/modelRuntime.json
index 0cbb22f1e1f..83b630ddd1c 100644
--- a/locales/zh-CN/modelRuntime.json
+++ b/locales/zh-CN/modelRuntime.json
@@ -38,6 +38,7 @@
"ProviderServiceUnavailable": "ๆไพ›ๅ•†ๆš‚ๆ—ถ่ฟ‡่ฝฝๆˆ–ไธๅฏ็”จใ€‚่ฏท็จๅŽ้‡่ฏ•ใ€‚",
"QuotaLimitReached": "ๆŠฑๆญ‰๏ผŒๆญคๅฏ†้’ฅ็š„ไปค็‰Œไฝฟ็”จ้‡ๆˆ–่ฏทๆฑ‚ๆฌกๆ•ฐๅทฒ่พพๅˆฐ้…้ข้™ๅˆถใ€‚่ฏทๅขžๅŠ ๅฏ†้’ฅ้…้ขๆˆ–็จๅŽ้‡่ฏ•ใ€‚",
"RateLimitExceeded": "ๆŠฑๆญ‰๏ผŒๆญคๅฏ†้’ฅ็š„ไปค็‰Œไฝฟ็”จ้‡ๆˆ–่ฏทๆฑ‚ๆฌกๆ•ฐๅทฒ่พพๅˆฐ้€Ÿ็އ้™ๅˆถใ€‚่ฏท็จๅŽ้‡่ฏ•ๆˆ–ๅขžๅŠ ๅฏ†้’ฅ้…้ขใ€‚",
+ "RequestBodyTooLarge": "่ฟ™ๆฌก่ฏทๆฑ‚่ถ…่ฟ‡ๆจกๅž‹ๆไพ›ๅ•†ๅ…่ฎธ็š„ๅคงๅฐใ€‚่ฏทๅŽ‹็ผฉๅฏน่ฏๆˆ–ๅ‡ๅฐ‘้™„ๅŠ ๅ†…ๅฎนๅŽ้‡่ฏ•ใ€‚",
"StateStorePersistError": "ๅฏน่ฏ็Šถๆ€ๅญ˜ๅ‚จ็š„ไธดๆ—ถ้—ฎ้ข˜ไธญๆ–ญไบ†ๆญคๆ“ไฝœใ€‚่ฏท้‡่ฏ•๏ผ›ๅฆ‚ๆžœ้—ฎ้ข˜ไป็„ถๅญ˜ๅœจ๏ผŒ่ฏท่”็ณปๆ”ฏๆŒใ€‚",
"StateStoreReadError": "ๆญคๆ“ไฝœๆ— ๆณ•็ปง็ปญ๏ผŒๅ› ไธบไผš่ฏ็Šถๆ€ไธๅฏ็”จใ€‚่ฏท้‡ๆ–ฐๆ‰“ๅผ€ๅฏน่ฏไปฅ็ปง็ปญ๏ผ›ๅฆ‚ๆžœ้—ฎ้ข˜ไป็„ถๅญ˜ๅœจ๏ผŒ่ฏท่”็ณปๆ”ฏๆŒไบบๅ‘˜ใ€‚",
"StreamChunkError": "่งฃๆžๆตๅผ่ฏทๆฑ‚็š„ๆถˆๆฏๅ—ๆ—ถๅ‘็”Ÿ้”™่ฏฏใ€‚่ฏทๆฃ€ๆŸฅๅฝ“ๅ‰APIๆŽฅๅฃๆ˜ฏๅฆ็ฌฆๅˆๆ ‡ๅ‡†่ง„่Œƒ๏ผŒๆˆ–่”็ณปๆ‚จ็š„APIๆไพ›ๅ•†ไปฅ่Žทๅ–ๅธฎๅŠฉใ€‚",
diff --git a/packages/locales/src/default/modelRuntime.ts b/packages/locales/src/default/modelRuntime.ts
index 78fb72e7e4d..d61409ad90c 100644
--- a/packages/locales/src/default/modelRuntime.ts
+++ b/packages/locales/src/default/modelRuntime.ts
@@ -75,6 +75,8 @@ export default {
"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.",
+ 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:
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
index 0a19b89c094..985db8e380c 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
@@ -4,7 +4,9 @@ import { AgentRuntimeErrorType } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
+import { ContextExceededPreFlightError } from '../../utils/resolveSafeMaxTokens';
import {
+ createAnthropicCompatibleParams,
createAnthropicCompatibleRuntime,
createDefaultAnthropicClient,
DEFAULT_ANTHROPIC_TIMEOUT,
@@ -146,6 +148,17 @@ describe('createDefaultAnthropicClient', () => {
});
describe('handleDefaultAnthropicError', () => {
+ it('classifies upstream 413 as an oversized request body', () => {
+ expect(
+ handleDefaultAnthropicError(
+ { message: 'Failed to buffer the request body: length limit exceeded', status: 413 },
+ { apiKey: 'test-key', baseURL: 'https://api.example.com/anthropic' },
+ ),
+ ).toMatchObject({
+ errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
+ });
+ });
+
it('should classify provider balance errors as insufficient quota', () => {
expect(
handleDefaultAnthropicError(
@@ -173,6 +186,84 @@ describe('handleDefaultAnthropicError', () => {
});
describe('createAnthropicCompatibleRuntime', () => {
+ it('returns a structured context error before dispatch when payload pre-flight fails', async () => {
+ const messagesCreate = vi.fn();
+ const Runtime = createAnthropicCompatibleRuntime({
+ chatCompletion: {
+ handlePayload: () => {
+ throw new ContextExceededPreFlightError({
+ ctx: 1_048_576,
+ minOutputTokens: 1024,
+ model: 'deepseek-v4-flash',
+ promptTokens: 1_200_000,
+ });
+ },
+ },
+ customClient: {
+ createClient: () => ({ messages: { create: messagesCreate } }) as unknown as Anthropic,
+ },
+ provider: 'deepseek',
+ });
+
+ await expect(
+ new Runtime({ apiKey: 'test-key' }).chat({ model: 'deepseek-v4-flash' } as any),
+ ).rejects.toMatchObject({
+ error: {
+ ctx: 1_048_576,
+ promptTokens: 1_200_000,
+ type: 'context_exceeded_pre_flight',
+ },
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ });
+ expect(messagesCreate).not.toHaveBeenCalled();
+ });
+
+ it('classifies an upstream 413 response as an oversized request body', async () => {
+ const messagesCreate = vi.fn().mockRejectedValue({
+ message: '<html>413 Request Entity Too Large</html>',
+ status: 413,
+ });
+ const Runtime = createAnthropicCompatibleRuntime({
+ chatCompletion: {
+ handlePayload: (payload) => ({ max_tokens: 1024, messages: [], model: payload.model }),
+ },
+ customClient: {
+ createClient: () => ({ messages: { create: messagesCreate } }) as unknown as Anthropic,
+ },
+ provider: 'deepseek',
+ });
+
+ await expect(
+ new Runtime({ apiKey: 'test-key' }).chat({ model: 'deepseek-v4-flash' } as any),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.RequestBodyTooLarge });
+ });
+
+ it.each([
+ [401, AgentRuntimeErrorType.InvalidGithubToken],
+ [500, AgentRuntimeErrorType.OllamaBizError],
+ ])('honors error type overrides for a %i response', async (status, expectedErrorType) => {
+ const messagesCreate = vi.fn().mockRejectedValue({ message: 'upstream error', status });
+ const Runtime = createAnthropicCompatibleRuntime(
+ createAnthropicCompatibleParams({
+ chatCompletion: {
+ handlePayload: (payload) => ({ max_tokens: 1024, messages: [], model: payload.model }),
+ },
+ customClient: {
+ createClient: () => ({ messages: { create: messagesCreate } }) as unknown as Anthropic,
+ },
+ errorType: {
+ bizError: AgentRuntimeErrorType.OllamaBizError,
+ invalidAPIKey: AgentRuntimeErrorType.InvalidGithubToken,
+ },
+ provider: 'test-provider',
+ }),
+ );
+
+ await expect(
+ new Runtime({ apiKey: 'test-key' }).chat({ model: 'test-model' } as any),
+ ).rejects.toMatchObject({ errorType: expectedErrorType });
+ });
+
it('should normalize default baseURL before creating a custom client', () => {
const createClient = vi.fn((options) => ({ baseURL: options.baseURL }) as unknown as Anthropic);
const Runtime = createAnthropicCompatibleRuntime({
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index 1f6379a475b..6d131aad10f 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -25,6 +25,7 @@ import { getModelPricing } from '../../utils/getModelPricing';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import { resolveMappedModelId } from '../../utils/modelIdMapping';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
+import { ContextExceededPreFlightError } from '../../utils/resolveSafeMaxTokens';
import { StreamingResponse } from '../../utils/response';
import type { LobeRuntimeAI } from '../BaseAI';
import {
@@ -306,7 +307,12 @@ export const createDefaultAnthropicClient = <T extends Record<string, any> = any
export const handleDefaultAnthropicError = <T extends Record<string, any> = any>(
error: any,
options: ConstructorOptions<T>,
+ errorType?: AnthropicCompatibleFactoryOptions<T>['errorType'],
): Omit<ChatCompletionErrorPayload, 'provider'> => {
+ const ErrorType = {
+ bizError: errorType?.bizError || AgentRuntimeErrorType.ProviderBizError,
+ invalidAPIKey: errorType?.invalidAPIKey || AgentRuntimeErrorType.InvalidProviderAPIKey,
+ };
const baseURL =
typeof options.baseURL === 'string' && options.baseURL
? options.baseURL
@@ -320,7 +326,7 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
return {
endpoint: desensitizedEndpoint,
error: error as any,
- errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ errorType: ErrorType.invalidAPIKey,
};
}
case 403: {
@@ -330,6 +336,13 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
errorType: AgentRuntimeErrorType.LocationNotSupportError,
};
}
+ case 413: {
+ return {
+ endpoint: desensitizedEndpoint,
+ error: error as any,
+ errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
+ };
+ }
default: {
break;
}
@@ -379,7 +392,7 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
return {
endpoint: desensitizedEndpoint,
error: errorResult,
- errorType: AgentRuntimeErrorType.ProviderBizError,
+ errorType: ErrorType.bizError,
message,
};
};
@@ -447,7 +460,6 @@ export const createAnthropicCompatibleParams = <T extends Record<string, any> =
baseURL,
chatCompletion: {
getPricingOptions: resolveDefaultAnthropicPricingOptions,
- handleError: handleDefaultAnthropicError,
handlePayload: buildDefaultAnthropicPayload,
...chatCompletion,
},
@@ -795,90 +807,30 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
desensitizedEndpoint = desensitizeUrl(this.baseURL);
}
- if (chatCompletion?.handleError) {
- const errorResult = chatCompletion.handleError(error, this._options);
- if (errorResult)
- return AgentRuntimeError.chat({
- ...errorResult,
- provider: this.id,
- } as ChatCompletionErrorPayload);
- }
-
- if ('status' in (error as any)) {
- switch ((error as Response).status) {
- case 401: {
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: error as any,
- errorType: ErrorType.invalidAPIKey,
- provider: this.id,
- });
- }
- case 403: {
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: error as any,
- errorType: AgentRuntimeErrorType.LocationNotSupportError,
- provider: this.id,
- });
- }
- default: {
- break;
- }
- }
- }
-
- const { errorResult, message } = handleAnthropicError(error);
-
- const errorMsg = errorResult.message || errorResult.error?.message;
-
- if (ErrorClassifier.isAccountDeactivated(errorMsg)) {
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.AccountDeactivated,
- message,
- provider: this.id,
- });
- }
-
- if (ErrorClassifier.isInsufficientQuota(errorMsg)) {
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.InsufficientQuota,
- message,
- provider: this.id,
- });
- }
-
- if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
+ if (error instanceof ContextExceededPreFlightError) {
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
- error: errorResult,
+ error: error.toPayload(),
errorType: AgentRuntimeErrorType.ExceededContextWindow,
- message,
+ message: error.message,
provider: this.id,
});
}
- if (ErrorClassifier.isRateLimitExceeded(errorMsg)) {
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.QuotaLimitReached,
- message,
- provider: this.id,
- });
+ if (chatCompletion?.handleError) {
+ const errorResult = chatCompletion.handleError(error, this._options);
+ if (errorResult)
+ return AgentRuntimeError.chat({
+ ...errorResult,
+ provider: this.id,
+ } as ChatCompletionErrorPayload);
}
+ const errorResult = handleDefaultAnthropicError(error, this._options, errorType);
return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: ErrorType.bizError,
- message,
+ ...errorResult,
provider: this.id,
- });
+ } as ChatCompletionErrorPayload);
}
};
};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index ddc7587bbe2..d8f6a241d6a 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -1377,6 +1377,29 @@ describe('LobeOpenAICompatibleFactory', () => {
});
});
+ it('should classify an HTML 413 response as RequestBodyTooLarge', async () => {
+ const apiError = new OpenAI.APIError(
+ 413,
+ null as any,
+ 'Failed to buffer request body',
+ new Headers({ 'content-type': 'text/html' }),
+ );
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
+
+ await expect(
+ instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-chat',
+ temperature: 0,
+ }),
+ ).rejects.toMatchObject({
+ error: { status: 413 },
+ errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
+ provider,
+ });
+ });
+
it('should throw AgentRuntimeError with invalidErrorType if no apiKey is provided', async () => {
try {
new LobeMockProvider({});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 173c26a52f4..db8d538c9d0 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -1428,6 +1428,15 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
});
}
+ case 413: {
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: error as any,
+ errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
+ provider: this.id,
+ });
+ }
+
default: {
break;
}
diff --git a/packages/model-runtime/src/errors/match.test.ts b/packages/model-runtime/src/errors/match.test.ts
index cd9d5116ad2..033abbb7b2b 100644
--- a/packages/model-runtime/src/errors/match.test.ts
+++ b/packages/model-runtime/src/errors/match.test.ts
@@ -50,6 +50,20 @@ describe('matchErrorPattern', () => {
);
});
+ it('classifies an HTTP 413 body as RequestBodyTooLarge', () => {
+ expect(matchErrorPattern({ message: '413 Request Entity Too Large' })?.code).toBe(
+ AgentRuntimeErrorType.RequestBodyTooLarge,
+ );
+ });
+
+ it('classifies the observed DeepSeek buffer rejection as RequestBodyTooLarge', () => {
+ expect(
+ matchErrorPattern({
+ message: 'Failed to buffer the request body: length limit exceeded',
+ })?.code,
+ ).toBe(AgentRuntimeErrorType.RequestBodyTooLarge);
+ });
+
it('classifies content moderation', () => {
expect(matchErrorPattern({ message: 'Content Exists Risk' })?.code).toBe(
AgentRuntimeErrorType.ContentModeration,
@@ -436,10 +450,7 @@ describe('matchErrorPattern โ€” gateway user/upstream residues by category', ()
},
{
cases: [
- [
- 'Request body too large for deepseek-r1 model',
- AgentRuntimeErrorType.InvalidRequestFormat,
- ],
+ ['Request body too large for deepseek-r1 model', AgentRuntimeErrorType.RequestBodyTooLarge],
[
'error getting file type: failed to download file from https://example.com/a.png',
AgentRuntimeErrorType.InvalidRequestFormat,
diff --git a/packages/model-runtime/src/errors/patterns.ts b/packages/model-runtime/src/errors/patterns.ts
index fa2d0363126..7195aa887ab 100644
--- a/packages/model-runtime/src/errors/patterns.ts
+++ b/packages/model-runtime/src/errors/patterns.ts
@@ -999,6 +999,23 @@ export const ERROR_PATTERNS: ErrorPattern[] = [
note: 'Alibaba/Qwen content-safety rejection, delivered as a JSON error code.',
},
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // RequestBodyTooLarge โ€” serialized request exceeded an upstream body limit
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ {
+ code: AgentRuntimeErrorType.RequestBodyTooLarge,
+ match: { kind: 'regex', value: /failed to buffer (?:the )?request body/i },
+ note: 'Observed from DeepSeek Anthropic-compatible HTTP 413 responses.',
+ },
+ {
+ code: AgentRuntimeErrorType.RequestBodyTooLarge,
+ match: sub('Request body too large for', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.RequestBodyTooLarge,
+ match: sub('413 Request Entity Too Large', { caseInsensitive: true }),
+ },
+
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// InvalidRequestFormat โ€” provider rejected as malformed
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -1148,7 +1165,6 @@ export const ERROR_PATTERNS: ErrorPattern[] = [
match: sub('function_declarations'),
note: 'custom gemini proxies mangle tool schema; lobehub-native schema bug fixed in #14740',
},
- { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('Request body too large for') },
{
code: AgentRuntimeErrorType.InvalidRequestFormat,
match: sub('error getting file type: failed to download file'),
@@ -1273,7 +1289,6 @@ export const ERROR_PATTERNS: ErrorPattern[] = [
{ code: AgentRuntimeErrorType.UpstreamHttpError, match: sub('400 status code') },
{ code: AgentRuntimeErrorType.UpstreamHttpError, match: sub('403 status code') },
{ code: AgentRuntimeErrorType.UpstreamHttpError, match: sub('404 status code') },
- { code: AgentRuntimeErrorType.UpstreamHttpError, match: sub('413 Request Entity Too Large') },
// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// ProviderBizError โ€” generic upstream wrappers that don't fit elsewhere. The
diff --git a/packages/model-runtime/src/errors/refine.test.ts b/packages/model-runtime/src/errors/refine.test.ts
index 72f4d965c58..d116cbaa8ee 100644
--- a/packages/model-runtime/src/errors/refine.test.ts
+++ b/packages/model-runtime/src/errors/refine.test.ts
@@ -172,6 +172,16 @@ describe('refineErrorCode', () => {
});
describe('HTTP-status fallback (no message match)', () => {
+ it('classifies a structured 413 as RequestBodyTooLarge', () => {
+ expect(
+ refineErrorCode({
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ httpStatus: 413,
+ message: 'opaque HTML response',
+ }),
+ ).toBe(AgentRuntimeErrorType.RequestBodyTooLarge);
+ });
+
it('uses the structured status when the message carries no pattern', () => {
expect(
refineErrorCode({
diff --git a/packages/model-runtime/src/errors/refine.ts b/packages/model-runtime/src/errors/refine.ts
index cf033d93171..8c42d9402bc 100644
--- a/packages/model-runtime/src/errors/refine.ts
+++ b/packages/model-runtime/src/errors/refine.ts
@@ -48,9 +48,10 @@ const STATUS_REFINABLE_CODES = new Set<string>([AgentRuntimeErrorType.ProviderBi
*/
const codeFromHttpStatus = (status: number | undefined): ILobeAgentRuntimeErrorType | undefined => {
if (!status) return undefined;
- // 429 / 402 have unambiguous semantics worth special-casing.
+ // These statuses have unambiguous semantics worth special-casing.
if (status === 429) return AgentRuntimeErrorType.RateLimitExceeded;
if (status === 402) return AgentRuntimeErrorType.InsufficientQuota;
+ if (status === 413) return AgentRuntimeErrorType.RequestBodyTooLarge;
if (status >= 500 && status <= 599) return AgentRuntimeErrorType.ProviderServiceUnavailable;
// Any other client error with no usable message โ†’ the bare-HTTP bucket.
if (status >= 400 && status <= 499) return AgentRuntimeErrorType.UpstreamHttpError;
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
index f7494de9738..d6116aa05e3 100644
--- a/packages/model-runtime/src/errors/specs.ts
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -318,6 +318,17 @@ export const ERROR_CODE_SPECS: SpecMap = {
countAsFailure: false,
description: 'Upstream rejected the request as malformed (bad JSON / schema / parameters).',
},
+ [AgentRuntimeErrorType.RequestBodyTooLarge]: {
+ code: AgentRuntimeErrorType.RequestBodyTooLarge,
+ numericId: 4006,
+ category: 'request',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Upstream rejected the serialized request body as too large.',
+ },
// โ€”โ€” Cloud-only (tier 9) โ€”โ€”
[ChatErrorType.LobeHubModelDeprecated]: {
code: ChatErrorType.LobeHubModelDeprecated,
diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
index c54e2368d86..0d311f8d117 100644
--- a/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.test.ts
@@ -31,6 +31,18 @@ describe('buildDeepSeekAnthropicPayload โ€” completion budget', () => {
).rejects.toBeInstanceOf(ContextExceededPreFlightError);
});
+ it('checks the context window when max_tokens is explicitly supplied', async () => {
+ const huge = 'lorem ipsum dolor '.repeat(560_000);
+
+ await expect(
+ buildDeepSeekAnthropicPayload({
+ max_tokens: 2048,
+ messages: [{ content: huge, role: 'user' }],
+ model: 'deepseek-v4-pro',
+ } as any),
+ ).rejects.toBeInstanceOf(ContextExceededPreFlightError);
+ });
+
// A normal small prompt must still produce a usable payload (no regression /
// no spurious pre-flight throw for the common case).
it('produces a payload with a positive max_tokens for a small prompt', async () => {
diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.ts
index 6545b161493..7101666169d 100644
--- a/packages/model-runtime/src/providers/deepseek/chatPayload.ts
+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.ts
@@ -6,7 +6,7 @@ import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFact
import type { ChatStreamPayload } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { isDeepSeekV4FamilyModel } from '../../utils/modelParse';
-import { resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';
+import { assertContextWithinWindow, resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';
import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
import { deepseekRuntimeModels } from './runtimeModels';
import { sanitizeDeepSeekJsonPayload } from './sanitizePayload';
@@ -128,6 +128,12 @@ export const buildDeepSeekAnthropicPayload = async (
shouldEnableDeepSeekThinking(payload),
);
+ // resolveSafeMaxTokens skips explicit completion budgets, but the input must
+ // still fit the model's context window before the upstream request is sent.
+ if (payload.max_tokens !== undefined) {
+ assertContextWithinWindow({ ...payload, messages: anthropicMessages }, deepseekRuntimeModels);
+ }
+
const resolvedMaxTokens =
payload.max_tokens ??
// Cap the completion budget against the actual input size instead of always
diff --git a/packages/model-runtime/src/utils/errorResponse.test.ts b/packages/model-runtime/src/utils/errorResponse.test.ts
index f58353a3bde..0ad3db70586 100644
--- a/packages/model-runtime/src/utils/errorResponse.test.ts
+++ b/packages/model-runtime/src/utils/errorResponse.test.ts
@@ -42,6 +42,11 @@ describe('createErrorResponse', () => {
expect(response.status).toBe(400);
});
+ it('returns a 400 status for RequestBodyTooLarge error type', () => {
+ const response = createErrorResponse(AgentRuntimeErrorType.RequestBodyTooLarge);
+ expect(response.status).toBe(400);
+ });
+
describe('Provider Biz Error', () => {
it('returns a 471 status for ProviderBizError error type', () => {
const errorType = AgentRuntimeErrorType.ProviderBizError;
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
index ab690fa5977..581a39a691d 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
@@ -16,6 +16,15 @@ describe('isNonRetryableRequestError', () => {
).toBe(true);
});
+ it('does not retry an oversized upstream request body on another channel', () => {
+ expect(
+ isNonRetryableRequestError({
+ error: { message: '<html>413 Request Entity Too Large</html>', status: 413 },
+ errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
+ }),
+ ).toBe(true);
+ });
+
it('returns true for terminal image generation errors', () => {
expect(
isNonRetryableRequestError({
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
index 84361ec7e05..1a31f1968e9 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
@@ -8,6 +8,8 @@ const NON_RETRYABLE_ERROR_TYPES = new Set<string>([
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([
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 1c30cd69a2c..bac6bed171f 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -200,6 +200,8 @@ export const AgentRuntimeErrorType = {
CapabilityNotSupported: 'CapabilityNotSupported',
/** Provider rejected the request as malformed (bad JSON, schema validation, etc.). */
InvalidRequestFormat: 'InvalidRequestFormat',
+ /** Upstream rejected the serialized request body as too large (HTTP 413). */
+ RequestBodyTooLarge: 'RequestBodyTooLarge',
/**
* Upstream proxy / gateway layer failed (openresty, litellm, HTML 5xx,
* Cloudflare 525) โ€” distinct from the provider's own service. Split out of