Skip to content

fix(llm): tolerate unparseable stored tool-call arguments in Anthropic/Google/AWS formatters - #6321

Merged
longcw merged 2 commits into
livekit:mainfrom
PranavMishra28:fix/provider-format-unparseable-tool-args
Aug 27, 2026
Merged

longcw merged 2 commits into
livekit:mainfrom
PranavMishra28:fix/provider-format-unparseable-tool-args

Conversation

@PranavMishra28

Copy link
Copy Markdown
Contributor

This PR contains:

  • New features
  • Changes to dev-tools e.g. CI config / github tooling
  • Docs
  • Bug fixes
  • Code refactor

What is the current behavior? (You can also link to an open issue here)

Fixes #6308.

FunctionCall.arguments holds the model's raw tool-call output and is only canonicalized to valid JSON when it parses successfully. When it can't be parsed β€” an open-weight model's output that json_repair can't recover (the call fails as a ToolError and the raw string persists), or history built outside the execution path (ChatContext.from_dict, a custom llm_node, restored session state) β€” the raw string stays in chat history verbatim.

The Anthropic, Google, and AWS chat-context formatters call json.loads(msg.arguments) directly in to_chat_ctx. A later, healthy turn that formats that history then raises json.JSONDecodeError and the whole request aborts. OpenAI and Mistral pass arguments through as an opaque string, so they don't hit this.

from livekit.agents.llm import ChatContext, FunctionCall, FunctionCallOutput

ctx = ChatContext.empty()
ctx.insert(FunctionCall(call_id="c1", name="lookup", arguments="not-a-json-object"))
ctx.insert(FunctionCallOutput(call_id="c1", name="lookup", output="tool error", is_error=True))
ctx.to_provider_format(format="anthropic")   # raises json.JSONDecodeError (same for "google" / "aws")

What is the new behavior?

Adds a shared parse_tool_call_arguments() helper in _provider_format/utils.py that returns the parsed dict when the stored arguments are a JSON object, and otherwise logs a warning and falls back to an empty object {}. The three JSON-object formatters call it instead of json.loads(...).

{} is preferred over a best-effort repair: the historical tool call already produced its output, so fabricating arguments the model never sent risks feeding wrong data back to the provider. A tool call's arguments are always a named-parameter object, so JSON that parses to a non-object (array, scalar, null) degrades the same way.

Tests added in tests/test_chat_ctx.py cover all three providers against unparseable arguments, a valid-args passthrough regression, and empty/non-object arguments. The unparseable/non-object cases fail on main (raise JSONDecodeError) and pass with this change.

Does this PR introduce a breaking change? (What changes might users need to make in their application due to this PR?)

No. Valid arguments format exactly as before; only previously-crashing inputs change behavior β€” from a raised JSONDecodeError to an empty-args object plus a warning log.

Other information:

Developed with Claude Code; reviewed and tested by Pranav before marking ready for review.

@CLAassistant

CLAassistant commented Jul 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@PranavMishra28
PranavMishra28 marked this pull request as ready for review July 5, 2026 01:32
@PranavMishra28
PranavMishra28 requested a review from a team as a code owner July 5, 2026 01:32
devin-ai-integration[bot]

This comment was marked as resolved.

@PranavMishra28
PranavMishra28 force-pushed the fix/provider-format-unparseable-tool-args branch from eaa86ee to 3e886e8 Compare July 7, 2026 00:06
… formats

The Anthropic, Google, and AWS chat-context formatters call
json.loads(msg.arguments) directly. FunctionCall.arguments is only
canonicalized to valid JSON when the model output parses; unparseable output
(unrecoverable open-weight calls, or history restored via ChatContext.from_dict)
persists verbatim, so formatting that history on a later turn raised
json.JSONDecodeError and aborted the whole request.

Add a shared parse_tool_call_arguments() helper that falls back to an empty
object (with a warning) when the arguments aren't a JSON object, and use it in
the three formatters. OpenAI/Mistral already pass arguments through as an opaque
string and are unaffected.

Fixes livekit#6308

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@PranavMishra28
PranavMishra28 force-pushed the fix/provider-format-unparseable-tool-args branch from 3e886e8 to 6cb0d1c Compare July 14, 2026 06:31
@PranavMishra28

Copy link
Copy Markdown
Contributor Author

@longcw rebased onto main so the conflict's cleared and CI's green again. small one β€” the anthropic/google/aws formatters call json.loads on stored tool-call args, so a call whose args never parsed takes down a later turn with a JSONDecodeError; this routes them through a shared helper that falls back to {} instead. mind a look when you get a sec? no rush

@longcw longcw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the pr! could you rebase it to main and something nit:

if not arguments:
return {}
try:
parsed = json.loads(arguments)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use parse_function_arguments from llm/utils.py?

…rguments

Per review: reuse llm/utils.py's parse_function_arguments instead of a local
json.loads. It raises ValueError when it cannot reach a dict, which is the right
contract for a live call the model can retry but not for replaying history, so
the wrapper catches that and falls back to {}.

Strictly better than the bare json.loads it replaces: json_repair, chat-template
token stripping and double-encoded unwrapping now apply to stored history too, so
arguments that would have been discarded are recovered instead. Covered by three
new cases (trailing comma, <|end|> leak, double-encoded); all nine fail against
the previous implementation.

The import is inside the function on purpose: llm/utils.py imports chat_context,
which imports this package, so a module-level import is a circular import.

Developed with Claude Code; reviewed and tested by Pranav before pushing.
@PranavMishra28

Copy link
Copy Markdown
Contributor Author

gimme 15

@PranavMishra28

Copy link
Copy Markdown
Contributor Author

both done, and your nit made the fix better than it was.

rebase. merged current main (259 commits). the only conflict was tests/test_chat_ctx.py, where your new _upsert_item tests and mine both landed at the end of the file β€” kept both sides, nothing dropped.

parse_function_arguments. switched to it. one adjustment: it raises ValueError when it can't reach a dict, which is the right contract where it's used today (a live call the model can retry next turn) but not here, since this path is replaying history that's already stored β€” raising is exactly the failure this PR exists to remove. so the wrapper catches ValueError and falls back to {}, and everything else is now yours.

that turns out to be a real upgrade over the json.loads I had, not just deduplication. json_repair, chat-template token stripping and double-encode unwrapping now apply to stored history too, so arguments my version would have thrown away come back intact:

stored arguments before after
{"a": 1,} {} {"a": 1}
{"a": <|end|>1} {} {"a": "end1"}
"{\"a\": 1}" (double-encoded) {} {"a": 1}

that matters more than it looks: ChatContext.from_dict history and custom llm_node output never went through prepare_function_arguments, so they were never canonicalized in the first place β€” those are precisely the entries that reach this code un-repaired. added three cases covering the above; all nine parametrizations fail against the old implementation, so they're not decorative.

one thing worth a second of your attention since it looks like sloppiness otherwise: the import is inside the function, deliberately. at module scope it's a cycle β€”

llm/__init__ -> remote_chat_context -> chat_context -> _provider_format/__init__
  -> anthropic -> _provider_format/utils -> llm/utils -> chat_context  (partially initialized)

ImportError: cannot import name 'ChatContext' from partially initialized module. the function-level import is the smallest thing that breaks it. the alternative is moving parse_function_arguments somewhere below chat_context in the import order, which is a real cleanup but a wider one than this PR should be making β€” happy to do it separately if you'd prefer that shape.

gate on the merged tree: ruff check clean, ruff format --check clean, check_types.py no issues in 644 source files, pytest tests/test_chat_ctx.py tests/test_tools.py 171 passed, 1 skipped.

your approval carried over the push, so this is yours to merge whenever β€” I don't have write access here.

@longcw
longcw merged commit 09cce87 into livekit:main Aug 27, 2026
12 checks passed
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.

to_provider_format crashes with JSONDecodeError when replaying a tool call whose arguments never parsed (Anthropic / Google / AWS)

3 participants