Repository navigation
Studio: coerce tool_call arguments to dict before chat templating (fixes MLX tool follow-up error) - #6807
Conversation
Strict tool chat templates (e.g. mlx-community Qwen3.5 checkpoints) iterate arguments.items() and raise "TypeError: Can only get item pairs from a mapping" when a prior assistant tool call is re-rendered on the next turn. The agentic loop stores arguments in the OpenAI JSON-string form (as_assistant_tool_call), which is correct on the wire and for llama-server, but the transformers / MLX paths apply_chat_template directly and hit the strict Jinja templates. Normalize each assistant tool_call's function.arguments from a JSON string to a dict inside apply_chat_template_for_generation (shared by both the MLX and safetensors paths). A dict renders on strict and lenient templates alike; non-JSON / non-dict values are left untouched, and the OpenAI-format as_assistant_tool_call (used by the GGUF path + API responses) is unchanged. Verified against the real mlx-community/Qwen3.5-2B-8bit template: string args raised the tester's error, the fix renders cleanly, and the lenient unsloth/Qwen3.5-0.8B template still works.
There was a problem hiding this comment.
Code Review
This pull request introduces a helper function _normalize_tool_call_arguments to parse assistant tool call arguments from JSON strings into dictionaries. This prevents errors in strict chat templates (such as Qwen) that expect a dictionary instead of a string. Additionally, comprehensive unit tests have been added to verify this behavior. There are no review comments, and the implementation looks solid, so I have no further feedback to provide.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
Render the original OpenAI string-arg form first and only coerce arguments to a dict when the template raises the mapping TypeError, instead of always coercing. Any template that already renders is now byte-identical (a template that emits arguments verbatim keeps the JSON string, not a Python dict repr). Verified across Llama-3, Qwen2.5, Qwen3, Qwen3.5, Phi-3.5 (byte-identical) and mlx-community/Qwen3.5-2B-8bit (strict -> fixed). Gemma-3 / Mistral tool-template errors are unrelated (role alternation / tool-id length) and identical with or without the change.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a07eef49ab
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| try: | ||
| return _render(messages) | ||
| except TypeError: |
There was a problem hiding this comment.
Retry normalization for non-TypeError template rejections
When a strict chat template rejects string function.arguments by raising its own exception instead of the Jinja items TypeError (the bundled Gemma templates call raise_exception for non-mapping arguments in studio/backend/assets/chat_templates/gemma-4.jinja:261), this except TypeError path is skipped, so valid OpenAI JSON argument strings are never coerced and follow-up generation still fails. Since the helper is meant to deserialize these strings before rendering strict templates, limiting the retry to TypeError leaves that class of templates broken.
Useful? React with 👍 / 👎.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9534cfd2b3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| from core.inference.chat_template_helpers import ( # noqa: E402 | ||
| _normalize_tool_call_arguments, | ||
| apply_chat_template_for_generation, |
There was a problem hiding this comment.
Load the helper without importing the inference package
In a dependency-light test environment, this import prevents the new regression test from being collected: Python executes core/inference/__init__.py before loading the submodule, which pulls in the backend orchestrator/logging stack (structlog, starlette, etc.). I checked by running pytest -q studio/backend/tests/test_chat_template_tool_arguments.py, and it fails during collection before exercising the helper. Since this file is specifically meant to unit-test the dependency-light helper, load chat_template_helpers.py directly (or stub the package imports) instead of importing through core.inference.
Useful? React with 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9534cfd2b3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| from core.inference.chat_template_helpers import ( # noqa: E402 | ||
| _normalize_tool_call_arguments, | ||
| apply_chat_template_for_generation, | ||
| ) |
There was a problem hiding this comment.
Avoid importing the helper through core.inference
In the lightweight backend test environment where structlog is not installed, this import executes core/inference/__init__.py before reaching the dependency-light helper, which pulls in orchestrator/loggers and fails during collection with ModuleNotFoundError: No module named 'structlog' when running pytest -q tests/test_chat_template_tool_arguments.py from studio/backend. Load chat_template_helpers.py directly by file path (as other dependency-light template tests do) or stub the heavy deps so this new regression test can run without the full Studio dependency set.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: core/inference/init.py is now lazy (PEP 562 getattr), so importing chat_template_helpers no longer runs the eager orchestrator/llama_cpp imports that pulled structlog. The test collects and passes standalone in a backend env without structlog, and the re-exports resolve unchanged on first access.
…ort standalone Importing any core.inference submodule ran the package __init__, which eagerly imported orchestrator and llama_cpp; both pull loggers -> structlog (and httpx), so a dependency-light helper like chat_template_helpers dragged in the full heavy stack and its unit test failed to collect in a backend env without structlog. Defer those imports to attribute access via PEP 562 __getattr__, mirroring the lazy pattern already in core/__init__.py. The re-exports resolve unchanged on first access.
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9ed85cc23f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| try: | ||
| return _render(messages) | ||
| except TypeError: |
There was a problem hiding this comment.
Handle strict templates that raise non-TypeError
If a local MLX/safetensors model uses a strict template that rejects string tool arguments via raise_exception instead of Jinja's items TypeError, this handler never normalizes the messages because _render records the generic exception and the outer retry only catches TypeError. Our bundled studio/backend/assets/chat_templates/gemma-4.jinja has exactly that validation pattern around lines 261-265, so a second tool turn with OpenAI string function.arguments still fails rather than retrying with the parsed dict.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in eb53bc0: the retry now also catches non-TypeError template errors (gemma-4.jinja rejects string arguments via raise_exception), still gated on there being a string arg to coerce, so the second tool turn re-renders with the parsed dict.
apply_chat_template_for_generation only retried the OpenAI JSON-string arguments coercion when the first render raised TypeError (the arguments.items() form). The bundled gemma-4.jinja instead rejects string arguments with raise_exception, which surfaces as a Jinja error, so a second tool turn with string function.arguments propagated and failed rather than retrying with the parsed dict. Broaden the outer catch to Exception, still gated on there being a string arg to normalize (normalized is messages -> re-raise), so unrelated template errors and templates that already render are unaffected.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Problem
On MLX (and any transformers model with a strict tool chat template), a second agentic turn after a successful tool call errors with:
The model calls the tool fine; the failure is on the follow-up generation once the prior tool call is in the conversation.
Root cause
The agentic loop appends the assistant tool call via
as_assistant_tool_call(), which serializesfunction.argumentsto a JSON string (the OpenAI wire format, also what the GGUF / llama-server path expects). But the MLX and transformers paths callapply_chat_templatedirectly, and stricter Jinja tool templates (e.g. themlx-communityQwen3.5 checkpoints) iteratearguments.items()and raiseTypeError: Can only get item pairs from a mapping.on the string form. Lenient templates (e.g.unsloth/Qwen3.5-0.8B) tolerate the string, which is why it only shows up on some checkpoints. Same class of bug as QwenLM/Qwen3-Coder#444.Fix
Normalize each assistant
tool_calls[].function.argumentsfrom a JSON string to a dict insideapply_chat_template_for_generation(the shared helper both the MLX and safetensors paths delegate to). A dict renders on strict and lenient templates alike; non-JSON / non-dict values are left untouched.as_assistant_tool_call()(OpenAI wire format, GGUF path, API responses, and its unit test) is unchanged.Validation
mlx-community/Qwen3.5-2B-8bittemplate: string args raised the tester's exact error; with the fix it renders cleanly (len 1415). Lenientunsloth/Qwen3.5-0.8Bstill renders.pytest tests/test_chat_template_tool_arguments.py(5 passing): string parsed to dict, dict untouched (no copy), non-JSON left as-is, strict-template render succeeds, non-tool messages pass through.