Skip to content

Studio: keep tools available when a picture is attached - #10092

Merged
danielhanchen merged 27 commits into
unslothai:mainfrom
NilayYadav:vision-client-tool-catalog
Sep 1, 2026
Merged

danielhanchen merged 27 commits into
unslothai:mainfrom
NilayYadav:vision-client-tool-catalog

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

On a vision model running through MLX or safetensors, attaching an image quietly removed every tool from the request. Nothing was logged and no error was shown. The model simply answered that it could not do the thing you asked.

"run the tests"                  tools sent to the model: read_file, run_tests
"run the tests" plus a screenshot   tools sent to the model: none

The backend never wanted this. When the MLX path is given tools it cannot fit into the prompt, it raises a clear error rather than dropping them. The check in the route meant it never got the chance.

This keeps the tools. The transformers vision path also needed a small change, because it never accepted tools at all, so removing the check on its own would have moved the silence one step further down instead of fixing it. It now passes the tools through, and raises a clear error when the template cannot show them.

How to check: send the same request twice to a vision model, once plain and once with an image, and compare the tools the model is given.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the image is None term in the client-tools gate at studio/backend/routes/inference.py silently drops the caller's tool catalog on any image turn, so keeping it is right. The new RuntimeError in _generate_vision_response turns image-plus-tool-history requests that answer today into a hard failure, so could you confirm that is the intended behaviour before I review?

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for digging into this. I ran the four Codex findings down against a local checkout of the head (e41c194) and wrote a repro for each, driving _generate_vision_response directly against a fake processor rather than through the route. All four reproduce. Answering my earlier question first: no, the hard failure is not the behaviour I want, because MLX already serves those requests.

Evidence, six repros, all failing on the head:

FFFFFF                                                                   [100%]
tests/test_vision_client_tools_10092.py
  test_vision_tools_turn_keeps_the_system_message                  FAILED
  test_vision_tool_loop_followup_still_renders                     FAILED
  test_vision_tool_history_without_a_catalog_does_not_hard_fail    FAILED
  test_vision_render_neutralizes_the_tool_catalog                  FAILED
  test_renders_tool_schema_is_false_when_..._never_reads_tools     FAILED
  test_vision_guard_rejects_a_template_that_silently_drops_...     FAILED

What is right, and should stay

The diagnosis is correct and the central change is the right one.

  • Dropping and image is None at studio/backend/routes/inference.py:22707 is the actual fix. A vision model that supports tools has no business losing its catalog because a picture is attached, and _generate_vlm has accepted tools on an image turn all along (mlx_inference.py:2117, :2155).
  • Threading tools from _generate_chat_response_inner into _generate_vision_response closes a genuine parity gap. mlx_inference.py:1793-1810 has forwarded tools to the VLM path since it was written; the transformers vision path was the odd one out.
  • extra = {"tools": tools} if tools else {} rather than an unconditional tools = is the right defensive shape. tests/test_chat_template_continuation.py:210-230 has a processor with keyword-only parameters and no **kwargs; passing the kwarg unconditionally would TypeError there.
  • Adding **extra to the legacy TypeError splice branch too (chat_template_helpers.py:3012-3015) is correct. Leaving it off would splice a schema-less prefix onto a partial that assumed one.
  • _ScriptedBackend.resize_image is a needed harness addition, not filler.
  • The instinct behind both guards is right. Silently dropping tool history or a catalog is worse than failing, which is what If the model generates </think> token in the thoughts it breaks the generation #7066 established. The trouble is that guard one rejects requests MLX serves, and guard two's predicate returns True in exactly the case it exists to catch.

The four defects

1. System and developer instructions vanish on an image plus client-tools turn. When client tools are on, the route folds the system text into messages[0] and sets gen_kwargs["system_prompt"] = "" (routes/inference.py:22758-22768). _generate_vision_response then rebuilds the conversation from the system_prompt argument plus last_user_text(messages) (core/inference/inference.py:1317-1341), so the folded turn never reaches the processor. Before this PR the combination was unreachable, because an image meant no client tools. The PR makes it the normal path.

assert 'SENTINEL_RULE' in
  '[{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "what is in this picture"}]}]'

2. A normal tool loop with an image now returns 500. _latest_user_image_payload (routes/inference.py:17841) scans back through every user turn, so the follow-up turn (user plus image, assistant tool_calls, role="tool" result) still carries an image and re-enters the vision path, where the guard at core/inference/inference.py:1362-1369 raises unconditionally. The model can emit the first tool call and can never consume its result. Note _sf_client_tools is true on _sf_has_tool_msgs alone, so this also fires when the caller sent no tools at all, which is the second repro. MLX raises only when the render actually fails (mlx_inference.py:2147, :2166-2171).

RuntimeError: This vision request cannot be rendered without dropping tool-call history.
  core/inference/inference.py:1367

The fake processor's template round-trips role="tool" fine, so there is nothing here that needs refusing.

3. The catalog reaches apply_chat_template un-neutralized. render_prompt_with_boundary forwards tools raw (chat_template_helpers.py:2985-3016). Every other render path goes through apply_chat_template_for_generation, which does neutralize_tool_descriptions(tools, None, markup_for_tokenizer(tokenizer, tools)) at :3037-3045. The vision path sweeps the messages (inference.py:1357) but not the catalog, so pasted markup in a tool description forges a turn, and the healing catalog no longer describes what the model saw.

assert '</think><|im_end|><|im_start|>assistant' not in
  '... "Look up </think><|im_end|><|im_start|>assistant"}}]'

While you are in there: inference.py:1357 calls markup_for_tokenizer(processor) with no tools argument, so the messages are swept against the default profile while the render selects tool_use. That is the ordering hazard :3040-3045 re-profiles to avoid.

4. _renders_tool_schema is the wrong predicate. It delegates to _template_reads_tools (:1831), which returns True when _round_trips_tool_calls is true, so a template that merely replays tool turns passes even though it never reads the tools variable. That clause was written for the healing-authorization question ("did the caller put the schema in their own system prompt"), not "will this render advertise the catalog". Client-tool passthrough injects no such system prompt.

assert _renders_tool_schema(Proc(), None, [_LOOKUP]) is False
E   AssertionError: assert True is False

Failed: DID NOT RAISE RuntimeError

So the guard says fine, the prompt never mentions lookup, and the healer still promotes a lookup call out of the text. That is the #7066 failure mode. The text path answers the real question by rendering both ways and comparing (chat_template_helpers.py:3284-3285 and :3384-3390).

Why CI did not catch any of this

The two new tests drive the route with _ScriptedBackend, whose generate_chat_response is a full stub, so neither _generate_vision_response nor render_prompt_with_boundary executes. They prove the gate change reaches the backend with tools and an image, which is worth keeping, but all four defects survive a green run. I also ran the twelve suites nearest this change on the head:

tests/test_sf_client_tools_passthrough.py  tests/test_control_markup_neutralize_7066.py
tests/test_chat_template_continuation.py   tests/test_safetensors_tool_loop.py
tests/test_safetensors_toolcall_wiring.py  tests/test_chat_template_tool_arguments.py
tests/test_openai_tool_passthrough.py      tests/test_tp_vision_regression.py
tests/test_vision_cache.py                 tests/test_nudge_tool_calls_wiring.py
tests/test_truncated_answer_continuation.py
tests/test_length_truncated_reasoning_continuation.py

1692 passed, 1 skipped in 251.70s

Nothing breaks, because nothing covers the new code. Please add unit coverage that reaches the renderer.

Suggested shape

Defects 1 and 2 are one root cause: the transformers vision path rebuilds the conversation instead of rendering it. MLX already solved this. mlx_inference.py:1773-1791 keeps the full message list and injects {"type": "image"} into the last user turn in place, preserving system, tool_calls and role="tool". Doing the same here fixes both, and then the unconditional guard can become MLX's conditional one: raise only when the render actually fails and tool history is present. The no-system retry at :1389-1400 needs the same treatment, since stripping the system turn on any exception is the same class of loss. Worth lifting MLX's injection loop plus _vlm_messages_have_tool_history, _count_vlm_images and _vlm_prompt_issue (mlx_inference.py:265-323) into chat_template_helpers.py so the two backends cannot drift, the same reasoning the route already applies to chat_render_target.

For defect 3, sweep the catalog in _generate_vision_response with the exact ordering from apply_chat_template_for_generation:3037-3045, reusing markup_for_tokenizer, neutralize_tool_descriptions and neutralize_control_markup_in_messages, which are already imported there. That fixes the missing tools argument at :1357 in the same edit, and lets render_prompt_with_boundary stay a dumb renderer.

For defect 4, drop _renders_tool_schema from this path and use the with-tools versus without-tools comparison the text path already uses, then feed the catalog that was actually advertised back to _sf_healing_tools and heal_gate (routes/inference.py:22740-22755), which today gate healing on a catalog nobody verified the vision render emitted. If a _renders_tool_schema-shaped predicate is kept anywhere, _template_reads_tools needs a flag to opt out of the _round_trips_tool_calls clause.

Happy to share the repro file if it saves you time.

… catalog

Keeping the client tool catalog on an image turn is right, but the transformers
vision renderer could not carry that catalog safely.

_generate_vision_response rebuilt the conversation from the system_prompt argument
plus last_user_text(), and the client-tools route clears system_prompt and folds the
system text into messages[0], so every system and developer instruction was dropped on
an image plus tools request. The same rebuild is why tool history had to be refused
outright, and because image extraction scans back through every user turn, that refusal
fired on turn two of any ordinary tool loop, including one where the caller sent no
tools at all and one under tool_choice "none". Studio's own frontend replays role
"tool" messages, so an image attached to a thread that had once run a tool went from
answering to failing.

Keep the conversation instead, and attach the image to the turn it belongs to, which is
what the MLX backend has always done. The pieces both backends need for that now live
in chat_template_helpers so the two cannot drift, and MLX picks up a fix for mutating
the caller's message dicts in place on the way past.

The catalog reached processor.apply_chat_template raw, while every other renderer
sweeps it through apply_chat_template_for_generation, so markup pasted into a tool
description, a name, a nested property or an enum value forged a turn in the prompt.
Sweep it in the same order the text path does, which also supplies the tools argument
markup_for_tokenizer was missing, so the messages are no longer profiled as "default"
while the render selects "tool_use".

_renders_tool_schema counted a template that merely replays tool turns as one that
advertises a schema, so the guard passed while the prompt carried nothing and the
healer still promoted calls the model was never shown. A processor is now held to the
stricter test, and whether the catalog actually reached the prompt is decided by
comparing the render with and against it, as the text path decides it. A template that
cannot advertise serves the turn without the catalog rather than failing it: there is
no native template to fall back to behind a processor, and renderable_tool_catalog
reports nothing advertised, so nothing is healed on the strength of it.

A request with no tools and no tool history keeps the collapse this path has always
used. Sending every prior turn instead would be a large prompt token increase on
ordinary multi-turn vision chat, which nothing here truncates, and that belongs to the
separate bug rather than to this fix.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-01T13:50:15.431053Z 9ccdfa9 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 66c4b73d95

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines 22708 to 22709
and _sf_features.get("supports_tools", False)
and ((payload.tools and len(payload.tools) > 0) or _sf_has_tool_msgs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Profile only the renderer used for image turns

When an image request uses a processor that advertises tools but its nested text tokenizer has an explicit non-tool template, allowing the request through this predicate still computes _sf_chat_targets as both objects at routes/inference.py:22730-22746. The catalog intersection therefore empties _sf_healing_tools, even though both the Transformers and MLX image paths render through the processor; text-form tool output is then relayed as ordinary content with no tool_calls. For image turns, profile only the processor that actually renders the prompt.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed in 9e4ae69. An image turn renders through the processor on both backends, _generate_vision_response and _generate_vlm, so the nested text tokenizer never selects a template for it and intersecting with its profile could only ever subtract. The intersection is now used for text turns only, where the two backends genuinely disagree about the render target, which is what the comment above it describes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correcting myself: I reacted 👍 to this and pushed a narrowing of _sf_chat_targets for image turns. That was wrong, and I have flipped the reaction and removed the change in 2dacdcf.

The mechanism described here cannot run. _sf_processor and _sf_tokenizer come from backend.models, and backend is always the orchestrator, whose parent-side mirror carries capability metadata and never a live tokenizer or processor. renderable_tool_catalog_for_targets documents exactly this. So both are None, chat_render_target(None, None) returns None, _sf_hf_target is _sf_mlx_target is True, and the tuple collapses to (None,). I checked it rather than reasoned about it:

chat_render_target(None, None) -> None
hf target is mlx target -> True
targets tuple -> (None,)

There is no two-target intersection to empty, so the catalog cannot be narrowed the way this describes, and my fix for it was dead code behind an is not None guard.

The underlying worry is real, though, and I have fixed the reachable form of it in 2dacdcf under the other thread: for an image turn the route was authorizing healing from the TOKENIZER template while the render uses the PROCESSOR template, which on Qwen2.5-VL never mentions tools at all. The worker now mirrors the processor body into chat_template_info and the route profiles image turns against that.

mlx_inference kept a re-export alias for prompt_serializes_structured_media that
nothing in the module used, only the test, which the import-hoist verifier fails as a
dangling hoisted import. The test follows the function to chat_template_helpers
instead.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

I pushed the fixes for all four items rather than leaving them with you, since they turned out to share one root cause. Two commits, bc36e9ea and e29b35b8.

Your gate change is untouched and it is the right fix. Everything I changed is the machinery behind it.

What was wrong. _generate_vision_response rebuilt the conversation from the system_prompt argument plus last_user_text(), which is exactly what the client-tools route empties. That single rebuild is why the system instruction disappeared and why tool history had to be refused outright. Keeping the conversation and attaching the image to the turn it belongs to, the way mlx_inference.generate_chat_response already does, fixes both. The pieces both backends need for that now live in chat_template_helpers so they cannot drift; MLX picks up a fix for mutating the caller's message dicts in place on the way past.

The catalog is now swept in the same order the text path uses, which also supplies the tools argument markup_for_tokenizer was missing. And whether the catalog actually reached the prompt is decided by comparing the render with and without it, rather than by the static profile.

One design call worth your attention. When a template cannot advertise the catalog, the turn is now served without it instead of failing. Three reasons: MLX and the text path both degrade rather than raise, a processor has no native template to fall back to, and refusing turns an answerable image question into an error. The #7066 risk is authorization, not availability, so I closed it at the other end: _renders_tool_schema now holds a processor to the strict test, renderable_tool_catalog reports nothing advertised, and healing switches off. Nothing is promoted on the strength of a catalog the model never saw.

Relevant to your original framing: the error text never actually reached users. worker.py turns the exception into gen_error, orchestrator.py wraps it with public=False, and safe_error_detail renders it as "An internal error occurred."

Scope. A request with no tools and no tool history keeps the collapse this path has always used. Sending the full history there would be a large prompt-token increase on ordinary multi-turn vision chat, which nothing on this path truncates. That history loss is a real bug, but a separate one.

Evidence.

  • A 384-cell matrix over template, conversation and catalog shapes, driving the real renderer through Jinja. Before: 176 cells raised, 96 leaked unsanitized tool markup into the prompt, 52 dropped the system instruction. After: 0 leaks, 0 dropped history, and the only dropped-system cells are the no-tools ones that are meant to keep the old behaviour. The 8 remaining refusals are one family, a template that raises on any system role in a conversation that has one with tool history present, where the only recovery would be dropping the instruction.
  • A parity harness that renders no-tools image requests against the merge base and this branch and compares prompts and kwargs: 810 comparisons, 0 mismatches.
  • The whole studio backend suite on both trees: no new failures, and the only difference is the six new regression tests going green.
  • ProcessorMixin.apply_chat_template probed in isolated venvs at transformers 4.51.3, 4.52.4, 4.53.3, 4.54.1, 4.55.4, 4.56.2, 5.0.0 and 5.4.0. tools is not a named parameter until 5.4.0, but **kwargs carries it into the Jinja context in every version, so the differential is sound across the supported range.
  • 4 operating systems by 6 accelerators through the real renderer, one distinct outcome, confirming nothing here is device or OS dependent.

Worth knowing for the future: supports_tools is computed from the tokenizer template while the vision render uses the processor template, and for a VLM those are routinely different files.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Keeping the old alias while re-pointing the import at another module is what the
import-hoist verifier flags as a silent re-point, and it is right to: same name, new
target is exactly the shape a bad rename takes. Call the helper by its own name.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 1, 2026
Preserving the conversation was gated on the catalog being non-empty, but
tool_choice "none" and a forced name matching no schema both arrive with tools=None
after the route has already folded the instruction into messages and cleared
system_prompt, so those turns took the collapse and lost it. Gate on that folded shape
as well. The ordinary path extracts system and developer turns into system_prompt and
leaves none behind in messages, so this cannot fire there.

The no-tools probe render shared one nonlocal conversation with the real render, so a
processor that rejects a system turn without a catalog and accepts it with one had the
throwaway probe strip the instruction out from under the render that was actually
served. Each render now records the conversation it used, and only the last one counts.

An image turn renders through the processor on both backends, so profiling the healing
catalog against the nested text tokenizer as well could empty it whenever that tokenizer
carries an explicit non-tool template, and a real tool call was then relayed as prose.
The two-target intersection is for the text turn on a vision model, where the backends
genuinely disagree about which object renders.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 1, 2026

@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: 9e4ae691ee

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
# that tokenizer carries an explicit non-tool template, and the healer then relays a
# real tool call as prose. The two-target intersection above is for the TEXT turn on
# a vision model, where the backends genuinely disagree about the render target.
_sf_chat_targets = (_sf_processor,)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Profile the renderer MLX actually selects for image turns

For an MLX image request whose processor lacks its own chat_template, _generate_vlm explicitly falls back to the nested tokenizer via chat_render_target, but this override profiles the processor instead. In particular, a nested tokenizer with named default and tool_use templates is evaluated here with processor selection semantics, so _sf_healing_tools can be emptied even though the actual tokenizer render advertises the tools; valid text-form tool calls are then returned as prose. Keep _sf_chat_targets aligned with _sf_mlx_target for this MLX fallback rather than assuming every image turn renders through the processor.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not reproducing this one, so 👎, but it is close and the reasoning is worth recording.

The MLX fallback and the override already agree, by construction rather than by accident. chat_render_target returns the nested tokenizer exactly when the processor has no usable chat_template (chat_template_helpers.py:1644-1652), and the mirror only stores processor_template when getattr(processor, "chat_template", None) is truthy (inference.py _load_chat_template_info). So in the case you describe, a processor without its own template, the mirrored value is None, _sf_image_tpl is None, and the route falls back to profiling the tokenizer body, which is the object _generate_vlm actually renders with. The override only carries a body when the processor has one, which is precisely when chat_render_target keeps the processor.

The transformers path lands in the same place for the same input: _generate_vision_response renders through the processor, but with no processor.chat_template apply_chat_template_for_generation reads the nested tokenizer body anyway.

The selection-semantics half of the point is real, though, and is fixed in 69ec534 from the other direction: a mirrored body is now explicitly flagged as a processor body via template_is_processor instead of being inferred from the target object, so it is no longer evaluated under tokenizer semantics. What I did not add is a processor-semantics evaluation of a TOKENIZER body, which is what this item would require, because that combination cannot arise.

pre-commit-ci Bot and others added 2 commits September 1, 2026 04:18
… turn

An image turn renders through the processor, whose chat template is a different file
from the tokenizer's on most VLMs. Qwen2.5-VL is the plain case: its processor body
never mentions tools while its tokenizer body does. The healer was authorized from the
tokenizer body, so a text-form call could be promoted for a schema that render never
carried, which is the failure unslothai#7066 exists to prevent and which this branch newly
exposes by keeping the catalog on image turns at all.

The route cannot read the processor directly. The orchestrator mirrors capability
metadata to the parent and keeps no live tokenizer or processor, which
renderable_tool_catalog_for_targets already documents. So the worker mirrors the
processor's template body into chat_template_info at load time, and the route profiles
image turns against that body instead of the tokenizer's. Text turns are unchanged.

This replaces the earlier attempt at the same problem, which narrowed the render-target
tuple for image turns. That tuple is built from processor and tokenizer objects that are
both None under the orchestrator, so it always collapses to a single None entry and the
narrowing could never run outside a test.

What the static read still cannot see is a processor body that names the tools variable
and renders identically with and without a catalog. The renderer detects that at run
time and logs it; none of the twelve shipped VLM templates surveyed behave that way,
since every one that replays tool turns also reads the variable.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…essor body

The mirror added in the previous commit never reached the parent. worker.py rebuilds
chat_template_info from a fixed whitelist when it forwards the load reply, and the new
key was not in it, so _sf_image_tpl was always None under the orchestrator and image
turns kept being profiled from the tokenizer template. Add the key to the whitelist,
with an AST test over that dict so a future field cannot be dropped the same way.

Once the body does arrive, it is judged with no live target beside it, and
_renders_tool_schema infers "processor" from the target object alone. A mirrored
processor body was therefore held to the permissive tokenizer rule, under which merely
replaying tool turns counts as advertising a schema. Say so explicitly instead:
template_is_processor travels with the body from the route down to the check. A
tokenizer body keeps the round-trip clause, because there the schema came from the
caller's own system prompt and a native template still sits behind it.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: fb4ee0edf4

ℹ️ 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 +3098 to +3104
if isinstance(body, str) and body:
return {**message, "content": [{"type": "text", "text": body}]}
# Absent, None or empty. A standard OpenAI assistant tool-call turn loses its
# content key entirely to exclude_none, and a template that iterates or indexes
# content raises on the missing field just as it does on a bare string, so the
# empty list is the representation that keeps the turn renderable.
return {**message, "content": []}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve strings for role-specific processor template branches

On an image-plus-tools follow-up, this unconditionally converts every non-list content value—including assistant and role="tool" messages—into multimodal part lists merely because the render target is a processor. Processor templates commonly need parts for multimodal user turns but special-case tool results as strings; such a branch can now serialize the list representation into <tool_response> or fail when it performs string operations, corrupting or rejecting an otherwise valid tool-loop replay. Only turns whose selected template expects part arrays should be wrapped, rather than changing all roles based on the renderer object's type.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not reproduced, so thumbs down, and this one contradicts the P1 you raised two rounds ago (3903161568) which argued the opposite. Rather than flip the code a third time on generic claims about what processor templates do, I went and read real ones. Downloaded chat_template.json for four VLM processors and checked how each handles content:

model iterates content is string guard role == 'tool' branch
Qwen2.5-VL-7B-Instruct yes yes no
gemma-3-4b-it yes yes no
llava-onevision-qwen2-7b-ov yes no no
pixtral-12b yes no no

Two of the four require part lists outright: llava-onevision does for content in message['content'] | selectattr('type', 'equalto', 'image') and pixtral does for chunk in message["content"], neither guarded, so a bare string breaks them. The other two carry an explicit if message['content'] is string guard and accept either form. Not one of the four has a role == 'tool' branch at all, so the specific hazard in your note, a tool branch performing string operations or serializing a list into <tool_response>, does not exist in any of them.

That is the evidence for wrapping every role, and it is the same evidence that made 3903161568 correct. If you have a concrete processor template whose tool or assistant branch requires a string, name it and I will gate on the selected body's shape instead; "only turns whose selected template expects part arrays" is not something I can implement without knowing which templates those are, and guessing is what produced this oscillation.

Templates fetched config-only into a scratch directory, nothing added to the PR.

Feature detection resolves a named collection down to one body, but the reasoning
prefill probe was handed the whole collection. Its <think> guard then tests the
collection's keys rather than the template text and returns False, so a selected
branch that prefills an open block is missed. Verified: with the selected string
the probe returns True and with the dict or list it returns False.
@danielhanchen

Copy link
Copy Markdown
Member

Round 12: three P1s. One fixed in 7073e8e, one rejected with evidence, one is the round-10 deferral re-raised.

Fixed (3903596956): the reasoning prefill probe was handed the whole named collection rather than the body feature detection had already resolved. The mechanism is the opposite sign to the one in the note, and the measurement is worth recording, since _sf_reasoning_prefill_mode never reaches _generation_prompt_opens_think with a collection; its "</think>" not in tpl guard tests the dict's KEYS and returns False first:

prefill(selected str) -> True
prefill(dict coll)    -> False
prefill(list coll)    -> False

So a selected branch that really does prefill an open block was being missed. Same root cause, same fix: the probe now gets the selected body.

Rejected (3903596962): this argued that wrapping assistant and tool turns as content parts corrupts processor templates that special-case tool results as strings. It directly contradicts 3903161568 from two rounds ago, which argued the opposite and which I acted on. Rather than flip the code a third time on generic claims, I read four real VLM processor templates. llava-onevision and pixtral iterate message['content'] unguarded and so REQUIRE part lists; Qwen2.5-VL and gemma-3 carry an explicit is string guard and accept either. None of the four has a role == 'tool' branch at all, so the hazard described does not exist in any of them. Detail and the table are on the thread. If someone can name a concrete template whose tool branch needs a string, I will gate on the selected body's shape.

Deferred (3903596949): same finding as 3903161555, answered there. It needs the worker to report its advertised catalog at render time, because the only existing back-channel arrives at gen_done, after a streaming turn has already emitted tool_call deltas. Queued as a separate PR against #7066, and the offer to hold this one instead still stands.

Validation on this head: targeted suites 1751 passed, 17 skipped; simulation matrices 26 passed over 402 cells with 0 markup leaks, 0 dropped system prompts, 0 dropped tool history; import-hoist and ruff clean.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A vision-marked model whose processor cannot process images has the image
ignored and renders through the tokenizer's text template. The turn-marking
added for historical images keyed only on an image being present, so a
string-only template was handed part lists. Gate it on the mirrored processor
body, which the worker omits for exactly that fallback; unknown means leave the
conversation as the caller sent it.
@danielhanchen

Copy link
Copy Markdown
Member

Round 13: one P1, fixed in 3a257ed.

The turn-marking I added for historical images keyed on an image being present, without checking that an image-capable processor would actually render. A vision-marked model whose processor cannot process images has its image ignored and goes through the tokenizer's text template, so a string-only template was handed part lists. Reproduced first, with a model carrying no mirrored processor body, and it failed on the previous head. Now gated on that mirrored body, which the worker already omits for exactly this fallback; unknown means the conversation goes through untouched, preserving pre-PR behaviour.

A fixture correction came with it: my round-9 test for the historical-image case had no processor_template, so under the new gate it was asserting on a model that would never render an image. It now describes an image-capable processor, which is what it always meant.

Validation on this head: targeted suites 1752 passed, 17 skipped; simulation matrices 26 passed over 402 cells with 0 markup leaks, 0 dropped system prompts, 0 dropped tool history; import-hoist and ruff clean; negative control fails the new test alone.

Tally after 13 rounds: 34 items, 26 fixed, 6 rejected, 1 deferred (the render-time catalog propagation, queued against #7066 with a standing offer to hold this PR). The last four rounds have all been review of my own fixes rather than the original change, and two of those fixes traced back to the same root question of which template body an image turn is judged by. That is now consistent across the mirror, the tool gate, the reasoning protocol, the prefill probe and the turn marking.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Four related corrections to the image-turn gating:

- "Will an image be placed" and "which body renders it" are different
  questions. An image-capable processor with no template of its own still
  places the image and falls back to the nested tokenizer, so both backends now
  mirror renders_image and the route keys the turn marker on that.
- The nudge retry attached the marker on the image alone, so a text-only
  fallback got part lists there too.
- Reasoning classification for a specific body no longer falls back to the
  tokenizer body or an unselected branch, which reported a native channel the
  renderer never selects.
- render_advertising_tools probes without tools first; when that render kept the
  system turn the role is supported, so a later catalog failure no longer drops
  the caller's instructions.
@danielhanchen

Copy link
Copy Markdown
Member

Round 14: four items, all real, all fixed in a0a3f96. Each has a regression test and a negative control that fails when that fix alone is reverted.

The central one (3904097309) names a flaw in last round's fix: I collapsed two different questions into one signal. "Will an image be placed" and "which body renders it" are not the same, because an image-capable processor with no template of its own still places the image and only falls back to the nested tokenizer for template selection. Both backends now mirror a separate renders_image flag through the worker whitelist, and the route keys the turn marker and the nudge retry (3904097312, a gap I left when fixing the same class last round) on that instead.

The other two: reasoning classification for a specific body no longer falls back to the tokenizer body or an unselected branch, measured as supports_reasoning: True widened versus nothing strict; and a catalog render failure no longer drops the system turn, since the no-tools probe that ran first already proved the role is supported.

Validation: targeted suites 1756 passed, 17 skipped; simulation matrices 26 passed over 402 cells with 0 markup leaks, 0 dropped system prompts, 0 dropped tool history; import-hoist and ruff clean.

Two process notes, both cases where the first attempt would have shipped something unproven. My first test for the reasoning fix stubbed _detect_safetensors_features through the route harness, so the flag was never exercised and the control passed with the fix reverted; it now calls the real classifier. And adding the renders_image gate made two of my own earlier tests fail because their fixtures never set it, describing models that would never render an image; I corrected the fixtures rather than loosening the gate.

Running tally: 38 items over 14 rounds, 30 fixed, 6 rejected, 1 deferred. The deferred P1 (render-time catalog propagation) is unchanged and still queued as a separate PR against #7066, with the standing offer to hold this one.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: a0a3f962d2

ℹ️ 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 Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review has converged. Codex returned no major issues on a0a3f96, which is this branch's code, with every inline item triaged and reacted.

Final tally: 38 items across 14 rounds, 30 fixed, 6 rejected with the reproduction attempt shown, 1 deferred.

The post-convergence comment pass is 9ccdfa9. It cut the PR's own comment lines from 237 to 70, a 70.5% reduction, and collapsed the test docstrings and several helper docstrings on top of that, so the net diff shrank by 230 lines. It is comment-only and machine-verified as such: comment_tools.py check --changed --base a0a3f962d --strip-docstrings reports code unchanged on all 7 files, and 1756 passed, 17 skipped is unchanged across it. That commit is the only thing sitting on top of the approved SHA, which is why the tooling now reads APPROVED_ON_ANCESTOR rather than approved at head. I have not re-triggered a review for it, since there is no code in it to review, but say the word if you would prefer one.

Surviving comments are the ones that name a wrong alternative, a real trap, or an invariant the code cannot state. Deleted wholesale: section banners, pointers, narration about what the code used to do, and restatements of the next line.

On CI, three checks are red and none of them is this branch:

  • Windows Unsloth GGUF CI: llama.cpp emitted two different completions for identical replays at temperature 0. The same workflow passed on this branch's four preceding heads, and both upstream GGUF inference smoke jobs pass. Flake.
  • Backend CI (Python 3.13): tests/test_non_gguf_reload_settings.py asserts a literal source string that get_status no longer contains. Fails identically on a clean origin/main checkout.
  • Backend CI (Repo tests CPU): tests/studio/test_model_picker_contracts.py::test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned. Also fails identically on origin/main.

The last two are worth a separate look: like the pre-commit.ci breakage earlier today, they are red on every PR against current main, not just this one. Everything else on the staging replica is green on this head, including MLX CI on Mac M1, which is the only real exercise of the shared mlx_inference.py path.

The one open question remains the deferred P1: healing stays authorized when a processor body names tools but renders identically for the concrete catalog. It needs the worker to report its advertised catalog at render time, because the only existing back-channel arrives at gen_done, after a streaming turn has already emitted tool_call deltas. That is a protocol change I did not want to land here, and it is the fix that would retire this whole class of bug rather than another gate. I will raise it against #7066. If you would rather this PR waited for it, I am happy to hold.

@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: 9ccdfa9a47

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

folded_system = not system_prompt and any(
isinstance(m, dict) and m.get("role") in ("system", "developer") for m in messages
)
if bool(tools) or has_tool_history or folded_system:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve history when tool_choice disables the catalog

When an image request supplies client tools but sets tool_choice="none" (or forces an unknown function), the passthrough explicitly keeps the full message history but sets gen_kwargs["tools"] = None at routes/inference.py:22991-23000. If the conversation also has no system or prior tool turn, every condition here is false, so the collapsed vision branch discards the earlier conversation and reattaches the selected image to the newest user text. This silently changes follow-up image questions despite the route intentionally choosing history-preserving templating; pass an explicit passthrough/history-preservation signal rather than inferring it from the remaining catalog.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants