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: parse fenced JSON structured responses (#20578)

Nekod8adff4c0b76
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index 10c1dfcc2b1..0e2a6e9a0fb 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { StructuredOutputError } from '@lobechat/model-runtime';
import type { CreateMessageParams } from '@lobechat/types';
import { AgentRuntimeErrorType, ChatErrorType, ThreadType } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
@@ -1642,6 +1643,77 @@ describe('aiChatRouter', () => {
expect(result.tracingId).toMatch(/^[0-9a-f-]{36}$/);
});
+ describe('unparsable structured output', () => {
+ const inputCompletionInput = {
+ messages: [{ content: 'complete: hello', role: 'user' }],
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ schema: {
+ name: 'input_completion',
+ schema: {
+ properties: { completion: { type: 'string' } },
+ type: 'object' as const,
+ },
+ },
+ tracing: { scenario: 'input_completion' },
+ };
+
+ it('returns an empty result instead of an internal error in schema mode', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: vi
+ .fn()
+ .mockRejectedValue(new StructuredOutputError('invalid JSON response text')),
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+ const result = await caller.outputJSON(inputCompletionInput);
+
+ expect(result.data).toBeUndefined();
+ expect(result.tracingId).toMatch(/^[0-9a-f-]{36}$/);
+ });
+
+ it('still throws in tool mode, where a missing tool call was already an error', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const structuredError = new StructuredOutputError('no tool calls returned');
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: vi.fn().mockRejectedValue(structuredError),
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ await expect(
+ caller.outputJSON({
+ ...inputCompletionInput,
+ schema: undefined,
+ tools: [
+ {
+ function: { name: 'pick', parameters: { properties: {}, type: 'object' } },
+ type: 'function',
+ },
+ ],
+ }),
+ ).rejects.toMatchObject({ cause: structuredError, code: 'INTERNAL_SERVER_ERROR' });
+ });
+
+ it('keeps mapping provider errors in schema mode', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: vi.fn().mockRejectedValue({
+ error: undefined,
+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ }),
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ await expect(caller.outputJSON(inputCompletionInput)).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ });
+ });
+ });
+
it('rejects a caller-supplied tracing.tracingId that is not a UUID', async () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const mockGenerateObject = vi.fn();
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index 38eef89cfec..76fea6f9e0a 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { TRACING_SCENARIOS } from '@lobechat/const';
-import { getErrorCodeSpec } from '@lobechat/model-runtime';
+import { getErrorCodeSpec, StructuredOutputError } from '@lobechat/model-runtime';
import type { CreateMessageParams, SendMessageServerResponse } from '@lobechat/types';
import { AiSendMessageServerSchema, RequestTrigger, StructureOutputSchema } from '@lobechat/types';
import { createTimingHelpers, createTimingRequestId } from '@lobechat/utils';
@@ -182,6 +182,14 @@ export const aiChatRouter = router({
},
);
} catch (error) {
+ // Schema mode used to resolve unparsable model text (e.g. plain prose) as `undefined`.
+ // Keep that as "no result" so best-effort callers such as input completion stay silent;
+ // provider, auth and budget failures still map below. Tool mode keeps throwing.
+ if (error instanceof StructuredOutputError && !input.tools) {
+ log('outputJSON got unparsable structured output: %s', error.message);
+ return { data: undefined, tracingId };
+ }
+
const runtimeTRPCError = createRuntimeTRPCError(error, {
silentHandlerLog: input.tracing?.scenario === TRACING_SCENARIOS.InputCompletion,
});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 815f407403f..ea59dce7fcb 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -2887,7 +2887,7 @@ describe('LobeOpenAICompatibleFactory', () => {
);
});
- it('should return undefined when JSON parsing fails', async () => {
+ it('should reject when JSON parsing fails', async () => {
const mockResponse = {
output_text: 'invalid json string',
};
@@ -2905,10 +2905,10 @@ describe('LobeOpenAICompatibleFactory', () => {
},
};
- const result = await instance.generateObject(payload);
-
- expect(consoleSpy).toHaveBeenCalledWith('parse json error:', 'invalid json string');
- expect(result).toBeUndefined();
+ await expect(instance.generateObject(payload)).rejects.toMatchObject({
+ name: 'StructuredOutputError',
+ });
+ expect(consoleSpy).not.toHaveBeenCalled();
consoleSpy.mockRestore();
});
@@ -2931,10 +2931,10 @@ describe('LobeOpenAICompatibleFactory', () => {
},
};
- const result = await instance.generateObject(payload);
-
- expect(consoleSpy).toHaveBeenCalledWith('parse json error:', '');
- expect(result).toBeUndefined();
+ await expect(instance.generateObject(payload)).rejects.toMatchObject({
+ name: 'StructuredOutputError',
+ });
+ expect(consoleSpy).not.toHaveBeenCalled();
consoleSpy.mockRestore();
});
@@ -3184,7 +3184,7 @@ describe('LobeOpenAICompatibleFactory', () => {
);
});
- it('should return undefined when JSON parsing fails with chat completions API', async () => {
+ it('should reject when JSON parsing fails with chat completions API', async () => {
const mockResponse = {
choices: [
{
@@ -3210,10 +3210,10 @@ describe('LobeOpenAICompatibleFactory', () => {
},
};
- const result = await instance.generateObject(payload);
-
- expect(consoleSpy).toHaveBeenCalledWith('parse json error:', 'This is not valid JSON');
- expect(result).toBeUndefined();
+ await expect(instance.generateObject(payload)).rejects.toMatchObject({
+ name: 'StructuredOutputError',
+ });
+ expect(consoleSpy).not.toHaveBeenCalled();
consoleSpy.mockRestore();
});
@@ -3244,10 +3244,10 @@ describe('LobeOpenAICompatibleFactory', () => {
},
};
- const result = await instance.generateObject(payload);
-
- expect(consoleSpy).toHaveBeenCalledWith('parse json error:', '');
- expect(result).toBeUndefined();
+ await expect(instance.generateObject(payload)).rejects.toMatchObject({
+ name: 'StructuredOutputError',
+ });
+ expect(consoleSpy).not.toHaveBeenCalled();
consoleSpy.mockRestore();
});
@@ -4491,3 +4491,31 @@ describe('LobeOpenAICompatibleFactory', () => {
});
});
});
+
+describe('schema response JSON fences', () => {
+ it.each([false, true])('accepts one JSON fence through responseApi=%s', async (responseApi) => {
+ const Runtime = createOpenAICompatibleRuntime({ provider: ModelProvider.OpenAI });
+ const runtime = new Runtime({ apiKey: 'test' });
+ const text = 'Analysis summary.\n```json\n{"ready":true}\n```';
+ if (responseApi) {
+ vi.spyOn(runtime['client'].responses, 'create').mockResolvedValue({
+ output_text: text,
+ } as any);
+ } else {
+ vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue({
+ choices: [{ message: { content: text } }],
+ } as any);
+ }
+ await expect(
+ runtime.generateObject({
+ model: 'gpt-4o',
+ responseApi,
+ messages: [{ role: 'user', content: 'Return ready' }],
+ schema: {
+ name: 'ready',
+ schema: { type: 'object', properties: { ready: { type: 'boolean' } } },
+ },
+ }),
+ ).resolves.toEqual({ ready: true });
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index b5955744d3f..9bbb994c593 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -93,7 +93,11 @@ import {
recordOpenAIResponsesResponse,
resolveOpenAIResponseWithMetadata,
} from './providerDiagnostics';
-import { parseStructuredToolArguments, StructuredOutputError } from './structuredOutput';
+import {
+ parseStructuredOutputText,
+ parseStructuredToolArguments,
+ StructuredOutputError,
+} from './structuredOutput';
export type { PollVideoStatusResult };
export * from './createVideo';
@@ -1233,15 +1237,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
const text = res.output_text;
log('received structured output from Responses API, length: %d', text?.length || 0);
- try {
- const result = JSON.parse(text);
- log('successfully parsed JSON output');
- return result;
- } catch (error) {
- log('failed to parse JSON output: %O', error);
- console.error('parse json error:', text);
- return undefined;
- }
+ return parseStructuredOutputText(text);
}
log('calling chat.completions.create for structured output');
@@ -1275,19 +1271,11 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
}
- const text = res.choices[0].message.content!;
+ const text = res.choices?.[0]?.message?.content;
log('received structured output from Chat Completions API, length: %d', text?.length || 0);
- try {
- const result = JSON.parse(text);
- log('successfully parsed JSON output');
- return result;
- } catch (error) {
- log('failed to parse JSON output: %O', error);
- console.error('parse json error:', text);
- return undefined;
- }
+ return parseStructuredOutputText(text);
} catch (error) {
// Provider HTTP normalization must not hide the structured-output recovery signal.
if (error instanceof StructuredOutputError) throw error;
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.test.ts
new file mode 100644
index 00000000000..dca9e18bf21
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseStructuredOutputText } from './structuredOutput';
+
+describe('parseStructuredOutputText', () => {
+ it.each([
+ '{"ready":true}',
+ '```json\n{"ready":true}\n```',
+ '```JSON\n{"ready":true}\n```',
+ '```JsOn\n{"ready":true}\n```',
+ 'Summary\n```json\r\n{"ready":true}\r\n```\nDone',
+ '```\n{"ready":true}\n```',
+ ])('reads a single unambiguous JSON value: %s', (text) => {
+ expect(parseStructuredOutputText(text)).toEqual({ ready: true });
+ });
+ it('preserves fence literals inside JSON strings', () => {
+ expect(parseStructuredOutputText('```json\n{"snippet":"```"}\n```')).toEqual({
+ snippet: '```',
+ });
+ });
+ it.each(['[1,2]', 'null', 'true'])('preserves valid JSON schema output %s', (text) => {
+ expect(parseStructuredOutputText(text)).toEqual(JSON.parse(text));
+ });
+ it.each([
+ undefined,
+ '',
+ 'private secret',
+ '```json\n{"private":\n```',
+ '```json\n{}\n```\n```json\n{}\n```',
+ '```javascript\n{}\n```',
+ '```json\n{}',
+ '```json\n{bad}\n```',
+ ])('rejects missing, invalid or ambiguous output without leaking it', (text) => {
+ expect(() => parseStructuredOutputText(text)).toThrowError(
+ /^Invalid structured output: (missing|invalid) JSON response text$/,
+ );
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.ts
index c24eee241b2..3405ab726ca 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.ts
@@ -21,3 +21,30 @@ export const parseStructuredToolArguments = (value: unknown): Record<string, unk
}
return parsed as Record<string, unknown>;
};
+
+/** Parse schema output, tolerating one fenced JSON block without repairing its contents. */
+export const parseStructuredOutputText = (value: unknown): unknown => {
+ if (typeof value !== 'string' || !value.trim()) {
+ throw new StructuredOutputError('missing JSON response text');
+ }
+ try {
+ return JSON.parse(value);
+ } catch {
+ // Some compatible providers wrap a valid response in Markdown despite json_schema.
+ // Only standalone fence lines delimit blocks; JSON strings may contain backticks.
+ const fences = [...value.matchAll(/^[ \t]*```([^\r\n]*)\r?$/gm)];
+ if (
+ fences.length === 2 &&
+ ['', 'json'].includes(fences[0][1].trim().toLowerCase()) &&
+ fences[1][1].trim() === ''
+ ) {
+ const contents = value.slice(fences[0].index! + fences[0][0].length, fences[1].index);
+ try {
+ return JSON.parse(contents);
+ } catch {
+ // Preserve the same explicit failure and never include private response text.
+ }
+ }
+ throw new StructuredOutputError('invalid JSON response text');
+ }
+};
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index a92ec3c610d..8d23093dbbf 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -4,6 +4,7 @@ export { mergeModelRuntimeHooks } from './core/mergeHooks';
export type { ModelRuntimeHooks } from './core/ModelRuntime';
export { ModelRuntime } from './core/ModelRuntime';
export { createOpenAICompatibleRuntime } from './core/openaiCompatibleFactory';
+export { StructuredOutputError } from './core/openaiCompatibleFactory/structuredOutput';
export * from './core/RouterRuntime';
export { createCallbacksTransformer } from './core/streams/protocol';
export * from './core/usageConverters';