Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: preserve flat JSON provider errors (#19404)

YuTengjing8a3e849a1c84
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/client.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/client.ts
new file mode 100644
index 00000000000..8c70da05bf4
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/client.ts
@@ -0,0 +1,21 @@
+import { isRecord } from '@lobechat/utils';
+import OpenAI from 'openai';
+
+/** Preserves flat JSON errors returned by OpenAI-compatible providers. */
+export class OpenAICompatibleClient extends OpenAI {
+ protected override makeStatusError(
+ status: number,
+ error: object,
+ message: string | undefined,
+ headers: Headers,
+ ) {
+ // The SDK only reads errorResponse.error and otherwise discards parsed JSON.
+ // https://github.com/openai/openai-node/blob/master/src/core/error.ts
+ const flatError =
+ isRecord(error) &&
+ !('error' in error) &&
+ (typeof error.message === 'string' || typeof error.reason === 'string');
+
+ return super.makeStatusError(status, flatError ? { error } : error, message, headers);
+ }
+}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/errorResponse.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/errorResponse.test.ts
new file mode 100644
index 00000000000..4707ea113c8
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/errorResponse.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import OpenAI from 'openai';
+import { describe, expect, it } from 'vitest';
+
+import { createOpenAICompatibleRuntime } from './index';
+
+const Runtime = createOpenAICompatibleRuntime({ provider: ModelProvider.OpenAI });
+
+describe('OpenAI-compatible error responses', () => {
+ it.each([
+ { code: 403, message: 'not enough balance', reason: 'NOT_ENOUGH_BALANCE' },
+ { message: 'Access denied', reason: 'ACCESS_DENY' },
+ ])('preserves flat provider errors: $reason', async (body) => {
+ const runtime = new Runtime({
+ apiKey: 'test-key',
+ fetch: async () => Response.json(body, { status: 403 }),
+ maxRetries: 0,
+ });
+
+ await expect(
+ runtime.client.chat.completions.create({ messages: [], model: 'test-model', stream: true }),
+ ).rejects.toMatchObject({
+ error: body,
+ message: expect.stringContaining(body.message),
+ status: 403,
+ });
+ });
+
+ it('preserves standard nested errors and SDK error types', async () => {
+ const error = { code: 'invalid_api_key', message: 'Invalid API key' };
+ const runtime = new Runtime({
+ apiKey: 'test-key',
+ fetch: async () => Response.json({ error }, { status: 401 }),
+ maxRetries: 0,
+ });
+
+ const request = runtime.client.chat.completions.create({ messages: [], model: 'test-model' });
+ await expect(request).rejects.toBeInstanceOf(OpenAI.AuthenticationError);
+ await expect(request).rejects.toMatchObject({ error, status: 401 });
+ });
+
+ it('keeps an empty 403 unclassified', async () => {
+ const runtime = new Runtime({
+ apiKey: 'test-key',
+ fetch: async () => new Response(null, { status: 403 }),
+ maxRetries: 0,
+ });
+
+ await expect(
+ runtime.client.chat.completions.create({ messages: [], model: 'test-model' }),
+ ).rejects.toMatchObject({
+ error: undefined,
+ message: '403 status code (no body)',
+ status: 403,
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 8ddb154ed1d..173c26a52f4 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -5,7 +5,7 @@ import debug from 'debug';
import type { AiFullModelCard, AiModelType } from 'model-bank';
import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
import type { ClientOptions } from 'openai';
-import OpenAI from 'openai';
+import type OpenAI from 'openai';
import type { Stream } from 'openai/streaming';
import { ErrorClassifier, refineErrorCode } from '../../errors';
@@ -75,6 +75,7 @@ import type { OpenAIStreamOptions } from '../streams';
import { OpenAIResponsesStream, OpenAIStream } from '../streams';
import { type ChatPayloadForTransformStream, readableFromAsyncIterable } from '../streams/protocol';
import { convertOpenAIResponseUsage, convertOpenAIUsage } from '../usageConverters/openai';
+import { OpenAICompatibleClient } from './client';
import { createOpenAICompatibleImage } from './createImage';
import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';
import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
@@ -387,7 +388,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
if (customClient?.createClient) {
this.client = customClient.createClient(initOptions as any);
} else {
- this.client = new OpenAI(initOptions);
+ this.client = new OpenAICompatibleClient(initOptions);
}
this.baseURL = baseURL || this.client.baseURL;
@@ -710,7 +711,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
if (customClient?.createClient) {
this.client = customClient.createClient(initOptions);
} else {
- this.client = new OpenAI(initOptions);
+ this.client = new OpenAICompatibleClient(initOptions);
}
this.baseURL = targetBaseURL;