Repository navigation
Tool-call healing (default on) and opt-in nudging for the client-tool passthrough - #6801
Conversation
…enai_message, StreamToolCallHealer, nudge helpers)
Small GGUF models often emit tool calls as text (<tool_call>{...}</tool_call>,
Gemma <|tool_call>, <function=> XML) instead of structured tool_calls. Studio's
enable-tools loop already heals these, but the client-tool passthrough
(unsloth run --disable-tools, unsloth start agents) relays them verbatim, so
the agent sees prose and the turn dies.
This module is the shared response-side repair layer the passthrough routes
will call: promote parsed text-form calls to structured calls, but only for
function names the client actually declared; coerce arguments through the same
canonical-key healing as the tool loop; never touch the upstream request body
(llama-server KV/slot reuse stays byte-identical). StreamToolCallHealer is the
streaming buffer-and-repair state machine: prose forwards immediately, only a
partial-signal tail or a suspected tool block is held, false alarms flush
verbatim, and a 64 KiB bound caps memory. nudge_should_retry/nudge_messages
support an opt-in single-retry nudge for non-streaming routes (wired later).
Kill-switch: UNSLOTH_DISABLE_TOOL_CALL_HEALING=1. Reuses
core/tool_healing.parse_tool_calls_from_text, strip_tool_call_markup, and
tool_loop_controller.coerce_tool_arguments unchanged.
…through Wire the passthrough healing core into /v1/chat/completions and /v1/responses, default ON whenever the request declares client tools: Non-streaming: heal_openai_message runs inside the existing response-mutation loop; a promoted call flips finish_reason to tool_calls and nulls the content, and the verbatim-bytes fast path still applies when nothing was healed. /v1/responses non-streaming inherits this through openai_chat_completions. Streaming: a StreamToolCallHealer per stream. Ordinary prose relays byte-for-byte (a fast path keeps upstream bytes when the healer passes a chunk through whole); once a tool signal appears, content is held, and at the finish/[DONE] boundary either synthetic delta.tool_calls chunks replace the markup (finish_reason rewritten to tool_calls, including the synthetic-finish path) or a false alarm flushes the held text verbatim. Structured upstream deltas put the healer to sleep after flushing anything held, so grammar-mode responses stay byte-identical. The Responses stream feeds healed calls through the same per-call state machinery as structured deltas (indexes live in a disjoint range so a healed call can never merge into a structured call's state), and the visible/reasoning split runs first so reasoning text is never promoted. parallel_tool_calls=false caps healed calls on every path. The upstream request body is never touched and healing issues no extra generation, so llama-server slot/KV-cache reuse is unchanged. Opt-out per request with auto_heal_tool_calls=false (Responses reads it from the extra-body); requests without tools relay verbatim.
…ssthrough Streaming: AnthropicPassthroughEmitter.enable_healing(allowed_tools) routes content deltas through the shared StreamToolCallHealer. A promoted call closes any open text block (only the safe prose prefix ever streamed into it), opens a synthetic tool_use block with a fresh toolu_* id, carries one input_json_delta, and closes; finish() then forces stop_reason to tool_use unless a truncation (max_tokens) wins. Structured upstream deltas flush anything held and put the healer to sleep, so grammar-mode responses are untouched, as is every stream where enable_healing is never called (Studio's own loop, no-tools requests). disable_parallel_tool_use caps healed calls too. Non-streaming: the OpenAI message dict is healed BEFORE block building, so the existing tool_use promotion loop and stop_reason line treat promoted calls exactly like native ones (finish_reason length still maps to max_tokens). The legacy tool-XML strip still runs on remaining text, so opted-out requests keep today's cleanup behavior byte-for-byte. auto_heal_tool_calls is now a typed field on AnthropicMessagesRequest (default True, mirroring Chat Completions) and threads into both passthrough calls. Healing never touches the upstream request body.
…assthrough When the model clearly tried to call a tool (a tool signal in the text) but healing produced nothing usable, re-ask once: the retry body is the original body plus an assistant turn (the model's own failed text) and a short user nudge naming the declared tools. The prompt prefix stays byte-identical, so llama-server reuses the slot's KV cache and only the two-message suffix is prefilled. The retry replaces the original response only when it actually yields a promotable or structured call; on any error or still-garbage output the original response is returned unchanged. Exactly one retry, non-streaming OpenAI and Anthropic passthroughs only (a stream has already emitted bytes). OPT-IN per user decision: nudge_tool_calls=true per request (typed on both ChatCompletionRequest and AnthropicMessagesRequest, lifted from the Responses extra-body), or UNSLOTH_TOOL_CALL_NUDGE=1 to flip the process default. auto_heal_tool_calls=false disables healing AND the nudge. Also align the non-streaming heal on allow_incomplete=True: the response is final, so a trailing unclosed tool block is a model failure worth repairing, matching the enable-tools loop's drain semantics.
There was a problem hiding this comment.
Code Review
This pull request introduces a tool-call healing mechanism for client-tool passthrough, allowing text-form tool calls from smaller models to be promoted back into structured tool calls on the response side, along with an opt-in single-retry nudge mechanism. The feedback highlights a critical reliability issue in passthrough_healing.py where helper functions like _last_assistant_text, response_has_promotable_calls, and nudge_should_retry do not catch AttributeError. If the message object in the response is None or not a dictionary, calling .get() on it will crash the server. Adding defensive type checks is highly recommended to prevent these unhandled exceptions.
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.
|
|
||
| def _last_assistant_text(data: Any) -> str: | ||
| """First-choice assistant content of a non-streaming chat response, or ''.""" | ||
| try: | ||
| message = data["choices"][0]["message"] | ||
| content = message.get("content") | ||
| return content if isinstance(content, str) else "" | ||
| except (KeyError, IndexError, TypeError): |
There was a problem hiding this comment.
Defensively verify that message is a dictionary before calling .get() on it. If message is None (which can happen in some API error responses), calling .get() will raise an unhandled AttributeError and crash the server.
def _last_assistant_text(data: Any) -> str:
\"\"\"First-choice assistant content of a non-streaming chat response, or ''.\"\"\"
try:
message = data[\"choices\"][0][\"message\"]
if not isinstance(message, dict):
return \"\"
content = message.get(\"content\")
return content if isinstance(content, str) else \"\"
except (KeyError, IndexError, TypeError):
return \"\"There was a problem hiding this comment.
Fixed in 54cdcd9. The three nudge helpers now go through a shared _first_choice_message helper that returns None unless choices[0].message is actually a dict, so upstream error bodies with message: null, empty choices, or a missing choices key can never raise. Added a parametrized test over nine malformed response shapes (test_malformed_response_shapes_never_raise).
|
|
||
| def response_has_promotable_calls(data: Any, allowed_tools: set) -> bool: | ||
| """True when a non-streaming chat response carries a usable tool call | ||
| (structured, or text-form that healing would promote). Used to decide | ||
| whether a nudge retry actually improved on the original response.""" | ||
| try: | ||
| message = data["choices"][0]["message"] | ||
| except (KeyError, IndexError, TypeError): | ||
| return False | ||
| if message.get("tool_calls"): | ||
| return True | ||
| text = message.get("content") | ||
| if not isinstance(text, str): | ||
| return False | ||
| return bool(_promote(parse_tool_calls_from_text(text, allow_incomplete = True), allowed_tools)) | ||
|
|
There was a problem hiding this comment.
Defensively verify that message is a dictionary before calling .get() on it. If message is None, calling .get() will raise an unhandled AttributeError and crash the server. Additionally, ensure the dictionary checks and property accesses are safely contained within the try-except block.
def response_has_promotable_calls(data: Any, allowed_tools: set) -> bool:
\"\"\"True when a non-streaming chat response carries a usable tool call
(structured, or text-form that healing would promote). Used to decide
whether a nudge retry actually improved on the original response.\"\"\"
try:
message = data[\"choices\"][0][\"message\"]
if not isinstance(message, dict):
return False
if message.get(\"tool_calls\"):
return True
text = message.get(\"content\")
except (KeyError, IndexError, TypeError):
return False
if not isinstance(text, str):
return False
return bool(
_promote(parse_tool_calls_from_text(text, allow_incomplete = True), allowed_tools)
)There was a problem hiding this comment.
Fixed in 54cdcd9 via the same shared _first_choice_message helper: a non-dict message means nothing to promote, so this returns False instead of raising.
| """True when the first response tried to call a tool but nothing healed. | ||
|
|
||
| Trigger only on: healing enabled (allowed_tools set), zero structured | ||
| calls, a tool signal present in the text, and zero promotable calls -- the | ||
| exact failure a single re-ask can fix. Clean prose never retries. | ||
| """ | ||
| if not allowed_tools: | ||
| return False | ||
| try: | ||
| message = data["choices"][0]["message"] | ||
| except (KeyError, IndexError, TypeError): | ||
| return False | ||
| if message.get("tool_calls"): | ||
| return False | ||
| text = message.get("content") | ||
| if not isinstance(text, str) or not has_tool_signal(text): | ||
| return False | ||
| return not _promote(parse_tool_calls_from_text(text, allow_incomplete = True), allowed_tools) | ||
|
|
||
|
|
||
| def nudge_messages(data: Any, allowed_tools: set) -> list: |
There was a problem hiding this comment.
Defensively verify that message is a dictionary before calling .get() on it. If message is None, calling .get() will raise an unhandled AttributeError and crash the server. Additionally, ensure the dictionary checks and property accesses are safely contained within the try-except block.
def nudge_should_retry(data: Any, allowed_tools: Optional[set]) -> bool:
\"\"\"True when the first response tried to call a tool but nothing healed.
Trigger only on: healing enabled (allowed_tools set), zero structured
calls, a tool signal present in the text, and zero promotable calls -- the
exact failure a single re-ask can fix. Clean prose never retries.
\"\"\"
if not allowed_tools:
return False
try:
message = data[\"choices\"][0][\"message\"]
if not isinstance(message, dict):
return False
if message.get(\"tool_calls\"):
return False
text = message.get(\"content\")
except (KeyError, IndexError, TypeError):
return False
if not isinstance(text, str) or not has_tool_signal(text):
return False
return not _promote(
parse_tool_calls_from_text(text, allow_incomplete = True), allowed_tools
)There was a problem hiding this comment.
Fixed in 54cdcd9 via the same shared _first_choice_message helper: malformed shapes short-circuit to no retry rather than raising mid-request.
llama-server error bodies can carry message: null (or no choices at all), and _last_assistant_text / response_has_promotable_calls / nudge_should_retry called .get() on the message without a dict check, so a malformed upstream response raised an AttributeError the surrounding except tuples did not catch, failing the request instead of degrading to 'nothing to heal'. Route the shape probing through one _first_choice_message helper that returns None for any non-dict message, and add a parametrized test over the malformed shapes.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 034264ea1b
ℹ️ 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".
| # Small models emit tool calls as text instead of structured tool_calls; | ||
| # promote them (declared client tools only) so the agent sees a real call. | ||
| if _allowed_tools and heal_openai_message(msg, _allowed_tools): | ||
| choice["finish_reason"] = "tool_calls" |
There was a problem hiding this comment.
Preserve length finish reasons when healing
If llama-server returns finish_reason: "length" after emitting a parseable text-form tool call, this unconditionally rewrites the choice to tool_calls. That tells non-streaming OpenAI clients/agents to execute the healed call even though generation was truncated and the arguments may have been cut off; the streaming and Anthropic paths already preserve truncation as the winning stop reason. Only upgrade stop to tool_calls here, or otherwise leave length unchanged while attaching the healed call.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 65b3046. The non-streaming heal now only upgrades a clean stop to tool_calls; a truncated generation keeps finish_reason length with the healed call still attached, so the client sees both the call and the truncation. This matches the streaming path (which already gated on stop) and the Anthropic path (where max_tokens wins in openai_finish_to_anthropic_stop). Test: test_length_finish_reason_preserved.
| _MAX_HOLD_CHARS = 64 * 1024 | ||
|
|
||
|
|
||
| def heal_gate(auto_heal: Optional[bool], tools: Optional[list]) -> Optional[set]: |
There was a problem hiding this comment.
Honor tool_choice when enabling healing
Because the healing gate only receives the declared tool list, every passthrough request with tools gets the full allowlist even when the client sent tool_choice: "none" or forced a specific function. In those turns, a model that ignores the hint and emits text-form markup for any declared tool will have it promoted into a real tool call, contradicting the request's tool-choice constraint; pass the effective tool choice into this gate and return no tools (or only the forced tool) as appropriate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 65b3046. heal_gate now takes the request's tool_choice (OpenAI shape): "none" disables healing outright, a forced function narrows the promotion allowlist to that single function (an undeclared forced name empties it), and auto/required/absent keep the full declared set. Wired through all five call sites: OpenAI chat stream and non-stream read it from the upstream body, Responses reads the translated chat-shape value, and both Anthropic passthroughs receive the already-converted shape (Anthropic {"type": "none"} maps to "none", {"type": "tool", "name": N} to the forced-function form). Unit tests plus a route-level test on each API.
| visible_delta = "".join(t for kind, t in events if kind == "text") | ||
| healed_calls = [v for kind, v in events if kind == "tool_call"] |
There was a problem hiding this comment.
Preserve healed event order in Responses streams
When a single Responses stream delta contains text on both sides of a healed tool call, the healer returns ordered events like text → tool_call → text, but this collapses all text into visible_delta and emits it before iterating healed_calls. That reorders trailing text ahead of the function_call item (and assigns output indexes in the wrong order), so clients reconstruct a different Responses output sequence than the model produced; emit the healer events in order instead of separating all text from all calls.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 65b3046. The Responses stream now serializes healer events in order through a shared _healed_event_sse helper instead of collapsing all text into visible_delta ahead of the calls, in both the main chunk loop and the end-of-stream finalize. Output indexes are therefore claimed in the order the model produced the items. Added ordering tests: text before and after a healed call keeps its position, and a call followed by trailing text claims the lower output_index (test_text_around_healed_call_keeps_order, test_call_before_trailing_text_claims_lower_output_index).
…eason, keep healed event order in Responses streams Three review findings on the passthrough healer: - heal_gate now honors the request's tool_choice: "none" disables healing outright and a forced function narrows the promotion allowlist to that one function, so healing can never contradict the request's tool-choice constraint. Wired through the OpenAI chat (stream and non-stream), Responses, and Anthropic (converted shape) passthroughs. - The OpenAI non-streaming heal only upgrades finish_reason "stop" to "tool_calls"; a truncated generation keeps "length" (the healed call stays attached) matching the streaming and Anthropic paths. - The Responses stream emits healer events in order instead of collapsing all text ahead of the healed calls, so text after a healed call no longer jumps ahead of the function_call item and output indexes are claimed in the order the model produced them.
|
Addressed both review rounds:
411 tests across the healing, Responses, OpenAI passthrough, and Anthropic suites pass, ruff clean. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 898f1546de
ℹ️ 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".
| self._holding = False | ||
| continue | ||
| self._id_offset += len(promoted) | ||
| events.extend(("tool_call", call) for call in promoted) |
There was a problem hiding this comment.
Preserve stream order between healed tool calls
When one buffered chunk contains multiple parseable calls with text between them, this appends every promoted call before the intervening text is rediscovered by strip_tool_call_markup. For example <tool_call>lookup...</tool_call> then <tool_call>read...</tool_call> is emitted as lookup, read, then the text then, even though the Responses/OpenAI stream code relies on healer event order to assign output indexes and preserve the model's sequence. Promote/strip one span at a time, or otherwise emit the stripped text between calls before the later call.
Useful? React with 👍 / 👎.
| return False | ||
| msg["tool_calls"] = calls | ||
| # OpenAI requires content = null on a pure tool-call turn. | ||
| msg["content"] = strip_tool_call_markup(content, final = True) or None |
There was a problem hiding this comment.
Preserve unpromoted tool blocks when healing allowed calls
Here calls has already been filtered to declared tools, but this strips every tool-call block from the message once any allowed call was found. If the model emits an undeclared text-form call in the same response as a declared one, the undeclared block is neither promoted nor returned as text, whereas a response containing only that undeclared call is relayed verbatim. Clients lose visibility into unsupported or hallucinated calls instead of seeing the unpromoted text.
Useful? React with 👍 / 👎.
| if message.get("tool_calls"): | ||
| return True |
There was a problem hiding this comment.
Reject nudge retries for undeclared structured tools
With nudge_tool_calls enabled, a retry that returns any structured tool_calls is accepted here without checking function.name against allowed_tools. If the model answers the retry with a structured call to a hallucinated/undeclared tool, the original response is replaced and the OpenAI/Responses/Anthropic paths forward a call the client never declared, while text-form retry output is filtered through _promote. Check structured retry calls against the declared allowlist before treating the retry as usable.
Useful? React with 👍 / 👎.
| return False | ||
| # allow_incomplete: the response is final, so a trailing unclosed block is a | ||
| # model failure worth repairing (same as the enable-tools loop at drain). | ||
| calls = _promote(parse_tool_calls_from_text(content, allow_incomplete = True), allowed_tools) |
There was a problem hiding this comment.
Require real function payload before final healing
Because final healing uses allow_incomplete=True, a response that only mentions a declared function tag such as Here is <function=lookup> syntax is parsed as a zero-argument lookup call and the visible text is stripped/promoted. This can make explanatory prose or code samples trigger client tools; for the <function=...> form, require a closing </function> or at least a parsed parameter before promoting at finalization.
Useful? React with 👍 / 👎.
…d undeclared text-form calls Promoting a subset used to strip ALL tool markup from the content, which silently deleted the text of any call naming an undeclared tool. The heal now declines entirely when any parsed call is unpromotable, so the whole message relays verbatim (pre-PR behavior) and no bytes are ever lost. In streaming, a declared call that completed before an undeclared one arrived is already emitted; the late undeclared markup still flushes as raw text. The nudge helpers mirror the same contract via a shared predicate.
|
One more hardening commit from an extended verification pass over this PR (40b2e41, formatting follow-up 940fc10): Promotion is now all-or-nothing per parse. Previously, when a response mixed a call to a declared tool with a call to an undeclared one, promoting the declared call stripped ALL tool markup from the content, silently deleting the undeclared call's text. The heal now declines entirely in that case and the message relays verbatim, so no bytes are ever lost. In streaming, a declared call that completed before the undeclared one arrived is already emitted; the late undeclared markup still flushes as raw text. New unit, stream, and route-level tests cover the mixed case. Verification summary for the whole PR beyond the unit suites:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f5278e962c
ℹ️ 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".
| delta = { | ||
| "tool_calls": [ | ||
| { | ||
| "index": healed_call_index, |
There was a problem hiding this comment.
Keep healed stream indexes disjoint from native calls
If a stream has already emitted a healed text-form call and llama-server later sends native delta.tool_calls, both calls can use index 0 because healed calls start at healed_call_index. OpenAI streaming clients merge tool-call deltas by tool_calls[].index, so the later native call's name/arguments can be appended to the synthetic call instead of becoming a separate call. Use a disjoint index range for healed calls, as the Responses stream does, or remap subsequent native indexes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aa44fc9. Once a healed call has been emitted, subsequent native delta.tool_calls indexes are shifted by the healed call count before relay, so a healed call at index 0 and a later native call can no longer merge under the same index. Test: test_healed_then_native_stream_indexes_disjoint asserts the healed call keeps index 0 and the native call arrives at index 1 with its own id.
| return False | ||
| msg["tool_calls"] = calls | ||
| # OpenAI requires content = null on a pure tool-call turn. | ||
| msg["content"] = strip_tool_call_markup(content, final = True) or None |
There was a problem hiding this comment.
Avoid stripping mixed-format calls that were never parsed
When one response mixes supported text formats, such as a JSON <tool_call>...</tool_call> followed by a declared <function=Read>...</function> call, parse_tool_calls_from_text returns only the JSON/Gemma candidates because it only parses <function=...> blocks if no earlier calls were found. The length check therefore passes for the parsed subset, and this line strips every tool block, so the second declared call is neither promoted nor left visible as text. Decline promotion when unparsed tool markup remains, or parse all formats before stripping.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aa44fc9, and more generally than the report. parse_tool_calls_from_text gains an optional with_spans return, and healing now removes EXACTLY the promoted calls' markup spans instead of blanket-stripping. That kills the whole class: a suppressed <function=...> block after a JSON call, a closed-but-unparseable <tool_call> block, and undeclared calls all keep every byte and relay as text. This supersedes the earlier all-or-nothing rule: declared calls now promote even in mixed responses, with zero data loss. The stream healer also processes one block per pass so text between two healed calls keeps its document position. Covered by new unit, stream, and route tests plus a fuzz invariant (15k chunking simulations, zero violations).
| if kind == "text": | ||
| if not value: | ||
| continue | ||
| out.extend(_ensure_message_open()) |
There was a problem hiding this comment.
Start a new Responses message after healed calls
When a healed Responses delta contains text on both sides of a promoted call (before <tool_call>... after), the post-call text reaches this branch after _tool_call_delta_events() has claimed a later output index, but _ensure_message_open() reuses the already-open pre-call message. Fresh evidence after the prior fix is that line 8492 does not open a new message after a tool event, so the trailing response.output_text.delta still carries the pre-call output_index, and response.completed.output groups all text before the function_call; clients reconstruct the wrong output order.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in aa44fc9. A healed call now closes the open message item (emitting the output_text.done / content_part.done / output_item.done triplet) and trailing text opens a fresh message item with a later output index, matching the native Responses stream shape. response.completed snapshots every message item with its own text. Test: test_healed_call_splits_message_items asserts the message / function_call / message item sequence, distinct item ids, per-item text attribution, and the per-item snapshot.
| if _allowed_tools: | ||
| heal_openai_message(message, _allowed_tools) |
There was a problem hiding this comment.
Preserve Anthropic block order after healing
For non-streaming Anthropic passthrough, a response like <tool_call>{...}</tool_call> done is healed here into message.tool_calls plus remaining text in message.content, but the block builder below always appends the text block before every tool_use block. In that scenario the client receives text before tool_use even though the model emitted the tool call first, which can make Anthropic clients replay a different content sequence than the assistant produced.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Keeping this one as is, deliberately. The non-streaming OpenAI shape carries no order information between message.content and message.tool_calls, so the block builder has always rendered text before tool_use for NATIVE structured calls too; making healed calls order-aware while native calls stay text-first would make the two cases inconsistent with each other. Text-before-tool_use is also the canonical Anthropic assistant-turn shape, so replaying [text, tool_use] plus a tool_result round-trips cleanly. The streaming path emits blocks in true document order since it sees the sequence as it happens.
…ll Responses message items, allowlisted nudge acceptance Four review findings on the passthrough healer: - parse_tool_calls_from_text gains an optional with_spans return so healing removes EXACTLY the promoted calls' markup. This supersedes the previous all-or-nothing rule: declared calls promote and every unpromoted byte (undeclared calls, unparseable closed blocks, suppressed alternate formats such as a <function=...> block after a JSON call) relays as text. The stream healer also processes one block per pass, so text between two healed calls keeps its document position instead of trailing them. - The OpenAI chat stream shifts native tool-call delta indexes past any already-emitted healed calls; clients merge deltas by index, so a healed call and a later native call can no longer merge into one. - A healed call in the Responses stream closes the open message item and trailing text opens a fresh one with a later output index, matching the native stream shape; response.completed snapshots every message item with its own text. - The nudge retry only replaces the original response when the retry's structured call names a DECLARED tool; a hallucinated undeclared call is not an improvement.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 10c80770c9
ℹ️ 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".
| if not allow_incomplete: | ||
| span_end = body_start + close_idx + len(_FUNC_CLOSE_TAG) | ||
| else: | ||
| span_end = body_end |
There was a problem hiding this comment.
Stop final XML parsing at closed function tags
When final healing runs with allow_incomplete=True, a bare closed XML call followed by prose, e.g. <function=web_search><parameter=query>cats</parameter></function> trailing, reaches this else path with body_end == len(content). That makes the trailing prose part of the last parameter and, with this span, removes it from visible content, so clients get a corrupted tool argument (cats ... trailing) and lose the text. Even in incomplete mode, prefer the real </function> boundary when it exists, only falling back to body_end for genuinely truncated calls.
Useful? React with 👍 / 👎.
| for tc in delta["tool_calls"]: | ||
| if isinstance(tc, dict) and isinstance(tc.get("index"), int): | ||
| tc["index"] += healed_call_index |
There was a problem hiding this comment.
Count healed calls when capping parallel streams
When parallel_tool_calls=false, a native index: 0 chunk has already survived _cap_parallel_tool_calls_sse_line; if a text-form call was healed earlier, healed_call_index is nonzero and this shift relays that native call as index: 1, so clients receive two tool calls despite requesting a single call. This happens when a model mixes a healed text-form call with a later structured delta; drop later native deltas once a healed call has filled the one allowed slot.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 745a1ca: with parallel_tool_calls=false, once a healed call has gone out the native tool_call deltas are dropped instead of index-shifted (the rest of the chunk still relays). Regression test drives a healed call followed by a native index-0 delta and asserts exactly one call reaches the client.
| if self._heal_disable_parallel and self._healed_call_count >= 1: | ||
| return [] |
There was a problem hiding this comment.
Apply the parallel cap after healed Anthropic calls
When /v1/messages is streaming with disable_parallel_tool_use, this guard only counts prior healed calls while native chunks are capped before the emitter knows a healed call consumed the single allowed slot. If the stream emits one healed text-form call and then a native structured index: 0 call, the native loop below still opens another tool_use block, so the client receives two tool uses despite disabling parallel tool use. Track a total emitted-tool-use count, or drop native calls after a healed call has filled the slot.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 745a1ca: the emitter's native loop now skips new tool calls when the healed-plus-native count already filled the single slot, and _emit_healed_tool_use counts open native states too, so the budget is shared in both orders. Test added.
| if payload.parallel_tool_calls is False and healed_tc_index >= 1: | ||
| return None |
There was a problem hiding this comment.
Include native Responses calls in the parallel cap
When /v1/responses streams with parallel_tool_calls=false, this cap only suppresses additional healed calls; a later native structured index: 0 call has already passed the upstream _drop_parallel_tool_call_deltas filter and is still processed by the native delta.tool_calls loop. In a stream that heals one text-form call and then receives a native tool-call delta, clients get two function_call output items despite disabling parallel calls. Count the healed call as occupying the single allowed slot before relaying subsequent native calls.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 745a1ca: native deltas that survived _drop_parallel_tool_call_deltas are skipped once a healed call claimed the slot, so only one function_call item is emitted. Test added.
…ion call parse_tool_calls_from_text(allow_incomplete=True) cut a <function=...> body only at an end-anchored </function>, so a fully closed call followed by trailing prose (<function=..>..</parameter></function> words) folded </parameter></function> and the prose into the tool argument and deleted the prose from visible content. The strict path (allow_incomplete=False) already cut at the real </function> via rfind. Do the same in both modes: trim the body at the real </function> when present and end the removal span there, falling back to the end-anchored strip and body_end only when the call is genuinely truncated. Add a regression test.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0c32143438
ℹ️ 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 ( | ||
| healer is not None | ||
| and not healer.dormant | ||
| and isinstance(chunk_data, dict) |
There was a problem hiding this comment.
Keep shifting native tool-call chunks after healing
When a healed text-form call has already emitted index 0 and the upstream then streams a native tool call over multiple chunks, only the first native chunk is shifted inside _heal_transform; structured_tool_call_seen() sets the healer dormant, so this gate relays all later native chunks with their original index. OpenAI clients merge tool-call deltas by index, so those later argument chunks can be appended to the healed call instead of the native call. Keep applying the healed offset to subsequent delta.tool_calls after healing goes dormant.
Useful? React with 👍 / 👎.
| if not parsed: | ||
| if len(self._buffer) > _MAX_HOLD_CHARS: | ||
| events.append(("text", self._buffer)) | ||
| self._buffer = "" | ||
| self._holding = False | ||
| continue | ||
| return events |
There was a problem hiding this comment.
Flush closed malformed tool-call blocks while streaming
With healing enabled, a closed but unparsable marker such as <tool_call>not json</tool_call> leaves parsed empty and this path returns without emitting anything unless the buffer exceeds 64 KiB or the stream ends. Because _holding stays true, subsequent normal text is also buffered until a later valid tool call or finalization, so streaming responses can appear stalled after a malformed/literal tool-call block even though that block can no longer become a valid call. Detect and flush closed unparsable blocks instead of waiting for EOF.
Useful? React with 👍 / 👎.
| for call, (start, end) in zip(parsed, spans): | ||
| promoted = _promote([call], self._allowed, id_offset = self._id_offset) | ||
| if promoted: |
There was a problem hiding this comment.
Preserve trailing text bytes after final healing
When the stream ends while a held incomplete-but-parseable call is promoted, any text after the promoted span is emitted through residue[pos:].strip(). That removes whitespace that was not part of the tool-call markup, e.g. <tool_call>{...} next is delivered as a tool call followed by next rather than next, which can change visible formatting or concatenate text around healed calls. Use the raw tail for emission and only use a stripped check to decide whether it is empty.
Useful? React with 👍 / 👎.
| # Nothing held or promoted: the healer passed the chunk | ||
| # through whole, so keep the verbatim upstream bytes. | ||
| return [raw_line] | ||
| lines = _healer_sse_lines(events) |
There was a problem hiding this comment.
Preserve role chunks before healed content
When an upstream OpenAI-compatible chunk carries delta.role (or other non-content delta fields) together with content that the healer rewrites, this serializes the synthetic content/tool-call chunks before the original chunk is appended with content removed. Clients can therefore see content or tool calls before the assistant role for that first chunk. Emit the remaining non-content delta first, or otherwise preserve its original ordering, before replaying healed content.
Useful? React with 👍 / 👎.
Codex round 5: the parallel-call caps counted healed and native calls separately, so a healed text-form call followed by a native structured delta double-emitted on all three streaming surfaces when the client disabled parallel calls. - OpenAI SSE: once a healed call went out with parallel_tool_calls false, native tool_call deltas are dropped instead of index-shifted. - Anthropic emitter: native deltas skip block allocation when the healed-plus-native count already filled the single slot, and healed emission counts open native states too. - Responses stream: native deltas that survived the chunk-level cap are skipped once a healed call claimed the slot. Also adds a span assertion for the closed-</function> trailing-prose parse fixed in the previous commit.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f25e01a0e1
ℹ️ 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".
| return any( | ||
| isinstance(tc, dict) | ||
| and isinstance(tc.get("function"), dict) | ||
| and tc["function"].get("name") in allowed_tools | ||
| for tc in tool_calls |
There was a problem hiding this comment.
Reject mixed undeclared nudge retries
Fresh evidence after the allowlist fix is that this any(...) treats a retry as usable if just one structured call is declared. When the nudge retry returns mixed tool_calls (for example, an undeclared hallucinated call plus a declared one), the callers replace the original response and then forward the whole message.tool_calls list (or, with parallel_tool_calls=false, may cap to the undeclared first call), so clients can still receive a tool they never declared; require all structured retry calls to be allowlisted or filter before accepting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8acc978: a nudge retry now replaces the original only when ALL structured calls name declared tools, so a mixed retry with a hallucinated call keeps the original response. Tests cover both orderings of the mixed list.
| if _allowed_tools: | ||
| heal_openai_message(message, _allowed_tools) |
There was a problem hiding this comment.
Preserve undeclared Anthropic text after healing
Fresh evidence after span-exact healing is that the Anthropic non-streaming builder still applies the legacy _TOOL_XML_RE strip to message.content immediately after this heal. If the model emits a declared text-form call followed by an undeclared/unpromoted call, heal_openai_message removes only the declared span but the strip below deletes the remaining undeclared block before building text content, so Anthropic clients lose the unsupported call instead of seeing it as text; skip the legacy strip when healing promoted, or only strip promoted spans.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3d3bd07 and tightened in dec1703: the legacy _TOOL_XML_RE strip is now gated on healing being active rather than on a call having been promoted, so undeclared-only and malformed-only responses also relay as text instead of being silently emptied (matching the OpenAI passthrough). Opt-out and no-tools requests keep the legacy strip byte-for-byte. Route tests pin the mixed and undeclared-only cases.
…eaming heal_openai_message promotes only declared text-form tool calls and span-trims just their markup, deliberately leaving every unpromoted byte (undeclared text-form calls included) in the content to relay as text. The Anthropic non-streaming builder then ran a blanket _TOOL_XML_RE strip over that content unconditionally, deleting the undeclared block before building the text part, so Anthropic clients silently lost a call the OpenAI non-streaming path preserves. The strip was harmless when healing was all-or-nothing but became data loss once healing turned span-exact. Gate the legacy strip on whether healing promoted a call, matching the OpenAI passthrough and the intent already stated in the comment above. Add a route-level regression test for the mixed declared+undeclared case.
…ropic text Codex round 6, two findings: - response_has_promotable_calls accepted a nudge retry when any one structured call named a declared tool, so a mixed retry (hallucinated undeclared call plus a declared one) replaced the original and the caller forwarded the undeclared call, or with parallel_tool_calls false could keep only it. All structured retry calls must be declared. - The Anthropic non-streaming builder still ran the legacy _TOOL_XML_RE strip after span-exact healing, deleting undeclared or malformed call text that healing deliberately preserved. The legacy strip now runs only when healing is off (no declared tools, or opted out), matching the OpenAI passthrough.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Fixed P1 in 9dee96d. What changed:
Validation:
|
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Fixed the four passthrough healing follow-ups in f69a557. What changed:
Validation:
|
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Local small-model e2e is green on the fork workflow. Fork PR / branch:
Run:
What it ran:
Passing evidence:
No A/B negative run was done here. This is after-state local-model proof only. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17fe722bd0
ℹ️ 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".
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Fixed in 159fd3e. The role-only prefix chunk now always has finish_reason null, so healed tool_call deltas are emitted before the terminal finish chunk. Added a regression test for the same-chunk role + content + finish_reason case. Validation:
|
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@codex review |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
Tool-call healing for the client-tool passthrough (unsloth run / unsloth API / coding agents)
Follow-up to #6613.
Problem
Studio's own chat loop heals malformed tool calls that small GGUF models emit as text (
<tool_call>{...}</tool_call>, Gemma<|tool_call>...,<function=...>XML) and nudges stalled models. Butunsloth run --disable-tools(plain OpenAI-compatible API serving) and every coding agent attached viaunsloth startuse the client-tool passthrough: the agent's own tools go verbatim to llama-server and the response is relayed verbatim back. On that path a text-form tool call reaches the agent as prose and the turn dies.--disable-toolscannot be dropped, since the agent must use its own tools, not Studio's.What this does
Runs the existing healer over passthrough RESPONSES, default ON whenever the request declares client tools:
/v1/chat/completionstool_calls,finish_reasonbecomestool_callsdelta.tool_callschunks, false alarms flush verbatim/v1/responses(Codex)/v1/messages(Claude)tool_useblocks,stop_reasonbecomestool_usetool_useblocksDesign guarantees:
parallel_tool_calls=falseand Anthropicdisable_parallel_tool_usecap healed calls too.Nudging (opt-in)
When the model clearly tried to call a tool (a tool signal in the text) but healing produced nothing usable, an OPT-IN single retry re-asks with the original prompt prefix intact plus a two-message nudge naming the declared tools, so the server reuses the slot's KV cache. Non-streaming only (a stream has already emitted bytes). The retry replaces the original response only when it actually yields a usable call. Enable per request with
nudge_tool_calls: true, or process-wide withUNSLOTH_TOOL_CALL_NUDGE=1.Controls
auto_heal_tool_calls: false(per request, all three APIs)UNSLOTH_DISABLE_TOOL_CALL_HEALING=1nudge_tool_calls: true/UNSLOTH_TOOL_CALL_NUDGE=1unsloth runandunsloth startneed no new flags.Verification
test_passthrough_healing.py(healer state machine units, route-level OpenAI stream/non-stream, Anthropic emitter and non-stream, nudge retry with POST-count and prefix-identity assertions) plus the full regression battery: 486 tests across the passthrough, anthropic, responses, XML-strip, parser, and tool-loop suites, ruff clean.finish_reason: stop; a no-tools request relays raw text verbatim; native grammar-mode tool calls pass through untouched; Claude Code attached via the connector completed a real Write tool turn end to end; llama-server logs confirm slot prefix reuse across turns.Note: current llama-server builds natively parse several text-form call shapes themselves, so this healer is the safety net for the combinations they miss (older builds, cross-template formats such as Gemma-style markers on non-Gemma models, and broken-JSON arguments).