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.

♻️ refactor(model-runtime): unify error codes into spec + pattern registry (#15262)

Arvin Xuc4b147554b33
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index 765ce5ea93d..93797d04f8a 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -6,6 +6,7 @@ import debug from 'debug';
import type { Pricing } from 'model-bank';
import { shouldDropUnsupportedClaudeAssistantPrefill } from '../../const/models';
+import { ErrorClassifier } from '../../errors';
import type {
ChatCompletionErrorPayload,
ChatMethodOptions,
@@ -20,9 +21,6 @@ import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
import { desensitizeUrl } from '../../utils/desensitizeUrl';
import { getModelPricing } from '../../utils/getModelPricing';
-import { isAccountDeactivatedError } from '../../utils/isAccountDeactivatedError';
-import { isExceededContextWindowError } from '../../utils/isExceededContextWindowError';
-import { isQuotaLimitError } from '../../utils/isQuotaLimitError';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
import { StreamingResponse } from '../../utils/response';
import type { LobeRuntimeAI } from '../BaseAI';
@@ -323,7 +321,7 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
const errorMsg = errorResult.message || errorResult.error?.message;
- if (isAccountDeactivatedError(errorMsg)) {
+ if (ErrorClassifier.isAccountDeactivated(errorMsg)) {
return {
endpoint: desensitizedEndpoint,
error: errorResult,
@@ -332,7 +330,7 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
};
}
- if (isExceededContextWindowError(errorMsg)) {
+ if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
return {
endpoint: desensitizedEndpoint,
error: errorResult,
@@ -341,7 +339,7 @@ export const handleDefaultAnthropicError = <T extends Record<string, any> = any>
};
}
- if (isQuotaLimitError(errorMsg)) {
+ if (ErrorClassifier.isRateLimitExceeded(errorMsg)) {
return {
endpoint: desensitizedEndpoint,
error: errorResult,
@@ -726,7 +724,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
const errorMsg = errorResult.message || errorResult.error?.message;
- if (isAccountDeactivatedError(errorMsg)) {
+ if (ErrorClassifier.isAccountDeactivated(errorMsg)) {
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
error: errorResult,
@@ -736,7 +734,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
});
}
- if (isExceededContextWindowError(errorMsg)) {
+ if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
error: errorResult,
@@ -746,7 +744,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
});
}
- if (isQuotaLimitError(errorMsg)) {
+ if (ErrorClassifier.isRateLimitExceeded(errorMsg)) {
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
error: errorResult,
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index dceb2c021c9..32c080e51fe 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -9,6 +9,7 @@ import OpenAI from 'openai';
import type { Stream } from 'openai/streaming';
import { isGPT5ProResponsesModel, responsesAPIModels } from '../../const/models';
+import { ErrorClassifier } from '../../errors';
import type {
ChatCompletionErrorPayload,
ChatCompletionTool,
@@ -39,10 +40,6 @@ import { desensitizeUrl } from '../../utils/desensitizeUrl';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { getModelPricing } from '../../utils/getModelPricing';
import { handleOpenAIError } from '../../utils/handleOpenAIError';
-import { isAccountDeactivatedError } from '../../utils/isAccountDeactivatedError';
-import { isExceededContextWindowError } from '../../utils/isExceededContextWindowError';
-import { isInsufficientQuotaError } from '../../utils/isInsufficientQuotaError';
-import { isQuotaLimitError } from '../../utils/isQuotaLimitError';
import { postProcessModelList } from '../../utils/postProcessModelList';
import {
assertContextWithinWindow,
@@ -1145,7 +1142,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
const errorMsg = errorResult.error?.message || errorResult.message;
- if (isAccountDeactivatedError(errorMsg)) {
+ if (ErrorClassifier.isAccountDeactivated(errorMsg)) {
log('account deactivated error detected from message');
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
@@ -1156,7 +1153,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
});
}
- if (isInsufficientQuotaError(errorMsg)) {
+ if (ErrorClassifier.isInsufficientQuota(errorMsg)) {
log('insufficient quota error detected from message');
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
@@ -1167,7 +1164,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
});
}
- if (isExceededContextWindowError(errorMsg)) {
+ if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
log('context length exceeded detected from message');
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
@@ -1178,7 +1175,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
});
}
- if (isQuotaLimitError(errorMsg)) {
+ if (ErrorClassifier.isRateLimitExceeded(errorMsg)) {
log('quota limit reached detected from message');
return AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
diff --git a/packages/model-runtime/src/errors/classifier.test.ts b/packages/model-runtime/src/errors/classifier.test.ts
new file mode 100644
index 00000000000..a336e3336cd
--- /dev/null
+++ b/packages/model-runtime/src/errors/classifier.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+
+import { ErrorClassifier } from './classifier';
+
+describe('ErrorClassifier', () => {
+ it('returns false for empty input', () => {
+ expect(ErrorClassifier.isExceededContextWindow(undefined)).toBe(false);
+ expect(ErrorClassifier.isInsufficientQuota('')).toBe(false);
+ expect(ErrorClassifier.isRateLimitExceeded(undefined)).toBe(false);
+ expect(ErrorClassifier.isAccountDeactivated('')).toBe(false);
+ });
+
+ it.each([
+ ["This model's maximum context length is 131072 tokens", true],
+ ['prompt is too long: 231426 tokens > 200000 maximum', true],
+ ['context_length_exceeded', true],
+ ['MAXIMUM CONTEXT LENGTH exceeded', true],
+ ['Invalid API key', false],
+ ['Rate limit exceeded', false],
+ ['Internal server error', false],
+ ])('isExceededContextWindow(%j) → %s', (msg, expected) => {
+ expect(ErrorClassifier.isExceededContextWindow(msg)).toBe(expected);
+ });
+
+ it.each([
+ ['Your account org-X is suspended due to insufficient balance, please recharge', true],
+ ['Insufficient Balance: Your account balance is too low', true],
+ ['Billing hard limit has been reached', true],
+ ['Your account has been deactivated', false],
+ ['Rate limit reached', false],
+ ['Context length exceeded', false],
+ ])('isInsufficientQuota(%j) → %s', (msg, expected) => {
+ expect(ErrorClassifier.isInsufficientQuota(msg)).toBe(expected);
+ });
+
+ it.each([
+ ['Resource exhausted', true],
+ ['rate_limit_exceeded', true],
+ ['Too many requests', true],
+ ['Insufficient balance', false],
+ ['Context length exceeded', false],
+ ])('isRateLimitExceeded(%j) → %s', (msg, expected) => {
+ expect(ErrorClassifier.isRateLimitExceeded(msg)).toBe(expected);
+ });
+
+ it.each([
+ ['Your account has been deactivated, please contact support', true],
+ ['Your account has been suspended due to policy violation', true],
+ // billing-suspension shouldn't fire as account-deactivation
+ ['Your account is suspended due to insufficient balance, please recharge', false],
+ ['Invalid API key', false],
+ ])('isAccountDeactivated(%j) → %s', (msg, expected) => {
+ expect(ErrorClassifier.isAccountDeactivated(msg)).toBe(expected);
+ });
+
+ it('isQuotaLimitReached is a deprecated alias for isRateLimitExceeded', () => {
+ expect(ErrorClassifier.isQuotaLimitReached('Too many requests')).toBe(true);
+ expect(ErrorClassifier.isQuotaLimitReached('Invalid API key')).toBe(false);
+ });
+});
diff --git a/packages/model-runtime/src/errors/classifier.ts b/packages/model-runtime/src/errors/classifier.ts
new file mode 100644
index 00000000000..8c5fadfcf6a
--- /dev/null
+++ b/packages/model-runtime/src/errors/classifier.ts
@@ -0,0 +1,49 @@
+import type { ILobeAgentRuntimeErrorType } from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+import { matchErrorPattern } from './match';
+
+const matches = (message: string | undefined, code: ILobeAgentRuntimeErrorType): boolean => {
+ if (!message) return false;
+ return matchErrorPattern({ message })?.code === code;
+};
+
+/**
+ * Discoverable namespace object that bundles all upstream-message predicates.
+ *
+ * Prefer this over the standalone `is*Error` utilities — they're kept as
+ * `@deprecated` shims for backward compatibility. New code should import from
+ * here:
+ *
+ * ```ts
+ * import { ErrorClassifier } from '@lobechat/model-runtime';
+ * if (ErrorClassifier.isExceededContextWindow(message)) { ... }
+ * ```
+ *
+ * For one-off classification or any code that isn't on this list, drop down
+ * to `matchErrorPattern({ message })?.code` directly — it returns the same
+ * info but with the full code as the discriminator.
+ */
+export const ErrorClassifier = {
+ /** Account-level balance / billing quota exhausted. */
+ isInsufficientQuota: (message?: string): boolean =>
+ matches(message, AgentRuntimeErrorType.InsufficientQuota),
+
+ /** Short-window rate limit (RPM / TPM / concurrency). Transient, retryable. */
+ isRateLimitExceeded: (message?: string): boolean =>
+ matches(message, AgentRuntimeErrorType.RateLimitExceeded),
+
+ /** @deprecated Renamed to `isRateLimitExceeded`. */
+ isQuotaLimitReached: (message?: string): boolean =>
+ matches(message, AgentRuntimeErrorType.RateLimitExceeded),
+
+ /** Prompt + tool payload exceeds the model context window. */
+ isExceededContextWindow: (message?: string): boolean =>
+ matches(message, AgentRuntimeErrorType.ExceededContextWindow),
+
+ /** Provider account suspended or deactivated. */
+ isAccountDeactivated: (message?: string): boolean =>
+ matches(message, AgentRuntimeErrorType.AccountDeactivated),
+};
+
+export type ErrorClassifierType = typeof ErrorClassifier;
diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.ts
new file mode 100644
index 00000000000..de9d1f849e1
--- /dev/null
+++ b/packages/model-runtime/src/errors/index.ts
@@ -0,0 +1,16 @@
+export { ErrorClassifier, type ErrorClassifierType } from './classifier';
+export { isUserSideError, matchErrorPattern, type MatchInput, type MatchResult } from './match';
+export { ERROR_PATTERNS, type ErrorPattern } from './patterns';
+export {
+ ERROR_CODE_SPECS,
+ type ErrorCodeSpec,
+ formatErrorRef,
+ getErrorCodeSpec,
+ parseErrorRef,
+} from './specs';
+export {
+ CATEGORY_NUMERIC_PREFIX,
+ type ErrorAttribution,
+ type ErrorCategory,
+ type ErrorSeverity,
+} from './taxonomy';
diff --git a/packages/model-runtime/src/errors/match.test.ts b/packages/model-runtime/src/errors/match.test.ts
new file mode 100644
index 00000000000..c10269fc27b
--- /dev/null
+++ b/packages/model-runtime/src/errors/match.test.ts
@@ -0,0 +1,162 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { isUserSideError, matchErrorPattern } from './match';
+import { ERROR_CODE_SPECS, formatErrorRef, parseErrorRef } from './specs';
+import { CATEGORY_NUMERIC_PREFIX } from './taxonomy';
+
+describe('matchErrorPattern', () => {
+ it('returns undefined for empty input', () => {
+ expect(matchErrorPattern({})).toBeUndefined();
+ expect(matchErrorPattern({ message: '' })).toBeUndefined();
+ });
+
+ it('matches case-insensitive substring patterns', () => {
+ expect(matchErrorPattern({ message: 'PROMPT IS TOO LONG' })?.code).toBe(
+ AgentRuntimeErrorType.ExceededContextWindow,
+ );
+ });
+
+ it('disambiguates 429-class rate limit from balance-class quota', () => {
+ expect(matchErrorPattern({ message: 'rate_limit_exceeded' })?.code).toBe(
+ AgentRuntimeErrorType.RateLimitExceeded,
+ );
+ expect(matchErrorPattern({ message: 'Insufficient Balance: recharge' })?.code).toBe(
+ AgentRuntimeErrorType.InsufficientQuota,
+ );
+ });
+
+ it('classifies provider 503 overload', () => {
+ expect(matchErrorPattern({ message: 'Our servers are currently overloaded' })?.code).toBe(
+ AgentRuntimeErrorType.ProviderServiceUnavailable,
+ );
+ });
+
+ it('classifies content moderation', () => {
+ expect(matchErrorPattern({ message: 'Content Exists Risk' })?.code).toBe(
+ AgentRuntimeErrorType.ContentModeration,
+ );
+ });
+
+ it('classifies router/no-channel failures separately from biz error', () => {
+ expect(matchErrorPattern({ message: 'No available keys in pool' })?.code).toBe(
+ AgentRuntimeErrorType.NoAvailableChannel,
+ );
+ });
+
+ it('classifies gemini-bridge proxy bugs as InvalidRequestFormat', () => {
+ expect(
+ matchErrorPattern({ message: 'For schema with properties, schema type should be OBJECT' })
+ ?.code,
+ ).toBe(AgentRuntimeErrorType.InvalidRequestFormat);
+ });
+
+ it('returns undefined for genuinely unknown errors', () => {
+ expect(matchErrorPattern({ message: 'something we have never seen before' })).toBeUndefined();
+ });
+});
+
+describe('isUserSideError', () => {
+ it('returns true when errorType has a non-failure spec', () => {
+ expect(isUserSideError(AgentRuntimeErrorType.InvalidProviderAPIKey)).toBe(true);
+ expect(isUserSideError(AgentRuntimeErrorType.RateLimitExceeded)).toBe(true);
+ expect(isUserSideError(AgentRuntimeErrorType.ExceededContextWindow)).toBe(true);
+ });
+
+ it('resolves the deprecated QuotaLimitReached alias to RateLimitExceeded spec', () => {
+ expect(isUserSideError(AgentRuntimeErrorType.QuotaLimitReached)).toBe(true);
+ });
+
+ it('returns false for harness-attributed errors', () => {
+ expect(isUserSideError(AgentRuntimeErrorType.StreamChunkError)).toBe(false);
+ expect(isUserSideError(AgentRuntimeErrorType.OperationInactivityTimeout)).toBe(false);
+ expect(isUserSideError(AgentRuntimeErrorType.AgentRuntimeError)).toBe(false);
+ });
+
+ it('upgrades a misclassified harness errorType via message pattern', () => {
+ // Harness sometimes labels TPM rejections as ExceededContextWindow or 500.
+ // The message pattern wins and rescues the classification.
+ expect(
+ isUserSideError(
+ 'ExceededContextWindow',
+ 'Rate limit reached for organization on tokens per minute (TPM)',
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false when neither type nor message matches', () => {
+ expect(isUserSideError(undefined, 'random unmatchable upstream error')).toBe(false);
+ });
+
+ it('every spec code lookup is symmetric', () => {
+ for (const code of Object.keys(ERROR_CODE_SPECS)) {
+ expect(ERROR_CODE_SPECS[code as keyof typeof ERROR_CODE_SPECS]?.code).toBe(code);
+ }
+ });
+});
+
+describe('numericId contract', () => {
+ const specs = Object.values(ERROR_CODE_SPECS).filter((spec) => spec !== undefined);
+
+ it('every spec has a 4-digit numericId', () => {
+ for (const spec of specs) {
+ expect(spec.numericId).toBeGreaterThanOrEqual(1000);
+ expect(spec.numericId).toBeLessThanOrEqual(9999);
+ }
+ });
+
+ it('numericIds are globally unique', () => {
+ const ids = specs.map((s) => s.numericId);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('leading digit matches category prefix', () => {
+ for (const spec of specs) {
+ const expectedPrefix = CATEGORY_NUMERIC_PREFIX[spec.category];
+ const actualPrefix = Math.floor(spec.numericId / 1000);
+ expect(
+ actualPrefix,
+ `${spec.code} (category=${spec.category}) has numericId ${spec.numericId} — expected prefix ${expectedPrefix}`,
+ ).toBe(expectedPrefix);
+ }
+ });
+
+ it('spec entries appear in source order sorted by numericId', () => {
+ // JS object keys preserve insertion order — this guard prevents future
+ // additions from being wedged into the wrong section.
+ const ids = specs.map((s) => s.numericId);
+ const sortedIds = [...ids].sort((a, b) => a - b);
+ expect(ids).toEqual(sortedIds);
+ });
+});
+
+describe('formatErrorRef / parseErrorRef', () => {
+ it('formats known code as Exxxx', () => {
+ expect(formatErrorRef(AgentRuntimeErrorType.InvalidProviderAPIKey)).toBe('E1001');
+ expect(formatErrorRef(AgentRuntimeErrorType.RateLimitExceeded)).toBe('E3001');
+ expect(formatErrorRef(AgentRuntimeErrorType.OperationInactivityTimeout)).toBe('E7002');
+ });
+
+ it('resolves the deprecated QuotaLimitReached alias via the spec', () => {
+ expect(formatErrorRef(AgentRuntimeErrorType.QuotaLimitReached)).toBe('E3001');
+ });
+
+ it('returns undefined for unknown / empty code', () => {
+ expect(formatErrorRef(undefined)).toBeUndefined();
+ expect(formatErrorRef('NotARealCode')).toBeUndefined();
+ });
+
+ it('parseErrorRef inverts formatErrorRef', () => {
+ expect(parseErrorRef('E1001')).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ expect(parseErrorRef('E3001')).toBe(AgentRuntimeErrorType.RateLimitExceeded);
+ });
+
+ it('parseErrorRef rejects malformed input', () => {
+ expect(parseErrorRef(undefined)).toBeUndefined();
+ expect(parseErrorRef('')).toBeUndefined();
+ expect(parseErrorRef('1001')).toBeUndefined();
+ expect(parseErrorRef('E10')).toBeUndefined();
+ expect(parseErrorRef('E99999')).toBeUndefined();
+ expect(parseErrorRef('E9999')).toBeUndefined();
+ });
+});
diff --git a/packages/model-runtime/src/errors/match.ts b/packages/model-runtime/src/errors/match.ts
new file mode 100644
index 00000000000..c960c92582c
--- /dev/null
+++ b/packages/model-runtime/src/errors/match.ts
@@ -0,0 +1,81 @@
+import type { ILobeAgentRuntimeErrorType } from '@lobechat/types';
+
+import { ERROR_PATTERNS, type ErrorPattern } from './patterns';
+import { getErrorCodeSpec } from './specs';
+
+export interface MatchInput {
+ errorType?: string;
+ message?: string;
+ provider?: string;
+}
+
+export interface MatchResult {
+ code: ILobeAgentRuntimeErrorType;
+ pattern: ErrorPattern;
+}
+
+const matchOne = (pattern: ErrorPattern, input: MatchInput): boolean => {
+ if (!input.message) return false;
+ if (pattern.errorType && pattern.errorType !== input.errorType) return false;
+ if (pattern.provider) {
+ const providers = Array.isArray(pattern.provider) ? pattern.provider : [pattern.provider];
+ if (!providers.includes(input.provider ?? '')) return false;
+ }
+
+ if (pattern.match.kind === 'substring') {
+ const value = pattern.match.value;
+ if (pattern.match.caseInsensitive) {
+ return input.message.toLowerCase().includes(value.toLowerCase());
+ }
+ return input.message.includes(value);
+ }
+
+ return pattern.match.value.test(input.message);
+};
+
+/**
+ * Walk the pattern registry and return the first matching code, or undefined.
+ *
+ * Order matters: patterns are evaluated top-to-bottom in `ERROR_PATTERNS`.
+ * Provider/errorType scoping should be used when a substring is ambiguous
+ * across providers.
+ */
+export const matchErrorPattern = (input: MatchInput): MatchResult | undefined => {
+ if (!input.message) return undefined;
+ for (const pattern of ERROR_PATTERNS) {
+ if (matchOne(pattern, input)) return { code: pattern.code, pattern };
+ }
+ return undefined;
+};
+
+/**
+ * True when the error originates from the user side and should be excluded
+ * from operational failure metrics.
+ *
+ * The decision is:
+ * 1. If `errorType` is a known code with `countAsFailure: false` in the spec
+ * table, treat as user-side.
+ * 2. Otherwise, try to classify by matching the message against the pattern
+ * registry and look up the resulting code's spec.
+ *
+ * Pattern matching runs whenever a message is present, regardless of
+ * `errorType`. The harness sometimes misclassifies (e.g. TPM as
+ * ExceededContextWindow, network drops as 500), so the message-pattern step
+ * is the gating mechanism — a substring hit overrides the upstream label.
+ */
+export const isUserSideError = (errorType?: string, message?: string): boolean => {
+ if (errorType) {
+ const spec = getErrorCodeSpec(errorType);
+ if (spec && !spec.countAsFailure) return true;
+ }
+
+ if (message) {
+ const match = matchErrorPattern({ errorType, message });
+ if (match) {
+ const spec = getErrorCodeSpec(match.code);
+ if (spec && !spec.countAsFailure) return true;
+ }
+ }
+
+ return false;
+};
diff --git a/packages/model-runtime/src/errors/patterns.ts b/packages/model-runtime/src/errors/patterns.ts
new file mode 100644
index 00000000000..e671b2140ac
--- /dev/null
+++ b/packages/model-runtime/src/errors/patterns.ts
@@ -0,0 +1,938 @@
+import type { ILobeAgentRuntimeErrorType } from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+/**
+ * One entry in the pattern registry.
+ *
+ * Patterns are matched against the upstream error message via either substring
+ * inclusion or regex test. Substring matching is the default and preferred form
+ * because it's cheap, debuggable, and resilient to whitespace.
+ *
+ * A pattern can be scoped to a specific `provider` or upstream `errorType` when
+ * the same substring could otherwise produce false positives across providers.
+ */
+export interface ErrorPattern {
+ /** Code produced when this pattern matches. */
+ code: ILobeAgentRuntimeErrorType;
+
+ /** Optional upstream errorType scope. When set, only matches errors carrying that errorType. */
+ errorType?: string;
+
+ /** Match rule. */
+ match:
+ | { kind: 'substring'; value: string; caseInsensitive?: boolean }
+ | { kind: 'regex'; value: RegExp };
+
+ /** Short note on origin / why the pattern is here. */
+ note?: string;
+
+ /** Optional provider scope (single key or list). When set, only matches errors from that provider. */
+ provider?: string | string[];
+}
+
+const sub = (value: string, opts?: { caseInsensitive?: boolean }): ErrorPattern['match'] => ({
+ kind: 'substring',
+ value,
+ caseInsensitive: opts?.caseInsensitive,
+});
+
+/**
+ * Source of truth for upstream-message-driven error classification.
+ *
+ * Layout: one section per `AgentRuntimeErrorType`. Within a section, patterns
+ * are roughly grouped by provider. Adding a new pattern is a one-line addition.
+ *
+ * Provenance: most entries are harvested from the agent-gateway production
+ * dashboard plus the previous `isXxxError.ts` utilities under
+ * `packages/model-runtime/src/utils/`.
+ */
+export const ERROR_PATTERNS: ErrorPattern[] = [
+ // ─────────────────────────────────────────────────────────────────────────
+ // ExceededContextWindow
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('maximum context length', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('context length exceeded', { caseInsensitive: true }),
+ },
+ { code: AgentRuntimeErrorType.ExceededContextWindow, match: sub('context_length_exceeded') },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('context window exceeds', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('exceeds the context window', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('prompt is too long', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('input is too long', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('input tokens exceed the configured limit', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('too many input tokens', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('exceeds the maximum number of tokens', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('maximum allowed number of input tokens', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('request too large for model', { caseInsensitive: true }),
+ },
+ { code: AgentRuntimeErrorType.ExceededContextWindow, match: sub('exceeded max context length') },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('Range of input length should be'),
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('CONTENT_LENGTH_EXCEEDS_THRESHOLD'),
+ note: 'kiro/claude-* via openai-compat proxy',
+ },
+ {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ match: sub('content exceeds maximum length of 100KB'),
+ },
+ { code: AgentRuntimeErrorType.ExceededContextWindow, match: sub('免费API限制模型输入token小于') },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // InsufficientQuota — account balance / billing exhausted (long-term)
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('insufficient balance', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('insufficient quota', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('account is suspended due to insufficient balance', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('balance is not enough', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('billing hard limit has been reached', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('exceeded your current quota', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('account overdue', { caseInsensitive: true }),
+ },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('please check your unpaid order') },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('Insufficient credits') },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('This request requires more credits'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('The free tier of the model has been exhausted'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Free credits temporarily have restricted access'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('The free period of this model ended'),
+ },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('user quota is not enough') },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('a subscription is required for access'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('this model requires a subscription'),
+ note: 'Ollama cloud paid-only model',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('does not have a valid coding plan subscription'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Third-party apps now draw from your extra usage'),
+ },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('余额不足或无可用资源包') },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('用户额度不足') },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('预扣费额度失败') },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('请检查 API Key 余额是否充足') },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('You exceeded your current quota, please check your plan'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('You exceeded your current token quota'),
+ note: 'Moonshot / kimi per-token quota',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub("You've reached your usage limit for this period"),
+ note: 'Kimi coding plan usage cap',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('depleted your monthly included credits'),
+ note: 'HuggingFace via newapi',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('reached your session usage limit, upgrade for higher limits'),
+ note: 'Ollama cloud per-session cap',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('This model is not available on your current plan'),
+ note: 'Pawan.krd plan gating',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('please make sure your account is in good standing'),
+ note: 'Aliyun Bailian overdue',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('your current token plan not support model'),
+ note: 'MiniMax coding plan',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Monthly request limit exceeded'),
+ note: 'LM Studio cloud monthly quota',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Your credit balance is too low to access the Anthropic API'),
+ },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('quota exhausted') },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Insufficient quota, please purchase a package or open the [overuse-switch]'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Access restricted. Deposit required to unlock premium models'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('You have exceeded the 5-hour usage quota'),
+ note: 'Volcengine coding plan rolling quota',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Insufficient account balance'),
+ note: 'xiaomimimo zero balance',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('达到使用量上限'),
+ note: 'longcat AppId usage cap',
+ },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('Token 额度不足') },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('usage limit exceeded (2056)'),
+ note: 'MiniMax coding plan token-plan cap',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Sorry, you have reached the limit of the free model quota'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('has reached the set inference limit'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('chat pre-consumed quota failed, user quota:'),
+ note: 'newapi-style proxy',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('token quota is not enough, token remain quota:'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub("exceeded today's quota for model"),
+ note: 'ModelScope daily quota',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('glm depleted for the current 5-hour window'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('data error, now time is smaller than order time'),
+ note: 'qwen subscription expired',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub(
+ 'Please check if your API Key balance is sufficient, or if you are using an unverified API Key',
+ ),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Prompt tokens limit exceeded:'),
+ note: 'OpenRouter monthly key limit',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Exceeded soft user limit per query:'),
+ note: 'OpenRouter / vsegpt per-query ceiling',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Key limit exceeded (monthly limit)'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Potentially out of budget'),
+ note: 'vsegpt budget rejection',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Credit required. To prevent abuse'),
+ note: 'zenmux positive-balance gate',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('has not been priced by the administrator'),
+ },
+ { code: AgentRuntimeErrorType.InsufficientQuota, match: sub('的价格尚未由管理员配置') },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('This IP address is already associated with another free account'),
+ note: 'OpenAI free-account IP ban',
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('your account balance is insufficient, please recharge'),
+ },
+ {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ match: sub('Your account requires verification before using the API'),
+ note: 'freemodel.dev phone verification',
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // RateLimitExceeded — short-window rate limit (transient, retryable)
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('resource exhausted', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('resource has been exhausted', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('rate limit reached', { caseInsensitive: true }),
+ },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('rate_limit_exceeded') },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('quota exceeded', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('too many requests', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('too many tokens', { caseInsensitive: true }),
+ },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('429 status code') },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('Concurrency limit exceeded') },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('reached organization TPD rate limit'),
+ },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub("exceed your organization's rate limit"),
+ },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('tokens per minute (TPM)') },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('Rate limit exceeded: free-models-'),
+ },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('Rate limit exceeded: limit_rpm/') },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('Key limit exceeded (weekly limit)'),
+ },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('BYOK access to') },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('您的账户已达到速率限制') },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('AppChatReverse: Chat failed, 429') },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('Your plan allows 1 concurrent request'),
+ },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('并发请求已达上限') },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('TPM limit reached') },
+ { code: AgentRuntimeErrorType.RateLimitExceeded, match: sub('您已达到默认总请求数限制') },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('concurrency limit exceeded; wait for an active request to finish'),
+ },
+ {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ match: sub('Request rate increased too quickly'),
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // ProviderServiceUnavailable — 503 / overload (transient)
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('Service temporarily unavailable'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('Upstream service temporarily unavailable'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('This model is currently experiencing high demand'),
+ },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('服务暂时不可用') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('所有供应商暂时不可用') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('当前分组上游负载已饱和') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('当前服务集群负载较高') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('该模型当前访问量过大') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('当前为整点高峰时段') },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('System is too busy now. Please try again later.'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('are cooling down via provider'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('The service may be temporarily overloaded, please try again later'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('All credentials for model'),
+ },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('没有可用的内网节点') },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('<title>503 Service Temporarily Unavailable</title>'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('<title>502 Bad Gateway</title>'),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('503 status code (no body)'),
+ },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('526 <!DOCTYPE html>') },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('Our servers are currently overloaded'),
+ },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('system cpu overloaded') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('system disk overloaded') },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('unknown error in the model inference server'),
+ note: 'ppio opaque inference error',
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ match: sub('已被所有启用端点禁用'),
+ note: 'lconai model disabled on every endpoint',
+ },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('502 status code') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('502: Bad gateway') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('502 <!DOCTYPE html>') },
+ { code: AgentRuntimeErrorType.ProviderServiceUnavailable, match: sub('503 Gateway Error') },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // ProviderNetworkError — connection / timeout
+ // ─────────────────────────────────────────────────────────────────────────
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('ETIMEDOUT') },
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('Request timed out') },
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('request to http://') },
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('request to https://') },
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('self-signed certificate') },
+ {
+ code: AgentRuntimeErrorType.ProviderNetworkError,
+ match: sub('Command aborted due to connection close'),
+ },
+ { code: AgentRuntimeErrorType.ProviderNetworkError, match: sub('Network connection lost') },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // NoAvailableChannel — router / proxy has no upstream
+ // ─────────────────────────────────────────────────────────────────────────
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('No available accounts') },
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('No endpoints found') },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('No allowed providers are available'),
+ },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('No endpoints available matching your guardrail'),
+ },
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('no available channels for model') },
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('No available channel for model') },
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('无可用渠道') },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('All upstream channels are currently unavailable'),
+ },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('No accounts in current group support model'),
+ },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('No available keys in pool'),
+ note: 'newapi key pool exhausted',
+ },
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('no_valid_channel_error') },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('The channel selected by channel affinity has been disabled'),
+ },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('ratio or price is not configured'),
+ },
+ { code: AgentRuntimeErrorType.NoAvailableChannel, match: sub('倍率或价格未配置') },
+ {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ match: sub('upstream rejected the request payload'),
+ note: 'freethe routing short-circuit',
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // ModelNotFound
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.ModelNotFound,
+ match: sub('does not exist or you do not have access to it'),
+ },
+ { code: AgentRuntimeErrorType.ModelNotFound, match: sub('does not exist') },
+ {
+ code: AgentRuntimeErrorType.ModelNotFound,
+ match: sub('Model not found, inaccessible, and/or not deployed'),
+ },
+ { code: AgentRuntimeErrorType.ModelNotFound, match: sub('The requested model is not supported') },
+ { code: AgentRuntimeErrorType.ModelNotFound, match: sub('已下线,请切换到') },
+ {
+ code: AgentRuntimeErrorType.ModelNotFound,
+ match: sub('Not found the model'),
+ note: 'moonshot',
+ },
+ {
+ code: AgentRuntimeErrorType.ModelNotFound,
+ match: sub('is no longer available as a free model'),
+ },
+ { code: AgentRuntimeErrorType.ModelNotFound, match: sub('is not a valid model ID') },
+ {
+ code: AgentRuntimeErrorType.ModelNotFound,
+ match: sub('reached its end of life on'),
+ note: 'newapi-style 410 Gone',
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // InvalidProviderAPIKey
+ // ─────────────────────────────────────────────────────────────────────────
+ { code: AgentRuntimeErrorType.InvalidProviderAPIKey, match: sub('Invalid token (request id:') },
+ { code: AgentRuntimeErrorType.InvalidProviderAPIKey, match: sub('您多次使用无效令牌') },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('You have used invalid tokens multiple times, please wait'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('auth_unavailable: no auth available'),
+ note: 'cliproxyapi credential removed',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('API key was reported as leaked'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('API key expired. Please renew the API key'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('API Key not found. Please pass a valid API key'),
+ },
+ { code: AgentRuntimeErrorType.InvalidProviderAPIKey, match: sub('this key is not enabled') },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('invalid_api_key', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ match: sub('invalidapikey', { caseInsensitive: true }),
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // InvalidGithubToken / InvalidGithubCopilotToken
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.InvalidGithubToken,
+ match: sub('Invalid GitHub Personal Access Token'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidGithubCopilotToken,
+ match: sub('No GitHub Copilot subscription or access denied'),
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // InvalidBedrockCredentials
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.InvalidBedrockCredentials,
+ match: sub('The request signature we calculated does not match'),
+ note: 'AWS SigV4 mismatch',
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // PermissionDenied
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.PermissionDenied,
+ match: sub('Your project has been denied access'),
+ },
+ { code: AgentRuntimeErrorType.PermissionDenied, match: sub('This token has no access to model') },
+ { code: AgentRuntimeErrorType.PermissionDenied, match: sub('该令牌无权访问模型') },
+ { code: AgentRuntimeErrorType.PermissionDenied, match: sub('您的 IP 不在令牌允许访问的列表中') },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // AccountDeactivated
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.AccountDeactivated,
+ match: sub('account has been deactivated', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.AccountDeactivated,
+ match: sub('account has been suspended', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.AccountDeactivated,
+ match: sub('account has been disabled', { caseInsensitive: true }),
+ },
+ {
+ code: AgentRuntimeErrorType.AccountDeactivated,
+ match: sub('account is disabled', { caseInsensitive: true }),
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // CapabilityNotSupported
+ // ─────────────────────────────────────────────────────────────────────────
+ { code: AgentRuntimeErrorType.CapabilityNotSupported, match: sub('not implemented') },
+ { code: AgentRuntimeErrorType.CapabilityNotSupported, match: sub('The model is not a VLM') },
+ { code: AgentRuntimeErrorType.CapabilityNotSupported, match: sub('is not a multimodal model') },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('Function call is not supported for this model'),
+ },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('`tool calling` is not supported with this model'),
+ },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('This model does not support assistant message prefill'),
+ },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('Tools are only supported on chat models'),
+ },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('Only google search tool and maps imagery grounding tool is supported'),
+ },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('--enable-auto-tool-choice and --tool-call-parser to be set'),
+ note: 'self-hosted vLLM missing tool-call flags',
+ },
+ {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ match: sub('does not support tool calling.'),
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // ContentModeration
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('violation of provider Terms Of Service'),
+ },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('Content violates usage guidelines'),
+ },
+ { code: AgentRuntimeErrorType.ContentModeration, match: sub('Attention Required! | Cloudflare') },
+ { code: AgentRuntimeErrorType.ContentModeration, match: sub('Sorry, you have been blocked') },
+ { code: AgentRuntimeErrorType.ContentModeration, match: sub('抱歉,您所输入的内容含有违规信息') },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('Content Exists Risk'),
+ note: 'DeepSeek',
+ },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('Input data may contain inappropriate content'),
+ },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('Your request contains prohibited content'),
+ note: 'Anthropic',
+ },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('DataInspectionFailed: Input text data may contain inappropriate content'),
+ note: 'Aliyun',
+ },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('This content was flagged for possible cybersecurity risk'),
+ note: 'OpenAI Trusted Access',
+ },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('output new_sensitive (1027)'),
+ note: 'MiniMax',
+ },
+ { code: AgentRuntimeErrorType.ContentModeration, match: sub('sensitive_words_detected') },
+ {
+ code: AgentRuntimeErrorType.ContentModeration,
+ match: sub('Output data may contain inappropriate content'),
+ note: 'sensenova output-side',
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // InvalidRequestFormat — provider rejected as malformed
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('text content blocks must be non-empty'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub("'tools' : maximum number of items"),
+ },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('无效的请求') },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('未正常接收到prompt参数') },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('image URLs are not currently supported'),
+ note: 'Ollama cloud requires base64',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('Expecting property name enclosed in double quotes'),
+ },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('Expecting value:') },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub("Expecting ',' delimiter:") },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('Unterminated string starting at'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('Expected string, received null'),
+ note: 'Zod: model returned null in tool call',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('parameter of the code model must be in JSON format'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub("Invalid value: ''. Supported values are: 'apply_patch_call'"),
+ note: 'non-spec-compliant openai-compat proxy',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub("'/required': got null, want array"),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('Last message must be from user'),
+ note: 'Jina embeddings chat-format mismatch',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('function call turn comes immediately after a user turn'),
+ note: 'Gemini tool-call ordering',
+ },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('Invalid image URL: ') },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('model should be in provider/model format'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('AiError: AiError: Invalid input'),
+ note: 'Cloudflare AI Workers opaque validation',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('Unsupported parameter: safety_identifier'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('(type=extra_forbidden)'),
+ note: 'strict pydantic proxies reject extra fields',
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('invalid function arguments json string'),
+ note: 'MiniMax 2013',
+ },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('fail to decode image config') },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('图片输入格式/解析错误') },
+ // Gemini schema bridge bugs from third-party openai-compat proxies that forward
+ // `parameters` without converting JSON Schema → Google Schema. Upstream proxy
+ // bugs, not harness bugs.
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('For schema with properties, schema type should be OBJECT'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('specified incorrect schema type field'),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub("didn't specify the schema type field"),
+ },
+ {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ match: sub('Proto field is not repeating, cannot start list'),
+ },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub('Unknown name "definitions"') },
+ { code: AgentRuntimeErrorType.InvalidRequestFormat, match: sub("function_response.response' (") },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // UserConfigError
+ // ─────────────────────────────────────────────────────────────────────────
+ {
+ code: AgentRuntimeErrorType.UserConfigError,
+ match: sub('OPENAI_API_VERSION environment variable is missing'),
+ note: 'Azure OpenAI missing api-version',
+ },
+ {
+ code: AgentRuntimeErrorType.UserConfigError,
+ match: sub('All providers have been ignored. To change your default ignored providers'),
+ note: 'OpenRouter privacy settings',
+ },
+ {
+ code: AgentRuntimeErrorType.UserConfigError,
+ match: sub('OpenAI API is only accessible over HTTPS'),
+ },
+ {
+ code: AgentRuntimeErrorType.UserConfigError,
+ match: sub("endpoint 'v1/responses' not provided"),
+ note: 'proxy missing Responses API',
+ },
+ {
+ code: AgentRuntimeErrorType.UserConfigError,
+ match: sub('Invalid URL (POST /v1/v1beta'),
+ note: 'user pasted /v1/ prefix into Gemini config',
+ },
+ {
+ code: AgentRuntimeErrorType.UserConfigError,
+ match: sub('is not allowed for this virtual key'),
+ },
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // ProviderBizError — generic upstream wrappers that don't fit elsewhere
+ // ─────────────────────────────────────────────────────────────────────────
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('Upstream request failed') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('Provider returned error') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('bad_response_status_code') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('bad response status code') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('convert_request_failed') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('failed to parse request') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('upstream error: do request failed') },
+ // Upstream Go gateway re-marshal failure — non-UTF-8 / lone-surrogate bytes
+ // in model tool-call output.
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub('failed to marshal request body to JSON'),
+ },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('Internal Server Error (ref:') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('400 status code') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('403 status code') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('404 status code') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('413 Request Entity Too Large') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('403 <!DOCTYPE html>') },
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub('525 <!DOCTYPE html>'),
+ note: 'Cloudflare 525 SSL handshake',
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub('<center>openresty</center>'),
+ note: 'user-configured proxy returning HTML',
+ },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('litellm.') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('410 status code (no body)') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('402 status code') },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('404 <!DOCTYPE html>') },
+ // Nvidia / nvidia_custom upstream Python crash — "unhashable type" TypeError.
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub("Internal server error: unhashable type: '"),
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub('[upstream:/v1/messages] Upstream returned HTTP'),
+ },
+ { code: AgentRuntimeErrorType.ProviderBizError, match: sub('上游请求参数无效') },
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub('Failed to parse fc related info to json format'),
+ note: 'internlm tool-call parser failure',
+ },
+ {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ match: sub('codewhisperer#ValidationException'),
+ note: 'kiro / AWS CodeWhisperer proxy malformed payload',
+ },
+];
diff --git a/packages/model-runtime/src/errors/specs.ts b/packages/model-runtime/src/errors/specs.ts
new file mode 100644
index 00000000000..f4d1c1c9ab1
--- /dev/null
+++ b/packages/model-runtime/src/errors/specs.ts
@@ -0,0 +1,533 @@
+import type { ILobeAgentRuntimeErrorType } from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+import type { ErrorAttribution, ErrorCategory, ErrorSeverity } from './taxonomy';
+
+export interface ErrorCodeSpec {
+ attribution: ErrorAttribution;
+ category: ErrorCategory;
+ code: ILobeAgentRuntimeErrorType;
+ /** Whether this error counts toward operational failure metrics. */
+ countAsFailure: boolean;
+
+ /** Short English description for dashboards / docs. */
+ description: string;
+ /** HTTP status code returned to the client. */
+ httpStatus: number;
+
+ /**
+ * Stable numeric identifier surfaced as `E<numericId>` (e.g. `E1001`).
+ *
+ * Append-only: once assigned, a (code, numericId) pair must never change so
+ * that external docs / support tickets / SDKs can reference it long-term.
+ * The leading digit must match `CATEGORY_NUMERIC_PREFIX[category]`; the
+ * remaining digits are assigned sequentially within the category bucket.
+ */
+ numericId: number;
+
+ /** Whether transport-level retry is allowed. */
+ retryable: boolean;
+
+ severity: ErrorSeverity;
+}
+
+type SpecMap = Partial<Record<ILobeAgentRuntimeErrorType, ErrorCodeSpec>>;
+
+/**
+ * Single source of truth for every runtime error code.
+ *
+ * To add a new code:
+ * 1. Add it to `AgentRuntimeErrorType` in `@lobechat/types/agentRuntime.ts`.
+ * 2. Add a spec entry here.
+ * 3. Add a locale key `response.<code>` in `src/locales/default/error.ts`.
+ * 4. (If user-side) add upstream message patterns in `./patterns.ts`.
+ */
+export const ERROR_CODE_SPECS: SpecMap = {
+ // ─── 1xxx Auth / Credentials ──────────────────────────────────────────
+ [AgentRuntimeErrorType.InvalidProviderAPIKey]: {
+ code: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ numericId: 1001,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 401,
+ retryable: false,
+ countAsFailure: false,
+ description: 'API key is invalid, revoked, or rejected by the upstream auth.',
+ },
+ [AgentRuntimeErrorType.InvalidGithubToken]: {
+ code: AgentRuntimeErrorType.InvalidGithubToken,
+ numericId: 1002,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 401,
+ retryable: false,
+ countAsFailure: false,
+ description: 'GitHub Personal Access Token is invalid or revoked.',
+ },
+ [AgentRuntimeErrorType.InvalidGithubCopilotToken]: {
+ code: AgentRuntimeErrorType.InvalidGithubCopilotToken,
+ numericId: 1003,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 401,
+ retryable: false,
+ countAsFailure: false,
+ description: 'No active GitHub Copilot subscription or access denied.',
+ },
+ [AgentRuntimeErrorType.InvalidBedrockCredentials]: {
+ code: AgentRuntimeErrorType.InvalidBedrockCredentials,
+ numericId: 1004,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 401,
+ retryable: false,
+ countAsFailure: false,
+ description: 'AWS Bedrock credentials are invalid or signature mismatch.',
+ },
+ [AgentRuntimeErrorType.InvalidVertexCredentials]: {
+ code: AgentRuntimeErrorType.InvalidVertexCredentials,
+ numericId: 1005,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 401,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Google Vertex credentials are invalid or service-account misconfigured.',
+ },
+ [AgentRuntimeErrorType.PermissionDenied]: {
+ code: AgentRuntimeErrorType.PermissionDenied,
+ numericId: 1006,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 403,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Provider denied access (project blocked, model gated, etc.).',
+ },
+ [AgentRuntimeErrorType.AccountDeactivated]: {
+ code: AgentRuntimeErrorType.AccountDeactivated,
+ numericId: 1007,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 403,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Provider account is suspended or deactivated.',
+ },
+ [AgentRuntimeErrorType.LocationNotSupportError]: {
+ code: AgentRuntimeErrorType.LocationNotSupportError,
+ numericId: 1008,
+ category: 'auth',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 403,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Provider unavailable from the caller geographic region.',
+ },
+
+ // ─── 2xxx Quota / Billing ─────────────────────────────────────────────
+ [AgentRuntimeErrorType.InsufficientQuota]: {
+ code: AgentRuntimeErrorType.InsufficientQuota,
+ numericId: 2001,
+ category: 'quota',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 429,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Account balance or billing quota exhausted.',
+ },
+
+ // ─── 3xxx Capacity ────────────────────────────────────────────────────
+ [AgentRuntimeErrorType.RateLimitExceeded]: {
+ code: AgentRuntimeErrorType.RateLimitExceeded,
+ numericId: 3001,
+ category: 'capacity',
+ severity: 'warning',
+ attribution: 'provider',
+ httpStatus: 429,
+ retryable: true,
+ countAsFailure: false,
+ description: 'Short-window rate limit (RPM / TPM / concurrency) reached.',
+ },
+ [AgentRuntimeErrorType.ProviderServiceUnavailable]: {
+ code: AgentRuntimeErrorType.ProviderServiceUnavailable,
+ numericId: 3002,
+ category: 'capacity',
+ severity: 'warning',
+ attribution: 'provider',
+ httpStatus: 503,
+ retryable: true,
+ countAsFailure: false,
+ description: 'Upstream returned 503 / overloaded / temporarily unavailable.',
+ },
+ [AgentRuntimeErrorType.NoAvailableChannel]: {
+ code: AgentRuntimeErrorType.NoAvailableChannel,
+ numericId: 3003,
+ category: 'capacity',
+ severity: 'warning',
+ attribution: 'provider',
+ httpStatus: 503,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Proxy / router has no available channel or key for the model.',
+ },
+ [AgentRuntimeErrorType.OllamaServiceUnavailable]: {
+ code: AgentRuntimeErrorType.OllamaServiceUnavailable,
+ numericId: 3004,
+ category: 'capacity',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Local Ollama service is not reachable.',
+ },
+ [AgentRuntimeErrorType.ComfyUIServiceUnavailable]: {
+ code: AgentRuntimeErrorType.ComfyUIServiceUnavailable,
+ numericId: 3005,
+ category: 'capacity',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Local ComfyUI service is not reachable.',
+ },
+
+ // ─── 4xxx Request / Model ─────────────────────────────────────────────
+ [AgentRuntimeErrorType.ModelNotFound]: {
+ code: AgentRuntimeErrorType.ModelNotFound,
+ numericId: 4001,
+ category: 'request',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 404,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Requested model does not exist or the token has no access to it.',
+ },
+ [AgentRuntimeErrorType.ExceededContextWindow]: {
+ code: AgentRuntimeErrorType.ExceededContextWindow,
+ numericId: 4002,
+ category: 'request',
+ severity: 'info',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Prompt + tool payload exceeds the model context window.',
+ },
+ [AgentRuntimeErrorType.ExceededToolLimit]: {
+ code: AgentRuntimeErrorType.ExceededToolLimit,
+ numericId: 4003,
+ category: 'request',
+ severity: 'info',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Tools array exceeds the configured count or payload limit.',
+ },
+ [AgentRuntimeErrorType.CapabilityNotSupported]: {
+ code: AgentRuntimeErrorType.CapabilityNotSupported,
+ numericId: 4004,
+ category: 'request',
+ severity: 'info',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Model does not support the requested capability (VLM / tool / prefill).',
+ },
+ [AgentRuntimeErrorType.InvalidRequestFormat]: {
+ code: AgentRuntimeErrorType.InvalidRequestFormat,
+ numericId: 4005,
+ category: 'request',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Upstream rejected the request as malformed (bad JSON / schema / parameters).',
+ },
+
+ // ─── 5xxx Safety ──────────────────────────────────────────────────────
+ [AgentRuntimeErrorType.ContentModeration]: {
+ code: AgentRuntimeErrorType.ContentModeration,
+ numericId: 5001,
+ category: 'safety',
+ severity: 'info',
+ attribution: 'user',
+ httpStatus: 451,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Upstream content-safety filter rejected the input or output.',
+ },
+
+ // ─── 6xxx Network ─────────────────────────────────────────────────────
+ [AgentRuntimeErrorType.ProviderNetworkError]: {
+ code: AgentRuntimeErrorType.ProviderNetworkError,
+ numericId: 6001,
+ category: 'network',
+ severity: 'warning',
+ attribution: 'system',
+ httpStatus: 504,
+ retryable: true,
+ countAsFailure: false,
+ description: 'Connection timeout / network drop talking to the provider.',
+ },
+
+ // ─── 7xxx Stream / Runtime ────────────────────────────────────────────
+ [AgentRuntimeErrorType.StreamChunkError]: {
+ code: AgentRuntimeErrorType.StreamChunkError,
+ numericId: 7001,
+ category: 'stream',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 500,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Failed to parse or process a streaming chunk from the provider.',
+ },
+ [AgentRuntimeErrorType.OperationInactivityTimeout]: {
+ code: AgentRuntimeErrorType.OperationInactivityTimeout,
+ numericId: 7002,
+ category: 'stream',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 504,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Gateway watchdog killed an idle agent operation.',
+ },
+ [AgentRuntimeErrorType.ConversationParentMissing]: {
+ code: AgentRuntimeErrorType.ConversationParentMissing,
+ numericId: 7003,
+ category: 'stream',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 500,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Conversation chain broken because an assistant/tool message lost its parent.',
+ },
+
+ // ─── 8xxx Provider (catch-all) ────────────────────────────────────────
+ [AgentRuntimeErrorType.AgentRuntimeError]: {
+ code: AgentRuntimeErrorType.AgentRuntimeError,
+ numericId: 8001,
+ category: 'provider',
+ severity: 'error',
+ attribution: 'harness',
+ httpStatus: 470,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Generic Agent Runtime module error.',
+ },
+ [AgentRuntimeErrorType.ProviderBizError]: {
+ code: AgentRuntimeErrorType.ProviderBizError,
+ numericId: 8002,
+ category: 'provider',
+ severity: 'error',
+ attribution: 'provider',
+ httpStatus: 471,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Generic provider biz error (unclassified upstream failure).',
+ },
+ [AgentRuntimeErrorType.ProviderNoImageGenerated]: {
+ code: AgentRuntimeErrorType.ProviderNoImageGenerated,
+ numericId: 8003,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'provider',
+ httpStatus: 471,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Image-generation provider returned no image.',
+ },
+ [AgentRuntimeErrorType.OllamaBizError]: {
+ code: AgentRuntimeErrorType.OllamaBizError,
+ numericId: 8004,
+ category: 'provider',
+ severity: 'error',
+ attribution: 'provider',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: true,
+ description: 'Ollama returned a biz error.',
+ },
+ [AgentRuntimeErrorType.ComfyUIBizError]: {
+ code: AgentRuntimeErrorType.ComfyUIBizError,
+ numericId: 8005,
+ category: 'provider',
+ severity: 'error',
+ attribution: 'provider',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: true,
+ description: 'ComfyUI returned a biz error.',
+ },
+ [AgentRuntimeErrorType.ComfyUIEmptyResult]: {
+ code: AgentRuntimeErrorType.ComfyUIEmptyResult,
+ numericId: 8006,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'provider',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: true,
+ description: 'ComfyUI workflow ran but produced no output.',
+ },
+ [AgentRuntimeErrorType.ComfyUIUploadFailed]: {
+ code: AgentRuntimeErrorType.ComfyUIUploadFailed,
+ numericId: 8007,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: false,
+ description: 'ComfyUI input upload failed.',
+ },
+ [AgentRuntimeErrorType.ComfyUIWorkflowError]: {
+ code: AgentRuntimeErrorType.ComfyUIWorkflowError,
+ numericId: 8008,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: false,
+ description: 'ComfyUI workflow definition is invalid.',
+ },
+ [AgentRuntimeErrorType.ComfyUIModelError]: {
+ code: AgentRuntimeErrorType.ComfyUIModelError,
+ numericId: 8009,
+ category: 'provider',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 472,
+ retryable: false,
+ countAsFailure: false,
+ description: 'ComfyUI model load / inference failed.',
+ },
+
+ // ─── 9xxx Config ──────────────────────────────────────────────────────
+ [AgentRuntimeErrorType.InvalidOllamaArgs]: {
+ code: AgentRuntimeErrorType.InvalidOllamaArgs,
+ numericId: 9001,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Ollama runtime arguments are invalid.',
+ },
+ [AgentRuntimeErrorType.InvalidComfyUIArgs]: {
+ code: AgentRuntimeErrorType.InvalidComfyUIArgs,
+ numericId: 9002,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'ComfyUI runtime arguments are invalid.',
+ },
+ [AgentRuntimeErrorType.UserConfigError]: {
+ code: AgentRuntimeErrorType.UserConfigError,
+ numericId: 9003,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description:
+ 'User-side misconfiguration (bad base URL, missing env var, virtual-key allowlist).',
+ },
+ [AgentRuntimeErrorType.NoAvailableProvider]: {
+ code: AgentRuntimeErrorType.NoAvailableProvider,
+ numericId: 9004,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'No provider is configured / enabled for the requested model.',
+ },
+ [AgentRuntimeErrorType.ConnectionCheckFailed]: {
+ code: AgentRuntimeErrorType.ConnectionCheckFailed,
+ numericId: 9005,
+ category: 'config',
+ severity: 'warning',
+ attribution: 'user',
+ httpStatus: 400,
+ retryable: false,
+ countAsFailure: false,
+ description: 'Provider connection check failed during setup.',
+ },
+};
+
+/**
+ * Aliases from deprecated string codes to their canonical replacements. Lets
+ * `getErrorCodeSpec('QuotaLimitReached')` still resolve to the spec for
+ * `RateLimitExceeded` so older callers and stored error records keep working.
+ */
+const CODE_ALIASES: Record<string, ILobeAgentRuntimeErrorType> = {
+ [AgentRuntimeErrorType.QuotaLimitReached]: AgentRuntimeErrorType.RateLimitExceeded,
+};
+
+/** Look up the spec for an error code; falls back to `undefined` when unknown. */
+export const getErrorCodeSpec = (
+ code: ILobeAgentRuntimeErrorType | string | undefined,
+): ErrorCodeSpec | undefined => {
+ if (!code) return undefined;
+ const canonical = CODE_ALIASES[code] ?? code;
+ return ERROR_CODE_SPECS[canonical as ILobeAgentRuntimeErrorType];
+};
+
+/**
+ * Format an error code as its stable numeric reference, e.g. `E1001`.
+ * Returns `undefined` for codes that are not in the spec table.
+ *
+ * Use this when surfacing the error in places that need a stable, language-
+ * independent identifier — support tickets, public docs anchors, external SDK
+ * error mapping, etc.
+ */
+export const formatErrorRef = (
+ code: ILobeAgentRuntimeErrorType | string | undefined,
+): string | undefined => {
+ const spec = getErrorCodeSpec(code);
+ if (!spec) return undefined;
+ return `E${spec.numericId}`;
+};
+
+const ERROR_REF_PATTERN = /^E(\d{4})$/;
+
+/**
+ * Inverse of `formatErrorRef`: parse `E1001` back into the matching error
+ * code. Returns `undefined` if the ref doesn't correspond to a known spec.
+ */
+export const parseErrorRef = (ref: string | undefined): ILobeAgentRuntimeErrorType | undefined => {
+ if (!ref) return undefined;
+ const match = ERROR_REF_PATTERN.exec(ref);
+ if (!match) return undefined;
+ const id = Number.parseInt(match[1], 10);
+ for (const spec of Object.values(ERROR_CODE_SPECS)) {
+ if (spec?.numericId === id) return spec.code;
+ }
+ return undefined;
+};
diff --git a/packages/model-runtime/src/errors/taxonomy.ts b/packages/model-runtime/src/errors/taxonomy.ts
new file mode 100644
index 00000000000..0a5d5173e81
--- /dev/null
+++ b/packages/model-runtime/src/errors/taxonomy.ts
@@ -0,0 +1,57 @@
+/**
+ * Error classification taxonomy.
+ *
+ * The taxonomy is orthogonal to the `AgentRuntimeErrorType` code. A code says
+ * *what* the error is; the taxonomy says *how to react to it*.
+ *
+ * Four dimensions:
+ *
+ * - `category` — semantic bucket for dashboard slicing.
+ * - `severity` — log level / alerting hint.
+ * - `attribution` — who owns the fix:
+ * - `user` — user changes their key / prompt / model / subscription and it works.
+ * - `provider`— upstream provider's problem; neither user nor lobehub can fix it directly.
+ * - `harness` — our (lobehub / model-runtime / agent-gateway) bug or shortcoming.
+ * - `system` — infra / network / OS layer.
+ * - `countAsFailure` — whether this error should be counted toward operational
+ * failure metrics. User-side errors are generally false (they're expected).
+ */
+export type ErrorCategory =
+ | 'auth' // credentials, account, permission
+ | 'quota' // balance, billing, plan limits
+ | 'capacity' // rate-limit, overload, no-channel
+ | 'request' // input format, context-window, capability
+ | 'safety' // content moderation
+ | 'network' // timeout, connection
+ | 'stream' // streaming-protocol-level failures
+ | 'provider' // generic provider biz error (catch-all)
+ | 'config'; // user misconfiguration
+
+export type ErrorSeverity = 'info' | 'warning' | 'error' | 'critical';
+
+export type ErrorAttribution = 'user' | 'provider' | 'harness' | 'system';
+
+/**
+ * Mapping of category → leading digit of the `numericId`.
+ *
+ * Used to assign and validate stable numeric error references like `E1001`
+ * (auth) / `E3001` (capacity) / `E8002` (provider). The first digit is the
+ * category bucket; the remaining three digits are assigned sequentially as
+ * codes are added.
+ *
+ * The `numericId` is **append-only**: once published, a (code, id) pair never
+ * changes, even if the string `code` is later renamed. This is the contract
+ * that lets `E1001` show up in support tickets / docs / external SDKs as a
+ * stable reference.
+ */
+export const CATEGORY_NUMERIC_PREFIX: Record<ErrorCategory, number> = {
+ auth: 1,
+ quota: 2,
+ capacity: 3,
+ request: 4,
+ safety: 5,
+ network: 6,
+ stream: 7,
+ provider: 8,
+ config: 9,
+};
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index eb52b6abde4..7227675937d 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -7,6 +7,25 @@ export { ModelRuntime } from './core/ModelRuntime';
export { createOpenAICompatibleRuntime } from './core/openaiCompatibleFactory';
export * from './core/RouterRuntime';
export * from './core/usageConverters';
+export {
+ CATEGORY_NUMERIC_PREFIX,
+ ERROR_CODE_SPECS,
+ ERROR_PATTERNS,
+ type ErrorAttribution,
+ type ErrorCategory,
+ ErrorClassifier,
+ type ErrorClassifierType,
+ type ErrorCodeSpec,
+ type ErrorPattern,
+ type ErrorSeverity,
+ formatErrorRef,
+ getErrorCodeSpec,
+ isUserSideError,
+ matchErrorPattern,
+ type MatchInput,
+ type MatchResult,
+ parseErrorRef,
+} from './errors';
export * from './helpers';
export { LobeAkashChatAI } from './providers/akashchat';
export { LobeAnthropicAI } from './providers/anthropic';
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index f700175be77..ad62af0b6ec 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -24,6 +24,7 @@ import {
AWSBedrockLlamaStream,
createBedrockStream,
} from '../../core/streams';
+import { ErrorClassifier } from '../../errors';
import type {
ChatMethodOptions,
ChatStreamPayload,
@@ -37,7 +38,6 @@ import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
import { getModelPricing } from '../../utils/getModelPricing';
-import { isExceededContextWindowError } from '../../utils/isExceededContextWindowError';
import { StreamingResponse } from '../../utils/response';
import { normalizeClaudeThinkingHistoryMessages } from '../anthropic/claudeThinkingHistory';
@@ -364,7 +364,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {
);
} catch (e) {
const err = e as Error & { $metadata: any };
- const errorType = isExceededContextWindowError(err.message)
+ const errorType = ErrorClassifier.isExceededContextWindow(err.message)
? AgentRuntimeErrorType.ExceededContextWindow
: AgentRuntimeErrorType.ProviderBizError;
diff --git a/packages/model-runtime/src/utils/errorResponse.ts b/packages/model-runtime/src/utils/errorResponse.ts
index 97faa5e676d..d8ae622d178 100644
--- a/packages/model-runtime/src/utils/errorResponse.ts
+++ b/packages/model-runtime/src/utils/errorResponse.ts
@@ -1,52 +1,18 @@
import type { ErrorResponse, ErrorType } from '@lobechat/types';
-import { ChatErrorType } from '@lobechat/types';
+import { getErrorCodeSpec } from '../errors';
import type { ILobeAgentRuntimeErrorType } from '../types';
-import { AgentRuntimeErrorType } from '../types';
const getStatus = (errorType: ILobeAgentRuntimeErrorType | ErrorType) => {
- // InvalidAccessCode / InvalidAzureAPIKey / InvalidOpenAIAPIKey / InvalidZhipuAPIKey ....
- if (errorType.toString().includes('Invalid')) return 401;
-
- switch (errorType) {
- case AgentRuntimeErrorType.InvalidProviderAPIKey: {
- return 401;
- }
-
- case AgentRuntimeErrorType.ExceededContextWindow: {
- return 400;
- }
-
- case AgentRuntimeErrorType.LocationNotSupportError: {
- return 403;
- }
-
- case AgentRuntimeErrorType.ModelNotFound: {
- return 404;
- }
+ // 1. Authoritative source: the unified spec table.
+ const spec = getErrorCodeSpec(errorType as ILobeAgentRuntimeErrorType);
+ if (spec) return spec.httpStatus;
- case AgentRuntimeErrorType.InsufficientQuota:
- case AgentRuntimeErrorType.QuotaLimitReached: {
- return 429;
- }
-
- // define the 471~480 as provider error
- case AgentRuntimeErrorType.AgentRuntimeError: {
- return 470;
- }
-
- case AgentRuntimeErrorType.ProviderBizError: {
- return 471;
- }
-
- // all local provider connection error
- case AgentRuntimeErrorType.OllamaServiceUnavailable:
- case ChatErrorType.OllamaServiceUnavailable:
- case AgentRuntimeErrorType.OllamaBizError: {
- return 472;
- }
- }
+ // 2. Fallback: legacy `Invalid*APIKey` shorthand codes (InvalidAccessCode,
+ // InvalidAzureAPIKey, InvalidOpenAIAPIKey, …) that are still in use.
+ if (errorType.toString().includes('Invalid')) return 401;
+ // 3. Bare numeric ChatErrorType values (BadRequest=400, Unauthorized=401, …).
return errorType as number;
};
diff --git a/packages/model-runtime/src/utils/googleErrorParser.ts b/packages/model-runtime/src/utils/googleErrorParser.ts
index f17a905cefa..429aa673fab 100644
--- a/packages/model-runtime/src/utils/googleErrorParser.ts
+++ b/packages/model-runtime/src/utils/googleErrorParser.ts
@@ -1,7 +1,6 @@
+import { ErrorClassifier } from '../errors';
import type { ILobeAgentRuntimeErrorType } from '../types/error';
import { AgentRuntimeErrorType } from '../types/error';
-import { isExceededContextWindowError } from './isExceededContextWindowError';
-import { isQuotaLimitError } from './isQuotaLimitError';
export interface ParsedError {
error: any;
@@ -116,11 +115,11 @@ export function parseGoogleErrorMessage(message: string): ParsedError {
return { error: { message }, errorType: AgentRuntimeErrorType.ProviderNoImageGenerated };
}
- if (isExceededContextWindowError(message)) {
+ if (ErrorClassifier.isExceededContextWindow(message)) {
return { error: { message }, errorType: AgentRuntimeErrorType.ExceededContextWindow };
}
- if (isQuotaLimitError(message)) {
+ if (ErrorClassifier.isRateLimitExceeded(message)) {
return { error: { message }, errorType: AgentRuntimeErrorType.QuotaLimitReached };
}
diff --git a/packages/model-runtime/src/utils/isAccountDeactivatedError.test.ts b/packages/model-runtime/src/utils/isAccountDeactivatedError.test.ts
deleted file mode 100644
index ab2a2bc0b6d..00000000000
--- a/packages/model-runtime/src/utils/isAccountDeactivatedError.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isAccountDeactivatedError } from './isAccountDeactivatedError';
-
-describe('isAccountDeactivatedError', () => {
- it('should return false for undefined/empty input', () => {
- expect(isAccountDeactivatedError(undefined)).toBe(false);
- expect(isAccountDeactivatedError('')).toBe(false);
- });
-
- it('should detect "account has been deactivated" errors', () => {
- expect(
- isAccountDeactivatedError('Your account has been deactivated, please contact support'),
- ).toBe(true);
- });
-
- it('should detect "account has been suspended" errors', () => {
- expect(
- isAccountDeactivatedError('Your account has been suspended due to policy violation'),
- ).toBe(true);
- });
-
- it('should detect "account has been disabled" errors', () => {
- expect(isAccountDeactivatedError('This account has been disabled')).toBe(true);
- });
-
- it('should detect "account is disabled" errors', () => {
- expect(isAccountDeactivatedError('Your account is disabled')).toBe(true);
- });
-
- it('should be case-insensitive', () => {
- expect(isAccountDeactivatedError('ACCOUNT HAS BEEN DEACTIVATED')).toBe(true);
- expect(isAccountDeactivatedError('Account Has Been Suspended')).toBe(true);
- });
-
- it('should return false for unrelated error messages', () => {
- expect(isAccountDeactivatedError('Insufficient Balance')).toBe(false);
- expect(isAccountDeactivatedError('Invalid API key')).toBe(false);
- expect(isAccountDeactivatedError('Rate limit reached')).toBe(false);
- });
-
- it('should NOT match billing-related account suspensions', () => {
- expect(
- isAccountDeactivatedError(
- 'Your account is suspended due to insufficient balance, please recharge',
- ),
- ).toBe(false);
- });
-});
diff --git a/packages/model-runtime/src/utils/isAccountDeactivatedError.ts b/packages/model-runtime/src/utils/isAccountDeactivatedError.ts
deleted file mode 100644
index ae8c8f1c9c2..00000000000
--- a/packages/model-runtime/src/utils/isAccountDeactivatedError.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-const ACCOUNT_DEACTIVATED_PATTERNS = [
- 'account has been deactivated', // OpenAI
- 'account has been suspended', // generic
- 'account has been disabled', // generic
- 'account is disabled', // generic
-];
-
-export const isAccountDeactivatedError = (message?: string): boolean => {
- if (!message) return false;
- const lower = message.toLowerCase();
- return ACCOUNT_DEACTIVATED_PATTERNS.some((p) => lower.includes(p));
-};
diff --git a/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts b/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts
deleted file mode 100644
index 52a62ffc959..00000000000
--- a/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isExceededContextWindowError } from './isExceededContextWindowError';
-
-describe('isExceededContextWindowError', () => {
- it('should return false for undefined/empty input', () => {
- expect(isExceededContextWindowError(undefined)).toBe(false);
- expect(isExceededContextWindowError('')).toBe(false);
- });
-
- it('should detect OpenAI/DeepSeek "maximum context length" errors', () => {
- expect(
- isExceededContextWindowError(
- "This model's maximum context length is 131072 tokens. However, your messages resulted in 140000 tokens.",
- ),
- ).toBe(true);
- });
-
- it('should detect OpenAI "context length exceeded" errors', () => {
- expect(isExceededContextWindowError('context length exceeded')).toBe(true);
- });
-
- it('should detect OpenAI "context_length_exceeded" code in message', () => {
- expect(isExceededContextWindowError('Error code: context_length_exceeded')).toBe(true);
- });
-
- it('should detect MiniMax "context window exceeds" errors', () => {
- expect(
- isExceededContextWindowError('invalid params, context window exceeds limit (2013)'),
- ).toBe(true);
- });
-
- it('should detect Aihubmix "exceeds the context window" errors', () => {
- expect(
- isExceededContextWindowError('This request exceeds the context window of this model'),
- ).toBe(true);
- });
-
- it('should detect Anthropic "prompt is too long" errors', () => {
- expect(isExceededContextWindowError('prompt is too long: 231426 tokens > 200000 maximum')).toBe(
- true,
- );
- });
-
- it('should detect Anthropic "input is too long" errors', () => {
- expect(isExceededContextWindowError('input is too long for this model')).toBe(true);
- });
-
- it('should detect Bedrock "too many input tokens" errors', () => {
- expect(isExceededContextWindowError('too many input tokens')).toBe(true);
- });
-
- it('should detect configured input token limit errors', () => {
- expect(
- isExceededContextWindowError(
- '400 Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 479832 tokens. Please reduce the length of the messages.',
- ),
- ).toBe(true);
- });
-
- it('should detect Google "exceeds the maximum number of tokens" errors', () => {
- expect(
- isExceededContextWindowError(
- 'The input token count exceeds the maximum number of tokens allowed',
- ),
- ).toBe(true);
- });
-
- it('should detect "maximum allowed number of input tokens" errors', () => {
- expect(isExceededContextWindowError('maximum allowed number of input tokens is 128000')).toBe(
- true,
- );
- });
-
- it('should detect "request too large for model" errors', () => {
- expect(isExceededContextWindowError('request too large for model')).toBe(true);
- });
-
- it('should be case-insensitive', () => {
- expect(isExceededContextWindowError('MAXIMUM CONTEXT LENGTH exceeded')).toBe(true);
- expect(isExceededContextWindowError('Prompt Is Too Long')).toBe(true);
- });
-
- it('should return false for unrelated error messages', () => {
- expect(isExceededContextWindowError('Invalid API key')).toBe(false);
- expect(isExceededContextWindowError('Rate limit exceeded')).toBe(false);
- expect(isExceededContextWindowError('Internal server error')).toBe(false);
- });
-});
diff --git a/packages/model-runtime/src/utils/isExceededContextWindowError.ts b/packages/model-runtime/src/utils/isExceededContextWindowError.ts
deleted file mode 100644
index c63b76c1f4f..00000000000
--- a/packages/model-runtime/src/utils/isExceededContextWindowError.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-const CONTEXT_WINDOW_PATTERNS = [
- 'maximum context length', // OpenAI/DeepSeek
- 'context length exceeded', // OpenAI
- 'context_length_exceeded', // OpenAI (code in message)
- 'context window exceeds', // MiniMax non-streaming
- 'exceeds the context window', // Aihubmix / generic
- 'prompt is too long', // Anthropic
- 'input is too long', // Anthropic
- 'input tokens exceed the configured limit', // OpenAI-compatible providers / wrapped upstream errors
- 'too many input tokens', // Bedrock
- 'exceeds the maximum number of tokens', // Google
- 'maximum allowed number of input tokens',
- 'request too large for model',
-];
-
-export const isExceededContextWindowError = (message?: string): boolean => {
- if (!message) return false;
- const lower = message.toLowerCase();
- return CONTEXT_WINDOW_PATTERNS.some((p) => lower.includes(p));
-};
diff --git a/packages/model-runtime/src/utils/isInsufficientQuotaError.test.ts b/packages/model-runtime/src/utils/isInsufficientQuotaError.test.ts
deleted file mode 100644
index eb0facb77a0..00000000000
--- a/packages/model-runtime/src/utils/isInsufficientQuotaError.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isInsufficientQuotaError } from './isInsufficientQuotaError';
-
-describe('isInsufficientQuotaError', () => {
- it('should return false for undefined/empty input', () => {
- expect(isInsufficientQuotaError(undefined)).toBe(false);
- expect(isInsufficientQuotaError('')).toBe(false);
- });
-
- it('should detect Moonshot "insufficient balance" errors', () => {
- expect(
- isInsufficientQuotaError(
- 'Your account org-d4cffdc846304e378e12254ef3c9cb16 <ak-f8fmexq3k3wi11gm63d1> is suspended due to insufficient balance, please recharge your account or check your plan and billing details',
- ),
- ).toBe(true);
- });
-
- it('should detect generic "Insufficient Balance" errors', () => {
- expect(isInsufficientQuotaError('Insufficient Balance: Your account balance is too low')).toBe(
- true,
- );
- });
-
- it('should detect "insufficient quota" errors', () => {
- expect(isInsufficientQuotaError('You have insufficient quota for this request')).toBe(true);
- });
-
- it('should detect "balance is not enough" errors', () => {
- expect(isInsufficientQuotaError('Your balance is not enough to complete this request')).toBe(
- true,
- );
- });
-
- it('should detect OpenAI "billing hard limit" errors', () => {
- expect(isInsufficientQuotaError('Billing hard limit has been reached')).toBe(true);
- });
-
- it('should NOT detect account deactivation as quota error', () => {
- expect(
- isInsufficientQuotaError('Your account has been deactivated, please contact support'),
- ).toBe(false);
- });
-
- it('should detect "exceeded your current quota" errors', () => {
- expect(
- isInsufficientQuotaError(
- 'You exceeded your current quota, please check your plan and billing details',
- ),
- ).toBe(true);
- });
-
- it('should be case-insensitive', () => {
- expect(isInsufficientQuotaError('INSUFFICIENT BALANCE')).toBe(true);
- expect(isInsufficientQuotaError('Insufficient Quota')).toBe(true);
- expect(isInsufficientQuotaError('BILLING HARD LIMIT HAS BEEN REACHED')).toBe(true);
- });
-
- it('should return false for unrelated error messages', () => {
- expect(isInsufficientQuotaError('Invalid API key')).toBe(false);
- expect(isInsufficientQuotaError('Context length exceeded')).toBe(false);
- expect(isInsufficientQuotaError('Too many requests')).toBe(false);
- expect(isInsufficientQuotaError('Rate limit reached')).toBe(false);
- });
-});
diff --git a/packages/model-runtime/src/utils/isInsufficientQuotaError.ts b/packages/model-runtime/src/utils/isInsufficientQuotaError.ts
deleted file mode 100644
index 4ae71dd9033..00000000000
--- a/packages/model-runtime/src/utils/isInsufficientQuotaError.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-const INSUFFICIENT_QUOTA_PATTERNS = [
- 'insufficient balance', // Moonshot / generic
- 'insufficient quota', // OpenAI
- 'account is suspended due to insufficient balance', // Moonshot
- 'balance is not enough', // generic
- 'billing hard limit has been reached', // OpenAI
- 'exceeded your current quota', // OpenAI
-];
-
-export const isInsufficientQuotaError = (message?: string): boolean => {
- if (!message) return false;
- const lower = message.toLowerCase();
- return INSUFFICIENT_QUOTA_PATTERNS.some((p) => lower.includes(p));
-};
diff --git a/packages/model-runtime/src/utils/isQuotaLimitError.test.ts b/packages/model-runtime/src/utils/isQuotaLimitError.test.ts
deleted file mode 100644
index d8342b0e15d..00000000000
--- a/packages/model-runtime/src/utils/isQuotaLimitError.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { isQuotaLimitError } from './isQuotaLimitError';
-
-describe('isQuotaLimitError', () => {
- it('should return false for undefined/empty input', () => {
- expect(isQuotaLimitError(undefined)).toBe(false);
- expect(isQuotaLimitError('')).toBe(false);
- });
-
- it('should detect Google "resource exhausted" errors', () => {
- expect(isQuotaLimitError('Resource exhausted')).toBe(true);
- });
-
- it('should detect Google "resource has been exhausted" errors', () => {
- expect(isQuotaLimitError('Resource has been exhausted (e.g. check quota).')).toBe(true);
- });
-
- it('should detect OpenAI "rate limit reached" errors', () => {
- expect(isQuotaLimitError('Rate limit reached for model gpt-4 in organization')).toBe(true);
- });
-
- it('should detect OpenAI "rate_limit_exceeded" code in message', () => {
- expect(isQuotaLimitError('Error code: rate_limit_exceeded')).toBe(true);
- });
-
- it('should detect "quota exceeded" errors', () => {
- expect(isQuotaLimitError('Quota exceeded for this API key')).toBe(true);
- });
-
- it('should detect "too many requests" errors', () => {
- expect(isQuotaLimitError('Too many requests, please slow down')).toBe(true);
- });
-
- it('should be case-insensitive', () => {
- expect(isQuotaLimitError('RESOURCE EXHAUSTED')).toBe(true);
- expect(isQuotaLimitError('Rate Limit Reached')).toBe(true);
- expect(isQuotaLimitError('TOO MANY REQUESTS')).toBe(true);
- });
-
- it('should return false for unrelated error messages', () => {
- expect(isQuotaLimitError('Invalid API key')).toBe(false);
- expect(isQuotaLimitError('Context length exceeded')).toBe(false);
- expect(isQuotaLimitError('Internal server error')).toBe(false);
- });
-});
diff --git a/packages/model-runtime/src/utils/isQuotaLimitError.ts b/packages/model-runtime/src/utils/isQuotaLimitError.ts
deleted file mode 100644
index deb5542d534..00000000000
--- a/packages/model-runtime/src/utils/isQuotaLimitError.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-const QUOTA_LIMIT_PATTERNS = [
- 'resource exhausted', // Google / VertexAI
- 'resource has been exhausted', // Google
- 'rate limit reached', // OpenAI
- 'rate_limit_exceeded', // OpenAI (code in message)
- 'quota exceeded', // generic
- 'too many requests', // generic
- 'too many tokens', // Moonshot / generic (e.g. "Too many tokens per day")
-];
-
-export const isQuotaLimitError = (message?: string): boolean => {
- if (!message) return false;
- const lower = message.toLowerCase();
- return QUOTA_LIMIT_PATTERNS.some((p) => lower.includes(p));
-};
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 27483732a22..1457f0a3d58 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -47,6 +47,18 @@ export const AgentRuntimeErrorType = {
NoAvailableProvider: 'NoAvailableProvider',
AccountDeactivated: 'AccountDeactivated',
+ /**
+ * Short-window rate limit (RPM / TPM / concurrency) hit on the provider side.
+ * Transient and retryable — distinct from `InsufficientQuota` which means
+ * the account-level balance is exhausted.
+ */
+ RateLimitExceeded: 'RateLimitExceeded',
+ /**
+ * @deprecated Use `RateLimitExceeded` instead. The legacy name conflated
+ * short-window rate limits with long-term quota exhaustion. Kept as an
+ * alias so older callers and stored data continue to resolve via
+ * `getErrorCodeSpec` / `isUserSideError`.
+ */
QuotaLimitReached: 'QuotaLimitReached',
InsufficientQuota: 'InsufficientQuota',
@@ -58,6 +70,24 @@ export const AgentRuntimeErrorType = {
InvalidProviderAPIKey: 'InvalidProviderAPIKey',
ProviderBizError: 'ProviderBizError',
+ // —— Added by unified error scheme (additive, all attribution-tagged in spec table) ——
+ /** Provider returned 503 / overloaded / "high demand" — transient, retryable. */
+ ProviderServiceUnavailable: 'ProviderServiceUnavailable',
+ /** Network timeout / connection drop talking to the provider. */
+ ProviderNetworkError: 'ProviderNetworkError',
+ /** 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. */
+ ContentModeration: 'ContentModeration',
+ /** Model lacks the requested capability (VLM / tool calling / prefill). */
+ CapabilityNotSupported: 'CapabilityNotSupported',
+ /** Provider rejected the request as malformed (bad JSON, schema validation, etc.). */
+ InvalidRequestFormat: 'InvalidRequestFormat',
+ /** User-side misconfiguration (wrong base URL, missing env var, virtual-key allowlist, etc.). */
+ UserConfigError: 'UserConfigError',
+ /** Gateway watchdog killed an idle agent operation — harness-side. */
+ OperationInactivityTimeout: 'OperationInactivityTimeout',
+
InvalidOllamaArgs: 'InvalidOllamaArgs',
OllamaBizError: 'OllamaBizError',
OllamaServiceUnavailable: 'OllamaServiceUnavailable',
diff --git a/src/locales/default/error.ts b/src/locales/default/error.ts
index 33d00b39cbd..105cf887ede 100644
--- a/src/locales/default/error.ts
+++ b/src/locales/default/error.ts
@@ -207,6 +207,8 @@ export default {
'Repeated image safety rejections detected. Similar prompts may temporarily pause image generation.',
'response.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.",
+ 'response.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.",
'response.ServerAgentRuntimeError':
'Sorry, the Agent service is currently unavailable. Please try again later or contact us via email for support.',
'response.StreamChunkError':
@@ -223,6 +225,22 @@ export default {
'The model "{{model}}" is no longer available. Please pick a current model from the model selector.',
'response.UnknownChatFetchError':
'Sorry, an unknown request error occurred. Please check the information below or try again.',
+ 'response.CapabilityNotSupported':
+ 'Sorry, this model does not support the requested capability (such as vision input or tool calling). Please switch to a model that supports it.',
+ 'response.ContentModeration':
+ 'Sorry, the content was rejected by the upstream safety filter. Please revise your prompt and try again.',
+ 'response.InvalidRequestFormat':
+ 'Sorry, the upstream provider rejected the request as malformed. Please check the input or try a different model.',
+ 'response.NoAvailableChannel':
+ 'Sorry, the proxy or router has no available channel for the requested model. Please switch the channel/key configuration or try again later.',
+ 'response.OperationInactivityTimeout':
+ 'The agent operation was idle for too long and was terminated. Please retry the request.',
+ 'response.ProviderNetworkError':
+ 'Connection to the provider timed out or was dropped. Please check your network and try again.',
+ 'response.ProviderServiceUnavailable':
+ 'The provider is temporarily overloaded or unavailable. Please try again shortly.',
+ 'response.UserConfigError':
+ 'Provider configuration is invalid (incorrect base URL, missing environment variable, virtual-key restriction, etc.). Please review the provider settings.',
'stt.responseError': 'Service request failed, please check the configuration or try again',
'supervisor.decisionFailed':
'The group host is unable to function. Please check your host configuration to ensure the correct model, API Key, and API endpoint are set.',
diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 6831c25ba87..bd0b24a3fb4 100644
--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -45,6 +45,11 @@ vi.mock('@/server/services/message', () => ({
// cloud-specific dependencies that are unavailable in the test environment
vi.mock('@lobechat/model-runtime', () => ({
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,
}));
vi.mock('@/business/client/model-bank/loadModels', () => ({
diff --git a/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
index c639cf741f2..12350b964d8 100644
--- a/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
+++ b/src/server/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
@@ -4,6 +4,12 @@ import { classifyLLMError } from '../llmErrorClassification';
describe('classifyLLMError', () => {
it('should classify rate limit errors as retry', () => {
+ expect(
+ classifyLLMError({ errorType: 'RateLimitExceeded', message: '429 rate limit' }).kind,
+ ).toBe('retry');
+ });
+
+ it('resolves the deprecated QuotaLimitReached alias the same as RateLimitExceeded', () => {
expect(
classifyLLMError({ errorType: 'QuotaLimitReached', message: '429 rate limit' }).kind,
).toBe('retry');
@@ -50,6 +56,50 @@ describe('classifyLLMError', () => {
expect(classifyLLMError(new Error('unexpected upstream issue')).kind).toBe('retry');
});
+ describe('spec-driven non-retryable codes', () => {
+ // These all carry `retryable: false` in `ERROR_CODE_SPECS`. Before the
+ // classifier was spec-driven, an errorType without an HTTP status would
+ // fall through to the default `retry` branch — causing pointless retry
+ // storms for requests the spec says should stop. Now the classifier reads
+ // straight from the spec table.
+ it.each([
+ ['ContentModeration', 'Content Exists Risk'],
+ ['InvalidRequestFormat', 'Range of input length should be 1 to 8192'],
+ ['UserConfigError', 'Invalid URL (POST /v1/v1beta'],
+ ['NoAvailableChannel', 'No available keys in pool'],
+ ['OperationInactivityTimeout', 'Operation idle for 1800s'],
+ ['CapabilityNotSupported', 'The model is not a VLM'],
+ ['LocationNotSupportError', 'service unavailable in this region'],
+ ['ExceededToolLimit', 'tools array exceeds limit'],
+ ])('classifies %s as stop (no HTTP status)', (errorType, message) => {
+ expect(classifyLLMError({ errorType, message }).kind).toBe('stop');
+ });
+ });
+
+ describe('spec-driven retryable codes', () => {
+ it.each([
+ ['ProviderServiceUnavailable', 'upstream temporarily overloaded'],
+ ['ProviderNetworkError', 'connection timed out'],
+ ['RateLimitExceeded', 'tokens per minute (TPM)'],
+ ])('classifies %s as retry (no HTTP status)', (errorType, message) => {
+ expect(classifyLLMError({ errorType, message }).kind).toBe('retry');
+ });
+ });
+
+ describe('legacy retry overrides', () => {
+ // These four codes are `retryable: false` in the spec but the runtime
+ // intentionally retries them because they're catch-alls / harness-level
+ // errors that often succeed on retry.
+ it.each([
+ 'AgentRuntimeError',
+ 'OllamaServiceUnavailable',
+ 'ProviderBizError',
+ 'StreamChunkError',
+ ])('classifies %s as retry despite spec saying non-retryable', (errorType) => {
+ expect(classifyLLMError({ errorType, message: 'something happened' }).kind).toBe('retry');
+ });
+ });
+
describe('non-string code / errorType defensive handling', () => {
// Regression: real-world provider errors sometimes carry numeric `code`
// (HTTP status) or a structured object in the error fields. Earlier versions
diff --git a/src/server/modules/AgentRuntime/llmErrorClassification.ts b/src/server/modules/AgentRuntime/llmErrorClassification.ts
index cdec3251e9e..165f12e1692 100644
--- a/src/server/modules/AgentRuntime/llmErrorClassification.ts
+++ b/src/server/modules/AgentRuntime/llmErrorClassification.ts
@@ -1,3 +1,5 @@
+import { ERROR_CODE_SPECS, getErrorCodeSpec } from '@lobechat/model-runtime';
+
type LLMErrorKind = 'retry' | 'stop';
interface ClassifiedLLMError {
@@ -13,27 +15,42 @@ interface LLMErrorSignal {
status?: number;
}
-const RETRY_ERROR_TYPES = new Set([
+/**
+ * Error codes the runtime should retry **despite** the spec table marking them
+ * non-retryable. These are catch-all / harness-level errors that are often
+ * transient in practice (a retried call frequently succeeds), so the operational
+ * retry loop is more aggressive than the spec's intrinsic retryability.
+ *
+ * Keep this set tight — every entry is a conscious deviation from the spec.
+ */
+const RETRY_OVERRIDES = new Set([
'AgentRuntimeError',
'OllamaServiceUnavailable',
'ProviderBizError',
- 'QuotaLimitReached',
'StreamChunkError',
]);
-const STOP_ERROR_TYPES = new Set([
- 'AccountDeactivated',
- 'ExceededContextWindow',
- 'InsufficientQuota',
- 'InvalidBedrockCredentials',
- 'InvalidGithubCopilotToken',
- 'InvalidGithubToken',
- 'InvalidOllamaArgs',
- 'InvalidProviderAPIKey',
- 'InvalidVertexCredentials',
- 'ModelNotFound',
- 'PermissionDenied',
- 'Unauthorized',
-]);
+
+/**
+ * Legacy `ChatErrorType` codes that aren't (yet) in `ERROR_CODE_SPECS` but need
+ * to map to `stop`. The numeric HTTP status `Unauthorized` (401) shows up as a
+ * string `errorType` in some code paths.
+ */
+const LEGACY_STOP_ERROR_TYPES = new Set(['Unauthorized']);
+
+const buildErrorTypeSets = () => {
+ const stop = new Set<string>();
+ const retry = new Set<string>(RETRY_OVERRIDES);
+ for (const spec of Object.values(ERROR_CODE_SPECS)) {
+ if (!spec) continue;
+ if (RETRY_OVERRIDES.has(spec.code)) continue;
+ if (spec.retryable) retry.add(spec.code);
+ else stop.add(spec.code);
+ }
+ for (const code of LEGACY_STOP_ERROR_TYPES) stop.add(code);
+ return { retry, stop };
+};
+
+const { retry: RETRY_ERROR_TYPES, stop: STOP_ERROR_TYPES } = buildErrorTypeSets();
const RETRY_KEYWORDS = [
'429',
@@ -192,8 +209,12 @@ const classifyKind = ({ code, errorType, message, status }: LLMErrorSignal): LLM
}
if (errorType) {
- if (STOP_ERROR_TYPES.has(errorType)) return 'stop';
- if (RETRY_ERROR_TYPES.has(errorType)) return 'retry';
+ // Resolve through the spec table so deprecated aliases (e.g. the legacy
+ // `QuotaLimitReached` → `RateLimitExceeded`) classify the same as their
+ // canonical replacement.
+ const canonical = getErrorCodeSpec(errorType)?.code ?? errorType;
+ if (STOP_ERROR_TYPES.has(canonical)) return 'stop';
+ if (RETRY_ERROR_TYPES.has(canonical)) return 'retry';
}
if (code) {
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
index 28a2913dc0c..5abc15e5c74 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
@@ -15,6 +15,11 @@ import {
vi.mock('@lobechat/model-runtime', () => ({
getModelPropertyWithFallback: vi.fn(),
+ // `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,
}));
// Mock trusted client to avoid server-side env access