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(model-runtime): guard tool_use.input against non-object parsed arguments (#14150)

Arvin Xu22e6e1dbcc88
diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
index 91697dcb95f..a1e830bb879 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
@@ -308,6 +308,134 @@ describe('anthropicHelpers', () => {
consoleErrorSpy.mockRestore();
});
+ it('recovers tool_call input from a single-element array (model wrapped args in [])', async () => {
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const message: OpenAIChatMessage = {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ id: 'call_wrapped',
+ type: 'function',
+ function: {
+ name: 'search',
+ arguments: '[{"query":"anthropic"}]',
+ },
+ },
+ ],
+ };
+
+ const result = await buildAnthropicMessage(message);
+
+ expect(result!.content).toEqual([
+ { id: 'call_wrapped', input: { query: 'anthropic' }, name: 'search', type: 'tool_use' },
+ ]);
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('recovered from array'),
+ expect.objectContaining({
+ arrayLength: 1,
+ id: 'call_wrapped',
+ name: 'search',
+ }),
+ );
+ consoleWarnSpy.mockRestore();
+ });
+
+ it('recovers tool_call input from element[0] when arguments parse to a multi-element array', async () => {
+ // LOBE-8201 β€” model emitted long writeLocalFile args containing many
+ // unescaped quotes, which JSON.parse re-segmented into a top-level array.
+ // element[0] usually still carries the first legit key (e.g. `content`),
+ // so prefer partial recovery over total loss.
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const message: OpenAIChatMessage = {
+ content: 'fix:',
+ role: 'assistant',
+ tool_calls: [
+ {
+ id: 'call_array',
+ type: 'function',
+ function: {
+ name: 'writeLocalFile',
+ arguments: '[{"content":"a"},{"content":"b"}]',
+ },
+ },
+ ],
+ };
+
+ const result = await buildAnthropicMessage(message);
+
+ expect(result!.content).toEqual([
+ { text: 'fix:', type: 'text' },
+ {
+ id: 'call_array',
+ input: { content: 'a' },
+ name: 'writeLocalFile',
+ type: 'tool_use',
+ },
+ ]);
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('recovered from array'),
+ expect.objectContaining({
+ arrayLength: 2,
+ id: 'call_array',
+ name: 'writeLocalFile',
+ }),
+ );
+ consoleWarnSpy.mockRestore();
+ });
+
+ it('falls back to {} when arguments parse to an empty array', async () => {
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const message: OpenAIChatMessage = {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ id: 'call_empty_array',
+ type: 'function',
+ function: { name: 'noop', arguments: '[]' },
+ },
+ ],
+ };
+
+ const result = await buildAnthropicMessage(message);
+
+ expect(result!.content).toEqual([
+ { id: 'call_empty_array', input: {}, name: 'noop', type: 'tool_use' },
+ ]);
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('fallback to {}'),
+ expect.objectContaining({ id: 'call_empty_array', parsedType: 'array' }),
+ );
+ consoleWarnSpy.mockRestore();
+ });
+
+ it('warns and falls back to empty input when tool_call arguments parse to null', async () => {
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const message: OpenAIChatMessage = {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ id: 'call_null',
+ type: 'function',
+ function: { name: 'noop', arguments: 'null' },
+ },
+ ],
+ };
+
+ const result = await buildAnthropicMessage(message);
+
+ expect(result!.content).toEqual([
+ { id: 'call_null', input: {}, name: 'noop', type: 'tool_use' },
+ ]);
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('tool_use.input fallback to {}'),
+ expect.objectContaining({ id: 'call_null', parsedType: 'null' }),
+ );
+ consoleWarnSpy.mockRestore();
+ });
+
it('should correctly convert function message', async () => {
const message: OpenAIChatMessage = {
content: 'def hello(name):\n return f"Hello {name}"',
diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
index ee760f91a7c..14e1d48456c 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
@@ -178,7 +178,50 @@ export const buildAnthropicMessage = async (
...(message.tool_calls.map((tool) => {
let input: Record<string, unknown> = {};
try {
- input = JSON.parse(tool.function.arguments);
+ const parsed = JSON.parse(tool.function.arguments);
+ // Anthropic requires tool_use.input to be a plain object.
+ // Models occasionally emit malformed JSON whose top-level shape
+ // is an array / null / primitive (e.g. unescaped quotes inside
+ // a long string arg make the parser re-segment the payload).
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ input = parsed;
+ } else if (
+ Array.isArray(parsed) &&
+ parsed.length > 0 &&
+ parsed[0] &&
+ typeof parsed[0] === 'object' &&
+ !Array.isArray(parsed[0])
+ ) {
+ // Best-effort recovery: either the model wrapped the args
+ // in `[...]` (length === 1, full recovery) or unescaped
+ // quotes re-segmented the payload (partial recovery β€”
+ // parsed[0] usually still carries the first legit key,
+ // e.g. `content` for writeLocalFile).
+ input = parsed[0] as Record<string, unknown>;
+ console.warn(
+ '[anthropic] tool_use.input recovered from array β€” parsed arguments was wrapped in []',
+ {
+ argumentsLength: tool.function.arguments?.length,
+ arrayLength: parsed.length,
+ id: tool.id,
+ name: tool.function.name,
+ },
+ );
+ } else {
+ console.warn(
+ '[anthropic] tool_use.input fallback to {} β€” parsed arguments is not a plain object',
+ {
+ argumentsLength: tool.function.arguments?.length,
+ id: tool.id,
+ name: tool.function.name,
+ parsedType: Array.isArray(parsed)
+ ? 'array'
+ : parsed === null
+ ? 'null'
+ : typeof parsed,
+ },
+ );
+ }
} catch (error) {
// Surface the failure instead of silently falling back to `{}`.
// Bad arguments should be sanitized upstream (context-engine
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.ts
index 0eb25498af1..0f70c2985e2 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts
@@ -288,6 +288,44 @@ describe('google contextBuilders', () => {
});
});
+ it('recovers functionCall.args from element[0] when arguments parse to an array', async () => {
+ // LOBE-8201 β€” same defense as Anthropic: prefer partial recovery from
+ // element[0] over total loss when malformed JSON parses to an array.
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const message = {
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '[{"content":"a"},{"content":"b"}]',
+ name: 'writeLocalFile',
+ },
+ id: 'call_array',
+ type: 'function',
+ },
+ ],
+ } as OpenAIChatMessage;
+
+ const converted = await buildGoogleMessage(message);
+
+ expect(converted).toEqual({
+ parts: [
+ {
+ functionCall: { args: { content: 'a' }, name: 'writeLocalFile' },
+ },
+ ],
+ role: 'model',
+ });
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('functionCall.args recovered from array'),
+ expect.objectContaining({
+ arrayLength: 2,
+ name: 'writeLocalFile',
+ }),
+ );
+ consoleWarnSpy.mockRestore();
+ });
+
it('should correctly convert function call message with thoughtSignature', async () => {
const message = {
role: 'assistant',
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index 62261be1488..0a8d418dc11 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -122,13 +122,49 @@ export const buildGoogleMessage = async (
// Handle assistant messages with tool_calls
if (!!message.tool_calls) {
return {
- parts: message.tool_calls.map<Part>((tool) => ({
- functionCall: {
- args: safeParseJSON(tool.function.arguments)!,
- name: tool.function.name,
- },
- thoughtSignature: tool.thoughtSignature,
- })),
+ parts: message.tool_calls.map<Part>((tool) => {
+ const parsed = safeParseJSON(tool.function.arguments);
+ // Gemini's functionCall.args requires a plain object, same constraint
+ // as Anthropic's tool_use.input. See anthropic.ts for the full
+ // recovery rationale.
+ let args: Record<string, unknown> = {};
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ args = parsed as Record<string, unknown>;
+ } else if (
+ Array.isArray(parsed) &&
+ parsed.length > 0 &&
+ parsed[0] &&
+ typeof parsed[0] === 'object' &&
+ !Array.isArray(parsed[0])
+ ) {
+ args = parsed[0] as Record<string, unknown>;
+ console.warn(
+ '[google] functionCall.args recovered from array β€” parsed arguments was wrapped in []',
+ {
+ argumentsLength: tool.function.arguments?.length,
+ arrayLength: parsed.length,
+ name: tool.function.name,
+ },
+ );
+ } else if (parsed !== undefined) {
+ console.warn(
+ '[google] functionCall.args fallback to {} β€” parsed arguments is not a plain object',
+ {
+ argumentsLength: tool.function.arguments?.length,
+ name: tool.function.name,
+ parsedType: Array.isArray(parsed)
+ ? 'array'
+ : parsed === null
+ ? 'null'
+ : typeof parsed,
+ },
+ );
+ }
+ return {
+ functionCall: { args, name: tool.function.name },
+ thoughtSignature: tool.thoughtSignature,
+ };
+ }),
role: 'model',
};
}