Repository navigation
Studio: keep tools available when a picture is attached - #10092
Conversation
|
Confirmed the |
|
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 Evidence, six repros, all failing on the head: What is right, and should stayThe diagnosis is correct and the central change is the right one.
The four defects1. System and developer instructions vanish on an image plus client-tools turn. When client tools are on, the route folds the system text into 2. A normal tool loop with an image now returns 500. The fake processor's template round-trips 3. The catalog reaches While you are in there: 4. So the guard says fine, the prompt never mentions Why CI did not catch any of thisThe two new tests drive the route with Nothing breaks, because nothing covers the new code. Please add unit coverage that reaches the renderer. Suggested shapeDefects 1 and 2 are one root cause: the transformers vision path rebuilds the conversation instead of rendering it. MLX already solved this. For defect 3, sweep the catalog in For defect 4, drop 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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| and _sf_features.get("supports_tools", False) | ||
| and ((payload.tools and len(payload.tools) > 0) or _sf_has_tool_msgs) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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, Your gate change is untouched and it is the right fix. Everything I changed is the machinery behind it. What was wrong. The catalog is now swept in the same order the text path uses, which also supplies the 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 Relevant to your original framing: the error text never actually reached users. 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.
Worth knowing for the future: |
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.
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.
There was a problem hiding this comment.
💡 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".
| # 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,) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
… 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.
…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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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": []} |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
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 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 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 Validation on this head: targeted suites |
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.
|
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 Validation on this head: targeted suites 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. |
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.
|
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 The other two: reasoning classification for a specific body no longer falls back to the tokenizer body or an unselected branch, measured as Validation: targeted suites Two process notes, both cases where the first attempt would have shipped something unproven. My first test for the reasoning fix stubbed 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. |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
|
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: 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:
The last two are worth a separate look: like the The one open question remains the deferred P1: healing stays authorized when a processor body names |
There was a problem hiding this comment.
💡 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: |
There was a problem hiding this comment.
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 👍 / 👎.
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.
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.