🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: reject malformed structured tool responses (#20509)
Nekod28985a76642
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 3d4e7436772..815f407403f 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -3322,6 +3322,96 @@ describe('LobeOpenAICompatibleFactory', () => {});describe('tools parameter support', () => {+ it('preserves structured-output errors when a provider wraps generic errors', async () => {+ const handleError = vi.fn((error: any) => ({ error }));+ const Runtime = createOpenAICompatibleRuntime({+ provider: 'wrapped-provider',+ chatCompletion: { handleError },+ });+ const runtime = new Runtime({ apiKey: 'test' });+ vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue({+ choices: [],+ } as any);+ await expect(+ runtime.generateObject({+ messages: [{ role: 'user', content: 'Return a result' }],+ model: 'test-model',+ tools: [+ { type: 'function', function: { name: 'result', parameters: { type: 'object' } } },+ ],+ }),+ ).rejects.toMatchObject({+ name: 'StructuredOutputError',+ message: 'Invalid structured output: no tool calls returned',+ });+ expect(handleError).not.toHaveBeenCalled();+ });++ it.each([+ ['missing choices', {}, 'no tool calls'],+ ['empty choices', { choices: [] }, 'no tool calls'],+ ['missing message', { choices: [{}] }, 'no tool calls'],+ ['missing tools', { choices: [{ message: {} }] }, 'no tool calls'],+ ['empty tools', { choices: [{ message: { tool_calls: [] } }] }, 'no tool calls'],+ [+ 'invalid JSON',+ {+ choices: [+ { message: { tool_calls: [{ function: { name: 'result', arguments: '{broken' } }] } },+ ],+ },+ 'invalid JSON',+ ],+ [+ 'null arguments',+ {+ choices: [+ { message: { tool_calls: [{ function: { name: 'result', arguments: 'null' } }] } },+ ],+ },+ 'JSON object',+ ],+ ])(+ 'rejects %s with an actionable structured-output error',+ async (_label, response, reason) => {+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ response as any,+ );+ await expect(+ instance.generateObject({+ messages: [{ content: 'Return a result', role: 'user' }],+ model: 'test-model',+ tools: [+ { type: 'function', function: { name: 'result', parameters: { type: 'object' } } },+ ],+ }),+ ).rejects.toThrow(`Invalid structured output: ${reason}`);+ },+ );++ it.each([+ ['missing output', {}, 'no tool calls'],+ ['empty output', { output: [] }, 'no tool calls'],+ ['text output', { output: [{ type: 'message' }] }, 'no tool calls'],+ [+ 'invalid JSON',+ { output: [{ type: 'function_call', name: 'result', arguments: '{broken' }] },+ 'invalid JSON',+ ],+ ])('rejects Responses API %s', async (_label, response, reason) => {+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(response as any);+ await expect(+ instance.generateObject({+ messages: [{ content: 'Return a result', role: 'user' }],+ model: 'test-model',+ responseApi: true,+ tools: [+ { type: 'function', function: { name: 'result', parameters: { type: 'object' } } },+ ],+ }),+ ).rejects.toThrow(`Invalid structured output: ${reason}`);+ });+it('should handle tools parameter with multiple tools', async () => {const mockResponse = {choices: [@@ -3946,7 +4036,7 @@ describe('LobeOpenAICompatibleFactory', () => {expect(requestPayload).not.toHaveProperty('reasoning_effort');});- it('should return undefined when no tool call found', async () => {+ it('should reject when no tool call found', async () => {const mockResponse = {choices: [{@@ -3971,18 +4061,15 @@ describe('LobeOpenAICompatibleFactory', () => {},};- const result = await instanceWithToolCalling.generateObject(payload);-- expect(consoleSpy).toHaveBeenCalledWith(- 'no tool call found in structured output response:',- mockResponse.choices[0].message,+ await expect(instanceWithToolCalling.generateObject(payload)).rejects.toThrow(+ 'Invalid structured output: no tool calls',);- expect(result).toBeUndefined();+ expect(consoleSpy).not.toHaveBeenCalled();consoleSpy.mockRestore();});- it('should return undefined when tool call arguments parsing fails', async () => {+ it('should reject when tool call arguments parsing fails', async () => {const mockResponse = {choices: [{@@ -4015,13 +4102,10 @@ describe('LobeOpenAICompatibleFactory', () => {},};- const result = await instanceWithToolCalling.generateObject(payload);-- expect(consoleSpy).toHaveBeenCalledWith(- 'parse tool call arguments error:',- mockResponse.choices[0].message.tool_calls[0],+ await expect(instanceWithToolCalling.generateObject(payload)).rejects.toThrow(+ 'Invalid structured output: invalid JSON',);- expect(result).toBeUndefined();+ expect(consoleSpy).not.toHaveBeenCalled();consoleSpy.mockRestore();});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 70a99a64440..b5955744d3f 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -93,6 +93,7 @@ import {recordOpenAIResponsesResponse,resolveOpenAIResponseWithMetadata,} from './providerDiagnostics';+import { parseStructuredToolArguments, StructuredOutputError } from './structuredOutput';export type { PollVideoStatusResult };export * from './createVideo';@@ -1125,24 +1126,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an// Structural type keeps this compatible across openai SDK majors (v6// widened tool_calls to a function/custom union).- const toolCalls = res.choices[0].message.tool_calls as+ const toolCalls = res.choices?.[0]?.message?.tool_calls as{ function?: { arguments: string; name: string } }[] | undefined;const toolCall =toolCalls?.find((item) => item.function?.name === tool.function.name) ?? toolCalls?.[0];- if (!toolCall?.function) {- // tool_choice forces this function, so a missing tool call means the- // provider misbehaved — surface it instead of silently returning undefined- console.error('no tool call found in structured output response:', res.choices[0]?.message);- return undefined;- }+ if (!toolCall?.function) throw new StructuredOutputError('no tool calls returned');- try {- return JSON.parse(toolCall.function.arguments);- } catch {- console.error('parse tool call arguments error:', toolCall);- return undefined;- }+ return parseStructuredToolArguments(toolCall.function.arguments);}async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {@@ -1162,7 +1153,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anif (tools) {log('using tools-based generation');- return this.generateObjectWithTools(payload, options, usagePayload);+ return await this.generateObjectWithTools(payload, options, usagePayload);}if (!schema) throw new Error('tools or schema is required');@@ -1298,6 +1289,9 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anreturn undefined;}} catch (error) {+ // Provider HTTP normalization must not hide the structured-output recovery signal.+ if (error instanceof StructuredOutputError) throw error;+const handledError = this.handleError(error);if (@@ -1847,26 +1841,15 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anawait options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));}- const functionCalls = res.output?.filter((item: any) => item.type === 'function_call');+ const functionCalls = res.output?.filter((item) => item.type === 'function_call');log('received %d function calls from Responses API', functionCalls?.length || 0);- try {- const result = functionCalls?.map((item: any) => ({- arguments:- typeof item.arguments === 'string' ? JSON.parse(item.arguments) : item.arguments,- name: item.name,- }));- log(- 'successfully parsed function calls: %O',- result?.map((r) => r.name),- );- return result;- } catch (error) {- log('failed to parse tool call arguments: %O', error);- console.error('parse tool call arguments error:', res);- return undefined;- }+ if (!functionCalls?.length) throw new StructuredOutputError('no tool calls returned');+ return functionCalls.map((item) => ({+ arguments: parseStructuredToolArguments(item.arguments),+ name: item.name,+ }));}log('calling chat.completions.create for tool calling');@@ -1902,29 +1885,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anawait options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));}- const toolCalls = res.choices[0].message.tool_calls!;+ const toolCalls = res.choices?.[0]?.message?.tool_calls;+ if (!toolCalls?.length) throw new StructuredOutputError('no tool calls returned');- log('received %d tool calls from Chat Completions API', toolCalls?.length || 0);-- try {- const result = toolCalls.map((item) => {- // OpenAI SDK v6 made tool calls a function|custom union; lobehub only emits function calls.- const { function: fn } = item as OpenAI.ChatCompletionMessageFunctionToolCall;- return {- arguments: JSON.parse(fn.arguments),- name: fn.name,- };- });- log(- 'successfully parsed tool calls: %O',- result.map((r) => r.name),- );- return result;- } catch (error) {- log('failed to parse tool call arguments: %O', error);- console.error('parse tool call arguments error:', res);- return undefined;- }+ return toolCalls.map((item) => {+ if (!('function' in item) || !item.function) {+ throw new StructuredOutputError('function tool call required');+ }+ return {+ arguments: parseStructuredToolArguments(item.function.arguments),+ name: item.function.name,+ };+ });}};};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.tsnew file mode 100644index 00000000000..c24eee241b2--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/structuredOutput.ts@@ -0,0 +1,23 @@+/** An upstream structured-output response cannot satisfy the required tool-call contract. */+export class StructuredOutputError extends Error {+ constructor(reason: string) {+ super(`Invalid structured output: ${reason}`);+ this.name = 'StructuredOutputError';+ }+}++export const parseStructuredToolArguments = (value: unknown): Record<string, unknown> => {+ let parsed = value;+ if (typeof value === 'string') {+ try {+ parsed = JSON.parse(value);+ } catch {+ // Do not attach the raw response or parser error: both can contain private model output.+ throw new StructuredOutputError('invalid JSON in tool arguments');+ }+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new StructuredOutputError('JSON object required for tool arguments');+ }+ return parsed as Record<string, unknown>;+};