Skip to content

Studio: coerce tool_call arguments to dict before chat templating (fixes MLX tool follow-up error) - #6807

Merged
danielhanchen merged 11 commits into
mainfrom
studio-tool-call-arguments-dict
Jul 6, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-tool-call-arguments-dict

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On MLX (and any transformers model with a strict tool chat template), a second agentic turn after a successful tool call errors with:

Error: Can only get item pairs from a mapping.

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 serializes function.arguments to a JSON string (the OpenAI wire format, also what the GGUF / llama-server path expects). But the MLX and transformers paths call apply_chat_template directly, and stricter Jinja tool templates (e.g. the mlx-community Qwen3.5 checkpoints) iterate arguments.items() and raise TypeError: 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.arguments from a JSON string to a dict inside apply_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

  • Against the real mlx-community/Qwen3.5-2B-8bit template: string args raised the tester's exact error; with the fix it renders cleanly (len 1415). Lenient unsloth/Qwen3.5-0.8B still 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.

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.

@gemini-code-assist gemini-code-assist Bot 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.

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.

pre-commit-ci Bot and others added 3 commits July 2, 2026 10:31
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +22 to +24
from core.inference.chat_template_helpers import ( # noqa: E402
_normalize_tool_call_arguments,
apply_chat_template_for_generation,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +22 to +25
from core.inference.chat_template_helpers import ( # noqa: E402
_normalize_tool_call_arguments,
apply_chat_template_for_generation,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 6b45dc20e6

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 5, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: eb53bc0e5c

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 1bac08d260

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen
danielhanchen merged commit e9ea45b into main Jul 6, 2026
36 of 38 checks passed
@danielhanchen
danielhanchen deleted the studio-tool-call-arguments-dict branch July 6, 2026 17:12
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.

1 participant