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(agent-runtime): sanitize invalid tool_call arguments to unbreak strict providers (#14033)

Arvin Xu6d339d6a6496
diff --git a/packages/context-engine/src/processors/ToolCall.ts b/packages/context-engine/src/processors/ToolCall.ts
index 9e4cd1c713e..64a3ba8f9a3 100644
--- a/packages/context-engine/src/processors/ToolCall.ts
+++ b/packages/context-engine/src/processors/ToolCall.ts
@@ -1,3 +1,4 @@
+import { sanitizeToolCallArguments } from '@lobechat/utils';
import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
@@ -129,11 +130,15 @@ export class ToolCallProcessor extends BaseProcessor {
return message;
}
- // Convert tools to tool_calls format
+ // Convert tools to tool_calls format.
+ // Sanitize `arguments` as a last line of defense against historical messages
+ // whose tool_calls arguments are invalid JSON (e.g. persisted before the
+ // server-side sanitizer landed, or produced by an older client). Strict
+ // providers like NVIDIA NIM otherwise 400 on the entire request. See LOBE-7761.
const tool_calls = message.tools.map(
(tool: any): MessageToolCall => ({
function: {
- arguments: tool.arguments,
+ arguments: sanitizeToolCallArguments(tool.arguments),
name: this.config.genToolCallingName
? this.config.genToolCallingName(tool.identifier, tool.apiName, tool.type)
: `${tool.identifier}.${tool.apiName}`,
diff --git a/packages/context-engine/src/processors/__tests__/ToolCall.test.ts b/packages/context-engine/src/processors/__tests__/ToolCall.test.ts
index d82fa3ca3d0..b1966f7f2cb 100644
--- a/packages/context-engine/src/processors/__tests__/ToolCall.test.ts
+++ b/packages/context-engine/src/processors/__tests__/ToolCall.test.ts
@@ -263,6 +263,57 @@ describe('ToolCallProcessor', () => {
role: 'assistant',
});
});
+
+ // LOBE-7761: protect against history poisoning from invalid tool_call arguments
+ it('should sanitize invalid tool arguments in history to "{}"', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: '',
+ id: 'msg1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'executeCode',
+ // exact shape from the LOBE-7761 NVIDIA/Qwen trace
+ arguments: '{, "description": "Create data models", "language": "python"}',
+ id: 'call_1',
+ identifier: 'code',
+ type: 'builtin',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].tool_calls[0].function.arguments).toBe('{}');
+ });
+
+ it('should pass through valid tool arguments unchanged (prompt-cache stable)', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const rawArgs = '{"description":"Create data models","language":"python"}';
+ const context = createContext([
+ {
+ content: '',
+ id: 'msg1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'executeCode',
+ arguments: rawArgs,
+ id: 'call_1',
+ identifier: 'code',
+ type: 'builtin',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].tool_calls[0].function.arguments).toBe(rawArgs);
+ });
});
describe('process - tool messages', () => {
diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
index 5ad886acee9..91697dcb95f 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts
@@ -272,6 +272,42 @@ describe('anthropicHelpers', () => {
]);
});
+ it('logs and falls back to empty input when tool_call arguments are invalid JSON', async () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const message: OpenAIChatMessage = {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ id: 'call_bad',
+ type: 'function',
+ function: {
+ name: 'search',
+ // LOBE-7761 Qwen shape β€” upstream sanitize should catch this, but
+ // if it doesn't we want noise in the logs rather than a silent drop.
+ arguments: '{, "query": "anthropic"}',
+ },
+ },
+ ],
+ };
+
+ const result = await buildAnthropicMessage(message);
+
+ expect(result!.content).toEqual([
+ { id: 'call_bad', input: {}, name: 'search', type: 'tool_use' },
+ ]);
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'parse tool call arguments error:',
+ expect.objectContaining({
+ id: 'call_bad',
+ name: 'search',
+ arguments: '{, "query": "anthropic"}',
+ }),
+ expect.any(Error),
+ );
+ consoleErrorSpy.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 c1b8262a157..ee760f91a7c 100644
--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts
+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts
@@ -179,7 +179,18 @@ export const buildAnthropicMessage = async (
let input: Record<string, unknown> = {};
try {
input = JSON.parse(tool.function.arguments);
- } catch {}
+ } catch (error) {
+ // Surface the failure instead of silently falling back to `{}`.
+ // Bad arguments should be sanitized upstream (context-engine
+ // ToolCallProcessor); if we reach here it means the defense
+ // was bypassed and the Anthropic call will proceed with empty
+ // input β€” worth knowing about.
+ console.error(
+ 'parse tool call arguments error:',
+ { id: tool.id, name: tool.function.name, arguments: tool.function.arguments },
+ error,
+ );
+ }
return {
id: tool.id,
input,
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 1ccaae093a9..b1c20e92992 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -18,6 +18,7 @@ export * from './object';
export * from './platform';
export * from './pricing';
export * from './safeParseJSON';
+export * from './sanitizeToolCallArguments';
export * from './sleep';
export * from './uriParser';
export * from './url';
diff --git a/packages/utils/src/sanitizeToolCallArguments.test.ts b/packages/utils/src/sanitizeToolCallArguments.test.ts
new file mode 100644
index 00000000000..5848387b480
--- /dev/null
+++ b/packages/utils/src/sanitizeToolCallArguments.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+
+import { sanitizeToolCallArguments } from './sanitizeToolCallArguments';
+
+describe('sanitizeToolCallArguments', () => {
+ it('passes valid JSON through unchanged to preserve prompt-cache keys', () => {
+ const input = '{"description":"Create data models","language":"python"}';
+ expect(sanitizeToolCallArguments(input)).toBe(input);
+ });
+
+ it('preserves whitespace and key order of valid JSON', () => {
+ const input = '{\n "a": 1,\n "b": 2\n}';
+ expect(sanitizeToolCallArguments(input)).toBe(input);
+ });
+
+ it('returns "{}" for empty string', () => {
+ expect(sanitizeToolCallArguments('')).toBe('{}');
+ });
+
+ it('returns "{}" for undefined', () => {
+ expect(sanitizeToolCallArguments(undefined)).toBe('{}');
+ });
+
+ it('falls back to "{}" on LOBE-7761 shape "{, ..."', () => {
+ // exact shape from the reported NVIDIA/Qwen trace
+ const input = '{, "description": "Create data models", "language": "python"}';
+ expect(sanitizeToolCallArguments(input)).toBe('{}');
+ });
+
+ it('falls back to "{}" for unrecoverable garbage', () => {
+ expect(sanitizeToolCallArguments('not json at all')).toBe('{}');
+ expect(sanitizeToolCallArguments('{{{')).toBe('{}');
+ });
+
+ it('recovers truncated JSON via partial-json and re-stringifies', () => {
+ // truncated mid-stream (common when max_tokens is exhausted)
+ const input = '{"description": "Create data models", "language": "py';
+ const out = sanitizeToolCallArguments(input);
+ const parsed = JSON.parse(out);
+ expect(parsed.description).toBe('Create data models');
+ // partial-json may or may not recover the truncated final key; either
+ // way, the output must be valid JSON
+ });
+
+ it('is idempotent on "{}"', () => {
+ expect(sanitizeToolCallArguments('{}')).toBe('{}');
+ expect(sanitizeToolCallArguments(sanitizeToolCallArguments('{}'))).toBe('{}');
+ });
+
+ it('does not widen scalar JSON to "{}"', () => {
+ // `null` / numbers / booleans are valid JSON β€” callers that want object
+ // arguments should enforce that separately. We only guarantee parseability.
+ expect(sanitizeToolCallArguments('null')).toBe('null');
+ expect(sanitizeToolCallArguments('123')).toBe('123');
+ expect(sanitizeToolCallArguments('true')).toBe('true');
+ });
+});
diff --git a/packages/utils/src/sanitizeToolCallArguments.ts b/packages/utils/src/sanitizeToolCallArguments.ts
new file mode 100644
index 00000000000..097c1747e34
--- /dev/null
+++ b/packages/utils/src/sanitizeToolCallArguments.ts
@@ -0,0 +1,29 @@
+import { safeParseJSON, safeParsePartialJSON } from './safeParseJSON';
+
+/**
+ * Ensure a tool_call `arguments` string is always valid JSON before it
+ * enters history or gets replayed to providers.
+ *
+ * Strict providers (e.g. NVIDIA NIM) validate the full message history on
+ * every request. A single malformed `arguments` string β€” even one produced
+ * many turns ago β€” causes a 400 on the entire request, terminating the op
+ * and wasting all accumulated tokens. See LOBE-7761.
+ *
+ * Behavior:
+ * - Valid JSON β†’ returned as-is (preserves prompt-cache keys).
+ * - Recoverable via partial-json β†’ re-stringified.
+ * - Unrecoverable β†’ "{}" so the tool_call structure survives and the
+ * model can replan on the next turn.
+ */
+export const sanitizeToolCallArguments = (argsStr: string | undefined): string => {
+ if (typeof argsStr !== 'string' || argsStr.length === 0) return '{}';
+
+ if (safeParseJSON(argsStr) !== undefined) return argsStr;
+
+ const recovered = safeParsePartialJSON(argsStr);
+ if (recovered !== undefined && typeof recovered === 'object' && recovered !== null) {
+ return JSON.stringify(recovered);
+ }
+
+ return '{}';
+};
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index b2261ae357c..cf7d128cbfe 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -29,7 +29,7 @@ import { parse } from '@lobechat/conversation-flow';
import { consumeStreamUntilDone } from '@lobechat/model-runtime';
import { chainCompressContext } from '@lobechat/prompts';
import { type ChatToolPayload, type MessageToolCall, type UIChatMessage } from '@lobechat/types';
-import { serializePartsForStorage } from '@lobechat/utils';
+import { sanitizeToolCallArguments, serializePartsForStorage } from '@lobechat/utils';
import debug from 'debug';
import { type MessageModel, MessageModel as MessageModelClass } from '@/database/models/message';
@@ -819,7 +819,14 @@ export const createRuntimeExecutors = (
},
onToolsCalling: async ({ toolsCalling: raw }) => {
const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);
- // Attach source (origin) and executor (dispatch target) for routing
+ // Attach source (origin) and executor (dispatch target) for routing.
+ // `arguments` are kept RAW here on purpose so the tool executor can
+ // still detect malformed JSON and return an `INVALID_JSON_ARGUMENTS`
+ // tool-result with the original bad string β€” that's the
+ // self-reflection signal the model needs to fix its own output.
+ // Sanitization happens later, only at the persist boundaries
+ // (DB write and state.messages push) to protect strict providers
+ // replaying history. See LOBE-7761.
const payload = resolvedCalls.map((p) => ({
...p,
executor: resolved.executorMap?.[p.identifier],
@@ -949,13 +956,24 @@ export const createRuntimeExecutors = (
metadata.isMultimodal = true;
}
+ // Sanitize tool_call `arguments` before persisting to DB so malformed
+ // JSON (e.g. Qwen emitting `{, ...}`) can't poison future context
+ // builds and 400 strict providers like NVIDIA NIM. See LOBE-7761.
+ const persistedTools =
+ toolsCalling.length > 0
+ ? toolsCalling.map((t) => ({
+ ...t,
+ arguments: sanitizeToolCallArguments(t.arguments),
+ }))
+ : undefined;
+
await ctx.messageModel.update(assistantMessageItem.id, {
content: finalContent,
imageList: imageList.length > 0 ? imageList : undefined,
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
reasoning: finalReasoning,
search: grounding,
- tools: toolsCalling.length > 0 ? toolsCalling : undefined,
+ tools: persistedTools,
});
} catch (error) {
console.error('[call_llm] Failed to update message:', error);
@@ -971,12 +989,26 @@ export const createRuntimeExecutors = (
// falls through to a DB query; when human-approve fires on the
// fresh LLM turn, both code paths miss and the op errors with
// "No assistant message found as parent for pending tool messages".
+ // Sanitize mirrors the DB write above β€” state.messages flows into the
+ // next LLM call payload, so the same poisoning risk applies here.
+ // See LOBE-7761.
+ const stateToolCalls =
+ tool_calls.length > 0
+ ? tool_calls.map((tc) => ({
+ ...tc,
+ function: {
+ ...tc.function,
+ arguments: sanitizeToolCallArguments(tc.function.arguments),
+ },
+ }))
+ : undefined;
+
newState.messages.push({
content,
id: assistantMessageItem.id,
reasoning: finalReasoning,
role: 'assistant',
- tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
+ tool_calls: stateToolCalls,
});
if (currentStepUsage) {
diff --git a/src/server/services/toolExecution/__tests__/builtin.test.ts b/src/server/services/toolExecution/__tests__/builtin.test.ts
index 2cb242e5a92..288b63e8bab 100644
--- a/src/server/services/toolExecution/__tests__/builtin.test.ts
+++ b/src/server/services/toolExecution/__tests__/builtin.test.ts
@@ -97,6 +97,25 @@ describe('BuiltinToolsExecutor truncated arguments', () => {
expect(mockApiHandler).not.toHaveBeenCalled();
});
+ // LOBE-7761: verify the self-reflection signal survives the new persist-time
+ // sanitizer. The fix sanitizes `tool_calls[].arguments` only at DB/state
+ // boundaries (to unbreak strict providers), so the raw bad string must still
+ // reach the executor β€” otherwise the model loses the "fix your JSON syntax"
+ // feedback and degrades to a generic "missing required field" error.
+ it('emits INVALID_JSON_ARGUMENTS for the LOBE-7761 Qwen shape with raw args echoed', async () => {
+ const invalid = '{, "description": "Create data models", "language": "python"}';
+
+ const result = await executor.execute(buildPayload(invalid), context);
+
+ expect(result.success).toBe(false);
+ expect(result.error?.code).toBe('INVALID_JSON_ARGUMENTS');
+ expect(result.content).toMatch(/not valid JSON/);
+ // Critical: the raw malformed string must appear in the tool-result content
+ // so the model can self-correct based on what it actually produced.
+ expect(result.content).toContain(invalid);
+ expect(mockApiHandler).not.toHaveBeenCalled();
+ });
+
it('still dispatches normally when argsStr is empty', async () => {
mockApiHandler.mockResolvedValueOnce({ content: 'ok', success: true });