Repository navigation
fix: recover from truncated JSON in tool call arguments - #4974
giulio-leone wants to merge 10 commits into
Conversation
|
Great catch on the trailing backslash edge case! Fixed in 1cc9d4a — now strips an unescaped trailing backslash before appending the closing quote, so |
|
Fixed in 5a78724 — replaced |
|
@giulio-leone wouldn't patching the JSON in this way cause incorrect arguments to be sent to the tools? in which case you would need to retry the call to the LLM so might as well just do that when you detect invalid JSON? e.g. |
|
Valid concern — you're right that repair can produce semantically different arguments (e.g. The tradeoff is: partial-but-structurally-valid JSON lets the tool execute with whatever was received, while a hard failure loses the entire call. In practice, LLM truncation typically occurs at the end of long arguments (e.g., large arrays, long strings), so the repaired result is often semantically close enough for the tool to succeed or return a meaningful error. That said, a retry-on-invalid-JSON strategy is also valid. The two approaches could be complementary: retry first, and only repair as a last resort if retries are exhausted or not configured. Happy to add a configurable behavior if that aligns better with the project's philosophy. |
|
Great point, @rajveerappan — you're right that silent repair can produce semantically incorrect arguments (e.g. a truncated array element missing fields). The motivation was to avoid a hard crash for the agent when the LLM returns truncated JSON (which happens in streaming scenarios), since the alternative is A few options:
I'm happy to pivot to option 3 (retry) if that better fits the project's philosophy, or to option 1 (repair + warning) as a middle ground. What's your preference? |
|
@rajveerappan You raise a valid point — the repaired JSON may semantically differ from the LLM's intent. However, I think repair-then-proceed is the right default for this scenario:
That said, if the livekit team prefers a retry-first approach, I'm happy to restructure this as: (1) try repair → (2) validate → (3) if validation fails, raise so the caller can retry. The current design already does this — if repair + validation fails, the original |
|
Good point. The JSON repair is a best-effort recovery for malformed tool arguments that would otherwise hard-fail. It only patches obvious syntax issues (missing quotes, trailing commas) without changing semantic content. If the model returned genuinely wrong arguments, those would still be sent, but without repair the call would fail with a parse error anyway. If you prefer a retry-first strategy, I can restructure. |
|
Hi! Gentle ping — this PR is rebased, CI passes, and ready for review. Happy to address any feedback. Thanks! |
|
@rajveerappan Great point — you're right that repairing truncated JSON can produce structurally valid but semantically wrong arguments (your The intent of this fix is a best-effort recovery for cases where the truncation is minor (e.g., missing closing braces/brackets at the end), which is the most common pattern with streaming tool calls. In those cases, the actual key-value pairs that were transmitted are complete — only the structural closers are missing. That said, I think your suggestion has merit. Would you prefer one of these approaches?
Happy to adjust based on your preference. |
|
@rajveerappan You raised a great point — I've addressed it in 0537372. The problem: repaired JSON can be structurally valid but semantically wrong (your What changed: after repair, the repaired arguments are now validated against the tool's Pydantic schema before execution. If the repaired JSON is missing required fields (i.e. truncation dropped them), Additionally, Test coverage: added tests for the exact scenario you described (truncation drops a required field → schema validation rejects it), plus the opt-out path and the happy path where only structural closers are missing. |
|
I don't think this is the right approach here. we cannot be expected to recover useful parameters from broken model output. we've not seen this behavior before with azure gpt-4.1. my suspicion is that there's something going on with your particular deployment/environment; and it should not be handled within the framework |
|
Hi @davidzhao, thanks for the candid feedback — I appreciate you taking the time. You may well be right that this is environment-specific to certain Azure GPT-4.1 deployments. We observed it consistently in our setup (tied to issue #4240), but if it's not reproducible in other environments, I understand why adding recovery logic to the framework feels like the wrong layer to address it. A couple of notes in case they affect your thinking, but no pressure either way:
That said, if you feel this doesn't belong in the framework regardless, I completely respect that — happy to close this PR. Just let me know your preference and I'll act on it. Thanks again for maintaining this project! |
LLMs (notably GPT-4.1 on Azure) sometimes return truncated JSON in streaming tool call arguments, causing ValueError: 'EOF while parsing a string'. This happens when the streaming response is cut off before the JSON is complete. Add a JSON repair fallback in prepare_function_arguments() that: 1. Tries pydantic_core.from_json() first (fast path, unchanged) 2. On ValueError, attempts to repair the truncated JSON by closing open string literals, brackets, and braces 3. Logs a warning when repair succeeds 4. Re-raises with a descriptive error if repair also fails The repair handles the most common truncation patterns: - Unfinished string values (missing closing quote) - Missing closing braces/brackets - Combinations of the above Fixes #4240
Replaced independent bracket/brace counters with a stack that tracks
nesting order. This correctly repairs nested JSON like
'{"arr": [{"a": 1' → '{"arr": [{"a": 1}]}' instead of the
incorrect '{"arr": [{"a": 1]}}'.
Added test for nested object-in-array repair.
Strip unescaped trailing backslash before appending closing quote to avoid producing an escaped-quote instead of a real string terminator.
Use stack-based counting instead of endswith() to correctly detect odd numbers of trailing backslashes (>=3) in truncated JSON strings.
…y, fix docstring - Use from_json() instead of json.loads() for consistent parsing behavior - Log only metadata (preview + length) instead of full raw tool arguments - Fix test docstring to match actual input (odd number including 1) Refs: #4974
Address reviewer concern that repairing truncated JSON could send
semantically incorrect arguments to tools (e.g. `{"a": 1` repaired
to `{"a": 1}` when the tool also required a "b" field).
Changes:
- After JSON repair, validate the repaired arguments against the tool's
Pydantic schema. If validation fails (e.g. required fields were lost
in truncation), raise ValueError so the caller can retry the LLM call
instead of invoking the tool with incomplete arguments.
- Add `repair_json` parameter to `prepare_function_arguments()`
(default True) so callers can opt out of repair entirely and always
raise on malformed JSON.
- Add tests for schema-validation rejection, repair opt-out, and the
happy path where all required fields survive truncation.
|
since this is working for you, you can define your own |
Problem
LLMs (notably GPT-4.1 on Azure) sometimes return truncated JSON in streaming tool call arguments. When the streaming response is cut off before the JSON is complete,
from_json()raisesValueError: EOF while parsing a string, causing tool calls to fail entirely.From issue #4240, a real-world example of truncated output:
{"success":true,"reason":"The message explicitly asks the user to confirm if their name is John Doe"}Was received as:
{"success":true,"reason":"The message explicitly asks the userThis affects ~10% of tool calls for some users, particularly with Azure GPT-4.1.
Solution
Add a JSON repair fallback in
prepare_function_arguments():pydantic_core.from_json()is tried firstThe repair handles the most common truncation patterns:
Tests
Added
TestTruncatedJsonRepairwith 4 test cases:Fixes #4240