Skip to content

Studio: parse Mistral [TOOL_CALLS] and rehearsal tool-call shapes - #5704

Merged
danielhanchen merged 59 commits into
mainfrom
daniel/studio-mistral-tool-call-rescue
Jul 7, 2026
Merged

danielhanchen merged 59 commits into
mainfrom
daniel/studio-mistral-tool-call-rescue

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Studio's tool-call rescue parsers (core/tool_healing.py and core/inference/tool_call_parser.py) recognise two shapes today: the <tool_call>{json}</tool_call> JSON-in-tag form used by Qwen / Granite, and the <function=name><parameter=k>v</parameter></function> Qwen-Coder XML form. They miss two other shapes that local models commonly emit when bypassing native function calling:

  • Mistral [TOOL_CALLS]name{json_args}. Devstral-Small-2 and Mistral-Small-3.x fall back to this bracket-tag serialisation. Today the call leaks to the UI as raw text and the agentic loop terminates without action.
  • Rehearsal name[ARGS]{json_args}. Reasoning models that "talk themselves into" a tool call inside thinking tokens emit this rehearsal form. Today it's ignored.

The parsers also don't strip <think>...</think> (or [THINK]...[/THINK]) blocks before matching, so a tool call emitted right after a reasoning preamble is sometimes attributed to the wrong span.

Fix

Two new strategies in parse_tool_calls_from_text (both parser modules), added after the existing two and only fired when the prior strategies returned nothing:

  1. Mistral bracket-tag matcher with a brace-balance scan that honours backslash escapes and quoted strings, so nested JSON in args stays intact.
  2. Rehearsal syntax matcher using the same scan helper.

Plus:

  • _THINK_TAG_RE.sub("", content) runs before any pattern match so post-reasoning calls are recognised regardless of position.
  • TOOL_XML_SIGNALS and core/inference/llama_cpp.py:4459 _TOOL_XML_SIGNALS gain [TOOL_CALLS] and [ARGS] so the streaming buffer actually invokes the parser when bracket-tag or rehearsal markup appears.
  • _TOOL_CLOSED_PATS / _TOOL_ALL_PATS in both parser modules and _TOOL_XML_RE in routes/inference.py:431 (the SSE strip) gain the new shapes so raw markup never leaks to the UI. The strip regex tolerates one level of nested JSON objects, sufficient for the args payloads we have seen in the wild.

A small _balanced_json_span helper consolidates the brace-balance scan shared by the two new strategies; _make_tool_call consolidates the OpenAI-shape dict construction.

The new patterns are adapted from forge (https://github.com/antoinezambelli/forge, MIT). Vendored functions carry an attribution note in the file header.

Test plan

  • 17 new parser cases in tests/test_safetensors_tool_loop.py::TestParser:
    • Mistral bracket-tag: basic, whitespace between name and {, nested JSON args, prose surround, bad-JSON dropped, object-with-array-value
    • Rehearsal: basic, prose surround, bad-JSON dropped
    • Thinking pre-strip: <think> ahead of XML and ahead of bracket-tag, [THINK] variant, think-block-hides-inner-call
    • XML wins over bracket-tag when both shapes appear in one message
    • Strip-markup: closed and unclosed-final variants for both new patterns
  • 27/27 TestParser cases pass (10 existing + 17 new).
  • 60/60 cases pass in the full test_safetensors_tool_loop.py.
  • 1552 passed, 4 skipped for studio/backend/tests/. The one pre-existing failure in test_training_worker_flash_attn.py::test_flash_linear_attention_installs_pinned_pair_for_qwen3_5 reproduces on main with this branch stashed; unrelated to these changes.
  • Smoke: unsloth studio boots cleanly via bash install.sh --local with UNSLOTH_STUDIO_HOME set; editable install picks up the edits live; GET /api/health returns healthy.

Backwards compatibility

The new strategies only fire when the existing strategies returned no tool calls, so on valid <tool_call> or Qwen XML input the parser output is byte-identical. Bracket-tag false positives on prose are bounded by requiring the args to decode as a JSON object.

Follow-ups (not in this PR)

  • Safetensors capability detection still distrusts templates that advertise tools via [TOOL_CALLS]. Now that the parser recognises that form, the gate can be revisited per model family with explicit allow-listing after live-sample probing.
  • The two parser modules (core/tool_healing.py and core/inference/tool_call_parser.py) carry near-duplicate regex sets. A follow-up could dedupe to a single source with the other module re-exporting; left out of this PR to keep the diff narrow.

Extends the rescue parsers in core/tool_healing.py and
core/inference/tool_call_parser.py to recognise two extra serialisations
local models commonly emit when bypassing native function calling:

* [TOOL_CALLS]name{json_args} (Devstral-Small-2, Mistral-Small-3.x).
* name[ARGS]{json_args} (reasoning-model rehearsal).

Both extractors use a brace-balance scan that honours escapes and
quoted strings so nested JSON args stay intact.

Also pre-strips <think>...</think> and [THINK]...[/THINK] blocks before
matching so calls emitted after a reasoning preamble are recognised
regardless of position.

Streaming gates (TOOL_XML_SIGNALS, llama_cpp.py _TOOL_XML_SIGNALS) and
the SSE strip regex (routes/inference.py _TOOL_XML_RE) gain the new
sentinels so the parser is actually invoked and the raw markup never
leaks to the UI.

@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: 6439d9f676

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


# Prefixes the streaming buffer watches for to gate in-progress text.
TOOL_XML_SIGNALS = ("<tool_call>", "<function=")
TOOL_XML_SIGNALS = ("<tool_call>", "<function=", "[TOOL_CALLS]", "[ARGS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Detect rehearsal prefix before flushing buffered text

In the safetensors loop, TOOL_XML_SIGNALS now includes bare [ARGS], but the buffering gate only treats text as a potential tool call when stripped.startswith(sig) or sig.startswith(stripped) (see safetensors_agentic.py buffering logic). For outputs that begin with rehearsal syntax like python[ARGS]{...}, the first chunk (python) fails both checks, is emitted as normal content, and only then does [ARGS] trigger draining. Because emitted content is only updated when length increases, that leaked tool-name prefix cannot be retracted, so users see stray text for valid tool calls.

Useful? React with 👍 / 👎.

# core/inference/tool_call_parser.py.
_TOOL_XML_SIGNALS = (
("<tool_call>", "<function=") if auto_heal_tool_calls else ()
("<tool_call>", "<function=", "[TOOL_CALLS]", "[ARGS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Prevent GGUF stream from leaking rehearsal markup

Adding [ARGS] to _TOOL_XML_SIGNALS does not integrate with the GGUF stream state machine: in llama_cpp.py BUFFERING, python[ARGS]{...} is misclassified as plain text after the initial python token and the state flips to STREAMING. In STREAMING, there is no second signal gate, so rehearsal markup is emitted to the client; later regex stripping cannot remove already-emitted text because content events are only sent when cleaned length grows. This means valid rehearsal tool calls can visibly leak tool-call text in the UI.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request expands tool-call parsing and stripping capabilities to support Mistral-style [TOOL_CALLS] and rehearsal name[ARGS] formats, while also introducing logic to strip reasoning blocks ( and [THINK]) before parsing. Feedback highlights several critical areas for improvement: the current signal detection for rehearsal syntax is ineffective for streaming buffers, and the regex for thinking blocks fails to handle unclosed tags during streaming. Additionally, the reviewer noted that the regex-based JSON stripping is limited to a single level of nesting, suggesting a more robust approach using balanced brace scanning. There is also a concern regarding logic duplication and inconsistency between the core parser and the tool healing module, specifically regarding ID generation and helper usage.

# core/inference/tool_call_parser.py.
_TOOL_XML_SIGNALS = (
("<tool_call>", "<function=") if auto_heal_tool_calls else ()
("<tool_call>", "<function=", "[TOOL_CALLS]", "[ARGS]")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Adding "[ARGS]" to _TOOL_XML_SIGNALS is ineffective for preventing rehearsal tool calls from leaking to the UI. The streaming state machine (lines 4708-4718) uses startswith to check these signals against the buffer. Since the rehearsal syntax is name[ARGS], the buffer will not start with [ARGS], and the markup will be streamed to the user until the safety net catches it at the end of the turn. Consider updating the detection logic to handle this non-prefix signal.

Comment on lines +92 to +94
_THINK_TAG_RE = re.compile(r"<think>.*?</think>|\[THINK\].*?\[/THINK\]", re.DOTALL)

# Mistral ``[TOOL_CALLS]name{json}`` prefix. Args extracted via

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The _THINK_TAG_RE regex only matches closed thinking blocks. During streaming, models often have an unclosed or [THINK] block. If a model emits tool-like markup (rehearsal) inside an unclosed thinking block, parse_tool_calls_from_text will fail to strip the block and may incorrectly identify and execute the rehearsal as a real tool call. Updating the regex to handle unclosed blocks at the end of the string ensures that tool calls are only recognized after the model has finished its reasoning preamble.

Suggested change
_THINK_TAG_RE = re.compile(r"<think>.*?</think>|\[THINK\].*?\[/THINK\]", re.DOTALL)
# Mistral ``[TOOL_CALLS]name{json}`` prefix. Args extracted via
_THINK_TAG_RE = re.compile(
r"<think>.*?(?:</think>|$)|\\[THINK\\].*?(?:\\[/THINK\\]|$)", re.DOTALL
)

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +53 to +55
_THINK_TAG_RE = re.compile(r"<think>.*?</think>|\[THINK\].*?\[/THINK\]", re.DOTALL)

def parse_tool_calls_from_text(content: str) -> list[dict]:
# Mistral ``[TOOL_CALLS]name{json}`` prefix.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The _THINK_TAG_RE regex should handle unclosed blocks to prevent rehearsal tool calls from being incorrectly parsed during streaming. See the corresponding comment in tool_call_parser.py for details.

Suggested change
_THINK_TAG_RE = re.compile(r"<think>.*?</think>|\[THINK\].*?\[/THINK\]", re.DOTALL)
def parse_tool_calls_from_text(content: str) -> list[dict]:
# Mistral ``[TOOL_CALLS]name{json}`` prefix.
_THINK_TAG_RE = re.compile(
r"<think>.*?(?:</think>|$)|\\[THINK\\].*?(?:\\[/THINK\\]|$)", re.DOTALL
)


# One level of nested JSON objects in the strip regexes. Deeper nesting
# may leave partial markup, but the call is still parsed correctly.
_BRACKETED_JSON_ONE_LEVEL = r"\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The _BRACKETED_JSON_ONE_LEVEL regex is limited to a single level of nested JSON objects. If a model emits a tool call with more deeply nested arguments (e.g., {"a": {"b": {"c": 1}}}), the stripping logic in _TOOL_CLOSED_PATS and _TOOL_XML_RE will fail to match the entire block, causing raw markup to leak to the UI. While this may cover common cases, leveraging the _balanced_json_span logic for stripping would provide a more robust solution that handles arbitrary nesting.

References
  1. Prioritize consistency with established coding patterns within a module by leveraging robust helpers like _balanced_json_span for parsing logic.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +237 to +267
"id": f"call_{len(tool_calls)}",
"type": "function",
"function": {
"name": tool_name,
"arguments": json.dumps(args),
},
}
)

# Pattern 4: Rehearsal name[ARGS]{json}.
if not tool_calls:
for m in _REHEARSAL_RE.finditer(content):
tool_name = m.group(1)
args_start = m.end()
args_end = _balanced_json_span(content, args_start)
if args_end is None:
continue
try:
args = json.loads(content[args_start : args_end + 1])
except (json.JSONDecodeError, ValueError):
continue
if not isinstance(args, dict):
continue
tool_calls.append(
{
"id": f"call_{len(tool_calls)}",
"type": "function",
"function": {
"name": tool_name,
"arguments": json.dumps(args),
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The implementation of Pattern 3 and 4 in this file duplicates logic from tool_call_parser.py but omits the make_tool_call helper and the id_offset parameter. This divergence increases maintenance burden and breaks the "lockstep" goal mentioned in the module docstring. Additionally, the hardcoded call{len(tool_calls)} ID generation differs from the id_offset-aware logic in the shared parser, which could lead to ID collisions if this module is used in multi-turn contexts where an offset is required.

References
  1. Prioritize consistency with established coding patterns within a module to reduce maintenance burden and ensure architectural alignment.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +437 to +438
r"|\[TOOL_CALLS\]\w+\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}"
r"|\b\w+\[ARGS\]\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The regex for stripping Mistral and rehearsal markup is limited to one level of nested JSON objects. Deeply nested arguments will fail to match and will leak to the UI. Consider using a more robust stripping method or increasing the nesting depth support.

References
  1. Prioritize consistency with established coding patterns by using robust stripping methods for markup to prevent UI leakage.

danielhanchen and others added 2 commits May 22, 2026 15:56
The pre-existing ``_THINK_TAG_RE`` only matched closed thinking
blocks (``<think>...</think>`` or ``[THINK]...[/THINK]``). During
streaming the model is still inside the open block when the parser
runs, so any tool-shaped markup the model is REHEARSING inside that
block survived the strip and could be executed as a real call.
Switch both copies of the regex (parser + healing) to accept the
trailing block being terminated by end-of-string in addition to
the explicit closer.

The ``_TOOL_XML_SIGNALS`` list on the llama_cpp streaming buffer
included ``[ARGS]`` to catch rehearsal syntax, but the gate used a
``startswith`` check against the buffer head -- rehearsal is shaped
``name[ARGS]{json}``, so the buffer never STARTS with ``[ARGS]``
and the signal had no effect. Add a substring fallback for the
bracket-style signals so the BUFFERING window can still divert the
stream into DRAINING when rehearsal markup arrives mid-buffer.

Adds three regression tests covering rehearsal inside unclosed
``<think>`` / ``[THINK]`` blocks (must yield no calls) and the
positive case after a closed think block (still parsed).

@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: 28200411b8

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

_TOOL_ALL_PATS = _TOOL_CLOSED_PATS + [
re.compile(r"<tool_call>.*$", re.DOTALL),
re.compile(r"<function=\w+>.*$", re.DOTALL),
re.compile(r"\[TOOL_CALLS\]\w+\s*\{.*$", re.DOTALL),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve trailing text after nested bracket tool calls

strip_tool_markup(..., final=True) can drop legitimate text that follows a valid bracket/rehearsal call when arguments contain deeper nested objects. parse_tool_calls_from_text accepts nested JSON via _balanced_json_span, but if the closed-strip regex at this line does not match that nesting depth, the fallback unclosed pattern (\{.*$) removes everything from the tool marker to end-of-string, so content after the call is lost (e.g., before [TOOL_CALLS]... } after becomes before). This truncates assistant content in the tool-call path and can silently remove post-call text.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 26, 2026 10:11
Resolve conflicts in the tool-call parser subsystem after main consolidated
the standalone parser into a thin shim that delegates to core/tool_healing.py:

- core/tool_healing.py: keep main's evolved JSON/Gemma/function-XML parser and
  fold in this branch's Mistral [TOOL_CALLS] and rehearsal name[ARGS] passes
  plus thinking-block stripping, so the canonical parser external servers use
  handles all five serializations. Union the strip patterns.
- core/inference/tool_call_parser.py: take main's delegating shim; extend
  TOOL_XML_SIGNALS with [TOOL_CALLS] and [ARGS] so the streaming buffer gates
  bracket-tag markup.
- core/inference/llama_cpp.py: take main's streaming strip helper and shared
  signal path, keeping this branch's mid-buffer substring check so rehearsal
  tags like [ARGS] that arrive mid-buffer are still caught.
- routes/inference.py: keep main's nudge and tool-selection helpers and union
  the display strip regex with the Mistral and rehearsal bracket-tag arms.

@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: 1d0a2a1b13

ℹ️ 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/core/tool_healing.py Outdated
"""
# Strip thinking blocks so post-reasoning calls are recognised and a call
# rehearsed inside an (optionally unclosed) reasoning block is not parsed.
content = _THINK_TAG_RE.sub("", 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.

P2 Badge Preserve literal think tags inside tool arguments

When a valid tool call includes literal <think>...</think> or [THINK]...[/THINK] text inside an argument (for example Python/render_html code or HTML), this unconditional pre-parse substitution removes that argument content before the real parser runs. In the XML parameter form it silently changes the payload (e.g. code containing "<think>x</think>" becomes ""), and in JSON-style calls it can also make the call unparseable, so valid tool calls execute with corrupted inputs or are dropped.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +80 to +83
_MISTRAL_BRACKET_RE = re.compile(r"\[TOOL_CALLS\](\w+)\s*(?=\{)")

# Rehearsal ``name[ARGS]{json}`` prefix.
_REHEARSAL_RE = re.compile(r"\b(\w+)\[ARGS\]\s*(?=\{)")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Accept hyphenated names in bracket parsers

For [TOOL_CALLS] and [ARGS] calls, restricting the tool name to \w+ rejects or truncates MCP tools whose OpenAI function names legitimately include dashes (the repo already tests names like mcp__srv__good-dash_ok and mcp__srv__list-issues). In that scenario [TOOL_CALLS]mcp__srv__list-issues{...} is not parsed at all, while mcp__srv__list-issues[ARGS]{...} is parsed as tool issues, so Studio cannot dispatch the intended tool.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
re.compile(r"<tool_call>.*$", re.DOTALL),
re.compile(r"<\|tool_call>.*$", re.DOTALL),
re.compile(r"<function=[\w-]+>.*$", re.DOTALL),
re.compile(r"\[TOOL_CALLS\]\w+\s*\{.*$", re.DOTALL),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Strip partial bracket signals while buffering

When [TOOL_CALLS] arrives as its own streamed chunk (or before the tool name / {), the buffering loops switch to DRAINING as soon as the signal is seen, then immediately run these streaming strip patterns before the rest of the call has arrived. Because this unclosed pattern only matches after a name and {, that partial marker is emitted as visible content and cannot be retracted by later cumulative diffs even though the completed call is parsed and executed.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated

# Pattern 3: Mistral bracket-tag [TOOL_CALLS]name{json}.
if not tool_calls:
for m in _MISTRAL_BRACKET_RE.finditer(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.

P2 Badge Skip bracket markers inside rejected parameters

With Auto-Heal disabled (allow_incomplete=False), an unclosed <function=...><parameter=...> wrapper is correctly rejected by the XML parser, but this fallback scan then searches inside that still-open parameter value and can promote literal text such as print('[TOOL_CALLS]web_search{"query":"x"}') into an executable web_search call. The earlier XML/Gemma scans explicitly avoid markers inside open parameters; the new bracket/rehearsal fallbacks need the same guard so strict-mode malformed outer calls do not execute argument contents as separate tools.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for parsing and stripping Mistral bracket-tag ([TOOL_CALLS]) and rehearsal ([ARGS]) tool-call formats, as well as stripping thinking blocks (<think>/[THINK]) before parsing. The reviewer feedback highlights potential streaming leaks where partial or unclosed tool-call prefixes can leak to the UI before the opening brace is generated, suggesting regex updates to match these prefixes immediately. Additionally, the reviewer recommends consolidating duplicate parsing loops for the new tool-call formats to improve maintainability.

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.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +47 to +48
re.compile(r"\[TOOL_CALLS\]\w+\s*\{.*$", re.DOTALL),
re.compile(r"\b\w+\[ARGS\]\s*\{.*$", re.DOTALL),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

During streaming generation (in the _S_STREAMING state), _strip_tool_markup_streaming is called on every new token. Because the unclosed regexes for [TOOL_CALLS] and [ARGS] require the opening brace { (e.g., [TOOL_CALLS]\w+\s*\{.*$), any partial tool call generated before the { (such as [TOOL_CALLS]web_search or web_search[ARGS]) will not match the regex and will be streamed/leaked to the UI. Once the { is generated, the regex matches and strips it from the cumulative text, but the already-streamed prefix cannot be erased from the UI, leaving a permanent visual leak.

Removing the requirement for { and matching the prefix immediately (similar to <tool_call>.*$) prevents this leak.

Suggested change
re.compile(r"\[TOOL_CALLS\]\w+\s*\{.*$", re.DOTALL),
re.compile(r"\b\w+\[ARGS\]\s*\{.*$", re.DOTALL),
re.compile(r"\[TOOL_CALLS\].*$", re.DOTALL),
re.compile(r"\b\w+\[ARGS\].*$", re.DOTALL),

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1588 to +1589
r"|\[TOOL_CALLS\]\w+\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}"
r"|\b\w+\[ARGS\]\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Similar to the streaming leak in _TOOL_ALL_PATS, the new patterns added to _TOOL_XML_RE require the opening brace { and a balanced JSON block. If the speculative buffer contains an incomplete or unclosed tool call at the end of the stream (e.g., [TOOL_CALLS]web_search{"query":"weather"), it will not be stripped and will leak to the UI.

We should update these patterns to support matching unclosed blocks up to the end of the string (\Z), similar to how the other XML/Gemma shapes are handled.

Suggested change
r"|\[TOOL_CALLS\]\w+\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}"
r"|\b\w+\[ARGS\]\s*\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}",
r"|\[TOOL_CALLS\]\w+\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?(?:\Z))"
r"|\b\w+\[ARGS\]\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?(?:\Z))",

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +520 to +568
# Pattern 3: Mistral bracket-tag [TOOL_CALLS]name{json}.
if not tool_calls:
for m in _MISTRAL_BRACKET_RE.finditer(content):
tool_name = m.group(1)
args_start = m.end()
args_end = _balanced_json_span(content, args_start)
if args_end is None:
continue
try:
args = json.loads(content[args_start : args_end + 1])
except (json.JSONDecodeError, ValueError):
continue
if not isinstance(args, dict):
continue
tool_calls.append(
{
"id": f"call_{id_offset + len(tool_calls)}",
"type": "function",
"function": {
"name": tool_name,
"arguments": json.dumps(args),
},
}
)

# Pattern 4: Rehearsal name[ARGS]{json}.
if not tool_calls:
for m in _REHEARSAL_RE.finditer(content):
tool_name = m.group(1)
args_start = m.end()
args_end = _balanced_json_span(content, args_start)
if args_end is None:
continue
try:
args = json.loads(content[args_start : args_end + 1])
except (json.JSONDecodeError, ValueError):
continue
if not isinstance(args, dict):
continue
tool_calls.append(
{
"id": f"call_{id_offset + len(tool_calls)}",
"type": "function",
"function": {
"name": tool_name,
"arguments": json.dumps(args),
},
}
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The parsing loops and dictionary construction for Pattern 3 ([TOOL_CALLS]) and Pattern 4 ([ARGS]) are identical. We can consolidate them into a single loop over the two regexes to reduce code duplication and improve maintainability.

    # Pattern 3 & 4: Mistral bracket-tag [TOOL_CALLS]name{json} and Rehearsal name[ARGS]{json}.
    if not tool_calls:
        for regex in (_MISTRAL_BRACKET_RE, _REHEARSAL_RE):
            for m in regex.finditer(content):
                tool_name = m.group(1)
                args_start = m.end()
                args_end = _balanced_json_span(content, args_start)
                if args_end is None:
                    continue
                try:
                    args = json.loads(content[args_start : args_end + 1])
                except (json.JSONDecodeError, ValueError):
                    continue
                if not isinstance(args, dict):
                    continue
                tool_calls.append(
                    {
                        "id": f"call_{id_offset + len(tool_calls)}",
                        "type": "function",
                        "function": {
                            "name": tool_name,
                            "arguments": json.dumps(args),
                        },
                    }
                )
            if tool_calls:
                break
References
  1. To improve efficiency, avoid redundant data iterations. Combine checks and transformations into a single loop and return computed values for callers to reuse.

@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: 5fc0ecc531

ℹ️ 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/core/tool_healing.py Outdated
Comment on lines +78 to +81
_MISTRAL_BRACKET_RE = re.compile(r"\[TOOL_CALLS\](\w+)\s*(?=\{)")

# Rehearsal ``name[ARGS]{json}`` prefix.
_REHEARSAL_RE = re.compile(r"\b(\w+)\[ARGS\]\s*(?=\{)")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Accept hyphenated bracket tool names

When enabled MCP/custom tools contain - in the function name (allowed by _OPENAI_FN_NAME_RE in studio/backend/core/inference/tools.py:836-839 and already supported by the XML/Gemma parsers), these new regexes do not capture the full name. For example [TOOL_CALLS]mcp__srv__list-issues{"q":"x"} is dropped entirely, while mcp__srv__list-issues[ARGS]{"q":"x"} matches only issues, so the tool loop rejects the real MCP call as disabled or can misdirect it if a shorter tool name exists.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +47 to +48
re.compile(r"\[TOOL_CALLS\]\w+\s*\{.*$", re.DOTALL),
re.compile(r"\b\w+\[ARGS\]\s*\{.*$", re.DOTALL),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Strip partial bracket tags while buffering

In the GGUF stream path, llama_cpp.py:8230-8237 enters DRAINING as soon as [TOOL_CALLS] or [ARGS] appears, but these new in-progress strip patterns do not match until the following tool name and { have also arrived. If the stream splits after the tag (for example [TOOL_CALLS] in one delta and web_search{...} in the next, or python[ARGS] before {), _strip_tool_markup_streaming emits the raw bracket marker to the UI before the call is parsed; the existing XML patterns strip bare open markers and these need equivalent partial-tag coverage.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
"""
# Strip thinking blocks so post-reasoning calls are recognised and a call
# rehearsed inside an (optionally unclosed) reasoning block is not parsed.
content = _THINK_TAG_RE.sub("", 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.

P2 Badge Preserve think tags inside tool arguments

When a parsed tool call's argument string contains literal <think>...</think> markup (for example python or render_html code that the user asked to output), this unconditional pre-strip runs before any tool-call spans are identified, so it removes the literal from the argument or can make the JSON tool call invalid; <function=python><parameter=code>print("<think>x</think>")</parameter></function> now executes with {"code":"print(\"\")"}. Restrict think-block removal to text outside tool-call payloads so real tool arguments are not corrupted.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +520 to +525
# Pattern 3: Mistral bracket-tag [TOOL_CALLS]name{json}.
if not tool_calls:
for m in _MISTRAL_BRACKET_RE.finditer(content):
tool_name = m.group(1)
args_start = m.end()
args_end = _balanced_json_span(content, args_start)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse the Mistral tool-call shapes already used in repo

The in-repo Mistral/Ollama templates emit [TOOL_CALLS] [ / [TOOL_CALLS][ JSON-array calls (unsloth/ollama_template_mappers.py:99-101 and 129-131) and Mistral-small-3.2 emits [TOOL_CALLS]name[CALL_ID]i[ARGS]{...} (unsloth/ollama_template_mappers.py:192-194), but this new path only handles [TOOL_CALLS]name{...}. Those outputs either produce no parsed calls or, for the [CALL_ID] form, fall through to the rehearsal parser and execute/reject tool 0 instead of the real tool name, so the advertised Mistral fallback still fails for supported templates.

Useful? React with 👍 / 👎.

Address review findings on the Mistral [TOOL_CALLS] / rehearsal [ARGS] paths:

- Accept hyphenated tool names in the bracket parsers and strip patterns.
  _MISTRAL_BRACKET_RE and _REHEARSAL_RE used \w+, which dropped or truncated
  MCP function names containing dashes (mcp__srv__list-issues). Use [\w-]+ to
  match the XML and Gemma parsers.
- Strip a partial bracket marker streamed before its opening brace. The
  trailing-unclosed patterns required the {, so a [TOOL_CALLS]web_search or
  python[ARGS] split across deltas leaked the raw marker to the UI. Match the
  bare marker to end-of-text, mirroring how the bare open tags are stripped.
  Closed pairs are unchanged so in-progress markup stays buffered until parsed.
- Strip a truncated bracket tail in the route-level display regex. _TOOL_XML_RE
  required a balanced JSON object; a tool call truncated by EOS now strips up
  to \Z, like the orphan-opening XML shapes. Complete calls still strip only
  their balanced JSON so following prose survives.

Add regression tests for hyphenated names, the streaming partial-marker strip,
and the unclosed-tail route strip.

@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: 51181215d4

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


# One level of nested JSON objects in the bracket-tag strip regexes. Deeper
# nesting may leak partial markup, but the call is still parsed correctly.
_BRACKETED_JSON_ONE_LEVEL = r"\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle JSON string braces when stripping bracket calls

When a valid [TOOL_CALLS]/[ARGS] call has an argument string containing a literal unmatched brace, such as [TOOL_CALLS]web_search{"query":"a } brace"}, the parser accepts it via the balanced JSON scanner but this strip regex treats braces inside strings as structure. The closed strip can remove only through the brace inside the string and leave brace"} visible, while an unmatched { in a string falls through to the unclosed pattern and drops all following prose; this pollutes the streamed UI and the assistant message kept for the next tool iteration. The same one-level regex shape is also copied into routes/inference.py for display cleanup.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +528 to +531
for m in _MISTRAL_BRACKET_RE.finditer(content):
tool_name = m.group(1)
args_start = m.end()
args_end = _balanced_json_span(content, args_start)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Skip nested bracket markers inside argument spans

This new fallback scans the entire message for every [TOOL_CALLS] marker without excluding spans already consumed as another bracket call's JSON arguments. If a valid call contains literal marker text in an argument, for example [TOOL_CALLS]python{"code":"print(\"[TOOL_CALLS]web_search{}\")"}, the parser returns both python and a spurious web_search call; similarly, a rehearsal call whose code string contains [TOOL_CALLS]... can have the inner marker executed instead of the real outer call because this pass runs before the rehearsal pass. The XML/Gemma path already tracks spans to avoid promoting markers inside argument data, and these new fallbacks need the same guard.

Useful? React with 👍 / 👎.

The chat template emits <parameter=k>\nVALUE\n</parameter>; the parameter-start
regex consumed the wrapping newline AND the value's first-line indentation via a
trailing \s*, then str.strip() removed the rest, corrupting code/diff arguments.
Narrow the trailing class to horizontal whitespace and trim exactly one wrapping
newline (_trim_param_value), preserving indentation. Matches SGLang's qwen3_coder
detector and the same fix on the multi-format parser. Add a regression test.

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

ℹ️ 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/core/tool_healing.py Outdated
Comment on lines +52 to +53
re.compile(r"\[TOOL_CALLS\].*$", re.DOTALL),
re.compile(r"\b[\w-]+\[ARGS\].*$", re.DOTALL),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require a call body before stripping bracket tails

With tools/Auto-Heal enabled, these new trailing patterns remove any literal [TOOL_CALLS] or word[ARGS] mention through EOF even when no JSON body exists and parse_tool_calls_from_text returns no call. For example, an answer explaining foo[ARGS] or [TOOL_CALLS] can be classified as a false-positive tool signal and then finalized via strip_tool_call_markup(..., final=True), truncating the visible response to the text before the marker. Require an actual {...}/parser-confirmed call span, or skip this cleanup on false positives, so malformed or literal prose is preserved.

Useful? React with 👍 / 👎.

Compress the comments in the Mistral [TOOL_CALLS] / rehearsal [ARGS] healing shim
and its callers to one or two lines, keeping the bracket-tag stripping rationale,
the thinking-block handling note, and the forge attribution intact.

Comment-only: no code or behavior change (verified with comment_tools.py check
--strip-docstrings; tests green).
Review follow-up for the Mistral/rehearsal healing shim:

- The <think>/[THINK] strip ran unconditionally over the whole content before
  parsing, so a real tool argument that legitimately contained a <think> /
  [THINK] literal was silently corrupted. Don't delete the blocks: compute the
  reasoning-block spans and skip any tool-call candidate that STARTS inside one,
  across all parse paths (JSON, Gemma, XML, bracket, rehearsal). A rehearsed call
  inside reasoning is still ignored; a real call after </think> still parses.
- The bracket-tag display strip used a fixed one-level-nesting regex, so a call
  with two-level-nested JSON args either leaked raw markup or, in final mode, let
  the catch-all eat the trailing prose. Add a balanced-brace
  _strip_bracket_tag_calls pass (any nesting depth) used by strip_tool_call_markup
  and the route display strip.

Add regressions: <think>/[THINK] literal inside a real argument, rehearsal-inside-
think with a real call after, and two-level-nested bracket/rehearsal strip keeping
trailing prose.

@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: 2ef1254588

ℹ️ 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/core/tool_healing.py Outdated
# not a real call, so skip any candidate that STARTS inside one. We no longer
# delete the blocks from ``content``: a real tool argument may legitimately
# contain a ``<think>`` / ``[THINK]`` literal, and stripping corrupted it.
_think_spans = [(t.start(), t.end()) for t in _THINK_TAG_RE.finditer(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.

P2 Badge Keep think-span detection out of tool arguments

When a tool argument contains an unclosed literal <think> or [THINK] and the model emits another content-format tool call in the same message, this raw scan marks everything through EOF as a thinking span before tool-call spans are known. The later call then starts inside _think_spans and is skipped; for example, a python call with code print('<think>') followed by a web_search call only returns the python call. Fresh evidence after the prior think-literal fix is that literals are no longer deleted, but they still poison subsequent span detection; exclude accepted tool-call payloads from _think_spans or subtract call spans before applying _in_think.

Useful? React with 👍 / 👎.

"<tool_call>",
"<|tool_call>",
"<function=",
"[TOOL_CALLS]",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop suppressing Mistral safetensors tools

Now that [TOOL_CALLS] is treated as a parser/streaming signal, Mistral safetensors templates still won't enter the tool loop: _detect_safetensors_features only preserves supports_tools for templates containing <tool_call>, <function=, or <|tool_call> (routes/inference.py:1268-1287), and _sf_use_tools gates on that flag (routes/inference.py:5869-5876). For templates that emit [TOOL_CALLS], this new parser path is never reached and the UI/API continue to disable local tools, so the capability gate needs to allow the bracket formats it now parses.

Useful? React with 👍 / 👎.

)

# Pattern 4: Rehearsal name[ARGS]{json}.
if not tool_calls:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse mixed bracket and rehearsal calls

If one assistant turn contains both new top-level formats, for example [TOOL_CALLS]web_search{"q":"x"} followed by python[ARGS]{"code":"..."}, the bracket loop appends the first call and this guard prevents the rehearsal loop from ever scanning the rest of the message. The tool loop supports multiple calls and _strip_bracket_tag_calls will remove both from the assistant content, so the second call is silently dropped rather than executed; collect both new formats in document order (with span checks) instead of making rehearsal contingent on zero bracket calls.

Useful? React with 👍 / 👎.

The think-strip fix replaced the unconditional think-block strip with a
span-skip (the block is kept and any tool-call candidate starting inside it is
ignored), but two comments still described the old strip-first behavior. Update
the _THINK_TAG_RE comment and the parse_tool_calls_from_text docstring.

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

ℹ️ 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
Comment on lines +1589 to +1590
r"|\[TOOL_CALLS\][\w-]+\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?\Z)"
r"|\b[\w-]+\[ARGS\]\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?\Z)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use balanced stripping for route bracket cleanup

In the Anthropic/tool paths that still call _TOOL_XML_RE.sub directly (checked routes/inference.py at lines 8674, 8860, and 9254), these new bracket alternatives only handle one nested object and otherwise fall back to .*?\Z. For a valid call with deeper nested args or braces inside a JSON string, direct cleanup removes trailing prose or leaves argument fragments, e.g. before [TOOL_CALLS]search{"f":{"g":{"h":1}}} after becomes before . The chat-completions helper avoids this via _strip_bracket_tag_calls, so these paths need the same balanced stripping instead of the raw regex.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
fm
for fm in _TC_FUNC_START_RE.finditer(content)
if not _inside_open_parameter(content, fm.start())
if not _inside_open_parameter(content, fm.start()) and not _in_think(fm.start())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve XML boundaries for skipped think calls

When Auto-Heal is enabled, if a model emits a real XML function call and then a <think> block that rehearses another <function=...> marker in the same assistant turn, filtering the rehearsed marker out of func_starts removes the boundary that next_func uses below. The first call's body then extends through the skipped think block, so its arguments are polluted or extra parameters are invented; for example <function=python><parameter=code>print(1)</parameter></function><think><function=web_search><parameter=query>x</parameter></function></think> parses as one python call whose code includes closing tags and whose args include query. Keep think-contained starts as non-executable boundaries, or truncate closed XML calls at their own </function>.

Useful? React with 👍 / 👎.

… keep it linear

- Parse the canonical Mistral array form (TOOL_CALLS followed by a JSON list of
  calls) and emit every call; parse the v11 shape that carries an opaque CALL_ID
  token between the name and ARGS (the function name is the token after
  TOOL_CALLS, never the call-id); and parse a Mistral call plus a rehearsal call
  in one message (the second was dropped yet still stripped from display).
- One shared balanced forward scan (_iter_bracket_spans) backs both the parser
  and the strip path, so they no longer diverge. It is linear: each regex is
  re-searched only once its cached match falls behind the cursor, replacing the
  per-match full-tail re-scan that was O(n^2) (O(n^3) over a stream). A length cap
  before the scan is a backstop.
- strip_tool_call_markup preserves think/reasoning blocks verbatim (the parser
  skips tool markup inside them), stripping only the visible text around them.
- _in_think uses bisect over the sorted think spans (was a linear scan per
  candidate).
- GGUF streaming strip runs the balanced bracket pre-pass before the regex
  patterns so nested-arg calls do not leak or eat trailing prose, and the
  BUFFERING ARGS detector requires the rehearsal name-ARGS shape.
- Tests: canonical array, array string-args, array strip keeps prose, Mistral
  plus rehearsal multi-call, v11 call-id name, think-rehearsal strip
  preservation, and bracket-strip linearity.

@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: 93d8685a9c

ℹ️ 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/core/tool_healing.py Outdated
if _in_think(start):
continue
try:
payload = json.loads(content[m.end() : end])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse comma-less Mistral tool arrays

When a Mistral/Ollama turn contains more than one tool call, the in-repo templates render adjacent objects inside [TOOL_CALLS] [...] without comma separators (unsloth/ollama_template_mappers.py:99-101 and 129-131). This new array path feeds that whole body directly to json.loads, so a shape like [TOOL_CALLS] [{"name":"a","arguments":{}} {"name":"b","arguments":{}}] is rejected, no tools execute, and the final cleanup strips the call text. Normalize or split the top-level objects before loading so the multi-call format the templates emit is honored.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 820b776: the array branch now decodes elements with a comma-tolerant raw_decode (_decode_array_items), so the comma-less multi-call form ollama_template_mappers.py renders recovers every call instead of dropping them all.

Comment thread studio/backend/routes/inference.py Outdated
# the trailing prose after it.
from core.tool_healing import _strip_bracket_tag_calls

return _TOOL_XML_RE.sub("", _strip_bracket_tag_calls(text))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve bracket rehearsals inside think spans

When thinking content is preserved and the model emits a rehearsal such as <think>plan: search[ARGS]{"q":"x"}</think>, this route-level cleanup runs the bracket stripper across the whole cumulative text before streaming/history storage, so the displayed reasoning becomes <think>plan: </think> even though the core parser/stripper intentionally skips tool-looking text inside think spans. Use the same think-aware strip path here, or split around think spans before calling _strip_bracket_tag_calls.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1589 to +1590
r"|\[TOOL_CALLS\][\w-]+\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?\Z)"
r"|\b[\w-]+\[ARGS\]\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?\Z)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Strip canonical Mistral arrays in direct route cleanup

The new route regex only recognizes [TOOL_CALLS] when it is followed by a function name, but the canonical Mistral shapes used in the repo are [TOOL_CALLS] [ / [TOOL_CALLS][ arrays. Several Anthropic/history cleanup paths still call _TOOL_XML_RE.sub directly instead of _strip_tool_xml_for_display (for example the content cleanup around routes/inference.py:8674), so those paths will leak raw [TOOL_CALLS] [...] text even though the helper can strip it. Add an array alternative here or route those call sites through the balanced helper.

Useful? React with 👍 / 👎.

Comment on lines +238 to +242
if end is None:
# Unbalanced / truncated body: skip just this marker and keep scanning
# (a later call may still be complete); the caller's catch-all strips
# the truncated tail.
cursor = m.end()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid rescanning inside unbalanced bracket payloads

When a bracket/rehearsal call starts but its JSON body is unbalanced, this branch advances only past the prefix and then resumes searching inside that rejected payload. If the malformed argument text contains a literal marker, e.g. [TOOL_CALLS]python{"code":"unterminated [TOOL_CALLS]web_search{}, the outer call is rejected but web_search is still returned and can execute even though it was data inside the failed call; treat the unbalanced bracket body as a consumed/rejected span or stop scanning that tail.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for parsing and stripping bracket-tag tool calls (such as Mistral's [TOOL_CALLS] and reasoning-model rehearsals like name[ARGS]), while also ensuring that <think> and [THINK] blocks are properly handled and skipped during execution. Feedback is provided to robustly handle CRLF (\r\n) line endings in _trim_param_value to prevent trailing carriage returns, and to update _strip_tool_xml_for_display so that it preserves think blocks consistently with strip_tool_call_markup to avoid UI display corruption.

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.

Comment on lines +435 to +445
def _trim_param_value(val: str) -> str:
"""Trim a single wrapping newline the chat template adds around an XML
parameter value (``<parameter=k>\nVALUE\n</parameter>``) while preserving any
significant leading indentation / trailing whitespace inside VALUE. Using
``str.strip()`` here destroyed the indentation of code/diff arguments; SGLang's
qwen3_coder detector trims only the wrapping newline."""
if val.startswith("\n"):
val = val[1:]
if val.endswith("\n"):
val = val[:-1]
return val

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The _trim_param_value function currently only checks for \n when trimming the wrapping newlines. If the LLM output or chat template uses \r\n (CRLF) line endings, a trailing \r will be left in the parameter value, which can corrupt code or diff arguments. We should handle both \r\n and \n line endings robustly.

def _trim_param_value(val: str) -> str:
    """Trim a single wrapping newline the chat template adds around an XML
    parameter value (<parameter=k>\nVALUE\n</parameter>) while preserving any
    significant leading indentation / trailing whitespace inside VALUE. Using
    str.strip() here destroyed the indentation of code/diff arguments; SGLang's
    qwen3_coder detector trims only the wrapping newline."""
    if val.startswith("\r\n"):
        val = val[2:]
    elif val.startswith("\n"):
        val = val[1:]
    if val.endswith("\r\n"):
        val = val[:-2]
    elif val.endswith("\n"):
        val = val[:-1]
    return val

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines 1596 to 1605
"""Apply route-level XML leak cleanup only when Auto-Heal is enabled."""
if not auto_heal_tool_calls:
return text
return _TOOL_XML_RE.sub("", text)
# Strip bracket-tag calls with the parser's balanced-brace scan first so a
# two-level-nested JSON arg is removed whole instead of the catch-all eating
# the trailing prose after it.
from core.tool_healing import _strip_bracket_tag_calls

return _TOOL_XML_RE.sub("", _strip_bracket_tag_calls(text))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The _strip_tool_xml_for_display function does not preserve think blocks when stripping tool calls. This is inconsistent with strip_tool_call_markup in core/tool_healing.py which explicitly preserves think blocks to avoid corrupting visible reasoning. If a model rehearses a tool call inside a think block, _strip_tool_xml_for_display will strip it, resulting in a corrupted/incomplete think block displayed in the UI. We should split the text by think spans and only strip tool calls outside of them.

def _strip_tool_xml_for_display(text: str, *, auto_heal_tool_calls: bool) -> str:
    """Apply route-level XML leak cleanup only when Auto-Heal is enabled."""
    if not auto_heal_tool_calls:
        return text
    from core.tool_healing import _strip_bracket_tag_calls, _THINK_TAG_RE

    think_spans = [m.span() for m in _THINK_TAG_RE.finditer(text)]
    if not think_spans:
        return _TOOL_XML_RE.sub("", _strip_bracket_tag_calls(text))

    pieces: list[str] = []
    prev = 0
    for s, e in think_spans:
        segment = text[prev:s]
        pieces.append(_TOOL_XML_RE.sub("", _strip_bracket_tag_calls(segment)))
        pieces.append(text[s:e])
        prev = e
    segment = text[prev:]
    pieces.append(_TOOL_XML_RE.sub("", _strip_bracket_tag_calls(segment)))
    return "".join(pieces)

@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: 93d8685a9c

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

"<|tool_call>",
"<function=",
"[TOOL_CALLS]",
"[ARGS]",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep safetensors rehearsal calls buffered

Adding [ARGS] to the shared signal set does not actually keep safetensors rehearsal calls buffered: run_safetensors_tool_loop still checks only stripped.startswith(sig) / sig.startswith(stripped) in its BUFFERING state, so a normal token split such as python then [ARGS]{...} falls through to STREAMING and emits python before the later [ARGS] detection drains and executes the tool. This leaks tool-call text for the safetensors backend; mirror the GGUF rehearsal substring check there or avoid exposing [ARGS] through this shared prefix list.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +41 to +42
re.compile(r"\[TOOL_CALLS\][\w-]+\s*" + _BRACKETED_JSON_ONE_LEVEL, re.DOTALL),
re.compile(r"\b[\w-]+\[ARGS\]\s*" + _BRACKETED_JSON_ONE_LEVEL, re.DOTALL),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve bracket calls inside thinking while streaming

These new bracket/rehearsal strip patterns are also consumed by streaming helpers that do not split around <think> / [THINK] blocks, unlike strip_tool_call_markup. When a reasoning block contains a rehearsed call such as <think>plan search[ARGS]{"q":"x"}</think> answer, the parser correctly skips it and final stripping preserves it, but the streaming cleanup deletes the rehearsal from the cumulative text before the route diffs it, corrupting visible reasoning. Apply the same think-span segmentation to the streaming cleanup paths.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1589 to +1590
r"|\[TOOL_CALLS\][\w-]+\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?\Z)"
r"|\b[\w-]+\[ARGS\]\s*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}|.*?\Z)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Route bracket stripping through the balanced helper

The new route-level bracket alternatives are still used directly by several _TOOL_XML_RE.sub call sites in this file, bypassing _strip_bracket_tag_calls. In those paths the canonical Mistral array form ([TOOL_CALLS] [{...}]) is not stripped at all, and deeper nested args fall through to the .*?\Z tail branch, so [TOOL_CALLS]search{"f":{"g":{"h":1}}} tail deletes tail; use the balanced display helper for those direct call sites or make this regex safe for the same shapes.

Useful? React with 👍 / 👎.

# Rehearsal shape ``name[ARGS]`` only;
# a bare ``[ARGS]`` in prose is not a
# call start (re caches the pattern).
if re.search(r"[\w-]\[ARGS\]", stripped_buf):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Buffer GGUF rehearsal names before the marker

This GGUF check only fires after [ARGS] is already in content_buffer; if the stream splits as python followed by [ARGS]{...}, the first token is treated as plain text, emitted, and only the later cumulative safety net executes the tool. The UI has already received the raw tool name by then, so valid rehearsal calls can still leak visible markup; keep buffering active tool-name prefixes (within the existing buffer cap) until you can rule out the following [ARGS] marker.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/tool_healing.py Outdated
re.compile(r"<\|tool_call>.*$", re.DOTALL),
re.compile(r"<function=[\w-]+>.*$", re.DOTALL),
re.compile(r"\[TOOL_CALLS\].*$", re.DOTALL),
re.compile(r"\b[\w-]+\[ARGS\].*$", re.DOTALL),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restore GGUF text after false [ARGS] matches

The new open-ended rehearsal strip removes everything from word[ARGS] to EOF during GGUF streaming even before a valid JSON payload exists. If the model is merely explaining that syntax or emits malformed markup, the safety parse later returns no tool calls and this path assumes the content was already streamed, so the answer remains truncated (for example foo[ARGS] means ... can leave only foo visible); restore content_accum on false positives or avoid applying the tail strip while still in the normal streaming path.

Useful? React with 👍 / 👎.

@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: 820b776bd4

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

# Buffer only on signals the healer's parser can promote -- narrower than the loops'
# TOOL_XML_SIGNALS: loop-only signals like the bare ``[ARGS]`` rehearsal marker (name-gated
# in the loops) would hold legitimate prose until finalization without ever promoting.
_HEAL_SIGNALS = ("<tool_call>", "<|tool_call>", "<function=", "[TOOL_CALLS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include rehearsal markers in passthrough healing

When a client-tool passthrough response emits the newly supported rehearsal shape, e.g. Bash[ARGS]{"cmd":"ls"}, this gate never calls parse_tool_calls_from_text because _HEAL_SIGNALS excludes [ARGS]. As a result heal_openai_message, nudge_should_retry, and the streaming healer leave the raw text in the response instead of promoting it to a declared tool call, even though the parser added in this change can parse that shape; the gate needs an active-tool-name check for NAME[ARGS] rather than filtering it out entirely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting: this is a deliberate, tested design tradeoff, not a dropped call.

The bare rehearsal marker is intentionally excluded from _HEAL_SIGNALS, and TestHealerSignalAlignment pins that. The parser can indeed read a bare NAME[ARGS]{json}, but the passthrough gate is a plain substring matcher shared with the streaming healer; if it buffered on the bare [ARGS] marker it would hold legitimate prose (for example the phrase foo[ARGS] in templates) until finalization without ever promoting, which test_prose_with_bare_args_marker_streams_through asserts must stream through incrementally.

Real Mistral tool calls on this client-tool passthrough arrive as [TOOL_CALLS], which IS a heal signal and IS promoted (test_bracket_tool_calls_still_promote_in_stream). The bare NAME[ARGS] form with no [TOOL_CALLS] is the reasoning-rehearsal shape, name-gated only inside the loop where that machinery exists; it is not a real single-format final-call format on the GGUF passthrough, so no declared-tool call is lost by leaving it out.

Comment on lines +791 to +792
if not isinstance(item, dict) or "name" not in item:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve skipped Mistral array bytes

When a [TOOL_CALLS] array contains an element the parser skips, such as [TOOL_CALLS][{"arguments":{}},{"name":"Bash","arguments":{"cmd":"ls"}}], this continue leaves tile_start at the start of the array, so the later valid call gets a span that includes the skipped element. with_spans consumers such as the passthrough healer drop promoted spans, so promoting the valid call silently deletes the skipped bytes instead of relaying them as text; the skipped interval needs to be preserved outside any promoted call span.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting as malformed-markup recovery.

The continue only fires for an array element that is not an object or has no name key. A real Mistral [TOOL_CALLS] array element is always an object with name and arguments; a nameless element such as {"arguments":{}} is malformed model output, not a legitimate single-format call. The valid call is still promoted correctly, and the only bytes folded into its span are that malformed fragment, which is part of the tool-call array markup, not prose and not a real call.

Valid-but-undeclared array elements are already kept as text with their own span (test_mistral_array_undeclared_middle_kept_as_text_others_promoted), so no real call and no real prose is ever dropped. Under the strict bar, malformed-markup recovery is out of scope.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1369 to +1370
if features.get("reasoning_always_on"):
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Don’t prefill reasoning for paired think templates

When a safetensors template is classified as reasoning_always_on because it contains hard-coded paired <think>...</think> markers for rendered assistant history, this unconditional True starts _ResponsesReasoningExtractor inside an unseen prefilled block even though the generation prompt may not have opened one. A normal answer that never emits </think> is then returned entirely as reasoning_content with empty visible content, so chat/Responses clients can see a blank answer for those templates; only enable prefilled mode when the generation prompt actually leaves <think> open.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed genuine and fixed in commit 1625d28.

Reproduced on a real released template: moonshotai/Kimi-K2-Thinking. detect_reasoning_flags classifies it reasoning_always_on because it carries no enable_thinking, reasoning_effort, or thinking keyword yet contains paired think markers and reasoning_content. Its generation prompt is the plain assistant marker with no open think tag; the paired markers come only from rendered assistant history. So _sf_reasoning_prefill_mode returned True while the prompt opened nothing, and a normal answer that never emits a think close marker was captured entirely as reasoning_content with blank visible content (verified end to end: a plain answer yields empty visible content under the current prefilled mode).

The fix gates the reasoning_always_on branch on the rendered generation prompt: it renders a probe prompt and prefills only when that prompt actually ends inside an open think tag. DeepSeek-R1, QwQ, and Qwen3-Thinking still prefill (verified they render an open think tag at the end of the generation prompt), while Kimi-shape history-only templates now start the extractor in normal mode and correctly parse the model's own think block.

Regression test test_g7b_reasoning_always_on_history_only_not_prefilled fails without the change (returns True) and passes with it; the full prefill-gate suite stays green.

Comment thread studio/backend/routes/inference.py Outdated
# honor it so we don't prefill and capture the answer.
if reasoning_effort == "none":
return False
return enable_thinking is not False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Match prefill mode to the rendered thinking flag

When API callers omit enable_thinking, this returns prefilled mode for every enable_thinking template, but the safetensors template helper only forwards enable_thinking when it is non-None, so templates that open <think> only under {% if enable_thinking is defined and enable_thinking %} render no prefilled block. In that default request, a normal answer without </think> is captured entirely as reasoning_content and the visible content is empty; prefilled mode needs to follow the actual rendered kwarg, not treat omission as enabled.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting: not reachable on a real template, and the suggested change would regress real ones.

When enable_thinking is omitted the kwarg is not forwarded, so the template renders with enable_thinking undefined, as noted. But every real enable_thinking template falls into one of two camps and neither blanks. Templates that open the think tag on undefined (Qwen3.5, Intern-S1, Ring-lite) render an unclosed think tag on a default request, so prefilled mode is required and treating omission as enabled is correct. Templates that render no prefill on undefined (Qwen3, GLM-4.5 and 4.6, Nemotron-Super-1.5) are self-thinking, so the model always emits a think close marker and the extractor parses it.

Matching prefill to the rendered flag (prefill only when enable_thinking is explicitly true) would blank the first camp instead: verified on the real Qwen3.5 template, an omitted request renders an unclosed think tag, and forcing normal mode there leaks the reasoning into the visible answer with empty reasoning_content.

A model that answers plainly by default drops the enable_thinking keyword from its template and is never classified enable_thinking, so it already gets normal mode. The assumed template (opening the think tag only when enable_thinking is defined and truthy, paired with a non-thinking default) does not exist among real released models. The reasoning_always_on decoupling that IS real is handled separately in item 3.

reasoning_always_on fires on any paired <think></think> in the template,
including markup that only renders PAST assistant history (Kimi-K2-Thinking)
while the generation prompt opens no <think>. Starting the reasoning extractor
in prefilled mode there captured a normal answer entirely as reasoning_content
and returned blank visible content. Prefill only when rendering the generation
prompt actually leaves <think> open (DeepSeek-R1 / QwQ / Qwen3-Thinking);
history-only templates start the extractor in normal mode and parse the model's
own <think>...</think>. Adds a Kimi-shape regression test.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector 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: 1625d28e4a

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

# Buffer only on signals the healer's parser can promote -- narrower than the loops'
# TOOL_XML_SIGNALS: loop-only signals like the bare ``[ARGS]`` rehearsal marker (name-gated
# in the loops) would hold legitimate prose until finalization without ever promoting.
_HEAL_SIGNALS = ("<tool_call>", "<|tool_call>", "<function=", "[TOOL_CALLS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Align rehearsal retry acceptance with healing

When a nudge retry returns a bare rehearsal call such as web_search[ARGS]{"query":"cats"}, response_has_promotable_calls() now accepts it because the shared parser can promote NAME[ARGS], but heal_openai_message_events() still gates on _has_heal_signal() and this signal list excludes [ARGS]. In the non-streaming passthrough routes, that means an initially unparseable response can be replaced by the retry data and then fail to heal, leaking the raw rehearsal text instead of returning tool_calls; either name-gate rehearsal here too or make retry acceptance use the same heal gate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rehearsal-marker family, already settled by design and pinned by TestHealerSignalAlignment. The [ARGS] marker is deliberately excluded from _HEAL_SIGNALS: a bare name[ARGS]{...} is the reasoning-rehearsal form, name-gated in the loops; ungated in the healer it would stall legitimate prose until finalization without ever producing a promotable call. On the real Mistral v11 template the committed call is always [TOOL_CALLS]name[ARGS]{...}, which carries the [TOOL_CALLS] heal signal and heals fine; a bare name[ARGS]{...} with no [TOOL_CALLS] is never a released-template committed call. The asymmetry cannot lose a real declared call: nudge_should_retry only fires when the original is non-promotable, so response_has_promotable_calls at most swaps one non-promotable body for another, and both relay their markup as text (identical data outcome, no tool_call dropped). The only way to turn the bare rehearsal into a tool_call is to heal bare [ARGS], which is exactly the design the test pins against. Rejecting.

Comment on lines +790 to +792
for item_idx, item in enumerate(payload):
if not isinstance(item, dict) or "name" not in item:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve skipped Mistral array elements

When a [TOOL_CALLS] array contains a decoded element without a top-level name before a valid call, this continue leaves tile_start pointing before the skipped element, so the next call's span covers and removes that malformed element. With with_spans consumers such as passthrough healing, promoting the later declared call silently deletes the unparseable bytes instead of relaying them as text.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Malformed-markup family, unreachable on a real template. A [TOOL_CALLS] array element without a top-level name is malformed Mistral: the released format is [TOOL_CALLS] followed by a JSON list of {"name":...,"arguments":...} objects where every element carries a name (confirmed against mistral-common and the Mistral tokenization docs). A valid declared call in the same array is still promoted correctly; only the adjacent nameless bytes are absorbed into its span. Named-but-undeclared elements are the real case and they already stay visible as text (test_mixed_array_filtered_first_keeps_its_bytes_only and _second_stays_visible pin that). So no real call is lost or altered; the only thing absorbed is broken markup with no name, which no released Mistral output emits. Rejecting.

Comment on lines +872 to +875
for pat in _TOOL_OPEN_XML_TAIL_PATS:
for m in pat.finditer(text):
if not any(s <= m.start() < e for s, e in spans):
spans.append(m.span())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep prose XML openers from hiding think blocks

If the model mentions a marker literally, e.g. <tool_call> is the syntax, before a <think>...</think> block, this treats that prose opener as an unclosed tool span through EOF. _think_spans_outside_tool_markup() then discards the later think span, so a gated web_search[ARGS]{...} rehearsed inside the thought block is parsed/executed instead of skipped; avoid using an unparseable open tail to mask later reasoning blocks.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Cross-format / quoted-example family, unreachable on a real single-format session. The scenario needs a literal tool_call XML opener mentioned as prose (the Qwen / Hermes serialization) placed before a think block that rehearses name[ARGS]{...} (the Mistral rehearsal serialization). Those are two different model families formats; a real single-format session never carries both. It also needs the prose marker to precede the think block, but reasoning models emit their think block first, not after visible prose. Treating an unclosed XML opener as an incomplete call through EOF is deliberate: a think tag inside a genuinely unclosed call arguments must stay argument data, not become a reasoning block. Reversing that to satisfy a prose-mention edge case would regress the real truncated-call case. Rejecting.

Comment on lines +776 to +777
closer = re.match(r"\s*\[/TOOL_CALLS\]", content[end:])
region_end = end + closer.end() if closer else end

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Absorb delayed Mistral closers before relaying

For streamed v11 Mistral output where [TOOL_CALLS]name[ARGS]{...} and the trailing [/TOOL_CALLS] arrive in separate chunks, the parser reports a complete call as soon as the JSON balances because the closer is only consumed when it is already present in the same buffer. StreamToolCallHealer then promotes the call immediately, and the later bare closer is not one of _HEAL_SIGNALS, so it is relayed as visible text; delay promotion for the optional closer or have the healer swallow a delayed closer.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Nonexistent-token / streaming-display-residue family. Verified against mistral-common authoritative SpecialTokens enum: [TOOL_CALLS] has no [/TOOL_CALLS] closing counterpart. Only [/AVAILABLE_TOOLS], [/TOOL_RESULTS], [/INST], [/SYSTEM_PROMPT] and [/THINK] are paired; [TOOL_CALLS] is a begin-of-tool marker whose call ends at end-of-sequence or the next control token. No released Mistral v11 model (Devstral, Magistral, Mistral-Small) emits [/TOOL_CALLS], so a delayed [/TOOL_CALLS] closer split across stream chunks cannot occur on a real template. Even on the defensive path, the call itself is promoted correctly with correct arguments; only a stray trailing marker would relay, which is display residue, not a lost, dropped, or wrong call. Rejecting.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1625d28e4a

ℹ️ 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 +818 to +822
call_spans.append((tile_start, item_end))
tile_start = item_end
if last_span_idx >= 0:
tile_start, _tile_end = call_spans[last_span_idx]
call_spans[last_span_idx] = (tile_start, region_end)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve mixed Mistral arrays in passthrough healing

When a single [TOOL_CALLS][...] array contains both declared and undeclared client tools, these tiled per-item spans split the shared array wrapper across calls. The passthrough healer removes spans for promoted calls but emits unpromoted spans as text, so with allowed tools {a, c} and an array [a, b, c], the client receives only ,{"name":"b",...} for the undeclared call (missing the [TOOL_CALLS][ prefix and closing ]) while a and c are promoted. That violates the passthrough contract that undeclared calls are relayed byte-intact; mixed arrays should be handled all-or-nothing or preserve the shared wrapper around unpromoted items.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting. This is the deliberate tiling design and it is already pinned by test_mistral_array_undeclared_middle_kept_as_text_others_promoted in studio/backend/tests/test_passthrough_healing.py. The tiling assigns every byte of the array to exactly one span, so no byte is ever deleted: the promoted calls' markup is stripped exactly once and each unpromoted element stays visible as text. In the allowed a,c over array a,b,c example the undeclared b is relayed as text and the test asserts its name survives, so there is no data loss; only the shared wrapper is redistributed to the promoted neighbours. The passthrough contract is byte preservation plus never inventing an undeclared tool, and both hold here. Reconstructing a standalone wrapper around each unpromoted middle element is a design change, not a correctness fix. It is also not a well-formed single-format real-session output: a passthrough model only sees the declared tools in its prompt, so a single array mixing a declared parallel call with a genuinely undeclared middle tool is a hallucination, not a legitimate emission.

Comment thread studio/backend/core/tool_healing.py Outdated
Comment on lines +811 to +812
"name": item.get("name", ""),
"arguments": json.dumps(args),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid double-encoding scalar array arguments

When the canonical Mistral array form carries a scalar string argument, e.g. [TOOL_CALLS][{"name":"web_search","arguments":"weather"}], this branch leaves args as the Python string and then serializes it again. The downstream argument healer receives "weather" instead of weather, so single-string tools such as web_search execute with a query that includes literal quotes; the existing <tool_call>{"arguments":"weather"} path passes the same scalar through without the extra encoding.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed and fixed in 8b78c91. Traced end to end: in the canonical Mistral array form a bare scalar string argument, for example the arguments value weather, was left as a Python string and then passed through json.dumps, producing the JSON string with literal quote characters around it. coerce_tool_arguments downstream json.loads that back to a plain string, which is not a Mapping, and heals it by wrapping the raw quoted form, so web_search ran with a query of weather that still carried the quote characters. The tool_call XML path already keeps the same scalar raw and heals to a clean query of weather, so the two formats disagreed. The fix serializes only a dict and leaves a scalar string raw, mirroring the XML path exactly. Canonical object arguments and JSON-string-of-object arguments are unchanged; added test_mistral_array_scalar_string_argument_not_double_encoded asserting both formats yield identical healed arguments.

if (
(opener is None or close.start() < opener.start())
and not any(cs <= close.start() < ce for cs, ce in call_spans)
and any(cs >= close.end() for cs, ce in call_spans)

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 Skip tool calls before a prefilled think close

For templates that prefill an opening <think> in the prompt, the model only emits the closing </think>, so a draft call before that close is still reasoning. This guard only adds the leading think span when there is another call after the close; with output like planning web_search[ARGS]{...}</think> final answer, the only call is before </think>, _in_think stays false, and the parser executes a tool the model merely rehearsed in its hidden reasoning.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting. The current behaviour is deliberate and pinned by test_stray_close_after_real_call_not_treated_as_prefill and test_rehearsal_inside_prefilled_think_is_ignored in studio/backend/tests/test_safetensors_tool_loop.py, added by commit 023e078. From the output text alone the parser cannot separate the prefilled case (planning, a draft call, then the closing think marker, no further call) from an ordinary non-prefilled answer that emits a real leading call before a stray closing think marker with nothing after it, for example Now web_search[ARGS]{...} then the closing think marker then answer. The two byte streams are identical, and the parser never sees whether the prompt prefilled an opening think tag. Commit 023e078 deliberately chose to fire the call in that ambiguous no-following-call case to avoid dropping a genuine leading call, which is data loss; requiring that a real call also follow the close keeps the rehearse-then-call case skipped while protecting the stray-close case. Dropping the leading call whenever nothing follows the close, as proposed, reintroduces exactly the drop that commit fixed and breaks its test.

# Buffer only on signals the healer's parser can promote -- narrower than the loops'
# TOOL_XML_SIGNALS: loop-only signals like the bare ``[ARGS]`` rehearsal marker (name-gated
# in the loops) would hold legitimate prose until finalization without ever promoting.
_HEAL_SIGNALS = ("<tool_call>", "<|tool_call>", "<function=", "[TOOL_CALLS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Flush malformed Mistral false alarms while streaming

Adding [TOOL_CALLS] to the streaming passthrough heal signals makes StreamToolCallHealer enter its hold state for bracket-tag text, but the false-alarm close detection only knows the XML/Gemma closers. If a model emits a complete but unparseable Mistral block such as [TOOL_CALLS]web_search{not json} and then continues with prose, every following chunk is withheld until finalize() (or the 64 KiB cap) instead of streaming through as raw text, regressing the passthrough contract that unparseable blocks relay normally.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting. Including [TOOL_CALLS] in the streaming heal signals is deliberate and pinned by TestHealerSignalAlignment in studio/backend/tests/test_passthrough_healing.py: unlike the bare [ARGS] rehearsal marker, [TOOL_CALLS] genuinely yields promotable calls (test_bracket_tool_calls_still_promote_in_stream), so it belongs in the set while [ARGS] stays out. The scenario needs a complete but unparseable Mistral block, for example [TOOL_CALLS]web_search{not json}, which is malformed markup, not a well-formed real-session emission; a real Mistral model emits valid JSON arguments and streams through fine (test_mistral_array_then_trailing_prose). There is also no data loss: a held block that never parses and has no recognised closer is exactly what the 64 KiB hold cap and the finalize path are for, so it flushes verbatim as text at the cap or at end of stream. That is bounded streaming latency on malformed input, not a dropped or corrupted call, and adding a Mistral false-alarm closer would only shave that latency on markup a real model does not produce.

A scalar string argument in the canonical Mistral [TOOL_CALLS] array
(for example [TOOL_CALLS][{"name":"web_search","arguments":"weather"}])
was run through json.dumps, turning weather into the JSON string
"weather". The downstream argument healer then wrapped that quoted
form, so a single-string tool like web_search searched for the literal
"weather" with quotes. The <tool_call> path already keeps a scalar
argument raw; mirror it here so only a dict is serialized. Add a
regression test asserting both paths yield the same healed arguments.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector 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: 8b78c91abf

ℹ️ 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 +791 to +792
if not isinstance(item, dict) or "name" not in item:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve skipped Mistral array items when tiling spans

When a [TOOL_CALLS] array contains a non-call element before a promotable tool call, such as [{"arguments":{"x":1}},{"name":"lookup",...}], this continue leaves tile_start at the start of the whole array. The span later emitted for lookup therefore covers the skipped element too, so heal_openai_message_events drops those unpromoted bytes when it promotes the declared call instead of preserving them as text. Advance/tile skipped item boundaries so only the promoted call's markup is removed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The nameless leading element in your example, the object carrying only arguments and no name, is not a well-formed Mistral array call: every [TOOL_CALLS] element must carry a name. The parser deliberately skips such malformed elements, and the byte-tiling folds them into the enclosing [TOOL_CALLS] region so the whole region is removed exactly once when a promotable call is present. Verified fresh at head 8b78c91: for the array [{arguments:...}, {name:lookup, ...}] the declared lookup call is still promoted and no declared call is lost; only the malformed nameless bytes leave with the region, which is malformed-markup cleanup, not data loss. Emitting that fragment as visible text would instead leak malformed tool-call residue to the client. The intended behavior for a well-formed but undeclared neighbour (kept as text) is pinned by test_mistral_array_undeclared_middle_kept_as_text_others_promoted, which passes. Declining.

Comment on lines +769 to +772
if not tool_calls:
for start, end, kind, m in _iter_bracket_spans(
content, enabled_tool_names = enabled_tool_names
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse bracket calls alongside XML calls

If a model emits mixed tool-call serializations in one turn, e.g. an XML <tool_call> followed by a Mistral [TOOL_CALLS]... call, this guard skips the bracket scan as soon as the XML call populated tool_calls. The local loops then strip all tool markup from content_text, so the later bracket call is silently discarded instead of executed. Run the bracket scan and merge its spans in document order rather than treating it as a fallback only.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The [TOOL_CALLS] bracket form is Mistral's control-token serialization; the XML tool_call form is the Hermes/Qwen serialization. Per Mistral's and vLLM's docs these are produced by different model families and handled by different parsers (mistral versus hermes), and a single model in a single real session emits exactly one of them. A message carrying both an XML call and a [TOOL_CALLS] call is cross-format two-parseable-calls (an echoed example or a rehearsal), not legitimate single-format output, so the deliberate fallback gate treats the alternate-format lookalike as data. Verified fresh at head 8b78c91 on the passthrough path (this PR's feature): for an XML call followed by [TOOL_CALLS]b{...} the XML call is promoted and the bracket text is relayed back as text, not discarded, so there is no data loss. In the enable-tools loop the lookalike is display-stripped but is not the model's real call, and executing it would be the exact false promotion this gate exists to prevent. Declining.

# Buffer only on signals the healer's parser can promote -- narrower than the loops'
# TOOL_XML_SIGNALS: loop-only signals like the bare ``[ARGS]`` rehearsal marker (name-gated
# in the loops) would hold legitimate prose until finalization without ever promoting.
_HEAL_SIGNALS = ("<tool_call>", "<|tool_call>", "<function=", "[TOOL_CALLS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Heal name-gated rehearsal calls in passthrough

In the client-tool passthrough path, heal_openai_message_events, nudge_should_retry, and StreamToolCallHealer all key off _HEAL_SIGNALS; because this tuple never matches NAME[ARGS]{...}, a declared client tool emitted in the new rehearsal format, e.g. lookup[ARGS]{"q":"x"}, bypasses healing/nudging and is relayed as assistant text. The shared parser now supports this shape, so passthrough needs an active-tool-name-gated [ARGS] signal instead of omitting it entirely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A real Mistral v11 tool call is emitted as [TOOL_CALLS]name[ARGS]{...} (or the pre-v11 [TOOL_CALLS] array). The [TOOL_CALLS] marker is already a heal signal, so genuine Mistral calls in the passthrough are healed. The bare name[ARGS]{...} shape without a leading [TOOL_CALLS] is the reasoning-model rehearsal form, which is name-ambiguous with prose. In the enable-tools loops it is gated on active tool names, but the passthrough streaming healer's signal check is substring-only and cannot name-gate, so adding [ARGS] to _HEAL_SIGNALS would hold any prose containing [ARGS] (for instance guidance like use the foo[ARGS] pattern) until finalization without ever promoting a call. That latency degradation is exactly what test_prose_with_bare_args_marker_streams_through and TestHealerSignalAlignment pin, both passing at head 8b78c91. _HEAL_SIGNALS is deliberately the promotable-only subset. Declining.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8b78c91abf

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

# Buffer only on signals the healer's parser can promote -- narrower than the loops'
# TOOL_XML_SIGNALS: loop-only signals like the bare ``[ARGS]`` rehearsal marker (name-gated
# in the loops) would hold legitimate prose until finalization without ever promoting.
_HEAL_SIGNALS = ("<tool_call>", "<|tool_call>", "<function=", "[TOOL_CALLS]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include rehearsal calls in passthrough healing

When server-side tools are disabled and the client-tool passthrough receives a reasoning-model call like web_search[ARGS]{"query":"cats"}, this signal list never matches it, so non-streaming responses return before calling parse_tool_calls_from_text and streaming responses relay the text immediately instead of promoting the declared tool. The new parser can already parse and filter NAME[ARGS]{...} calls by the declared tool name, so this path still drops one of the newly supported tool-call formats for passthrough clients; use a name-gated rehearsal detector here rather than omitting the format entirely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The bare name[ARGS] rehearsal marker is deliberately kept out of the healer signal set, and this is the sixth re-frame of that same request. The parser can indeed read name[ARGS]{json}, but the healer only buffers on the unambiguous markup openers it can promote without withholding prose. The rehearsal marker is name-gated in the loops; a name-gated detector in the healer still risks stalling legitimate prose, because declared tool names are often ordinary words (a tool named search or read makes prose like use the search[ARGS] pattern buffer until finalize). This alignment is pinned by test_heal_signals_are_promotable_formats_only and test_prose_with_bare_args_marker_streams_through, so this is a deliberate signal-scope choice, not a dropped well-formed call.

if (
(opener is None or close.start() < opener.start())
and not any(cs <= close.start() < ce for cs, ce in call_spans)
and any(cs >= close.end() for cs, ce in call_spans)

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 Do not execute prefilled-only rehearsals

For enable_thinking templates that prefill an open <think> in the prompt, model output can start inside hidden reasoning and only close it with </think>. If that hidden reasoning contains a rehearsal such as web_search[ARGS]{...} and the model then gives a normal answer without any later tool call, this guard refuses to mark the leading 0..</think> region as thinking, so parse_tool_calls_from_text() treats the hidden rehearsal as an executable call. The protection should not depend on there being another call after the close tag.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The follow-a-call requirement on line 897 was added on purpose by commit 023e078 to stop a real leading call from being swallowed. The case you describe, a rehearsal before the close and no call afterwards, is textually identical to the pinned test_stray_close_after_real_call_not_treated_as_prefill case: Now web_search[ARGS]{...} then the close-think marker then answer, which must still fire web_search. Both are the same shape, prose then name[ARGS]{..} then close-think then prose, so content cannot tell a hidden rehearsal from a genuine leading call. Dropping the after-close requirement makes the pinned test regress from firing web_search to producing no call at all, which is the exact data loss that guard fixes. A prior change here was rejected for the same reason; this re-frame lands on the guard line but is the same regression.

Comment on lines +823 to +825
if last_span_idx >= 0:
tile_start, _tile_end = call_spans[last_span_idx]
call_spans[last_span_idx] = (tile_start, region_end)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve undecoded Mistral array bytes

When decoding a [TOOL_CALLS][...] array, _decode_array_items can stop after the first valid object, e.g. [TOOL_CALLS][{"name":"lookup","arguments":{}} THIS SHOULD STAY]. This code then extends the last parsed call's span to region_end, so passthrough healing/display stripping promotes lookup and removes the undecoded tail even though unparseable bytes are supposed to remain text; only extend to the last decoded item, or reject partial arrays, so malformed trailing content is not silently swallowed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

That input is malformed Mistral markup: [TOOL_CALLS][{...} THIS SHOULD STAY] is not a valid JSON array, so the trailing bytes are markup residue inside the array brackets, not a separate prose answer. Prose after the closing bracket is preserved (test_mistral_array_then_trailing_prose keeps all done). Comma-less multi-call arrays still decode every element, so a genuine second call is never dropped; only bytes that no JSON decoder can read, sitting inside the array brackets, are consumed with the malformed array. The declared-tool tiling that keeps an undeclared middle element as text is pinned by test_mistral_array_undeclared_middle_kept_as_text_others_promoted. Extending the last span to region_end is the deliberate one-array-one-region strip; recovering arbitrary bytes from inside a malformed array is out of scope.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

danielhanchen added a commit that referenced this pull request Jul 6, 2026
* studio: deterministic backend tool-calling wiring test

Add a deterministic, download-free test that exercises the shared tool-calling
seam both inference backends use. InferenceBackend (transformers) and
MLXInferenceBackend both render the prompt through
apply_chat_template_for_generation(..., tools=...) and stream cumulative text
into run_safetensors_tool_loop. The existing test_safetensors_tool_loop.py
covers the parser and the loop state machine with fake generators but does not
cover the backend's own tool-injection seam, so a regression that drops the
tool schema before the tokenizer, or fails to feed a tool result back into
generation, would slip through.

The test drives that seam with fakes: a tokenizer that records the tools it is
handed, a canned tool-call generation, and a stub executor. It asserts the full
chain: tools reach the chat template, the loop parses the call, the tool is
dispatched once with the parsed arguments, the result is fed back, generation
re-enters, and the final answer streams after the tool result. It also guards
that the raw tool-call markup never leaks to the client as content.

The test imports no torch, unsloth, or mlx, so it runs in the portable Backend
CI alongside the tool-call parser tests and stays sub-second. Follow-up to the
parser test PRs #5620 and #5704.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studio: assert the tool result is fed back before the final turn

Strengthen the wiring test so single_turn records each turn's conversation and
the test asserts the tool result message is present in the conversation handed
to the final generation turn. Event ordering alone did not catch a loop that
stops appending the tool output before re-entering generation, because the fake
generation ignores the conversation; this closes that gap.

* studio: tighten comments in tool-calling wiring test

* studio: shorten comments in tool-calling wiring test

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

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

1 similar comment
@chatgpt-codex-connector

Copy link
Copy Markdown

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

@chatgpt-codex-connector

Copy link
Copy Markdown

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

@danielhanchen
danielhanchen merged commit f109e7f into main Jul 7, 2026
46 of 47 checks passed
@danielhanchen
danielhanchen deleted the daniel/studio-mistral-tool-call-rescue branch July 7, 2026 01:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant