Skip to content

fix: handle malformed JSON in LiteLLM tool call arguments gracefully#5010

Open
yasumorishima wants to merge 2 commits intogoogle:mainfrom
yasumorishima:fix/malformed-tool-call-json
Open

fix: handle malformed JSON in LiteLLM tool call arguments gracefully#5010
yasumorishima wants to merge 2 commits intogoogle:mainfrom
yasumorishima:fix/malformed-tool-call-json

Conversation

@yasumorishima
Copy link
Copy Markdown

Summary

Fixes #5008

When a LiteLLM model returns malformed or truncated JSON in tool_call.function.arguments, the non-streaming response parser (_message_to_generate_content_response) previously crashed the entire invocation with JSONDecodeError.

This PR wraps the json.loads call in a try/except JSONDecodeError block, skips the affected tool call with a warning log, and continues processing any remaining valid tool calls.

Key design decisions:

  • Aligns the non-streaming path with the streaming path (_finalize_tool_call_response), which already handles this case
  • The warning log omits raw arguments and redacts the tool call ID to avoid leaking user data
  • Skipping (rather than raising) allows valid sibling tool calls in the same response to proceed

Testing plan

Unit tests added in tests/unittests/models/test_litellm.py:

  • test_message_to_generate_content_response_malformed_tool_call_json — mixed valid/malformed tool calls; verifies only valid ones are included in the response
  • test_message_to_generate_content_response_all_malformed_tool_calls — all tool calls malformed; verifies empty parts (no crash)
$ python -m pytest tests/unittests/models/test_litellm.py -v
...
247 passed in 6.20s

@rohityan rohityan self-assigned this Mar 26, 2026
When a LiteLLM model returns malformed or truncated JSON in
tool_call.function.arguments, the non-streaming response parser
now catches JSONDecodeError, logs a warning, and skips the
affected tool call instead of crashing the entire invocation.

The streaming path already handled this case; this fix aligns
the non-streaming path with the same behavior.

Fixes google#5008
Per CodeRabbit review: logger.warning no longer logs raw tool call
arguments or tool call id, which may contain user data.
@yasumorishima yasumorishima force-pushed the fix/malformed-tool-call-json branch from c670d6c to 3809fd5 Compare March 26, 2026 17:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[LiteLlm] JSONDecodeError on malformed tool_call.function.arguments crashes run before callbacks can recover

2 participants