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: move LLM error classifier into agent-runtime (#16871)

Arvin Xu5bb36b0fedb8
diff --git a/apps/server/src/modules/AgentRuntime/llmErrorClassification.ts b/apps/server/src/modules/AgentRuntime/llmErrorClassification.ts
index 165f12e1692..8464f834f44 100644
--- a/apps/server/src/modules/AgentRuntime/llmErrorClassification.ts
+++ b/apps/server/src/modules/AgentRuntime/llmErrorClassification.ts
@@ -1,281 +1,13 @@
+import {
+ type ClassifiedLLMError,
+ createLLMErrorClassifier,
+ type LLMErrorKind,
+} from '@lobechat/agent-runtime';
import { ERROR_CODE_SPECS, getErrorCodeSpec } from '@lobechat/model-runtime';
-type LLMErrorKind = 'retry' | 'stop';
-
-interface ClassifiedLLMError {
- code?: string;
- kind: LLMErrorKind;
- message: string;
-}
-
-interface LLMErrorSignal {
- code?: string;
- errorType?: string;
- message: string;
- status?: number;
-}
-
-/**
- * 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',
- 'StreamChunkError',
-]);
-
-/**
- * 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',
- 'connection',
- 'econn',
- 'network',
- 'rate limit',
- 'timeout',
- 'timed out',
- 'temporarily unavailable',
-];
-const STOP_KEYWORDS = [
- '403',
- 'context window',
- 'api key',
- 'billing',
- 'forbidden',
- 'insufficient quota',
- 'invalid request',
- 'maximum context length',
- 'model not found',
- 'permission denied',
- 'payload',
- 'too many tokens',
- 'unauthorized',
-];
-
-const hasAnyKeyword = (text: string, keywords: string[]) =>
- keywords.some((keyword) => text.includes(keyword));
-
-const normalizeCode = (value?: unknown): string | undefined => {
- if (typeof value !== 'string' || !value) return;
-
- return value
- .trim()
- .toUpperCase()
- .replaceAll(/[\s-]+/g, '_');
-};
-
-const normalizeErrorType = (value?: unknown): string | undefined => {
- if (typeof value !== 'string') return undefined;
- const trimmed = value.trim();
- return trimmed || undefined;
-};
-
-const tryExtractStatus = (message: string) => {
- const matches = message.match(/\b([45]\d{2})\b/);
- if (!matches) return;
-
- const status = Number(matches[1]);
- return Number.isNaN(status) ? undefined : status;
-};
-
-// Some providers (notably bare HTTP proxies) only surface the HTTP status as a
-// numeric `code` on the error object, with no `status`/`statusCode`. Treat
-// those numeric codes as status so classifyKind can still map 401/403 to stop
-// and 429/5xx to retry without falling through to message-keyword matching.
-const numericStatusFromCode = (...codes: unknown[]): number | undefined => {
- for (const code of codes) {
- if (typeof code === 'number' && Number.isFinite(code)) return code;
- }
- return undefined;
-};
-
-const normalizeSignal = (error: unknown): LLMErrorSignal => {
- if (typeof error === 'string') {
- const message = error.toLowerCase();
- return { message, status: tryExtractStatus(message) };
- }
-
- if (error instanceof Error) {
- const raw = error as Error & {
- code?: unknown;
- errorType?: unknown;
- status?: number;
- statusCode?: number;
- type?: unknown;
- };
- const message = (raw.message || raw.name || 'unknown error').toLowerCase();
-
- return {
- code: normalizeCode(raw.code),
- errorType: normalizeErrorType(raw.errorType || raw.type),
- message,
- status:
- typeof raw.status === 'number'
- ? raw.status
- : typeof raw.statusCode === 'number'
- ? raw.statusCode
- : (numericStatusFromCode(raw.code) ?? tryExtractStatus(message)),
- };
- }
-
- if (error && typeof error === 'object') {
- const raw = error as {
- code?: unknown;
- error?: {
- code?: unknown;
- error?: { code?: unknown; message?: string; status?: number; type?: unknown };
- errorType?: unknown;
- message?: string;
- status?: number;
- type?: unknown;
- };
- errorType?: unknown;
- message?: string;
- status?: number;
- statusCode?: number;
- type?: unknown;
- };
- const nested = raw.error;
- const nestedError = nested?.error;
- const message = (
- raw.message ||
- nested?.message ||
- nestedError?.message ||
- 'unknown error'
- ).toLowerCase();
-
- return {
- code: normalizeCode(raw.code || nested?.code || nestedError?.code),
- errorType: normalizeErrorType(
- raw.errorType || raw.type || nested?.errorType || nested?.type || nestedError?.type,
- ),
- message,
- status:
- typeof raw.status === 'number'
- ? raw.status
- : typeof raw.statusCode === 'number'
- ? raw.statusCode
- : typeof nested?.status === 'number'
- ? nested.status
- : typeof nestedError?.status === 'number'
- ? nestedError.status
- : (numericStatusFromCode(raw.code, nested?.code, nestedError?.code) ??
- tryExtractStatus(message)),
- };
- }
-
- return { message: 'unknown error' };
-};
-
-const classifyKind = ({ code, errorType, message, status }: LLMErrorSignal): LLMErrorKind => {
- if (errorType === 'ProviderBizError') {
- if (status === 400 || status === 422) return 'stop';
- if (message.includes('invalid_request_error') || message.includes('invalid request')) {
- return 'stop';
- }
- if (
- message.includes('input_schema') ||
- message.includes('field required') ||
- message.includes('missing required')
- ) {
- return 'stop';
- }
- }
-
- if (errorType) {
- // 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) {
- if (code.includes('UNAUTHORIZED') || code.includes('FORBIDDEN')) return 'stop';
- if (code.includes('MODEL_NOT_FOUND')) return 'stop';
- if (code.includes('RATE_LIMIT') || code.includes('TIMEOUT')) return 'retry';
- }
-
- if (status !== undefined) {
- if (status === 401 || status === 403) return 'stop';
- if (status === 400 || status === 404 || status === 409 || status === 422) return 'stop';
- if (status === 408 || status === 425 || status === 429 || status >= 500) return 'retry';
- }
-
- if (hasAnyKeyword(message, STOP_KEYWORDS)) return 'stop';
- if (hasAnyKeyword(message, RETRY_KEYWORDS)) return 'retry';
-
- return 'retry';
-};
-
-/**
- * Extract a human-readable message for the fallback path without relying on
- * normalizeSignal (which might be the thing that just threw).
- */
-const bestEffortMessage = (error: unknown): string => {
- try {
- if (error instanceof Error && typeof error.message === 'string' && error.message.length > 0) {
- return error.message;
- }
- if (typeof error === 'string' && error.length > 0) return error;
- if (error && typeof error === 'object') {
- const e = error as { message?: unknown; error?: { message?: unknown } };
- if (typeof e.message === 'string' && e.message.length > 0) return e.message;
- const nested = e.error?.message;
- if (typeof nested === 'string' && nested.length > 0) return nested;
- }
- } catch {
- // Property access itself can throw (e.g. hostile Proxy). Fall through to default.
- }
- return 'unknown error';
-};
-
-export const classifyLLMError = (error: unknown): ClassifiedLLMError => {
- // Defensive: a classifier that throws would mask the original provider error
- // behind the classifier's own TypeError (e.g. `e.trim is not a function`),
- // making prod debugging impossible. If anything below throws, fall back to a
- // conservative "stop" decision that preserves the original error message.
- try {
- const signal = normalizeSignal(error);
-
- return {
- code: signal.code || signal.errorType,
- kind: classifyKind(signal),
- message: signal.message,
- };
- } catch (classificationError) {
- return {
- kind: 'stop',
- message: bestEffortMessage(error),
- };
- }
-};
+export const classifyLLMError = createLLMErrorClassifier({
+ errorCodeSpecs: Object.values(ERROR_CODE_SPECS),
+ getErrorCodeSpec,
+});
export type { ClassifiedLLMError, LLMErrorKind };
diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.ts
index f0d41690228..559cfd01b4b 100644
--- a/packages/agent-runtime/src/utils/index.ts
+++ b/packages/agent-runtime/src/utils/index.ts
@@ -1,3 +1,4 @@
+export * from './llmErrorClassifier';
export * from './messageSelectors';
export * from './replay';
export * from './runtimeRetry';
diff --git a/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts b/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts
new file mode 100644
index 00000000000..90b2a91856e
--- /dev/null
+++ b/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ classifyLLMError,
+ createLLMErrorClassifier,
+ type LLMErrorCodeSpecLike,
+} from './llmErrorClassifier';
+
+const specsByCode: Record<string, LLMErrorCodeSpecLike> = {
+ AgentRuntimeError: { code: 'AgentRuntimeError', retryable: false },
+ ExceededToolLimit: { code: 'ExceededToolLimit', retryable: false },
+ InvalidProviderAPIKey: { code: 'InvalidProviderAPIKey', retryable: false },
+ RateLimitExceeded: { code: 'RateLimitExceeded', retryable: true },
+};
+
+const classifyWithSpecs = createLLMErrorClassifier({
+ errorCodeSpecs: Object.values(specsByCode),
+ getErrorCodeSpec: (code) =>
+ code === 'QuotaLimitReached' ? specsByCode.RateLimitExceeded : specsByCode[code],
+});
+
+describe('llmErrorClassifier', () => {
+ it('classifies error types from an injected spec table', () => {
+ expect(
+ classifyWithSpecs({ errorType: 'RateLimitExceeded', message: 'tokens per minute' }).kind,
+ ).toBe('retry');
+ expect(
+ classifyWithSpecs({ errorType: 'ExceededToolLimit', message: 'tools exceeded' }).kind,
+ ).toBe('stop');
+ expect(
+ classifyWithSpecs({ errorType: 'InvalidProviderAPIKey', message: 'key rejected' }).kind,
+ ).toBe('stop');
+ });
+
+ it('resolves deprecated aliases through the injected spec lookup', () => {
+ expect(
+ classifyWithSpecs({ errorType: 'QuotaLimitReached', message: 'legacy rate limit' }).kind,
+ ).toBe('retry');
+ });
+
+ it('keeps runtime retry overrides ahead of non-retryable specs', () => {
+ expect(
+ classifyWithSpecs({ errorType: 'AgentRuntimeError', message: 'fallback runtime error' }).kind,
+ ).toBe('retry');
+ });
+
+ it('stops ProviderBizError invalid request shapes but retries transient ones', () => {
+ expect(
+ classifyWithSpecs({
+ error: {
+ error: {
+ message: 'tools.0.custom.input_schema: Field required',
+ type: 'invalid_request_error',
+ },
+ errorType: 'ProviderBizError',
+ },
+ errorType: 'ProviderBizError',
+ }).kind,
+ ).toBe('stop');
+
+ expect(
+ classifyWithSpecs({
+ error: { message: '429 rate limit exceeded' },
+ errorType: 'ProviderBizError',
+ }).kind,
+ ).toBe('retry');
+ });
+
+ it('falls back to numeric status and keyword classification without injected specs', () => {
+ expect(classifyLLMError({ code: 401, message: 'upstream refused' }).kind).toBe('stop');
+ expect(classifyLLMError({ code: 429, message: 'upstream refused' }).kind).toBe('retry');
+ expect(classifyLLMError(new Error('unexpected upstream issue')).kind).toBe('retry');
+ });
+
+ it('preserves a valid result when provider error shapes contain non-string fields', () => {
+ expect(
+ classifyWithSpecs({ errorType: { nested: 'structured' }, message: 'structured type' }),
+ ).toEqual({
+ kind: 'retry',
+ message: 'structured type',
+ });
+
+ expect(
+ classifyWithSpecs({
+ error: { error: { code: 401, message: 'proxy refused upstream' } },
+ }).kind,
+ ).toBe('stop');
+ });
+});
diff --git a/packages/agent-runtime/src/utils/llmErrorClassifier.ts b/packages/agent-runtime/src/utils/llmErrorClassifier.ts
new file mode 100644
index 00000000000..001ae9639f6
--- /dev/null
+++ b/packages/agent-runtime/src/utils/llmErrorClassifier.ts
@@ -0,0 +1,281 @@
+export type LLMErrorKind = 'retry' | 'stop';
+
+export interface ClassifiedLLMError {
+ code?: string;
+ kind: LLMErrorKind;
+ message: string;
+}
+
+export interface LLMErrorCodeSpecLike {
+ code: string;
+ retryable: boolean;
+}
+
+export interface LLMErrorClassifierOptions {
+ errorCodeSpecs?: ReadonlyArray<LLMErrorCodeSpecLike | undefined>;
+ getErrorCodeSpec?: (code: string) => LLMErrorCodeSpecLike | undefined;
+ legacyStopErrorTypes?: readonly string[];
+ retryOverrides?: readonly string[];
+}
+
+interface LLMErrorSignal {
+ code?: string;
+ errorType?: string;
+ message: string;
+ status?: number;
+}
+
+const DEFAULT_RETRY_OVERRIDES = [
+ 'AgentRuntimeError',
+ 'OllamaServiceUnavailable',
+ 'ProviderBizError',
+ 'StreamChunkError',
+] as const;
+
+const DEFAULT_LEGACY_STOP_ERROR_TYPES = ['Unauthorized'] as const;
+
+const RETRY_KEYWORDS = [
+ '429',
+ 'connection',
+ 'econn',
+ 'network',
+ 'rate limit',
+ 'timeout',
+ 'timed out',
+ 'temporarily unavailable',
+];
+const STOP_KEYWORDS = [
+ '403',
+ 'context window',
+ 'api key',
+ 'billing',
+ 'forbidden',
+ 'insufficient quota',
+ 'invalid request',
+ 'maximum context length',
+ 'model not found',
+ 'permission denied',
+ 'payload',
+ 'too many tokens',
+ 'unauthorized',
+];
+
+const hasAnyKeyword = (text: string, keywords: string[]) =>
+ keywords.some((keyword) => text.includes(keyword));
+
+const normalizeCode = (value?: unknown): string | undefined => {
+ if (typeof value !== 'string' || !value) return;
+
+ return value
+ .trim()
+ .toUpperCase()
+ .replaceAll(/[\s-]+/g, '_');
+};
+
+const normalizeErrorType = (value?: unknown): string | undefined => {
+ if (typeof value !== 'string') return undefined;
+ const trimmed = value.trim();
+ return trimmed || undefined;
+};
+
+const tryExtractStatus = (message: string) => {
+ const matches = message.match(/\b([45]\d{2})\b/);
+ if (!matches) return;
+
+ const status = Number(matches[1]);
+ return Number.isNaN(status) ? undefined : status;
+};
+
+// Some providers (notably bare HTTP proxies) only surface the HTTP status as a
+// numeric `code` on the error object, with no `status`/`statusCode`.
+const numericStatusFromCode = (...codes: unknown[]): number | undefined => {
+ for (const code of codes) {
+ if (typeof code === 'number' && Number.isFinite(code)) return code;
+ }
+ return undefined;
+};
+
+const normalizeSignal = (error: unknown): LLMErrorSignal => {
+ if (typeof error === 'string') {
+ const message = error.toLowerCase();
+ return { message, status: tryExtractStatus(message) };
+ }
+
+ if (error instanceof Error) {
+ const raw = error as Error & {
+ code?: unknown;
+ errorType?: unknown;
+ status?: number;
+ statusCode?: number;
+ type?: unknown;
+ };
+ const message = (raw.message || raw.name || 'unknown error').toLowerCase();
+
+ return {
+ code: normalizeCode(raw.code),
+ errorType: normalizeErrorType(raw.errorType || raw.type),
+ message,
+ status:
+ typeof raw.status === 'number'
+ ? raw.status
+ : typeof raw.statusCode === 'number'
+ ? raw.statusCode
+ : (numericStatusFromCode(raw.code) ?? tryExtractStatus(message)),
+ };
+ }
+
+ if (error && typeof error === 'object') {
+ const raw = error as {
+ code?: unknown;
+ error?: {
+ code?: unknown;
+ error?: { code?: unknown; message?: string; status?: number; type?: unknown };
+ errorType?: unknown;
+ message?: string;
+ status?: number;
+ type?: unknown;
+ };
+ errorType?: unknown;
+ message?: string;
+ status?: number;
+ statusCode?: number;
+ type?: unknown;
+ };
+ const nested = raw.error;
+ const nestedError = nested?.error;
+ const message = (
+ raw.message ||
+ nested?.message ||
+ nestedError?.message ||
+ 'unknown error'
+ ).toLowerCase();
+
+ return {
+ code: normalizeCode(raw.code || nested?.code || nestedError?.code),
+ errorType: normalizeErrorType(
+ raw.errorType || raw.type || nested?.errorType || nested?.type || nestedError?.type,
+ ),
+ message,
+ status:
+ typeof raw.status === 'number'
+ ? raw.status
+ : typeof raw.statusCode === 'number'
+ ? raw.statusCode
+ : typeof nested?.status === 'number'
+ ? nested.status
+ : typeof nestedError?.status === 'number'
+ ? nestedError.status
+ : (numericStatusFromCode(raw.code, nested?.code, nestedError?.code) ??
+ tryExtractStatus(message)),
+ };
+ }
+
+ return { message: 'unknown error' };
+};
+
+const buildErrorTypeSets = (options: LLMErrorClassifierOptions) => {
+ const retryOverrides = new Set(options.retryOverrides ?? DEFAULT_RETRY_OVERRIDES);
+ const stop = new Set<string>();
+ const retry = new Set<string>(retryOverrides);
+
+ for (const spec of options.errorCodeSpecs ?? []) {
+ if (!spec) continue;
+ if (retryOverrides.has(spec.code)) continue;
+ if (spec.retryable) retry.add(spec.code);
+ else stop.add(spec.code);
+ }
+
+ for (const code of options.legacyStopErrorTypes ?? DEFAULT_LEGACY_STOP_ERROR_TYPES) {
+ stop.add(code);
+ }
+
+ return { retry, retryOverrides, stop };
+};
+
+const createKindClassifier = (options: LLMErrorClassifierOptions = {}) => {
+ const { retry: retryErrorTypes, stop: stopErrorTypes } = buildErrorTypeSets(options);
+
+ return ({ code, errorType, message, status }: LLMErrorSignal): LLMErrorKind => {
+ if (errorType === 'ProviderBizError') {
+ if (status === 400 || status === 422) return 'stop';
+ if (message.includes('invalid_request_error') || message.includes('invalid request')) {
+ return 'stop';
+ }
+ if (
+ message.includes('input_schema') ||
+ message.includes('field required') ||
+ message.includes('missing required')
+ ) {
+ return 'stop';
+ }
+ }
+
+ if (errorType) {
+ const canonical = options.getErrorCodeSpec?.(errorType)?.code ?? errorType;
+ if (stopErrorTypes.has(canonical)) return 'stop';
+ if (retryErrorTypes.has(canonical)) return 'retry';
+ }
+
+ if (code) {
+ if (code.includes('UNAUTHORIZED') || code.includes('FORBIDDEN')) return 'stop';
+ if (code.includes('MODEL_NOT_FOUND')) return 'stop';
+ if (code.includes('RATE_LIMIT') || code.includes('TIMEOUT')) return 'retry';
+ }
+
+ if (status !== undefined) {
+ if (status === 401 || status === 403) return 'stop';
+ if (status === 400 || status === 404 || status === 409 || status === 422) return 'stop';
+ if (status === 408 || status === 425 || status === 429 || status >= 500) return 'retry';
+ }
+
+ if (hasAnyKeyword(message, STOP_KEYWORDS)) return 'stop';
+ if (hasAnyKeyword(message, RETRY_KEYWORDS)) return 'retry';
+
+ return 'retry';
+ };
+};
+
+/**
+ * Extract a human-readable message for the fallback path without relying on
+ * normalizeSignal (which might be the thing that just threw).
+ */
+const bestEffortMessage = (error: unknown): string => {
+ try {
+ if (error instanceof Error && typeof error.message === 'string' && error.message.length > 0) {
+ return error.message;
+ }
+ if (typeof error === 'string' && error.length > 0) return error;
+ if (error && typeof error === 'object') {
+ const e = error as { message?: unknown; error?: { message?: unknown } };
+ if (typeof e.message === 'string' && e.message.length > 0) return e.message;
+ const nested = e.error?.message;
+ if (typeof nested === 'string' && nested.length > 0) return nested;
+ }
+ } catch {
+ // Property access itself can throw (e.g. hostile Proxy). Fall through to default.
+ }
+ return 'unknown error';
+};
+
+export const createLLMErrorClassifier = (options: LLMErrorClassifierOptions = {}) => {
+ const classifyKind = createKindClassifier(options);
+
+ return (error: unknown): ClassifiedLLMError => {
+ try {
+ const signal = normalizeSignal(error);
+
+ return {
+ code: signal.code || signal.errorType,
+ kind: classifyKind(signal),
+ message: signal.message,
+ };
+ } catch {
+ return {
+ kind: 'stop',
+ message: bestEffortMessage(error),
+ };
+ }
+ };
+};
+
+export const classifyLLMError = createLLMErrorClassifier();