studio: tool calling + healing parity for Llama-3, Mistral, Gemma 4 on safetensors + MLX (#5620)

* studio: tool calling for Llama-3, Mistral, Gemma 4 on safetensors + MLX (#5615)

Adds tool calling for Llama-3, Mistral (pre-v11 + v11+ + [ARGS]), and Gemma 4 to the safetensors / transformers and MLX backends. Parser patched against llama.cpp / vLLM / SGLang per-family parsers and normalises to OpenAI shape. 96 targeted unit tests + cross-OS staging CI (ubuntu / macos-14 / windows) green on the multi-format probe.

* studio: tool-call healing parity between safetensors / MLX and GGUF

After the multi-format parser landed in #5615, the safetensors / MLX
agentic loop and the GGUF loop still differed on healing behaviour.
This commit closes the gaps in both directions so the two backends
react the same way to identical model output.

Changes:

1. core/inference/llama_cpp.py -- the GGUF BUFFERING state machine
   now wakes on every emission marker the shared parser knows. Was
   ("<tool_call>", "<function="); is now the five-tuple imported
   from core.inference.tool_call_parser (Qwen / Qwen3.5 / Llama-3
   <|python_tag|> / Mistral [TOOL_CALLS] / Gemma 4 <|tool_call>).
   Stream cleanup is delegated to the same shared strip_tool_markup
   so leaked markup from any family is removed from assistant
   content.

2. core/inference/llama_cpp.py -- per-tool canonical heal key. When
   a tool arguments field is a bare string and JSON parsing fails,
   the GGUF path now heals to {"code": raw_args} for python,
   {"command": raw_args} for terminal, and {"query": raw_args} for
   everything else. Was hard-coded to {"query": raw_args}, which
   silently routed every python / terminal emission through
   web_search. Mirrors safetensors_agentic._CANONICAL_HEAL_ARG.

3. core/inference/safetensors_agentic.py -- re-prompt on plan-
   without-action. When the model emits a short forward-looking
   intent ("I'll search for that", "Let me check", "First, I
   will...") and no tool call, the loop nudges the model to act
   instead of silently returning a plan-only answer. Up to
   _MAX_REPROMPTS=3 (matches GGUF). The intent regex, character
   cap, and instruction text are byte-identical to the GGUF path.
   The buffer-end fall-through is unified so a buffered intent
   emission that never exits the BUFFERING state still triggers
   the re-prompt.

4. core/inference/safetensors_agentic.py -- extra iteration slots
   for re-prompts. The loop now budgets max_tool_iterations +
   _MAX_REPROMPTS + 1 total iterations and tracks the tool-call
   count separately, so a stalling model can be nudged 3x without
   eating the caller's tool-call budget. Mirrors the _extra slot
   reservation in the GGUF path.

Tests (14 new safetensors-side units; 5 GGUF parity pins):

  TestLoopRePrompt                 -- intent-trigger, plain-answer,
                                      no-tools, cap-at-three, budget
                                      preserved, buffer-end intent.
  TestLoopCanonicalHealKey         -- python / terminal / unknown.
  TestGGUFSafetensorsHealingParity -- shared markers used, shared
                                      strip used, canonical heal keys
                                      identical, intent regex matches
                                      same phrases, _MAX_REPROMPTS
                                      equal on both backends.

All 110 targeted tests pass locally; the broader tool / inference /
model-config / sandbox / anthropic / mlx suites stay green.

Why this matters

Without this parity, Llama-3.2 / Mistral / Gemma 4 emissions on Mac
(MLX) and Linux-safetensors stop the agentic loop as soon as the
model says "Let me...", because the GGUF re-prompt logic never
existed on these backends. The two-marker GGUF BUFFERING tuple also
let non-Qwen tool emissions stream out as plain prose when
llama-server's structured channel did not pick them up. Both paths
now drain the same way, heal the same way, and re-prompt the same
way -- so a tool call that works on GGUF works identically on
safetensors / MLX.

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

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

* studio: fix tool-call parser bugs from gemini review on #5620

Three high-priority gemini findings on the tool-call parsing additions:

  1. unicode_escape on UTF-8 bytes corrupts non-ASCII literals
     (e.g.  becomes â\x9c¨). Replace with json.loads on a quoted
     string -- preserves emoji / CJK / RTL while still handling
     \n \t \uXXXX escapes.

  2. Llama-3 sentinel stripping is order-dependent. A leading
     `<|eot_id|><|begin_of_text|>` left `<|begin_of_text|>` behind
     because the loop had already passed that sentinel. Loop until
     no sentinel matches at the start.

  3. Mistral v11+ `[TOOL_CALLS] name { json }` regex uses non-greedy
     `\{.*?\}` which truncates at the first `}` of a nested JSON
     argument, leaking the tail (e.g. `}}`) into user-visible
     streamed text. Same problem for the v0.3 array pattern with
     nested brackets. Strip those with balanced brace/bracket
     scanning via a new `_strip_mistral_closed_calls` helper called
     from `strip_tool_markup`.

Also fix the inference routes' parallel `_TOOL_XML_RE`:

  - Same nested-JSON truncation in the Mistral patterns; route the
    strip through the parser's balanced-scan helper via a thin
    `_strip_tool_xml` wrapper that all existing callers now use.
  - Llama-3 `<|python_tag|>[^\n<]*` stopped at any `<`, leaking the
    tail of any tool call whose argument contained a literal `<`
    (queries, code snippets). Relax to `[^\n]*` which keeps the
    strip confined to the actual end-of-line.

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

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

* studio/routes: make python_tag strip multi-line aware

Earlier revisions of _TOOL_XML_RE in studio.backend.routes.inference
oscillated between two bug shapes:

  5615    r"<\|python_tag\|>[^\n<]*"   -- stopped at any literal "<"
                                         so code='if x < 10: pass'
                                         leaked '< 10: pass)' to the
                                         user.
  5620.1  r"<\|python_tag\|>[^\n]*"    -- single-line only; the second
                                         line of
                                         python.call(code="a\nb")
                                         leaked.

The full parser (_parse_llama3_python_tag) already handles both via
balanced-brace scanning, so the parsing path was fine; the LEAK was
in the streaming strip path that runs on every cumulative emission
while content is still arriving.

Switch to r"<\|python_tag\|>(?:[^<]|<(?!\|))*" so the strip consumes:

  * any character that is not a "<" (newlines, JSON, code, ...),
  * a "<" only when it is NOT followed by "|" (i.e. NOT a Llama-3
    sentinel start like <|eot_id|>, <|eom_id|>, <|begin_of_text|>).

This means:

  * code='if x < 10' stays inside the strip (5615 fix preserved),
  * multi-line code stays inside the strip (5620 round 2),
  * the strip terminates at the next Llama-3 sentinel so trailing
    assistant content survives.

Tests: TestRoutesPythonTagStrip (8 cases)
  pytest test_safetensors_tool_loop.py test_safetensors_capability_advertise.py
    -> 118 passed in 1.81s (was 110).

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

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

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

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

* studio: tighten verbose comments in tool-call parser sections

Comments were narrating what the code already says. Cut historical
"earlier revisions used X, then Y" narratives down to one-line WHY
notes where the footgun still matters (canonical heal-key parity,
balanced-brace vs non-greedy regex, ``(?:[^<]|<(?!\|))*`` over
``[^\n<]*``/``[^\n]*``). Drop section-header banners.

No behaviour change. Re-ran:
  pytest studio/backend/tests/test_safetensors_tool_loop.py \
         studio/backend/tests/test_safetensors_capability_advertise.py -q
  -> 118 passed.
Regression replay (parser + _coerce_arguments on the 5 #5615 inputs)
  -> 21/21.

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

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

* studio: parser robustness fixes for PR #5620

Three surgical extensions to the multi-format tool-call parser, each
covering a real fine-tune / template emission shape that the current
parser silently drops. No path narrows; all changes widen what is
accepted.

1. `_parse_tool_call_json` now accepts both `arguments` and
   `parameters` keys. A Hermes / Qwen `<tool_call>{json}</tool_call>`
   wrapper around a Llama-3.2 fine-tune that emits the `parameters`
   key was extracting the tool name and silently discarding the
   args, producing a working-shaped call with an empty payload. The
   bare-JSON and python_tag paths already accepted both keys; this
   path now matches them.

2. `_TC_FUNC_START_RE`, `_TC_PARAM_START_RE`, and `_TC_PARAM_CLOSE_RE`
   now also match the attribute form
   `<function name="..."><param name="...">v</param></function>` used
   by MiniCPM-5 and MiniMax-M2. Names land in either capture group,
   and `</param>` is accepted as a short close.

3. `_parse_llama3_bare_json` sentinel-strip now consumes the role
   label inserted between `<|start_header_id|>` and
   `<|end_header_id|>` by Meta's official Llama-3.x chat template.
   Without this, every assistant turn re-fed through the template
   prefix `<|start_header_id|>assistant<|end_header_id|>\n\n{json}`
   parsed to zero calls, so any history-with-tool-call round-trip
   in production silently dropped.

Tests in `studio/backend/tests/test_safetensors_tool_loop.py`:

* `TestParserRobustness::test_tool_call_json_accepts_parameters_key`
* `TestParserRobustness::test_function_xml_attribute_form`
* `TestParserRobustness::test_function_xml_attribute_form_multi_param`
* `TestParserRobustness::test_function_xml_legacy_equals_form_still_works`
  (regression guard for the existing `<function=name>` syntax)
* `TestParserRobustness::test_llama3_chat_template_round_trip`
* `TestParserRobustness::test_llama3_round_trip_all_roles`
* `TestParserRobustness::test_llama3_round_trip_with_eot_prefix`

`pytest studio/backend/tests/test_safetensors_tool_loop.py
        studio/backend/tests/test_safetensors_capability_advertise.py -q`
goes from 118 to 125 passed.

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

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

* studio: terminate function-XML body at </function>, not just </tool_call>

`_parse_function_xml` was looking for `</tool_call>` (the Hermes
wrapper) as the body terminator. When a model emits a standalone
`<function=NAME><parameter=K>v</parameter></function>` followed by
explanatory prose (which models routinely do), no `</tool_call>` is
present, so the body extended to end-of-string and the trailing
prose leaked into the LAST parameter value.

Pre-existing on main (the legacy `<function=NAME>` form had this
bug too). Same affects PR #5620's new attribute-form
`<function name="NAME"><param name="K">v</param></function>`
emission used by MiniCPM-5 / MiniMax-M2.

Fix: `_TC_END_TAG_RE` now matches either `</tool_call>` OR
`</function>`. The existing `_TC_FUNC_CLOSE_RE` / `_TC_PARAM_CLOSE_RE`
strips are unchanged. Multi-call inputs still bound each function
at the next `<function=` start, so no over-eager consumption.

New tests:

* `test_function_xml_followed_by_prose` (legacy form + prose)
* `test_function_attribute_xml_followed_by_prose` (attribute form + prose)

Existing `test_code_with_embedded_xml` still passes (a parameter
value containing literal `<a></a>` is preserved because the
embedded close tag is `</a>`, not `</function>`).

`pytest studio/backend/tests/test_safetensors_tool_loop.py
        studio/backend/tests/test_safetensors_capability_advertise.py -q`
goes from 125 to 127 passed.

* Studio: tighten Llama-3.2 bare-JSON guard

A fuzz pass on PR #5811 turned up that ``_parse_llama3_bare_json``
accepted ``parameters`` as a string, contradicting the docstring's
"parameters or arguments is a dict" guard. Prose JSON like
``{"name":"foo","parameters":"a sentence"}`` would wrongly fire the
parser, which the agentic loop would then heal into a real
``foo(query="a sentence")`` call.

Same code lives on this branch, so the same fix applies here.

Tightened guard:

  - ``parameters`` must be a dict (Llama-3 spec).
  - ``arguments`` may be a dict, or a JSON-encoded string that
    decodes to a dict (OpenAI shape, e.g.
    ``"arguments":"{\"q\":\"x\"}"``). Plain non-JSON strings or
    JSON-strings of lists / scalars / null no longer pass.

Mirrors the fix landed in PR #5811 commit 615b8608. Adds the same
4 regression tests under TestParserMultiFormat.

Existing test suite stays green: 127 -> 131 passing.

* studio: fix safetensors tool-call parser gaps vs llama.cpp (Mistral CALL_ID / THINK, attribute-form signal)

Three GGUF-parity fixes to the safetensors tool-call parser, each matching
llama.cpp's reference behaviour:

- Mistral Small 3.2 emits [TOOL_CALLS]name[CALL_ID]<id>[ARGS]{json}. The
  parser stopped after the name on seeing [CALL_ID] (neither [ARGS] nor {),
  dropping the call. Skip an optional [CALL_ID]<id> segment in both the
  parse and strip paths. llama.cpp parses this (test-chat.cpp:4785).

- Magistral wraps reasoning in [THINK]...[/THINK]. A [TOOL_CALLS] inside the
  reasoning was parsed as a real call, producing a phantom call. Strip a
  leading [THINK] block before scanning so only the post-reasoning call
  counts (test-chat.cpp:2285); a literal [THINK] inside a later argument is
  left intact.

- The standalone MiniCPM-5 / MiniMax-M2 <function name="..."> attribute form
  parsed correctly but was absent from TOOL_XML_SIGNALS and the markup strip
  patterns, so the streaming safety-net parse was gated off (dropping the
  call) and markup leaked into displayed text. Add the signal and broaden
  the strip regexes.

Adds regression tests for all three.

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

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

* studio: fire safetensors tool calls for the bare-JSON (Llama-3.2) form

The agentic loop's streaming safety-net parse was gated on
has_tool_signal(), which is False for the Llama-3.1 / 3.2 bare-JSON tool
form {"name":..,"parameters":..} (no XML marker). Real tool calls were
therefore dropped: the loop logged "model planned without calling tools",
re-prompted three times, then gave up with zero tool calls, while GGUF's
llama-server parses the same emission natively.

Run parse_tool_calls_from_text() unconditionally in the safety net. The
parser is strict (only fires on a valid tool-call shape) so plain answers
are unaffected. Reproduced on a real unsloth/Llama-3.1-8B-Instruct run:
the model emits {"name":"web_search","parameters":{...}} which now
executes the tool instead of being re-prompted into a no-op.

Adds a loop regression test for the bare-JSON form.

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

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

* Studio: complete strict-mode contract and fix parser import paths

Address review findings on the multi-format tool-call parser:

- Honor allow_incomplete=False in the remaining sub-parsers. The Llama-3
  <|python_tag|>NAME.call(...) parser, the pre-v11 Mistral [TOOL_CALLS] array
  parser, and the Gemma 4 <|tool_call> parser ignored strict mode, so a
  truncated call (missing closing paren, ], or <tool_call|>) was still healed
  and executed with Auto-Heal disabled. Thread strictness through and reject
  the unclosed forms, matching the JSON and function-XML paths.
- Drop the duplicate tool_call_parser import block in llama_cpp.py and the
  redundant un-aliased TOOL_XML_SIGNALS; only the _SHARED_TOOL_XML_SIGNALS
  alias is used as a value.
- Import _strip_mistral_closed_calls from core.inference.tool_call_parser in
  routes/inference.py instead of studio.backend.core... The self-contained
  run.py launch mode only puts studio/backend on sys.path, so the absolute
  package path raised ModuleNotFoundError on the server-tool strip path.

Add strict-mode regression tests for the truncated Llama-3 dot-call and the
unclosed Mistral array.

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

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

* Studio: preserve XML param indentation and alias Mistral array parameters

Two parser-correctness fixes found by auditing against the model chat templates
and the SGLang / vLLM reference parsers:

- Qwen3.5 XML parameter values lost their leading indentation. The chat template
  emits <parameter=k>\nVALUE\n</parameter>, but the parameter-start regex ate the
  wrapping newline AND the value's first-line indentation with a trailing \s*,
  then str.strip() removed the rest. Narrow the trailing class to horizontal
  whitespace only and trim exactly one wrapping newline (via _trim_param_value),
  preserving indentation in code/diff arguments. Matches SGLang's qwen3_coder
  detector. Applies to both _parse_function_xml (tool_call_parser.py) and the XML
  path in tool_healing.py.
- Mistral pre-v11 array objects keyed on parameters dropped their payload.
  _consume_mistral_call read only the arguments key; alias parameters the same way
  the JSON/XML paths and SGLang's base detector do.

Add regression tests for preserved multi-line indentation and the array
parameters alias.

* Studio: tighten tool-call parser comments

Make the comments in the multi-format tool-call parser and its callers succinct:
compress verbose docstrings/blocks to one or two lines, drop ones that restate the
code, and trim the tiny balanced-scanner helpers. Correctness rationale and
upstream provenance (SGLang/llama.cpp parity, the strict-mode / Auto-Heal
contract, whitespace-preservation, and the Unicode / full-width-pipe notes) are
kept in compact form.

Comment-only: no code or behavior change (verified with comment_tools.py check
--strip-docstrings; parser suite green).

* Studio: make Llama-3 .call and Mistral-array healing parsing linear

Two more O(n^2) ReDoS paths in the multi-format parser, both reachable from
the agentic loop on a long truncated body with no length cap:

- _LLAMA3_KV_RE.finditer over a .call(...) body retried at every offset of a
  long word run / unterminated quote (40K -> 14s). Replace with a hand-scan
  that reuses the same key/number/literal sub-regexes via anchored match and
  walks the string body by hand, so an unterminated quote is O(n). Verified
  byte-identical to the old regex over 200K fuzzed inputs.
- _parse_mistral_array healing ran _balanced_brace_end from every { in the
  body (20K -> 17s). Walk top-level objects, advancing past each balanced
  {...}; this also drops the phantom call the old scan emitted from a nested
  argument object.

Add adversarial-length linearity regressions plus positive .call kwargs and
unclosed-array recovery coverage.

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

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

* Studio: honor strict mode in safety-net, keep empty Gemma args, strip attribute-form function XML

- safetensors safety-net parser now forwards allow_incomplete=auto_heal_tool_calls,
  matching the draining path, so a late incomplete tool call is not healed and
  executed when Auto-Heal is off.
- Gemma empty bare value ({k:}) now serialises as "" instead of invalid {"k":},
  which previously dropped the whole call.
- Route _TOOL_XML_RE also strips the <function name="..."> attribute form
  (MiniCPM-5 / MiniMax-M2) so it no longer leaks to the UI.

* Studio: fix attribute-form function-XML literal close tag and zero-arg strict call

Addresses Codex review of the <function name="..."> attribute form in
_parse_function_xml (MiniCPM-5 / MiniMax-M2):
- End the call body at the LAST </function> / </tool_call> within the call's
  window, so a literal close tag inside a code/search argument (e.g.
  print("</function>")) is preserved instead of truncating the call.
- Accept a closed call with no parameters as a valid zero-argument call in strict
  mode (the function close is already required), instead of rejecting it as a
  truncated call.
- Tests for both, mirroring the legacy <function=...> coverage.

* Studio: fix tool-call parser/loop review findings on the multi-format path

Address the live code-review findings on the safetensors/MLX + GGUF tool path:

- routes: include the attribute form <function name="..."> in the safetensors
  capability whitelist so MiniCPM-5 / MiniMax-M2 templates keep the tool pill
  (parser already handles the form; the post-filter wrongly suppressed it).
- safetensors loop: build the plan-without-action re-prompt from the active
  tools instead of a hardcoded web_search/python string, and gate it on
  auto_heal_tool_calls, matching the GGUF loop.
- safetensors loop: hold a leading bare-JSON object ({"name":..,"parameters":..})
  during BUFFERING until it closes, then drain it as a tool call instead of
  streaming the raw JSON to clients. The DRAINING/STREAMING resolvers still
  recover a plain JSON answer, so this can never drop content.
- parser: anchor the Llama-3 <|python_tag|>NAME.call(...) scan to the tag and
  chain ; -separated calls, so all semicolon-separated built-ins parse and a
  literal <|python_tag|>x.call(...) inside a JSON string argument no longer
  fires the wrong tool.
- parser: consume the optional trailing </s> after a named Mistral
  [TOOL_CALLS]name{json} call, mirroring the array shape.
- GGUF streaming strip: use the shared parser patterns (which know
  [TOOL_CALLS] and <|python_tag|>) so a textual tool call entering DRAINING is
  stripped instead of leaking the marker to streaming clients.
- routes: hoist the _strip_mistral_closed_calls import to module level.

Adds regression tests covering each fix; existing parser suite stays green.

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

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

* Studio: harden multi-format tool-call detection from review findings

Apply five targeted fixes from the review pass over the multi-format tool
path:

- routes: route display strip delegates to _strip_tool_xml so Mistral
  [TOOL_CALLS] blocks with nested JSON are removed from streamed display
  text, not just the XML forms.
- tool_call_parser: skip function/parameter starts that fall inside an
  already-open parameter block (_inside_open_parameter) so nested example
  payloads are not mis-parsed as new calls; extract
  strip_llama3_leading_sentinels so the bare-JSON guard is shared.
- safetensors_agentic: probe bare JSON through strip_llama3_leading_sentinels
  before the balanced-brace check so a leaked header sentinel does not defeat
  the guard.
- tool_healing: allow dotted tool names in the Gemma wrapped start pattern.
- llama_cpp (GGUF): buffer wrapper-less Llama-3.2 {"name":..} calls that carry
  no XML signal, drain a complete object silently and hold an incomplete one,
  and run the end-of-stream safety net unconditionally so markerless calls are
  detected and never leak the raw JSON (including truncated fragments).

Adds regression tests for the GGUF bare-JSON streaming path and the Mistral
display strip.

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

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

* Studio: stop bare-JSON tool calls leaking at EOF, oversized, and into history

The second review pass flagged that the Llama-3.2 bare-JSON tool-call handling
still leaked raw JSON in several spots; ``strip_tool_markup`` only knows
XML/bracket markup, so the bare-JSON form survived it. Fix them symmetrically
across the safetensors and GGUF loops:

- Safetensors stream-end resolver now routes a held bare-JSON fragment to
  DRAINING (mirroring GGUF) so a truncated ``{"name":..`` cut off by the end of
  the stream is dropped instead of flushed as assistant content. The 7/10
  reviewer finding.
- Both loops now drain (suppress) an oversized still-open bare-JSON call once it
  passes ``_MAX_BARE_JSON_BUFFER`` instead of streaming the raw prefix, gated on
  a ``"name"`` key so a giant plain JSON answer still streams; a complete
  oversized call still executes via the safety net.
- Add a shared ``strip_leading_bare_json_call`` helper and apply it to the
  content kept for the assistant turn in both loops, so an executed bare-JSON
  call is not replayed as visible text or fed back as next-turn history.

Plain JSON answers without a ``"name"`` key are untouched throughout. Adds
regression tests for the EOF, oversized, and next-turn cases on both backends
plus unit tests for the helper.

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

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

* Studio: bound the Llama-3 python_tag strip on real control sentinels

The route display strip's <|python_tag|> arm ran to the next <| of any kind.
A tool-call argument carrying a literal <|...|> token (for example <|cite|>
inside a string value) truncated the strip early and leaked the call tail into
the visible response. Narrow the stop condition to the genuine Llama control
sentinels (eot_id, eom_id, python_tag, start/end_header_id, begin_of_text,
finetune_right_pad_id) so embedded markup and JSON are consumed while real
header/turn boundaries still bound the strip.

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

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

* Studio: gate markerless bare JSON on enabled tools and close parser/strip asymmetries

The Llama-3.2 custom_tools bare-JSON form has no marker, so any JSON object with a
name key was read as a tool call. An ordinary JSON answer like
{"name":"Alice","parameters":{"age":30}} was misclassified as a call to a
disabled tool and dropped from the visible response. Gate the markerless form on
the enabled tool names (threaded through parse_tool_calls_from_text and
strip_leading_bare_json_call, supplied by both streaming loops): an object whose
name is not an enabled tool is ordinary content. The marker-based forms keep
their name-agnostic behaviour (an explicit signal is a real call attempt), and
unrestricted mode stays ungated.

Also fix two parser/strip asymmetries the parser already tolerated:
- A literal </function> inside a parameter value (print("</function>")) truncated
  both the core and route strips at the first close, leaking the tail. Extend the
  strip to the call's real close (last </function> before the next opener),
  mirroring the parser, without merging separate calls.
- The single-object Mistral [TOOL_CALLS]{...} shape parsed but _strip_mistral_closed_calls
  left it, leaking the raw object into display. Strip the balanced object while
  keeping trailing prose, matching the array and name shapes.

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

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

* Studio tools: gate GGUF bare-JSON suppression on enabled tools and fix python-tag exponent parsing

Pass-4 review follow-ups on the GGUF tool loop and Llama-3 parser:

- The GGUF bare-JSON suppression sites still keyed off a raw "name" substring,
  so an ordinary JSON answer whose name is not an enabled tool was dropped when
  it was truncated, oversized, or reached the no-tool DRAINING fallback (the
  parser, helper, and safetensors paths were already gated). All three sites now
  use the shared enabled-name gate, and a held bare-JSON buffer that turns out not
  to be an enabled call is shown as the answer instead of dropped at stream end.
- The Llama-3 python-tag numeric kwarg regex matched only the mantissa, so
  scientific notation was truncated to its leading digits (1e-3 parsed as 1) and a
  tool executed with the wrong value. The regex now accepts exponent and decimal
  forms, and the int/float classification keys off the exponent too.

Adds regression tests for the truncated / oversized disabled-name JSON cases (and
a counterpart that a truncated enabled call still does not leak) plus the
scientific-notation kwargs.

* Studio tools: gate safetensors bare-JSON drain, fix nested-name gate and function-XML strip

Pass-4 review follow-ups on the shared parser / safetensors loop:

- The safetensors oversized and end-of-stream bare-JSON drain branches keyed off
  a raw "name" substring, so a large or truncated ordinary JSON answer whose name
  is not an enabled tool was drained instead of streamed. Both now use the shared
  enabled-tool-name gate, matching the GGUF path.
- strip_leading_bare_json_call matched the first "name" anywhere, so a plain JSON
  answer with a nested name equal to an enabled tool ({"result":{"name":"web_search"}})
  was wrongly suppressed. It now extracts the TOP-LEVEL name only, walking past
  nested objects/arrays and keeping the text when a top-level value is truncated.
- The function-XML display strip used a regex negative-lookahead that stopped at a
  literal <function=...> opener inside a parameter value and then dropped the rest
  of the answer to EOF. A scan-based strip mirrors the parser (ignores openers
  inside an open <parameter> via _inside_open_parameter) and closes each call at its
  real </function>, so trailing assistant text after such a call survives.

Adds regression tests for each.

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

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

* Tool parsing: 3.9 import safety, disabled-Auto-Heal contract, capability gate

Round-2 review follow-ups on the multi-format tool-call parser:

- tool_call_parser: add `from __future__ import annotations`. The module
  is dependency-light by design (external llama-server wrappers import it
  standalone) and the package targets python >=3.9, where its PEP 604
  `int | None` return annotations would raise TypeError on import.
- safetensors + GGUF drain fallback: gate the leading bare-JSON strip on
  auto_heal_tool_calls. With Auto-Heal off, a truncated enabled-name
  fragment that did not parse now stays visible, matching the XML strip
  in the same branch and the disabled-Auto-Heal contract. With Auto-Heal
  on it is still suppressed.
- safetensors capability gate: match the bare-JSON `{"name":` template
  marker with a whitespace/escape-tolerant regex so a pretty-printed
  `{ "name" :` or JSON-escaped `{\"name\":` template is not mis-classified
  as tool-less. The parser already accepts that whitespace via
  raw_decode, so the gate must too.

Regression tests added for each case.

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

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

* Tool parsing: symmetric "function" bare-JSON alias and route strip parity

Round-3 review follow-ups, all parser/strip symmetry fixes.

- Bare-JSON "function" alias: the markerless parser accepts a call name via
  obj.get("name") or obj.get("function"), but the strip/gates only knew "name",
  so a {"function":<enabled tool>} call executed while its raw JSON leaked. Teach
  _top_level_bare_json_name the alias (with "name" precedence and the same nested
  and truncated-name guards), and widen the guards in strip_leading_bare_json_call,
  the safetensors and GGUF _looks_like_enabled_bare_json gates, and the route
  capability marker regex.
- Route display/history cleanup: strip a tail-only </param> alias close (the
  parser accepts <param name="...">...</param>), and run the parser's guarded
  function-XML scan (_inside_open_parameter) before _TOOL_XML_RE so a literal
  nested <function=...></function> inside an argument value does not truncate the
  strip and leak the tail.

Regression tests added for each.

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

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

* Studio tools: honor tool budget in GGUF loop and guard function-XML streaming strip

Round 4 review fixes. Both are asymmetric-fix bugs where the final/steady path got a
guard the analogous streaming/loop path did not.

- GGUF tool-call budget: the safetensors loop counts real tool-call turns against
  max_tool_iterations (re-prompt stalls excepted), but the GGUF loop only bounded the
  turn count by the enlarged range (max_tool_iterations + _MAX_REPROMPTS). Since this
  PR raised _MAX_REPROMPTS from 1 to 3, a model that keeps making valid tool calls
  could run up to three extra tool rounds (with max_tool_iterations=1, four rounds
  instead of one). Add a _tool_iters_done counter that increments only when a tool
  actually executed in the turn, and stop once the caller's budget is spent so the
  post-loop final-answer nudge fires. A duplicate/disabled no-op turn is a correction
  turn (like a plan-without-action re-prompt) and does not consume budget, preserving
  the existing "already completed" re-prompt behavior.

- Streaming display strip: the final strip runs the guarded _strip_function_xml_calls
  scanner (a literal <function=...> inside a parameter value is data, not a nested
  call), but the GGUF and safetensors streaming strips still used only the open-ended
  regex arms. When a tool-call argument contained literal function markup, the regex
  tail ate everything to end-of-text and dropped the real trailing prose after the
  call's true </function>. Run the guarded scanner (and the balanced Mistral strip)
  before the regex arms in both streaming paths so streaming and final display agree.

Adds regression tests: GGUF valid tool calls respect max_tool_iterations, and the
streaming strip keeps trailing prose after a function-XML call with a literal marker.

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

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

* Studio tools: safetensors tool budget counts only executed turns (GGUF parity)

Follow-up to the GGUF budget fix. The safetensors loop charged max_tool_iterations
per non-re-prompt iteration (iteration + 1 - reprompt_count), so a duplicate/disabled
no-op turn spent a budget slot even though no tool ran. With a small cap this dropped
real work: for max_tool_iterations=2, a model that made a valid call, repeated it (an
internal no-op correction turn), then made a distinct valid call executed only the
first -- the third turn was sent with no tools and the distinct call was ignored.

Track whether a turn actually executed a tool (set on record_result) and count only
those turns against the cap, matching the GGUF loop. A duplicate/disabled no-op is a
correction turn -- like a plan-without-action re-prompt -- and no longer consumes
budget, so the model still gets its "already completed" nudge and another tool-enabled
turn. Adds a regression test for the small-cap duplicate-then-distinct-call flow.

* Studio: render the reasoning block for safetensors and MLX like GGUF

enable_thinking chat templates (Qwen3/Qwen3.5/GLM) prefill an unclosed <think>
into the generation prompt, so the model emits only the closing </think> then
the answer. The safetensors/MLX chat stream emitted that as plain content, so
the reasoning showed inline with no collapsible thinking block, while GGUF
(which surfaces reasoning via reasoning_content) rendered one. This brings
safetensors and MLX to parity.

- _ResponsesReasoningExtractor gains a reasoning_prefilled mode that starts
  inside the reasoning block and splits on the first </think>; default False
  keeps GGUF and every existing caller byte-identical. It suppresses a stray
  re-emitted <think> and holds partial markers back across chunk boundaries.
- _sf_reasoning_prefill_mode gates the mode on reasoning being enabled for the
  request, an enable_thinking or enable_thinking_effort style, and the template
  actually using the standard <think>/</think> markers. Models with a bespoke
  reasoning channel (e.g. gemma's <|think|>/<|channel>) are excluded so their
  answer is never swallowed; gpt-oss (Harmony) and thinking-off requests are
  excluded too.
- sf_tool_stream and stream_chunks (the latter also serves MLX) feed text
  through the extractor, emitting reasoning_content then content deltas, with a
  per-turn reset in the tool loop and a flush before each tool_start; only the
  visible delta reaches the monitor reply. The two non-streaming drains split
  reasoning_content the same way.
- Tests: extractor prefilled mode (streaming and edge cases), the gate matrix
  including the gemma-style exclusion, and a route-replay of the tool-loop
  reasoning stream.

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

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

* studio: don't force a tool re-prompt on a negated intent (safetensors parity)

The safetensors _INTENT_SIGNAL claimed to mirror GGUF but was missing the
negative lookahead, so a refusal like "I will not search the web for that"
matched the "i will" intent and triggered the plan-without-action re-prompt
(STOP... you MUST call a tool), overriding a valid no-tool answer. GGUF already
excludes not/never. Add the same (?!\s+(?:not|never)\b) lookahead so both
backends agree. Extends the intent parity test with negated refusals.

* Studio: trim redundant comments (comment-only, AST-verified)

* Studio: prevent Gemma tool-parser DoS on stray delimiters

_gemma_parse_value returned the input index unchanged when text[i] was a
stray delimiter (,}]), so the list and mapping caller loops that advance
on the returned index spun forever at 100% CPU on malformed input such as
[},]. Advance past the delimiter so parsing always terminates.

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

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

* Studio: strip Magistral [THINK] reasoning from final display/history

strip_tool_markup removed [TOOL_CALLS] and <function> markup but left a
leading Magistral [THINK]...[/THINK] block intact, so its bracket-form
reasoning (not the <think> the reasoning channel renders) leaked into the
safetensors display and conversation history while GGUF/llama.cpp routes
it natively. Drop the leading reasoning block at end-of-turn (final=True)
via the existing _strip_mistral_reasoning helper; streaming is untouched.

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

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

* Honor reasoning_effort none in safetensors prefill; strip Magistral reasoning while streaming

Two safetensors/MLX reasoning fixes surfaced in review:

_sf_reasoning_prefill_mode only checked enable_thinking, so an
enable_thinking_effort (GLM-5.2) request that disables thinking via
reasoning_effort=none (without enable_thinking=False) still began in
prefilled-<think> mode. A plain answer with no </think> was then swallowed
whole into reasoning_content and the visible response came back empty. Thread
reasoning_effort into the predicate and treat none as disabled, mirroring
_request_reasoning_kwargs.

strip_tool_markup_streaming stripped tool markup but not the leading Magistral
[THINK]...[/THINK] bracket block, so the raw chain-of-thought leaked into the
streamed safetensors content instead of the reasoning drawer (GGUF routes it
natively). Apply _strip_mistral_reasoning first, matching the final strip; an
unclosed [THINK] is held from the marker on so nothing flickers.

* Mistral outer call wins over XML literals; align healer signals with its parser

Two follow-ups on the shared-parser ordering after the healing-passthrough
merge:
- A well-formed [TOOL_CALLS] call whose JSON arguments quote tool XML parsed
  the literal instead of the outer call (executing the wrong tool). When the
  first XML signal sits inside a leading balanced Mistral body it is argument
  data, so the Mistral parser now runs first; an XML signal before the trigger
  keeps the normal order, so a [TOOL_CALLS] literal inside an XML call's
  arguments still stays data.
- passthrough_healing buffered streams on the parser module's broadened signal
  list (now including <|python_tag|> and [TOOL_CALLS]) but promotes with
  core.tool_healing, which does not parse those forms: a streamed Mistral or
  Llama text call was held until finalization and flushed as prose. The healer
  keeps its own signal list limited to the formats it can promote, restoring
  immediate streaming for the rest.

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

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

* Address review: leading envelopes win over rehearsed literals

- New _first_foreign_tool_signal shared by the leading-envelope guards adds
  <|python_tag|> to the protected signal set: the spelled-out literal inside a
  Mistral call's arguments (a query about Llama built-in tool syntax) executed
  the inner literal instead of the outer call.
- New _xml_signal_inside_leading_bare_json guard, sibling of the Mistral one:
  a leading bare-JSON call whose string argument quotes tool XML (a code value
  citing <function=...>) had the literal promoted by the shared XML pass
  before the bare-JSON parser ran.
- Magistral [THINK]...[/THINK] is dropped once at parse entry instead of only
  inside the Mistral parser, so a call rehearsed in the think block in a
  foreign format can no longer be promoted while the real call after the
  block is lost. Parse now agrees with the display strip.

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

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

* Address review: a disabled leading bare-JSON object keeps its literals as data

When the leading bare-JSON object is ordinary content (name not an enabled
tool), the guard proved the first tool signal sits inside it, so falling
through to the XML/python_tag passes promoted quoted string data as a real
call. Drop the object and parse only the tail: a real call after the object
still parses, nothing inside it can be promoted.

* Address review: Mistral literals inside leading JSON, whitespace-tolerant wrapped Gemma opener

- The leading bare-JSON guard now treats the [TOOL_CALLS] trigger as a
  foreign signal: the Mistral parser runs before the bare-JSON one, so a
  literal quoted inside the leading object's strings was promoted over the
  outer call (or over ordinary JSON content).
- tool_healing's wrapped Gemma opener tolerates whitespace around call and
  the colon: sampling drift emits call: name{ and call : name{, and
  rejecting those lost the call entirely because no fallback re-parses the
  wrapped form. Strict mode still requires the closing tag.

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

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

* Address review: accept dotted Gemma argument keys in the key-quoting scanner

The scanner quoted keys of [alnum_-] only, so a dotted key (user.name:...)
was left unquoted, json.loads failed, and the whole wrapped call was lost
(parse empty, strip wipes the markup). Dots now match the parser's own
key/name charset.

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

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

* Address review: leading Mistral call owns the turn, dotted keys after bare values

- A LEADING parseable [TOOL_CALLS] call now runs the Mistral parser first
  unconditionally: literal XML in trailing prose after the call was promoted
  by the earlier shared XML pass, executing the quoted example instead of
  the real leading call. XML leading keeps the normal order.
- _GEMMA_NEXT_KEY_RE accepts dots so a dotted key after a bare value
  (query:foo,user.name:bob) ends the value at the comma instead of being
  swallowed into it, matching the round-earlier key-quoting charset.

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

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

* Address review: markup quoted inside a nameless leading JSON answer stays data

The leading bare-JSON guard required a top-level name, so a structured JSON
answer quoting tool markup in its strings (a response_format turn
documenting a tool's syntax) had the literal promoted by the later passes.
A nameless leading object that parses as real JSON now routes through the
same decline-then-parse-the-tail path; non-JSON braced prose keeps the old
behaviour, and a real call after the answer still parses.

* Compress docstrings in the multi-format tool parser to their contract essence

* verify_import_hoist: exempt __future__ imports and same-diff relocations

Two false positives fired on this PR's refactor. A from __future__ import
is a compiler directive whose name never appears as a runtime load, so
HOISTED-IMPORT-UNUSED can never see it used, yet the file requires it for
PEP 604 annotations on Python 3.9. TARGET-CHANGED flagged the deliberate
move of the strip-pattern constants into core.inference.tool_call_parser
as a silent re-point even though the old module-level target was removed
and the new one added in the same diff. Both get narrow exemptions; a
re-point to a pre-existing target is still caught, and the self-test
negative controls all pass unchanged.

* Leading bare-JSON calls own the turn; function calls end at the first balanced close

The XML-signal guard for a leading bare-JSON call required the signal
strictly inside the object, so a trailing XML example stole the turn
from the leading call; it now applies the same inside-or-after rule as
the Mistral guard. Function-XML calls also ended at the LAST close tag,
which let prose after a closed call that mentions a literal close tag
get swallowed into the final parameter value; calls now end at the
first close tag that is not inside an open parameter, and the strip
mirrors the same rule so parse and strip agree.

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

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

* Attribute-form calls end at the first balanced close; bare-JSON strip requires the call shape

The attribute form parser still kept the last close tag in the call
window, folding prose after a closed call into the final parameter
value. It now takes the first close not inside an open parameter, the
same rule the equals form and the strip already use.

The leading bare-JSON strip deleted any closed object whose top-level
name matched an enabled tool, including plain JSON answers the parser
correctly rejects as non-calls. The strip (and the drain gate that
delegates to it) now requires the parser's exact call shape, so answers
like {"name":"web_search","result":...} stream and display intact.

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

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

* False-alarm markers keep the answer; the bare-JSON strip consumes the whole chain

The trailing strip arms dropped everything from a bare marker to EOF,
so a normal answer that mentions [TOOL_CALLS] or another marker
literally was truncated (or fully swallowed when it started with the
literal) after the no-call drain fallback. Those arms now require a
call-shaped lookahead or marker-at-EOF before dropping; truncated real
calls still strip.

Chained bare-JSON turns executed both calls but stripped only the first
object, so the second call's raw JSON replayed into the next assistant
history message alongside the structured tool_calls. The strip now
consumes the entire chained run of call-shaped enabled objects while
non-call answers, disabled names, and trailing prose stay intact.

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

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

* Attribute-form containment, parameter-close-decides rule, preamble-tolerant Mistral guard, strict strip shape

Four document-order and containment fixes. A leading attribute-form
call now parses before the shared XML pass, so markup quoted in its
parameter stays data. The open-parameter scan lets the parameter's own
close tag decide, so any number of literal function closes inside one
value stay data, restoring the pre-close-scan behavior for multi-close
arguments. The leading-Mistral guard tolerates a visible preamble, with
the leading-bare-JSON guard running first so a trigger quoted inside a
leading JSON object stays data. The bare-JSON strip requires the
parser's top-level name in every mode, so nested-name JSON answers
survive name-agnostic stripping.

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

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

* Let a leading <|python_tag|> call own the turn over quoted XML literals

The leading-call ownership contract (a leading executable call owns the turn;
foreign markup quoted in its string arguments or trailing prose stays data) was
enforced for the bare-JSON, Mistral and attribute-form leading calls but not
for the Llama-3 <|python_tag|> form. The shared tool_healing XML pass runs
before _parse_llama3_python_tag and does not recognise <|python_tag|>, so a
<function=...> / <tool_call> / [TOOL_CALLS] literal quoted inside a
<|python_tag|> .call(...) string argument (or its JSON parameters) was promoted
and the wrong tool executed. Well-formed single-format examples:

  <|python_tag|>web_search.call(query="... <function=foo> ...")  ->  foo
  <|python_tag|>python.call(code="<function=render_html>..</function>")  ->  render_html

both returned the phantom inner tool instead of the real leading call.

Add a leading-<|python_tag|> guard mirroring the other leading-call guards:
when the tag is the first tool signal, parse it before tool_healing so quoted
foreign markup stays data. A foreign signal before the tag keeps normal
document order. Added TestPythonTagOuterOverXmlLiteral (7 cases).

* studio: tighten tool-calling comments to be shorter and clearer

* studio: shorten tool-format comments in changed files

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <michaelhan2050@gmail.com>
Co-authored-by: Daniel Han <info@unsloth.ai>
Co-authored-by: danielhanchen <danielhanchen@users.noreply.github.com>
This commit is contained in:
Daniel Han 2026-07-06 10:06:06 -07:00 committed by GitHub
commit f0a5c52821
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 5253 additions and 161 deletions

View file

@ -564,6 +564,9 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
for n, tids in b["module_import_targets"].items():
if tids & after_used:
continue # resolved -> fine
# `from __future__ import ...` is a compiler directive whose name is never loaded; skip it.
if all(t.startswith("from:__future__:") for t in tids):
continue
newly_added = bool(tids - before_module_targets)
was_used_before = bool(tids & before_used)
if newly_added or was_used_before:
@ -588,9 +591,19 @@ def compare(before_src: str, after_src: str, path: str) -> list[tuple[str, str]]
# package object and only *add* submodule attributes (e.g. adding
# `import urllib.error` next to `import urllib.request`). Nothing the name
# resolved to before is lost, so no reference is re-pointed -- skip it.
#
# A deliberate *relocation* is also benign: a name's import source moves A -> B in
# THIS diff (old `from A import x` removed, new `from B import x` added). Mirrors the
# TARGET-MISSING tolerance. Re-pointing to a pre-existing target (clash) is NOT exempted.
removed_module_targets = before_module_targets - after_module_targets
for key, tafter in b["target_by_use"].items():
tbefore = a["target_by_use"].get(key)
if tbefore and tbefore != tafter and (tbefore - tafter):
lost = tbefore - tafter
gained = tafter - tbefore
relocated = lost <= removed_module_targets and gained <= added_module_targets
if relocated:
continue
findings.append(
(
"BLOCKER",

View file

@ -38,9 +38,21 @@ from core.inference.llama_server_args import (
strip_shadowing_flags,
strip_split_mode_only,
)
from core.tool_healing import (
# Share strip / signal constants with the multi-format parser so BUFFERING also
# catches Llama-3 / Mistral / Gemma 4.
from core.inference.tool_call_parser import (
_TOOL_ALL_PATS,
strip_tool_call_markup,
_balanced_brace_end,
_strip_function_xml_calls,
_strip_mistral_closed_calls,
TOOL_XML_SIGNALS as _SHARED_TOOL_XML_SIGNALS,
RAG_MAX_SEARCHES_PER_TURN,
RAG_SEARCH_CAP_NUDGE,
parse_tool_calls_from_text as _shared_parse_tool_calls_from_text,
strip_leading_bare_json_call,
strip_llama3_leading_sentinels,
strip_tool_markup as _shared_strip_tool_markup,
)
from utils.native_path_leases import child_env_without_native_path_secret
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
@ -48,12 +60,6 @@ from utils.subprocess_compat import (
windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
)
from utils.process_lifetime import child_popen_kwargs as _child_popen_kwargs
from core.inference.tool_call_parser import (
RAG_MAX_SEARCHES_PER_TURN,
RAG_SEARCH_CAP_NUDGE,
TOOL_XML_SIGNALS,
parse_tool_calls_from_text as _shared_parse_tool_calls_from_text,
)
from core.inference.tool_loop_controller import (
ToolLoopController,
tool_event_provenance,
@ -220,7 +226,7 @@ _INTENT_SIGNAL = re.compile(
r"\b(?:now i|next i)\b"
r")"
)
_MAX_REPROMPTS = 1
_MAX_REPROMPTS = 3
# Default max_tokens to the effective context when known. The floor is high
# enough for reasoning-heavy GGUFs and max_tokens-omitting API clients.
@ -7881,12 +7887,17 @@ class LlamaCppBackend:
# ── Message building (OpenAI format) ──────────────────────────
@staticmethod
def _parse_tool_calls_from_text(content: str, *, allow_incomplete: bool = True) -> list[dict]:
"""Thin wrapper around the shared parser in tool_call_parser
so safetensors and llama_cpp pick up the same fixes."""
def _parse_tool_calls_from_text(
content: str,
*,
allow_incomplete: bool = True,
enabled_tool_names: Optional[set] = None,
) -> list[dict]:
"""Wrapper around the shared parser; ``enabled_tool_names`` gates the markerless bare-JSON form."""
return _shared_parse_tool_calls_from_text(
content,
allow_incomplete = allow_incomplete,
enabled_tool_names = enabled_tool_names,
)
@staticmethod
@ -8406,11 +8417,17 @@ class LlamaCppBackend:
) -> str:
if not (auto_heal_tool_calls or force):
return text
return strip_tool_call_markup(text, final = final)
return _shared_strip_tool_markup(text, final = final)
def _strip_tool_markup_streaming(text: str, *, force: bool = False) -> str:
if not (auto_heal_tool_calls or force):
return text
# Shared patterns so a textual Mistral/Llama call entering DRAINING is stripped, not
# leaked. Mistral first; no final trim so incremental length comparisons hold.
text = _strip_mistral_closed_calls(text)
# Parser-accurate function-XML scan before the regex arms so a literal ``<function=...>``
# in a value doesn't make the tail eat trailing prose after the real ``</function>``.
text = _strip_function_xml_calls(text, final = True)
for pat in _TOOL_ALL_PATS:
text = pat.sub("", text)
return text
@ -8456,6 +8473,13 @@ class LlamaCppBackend:
cumulative_display += "<think>" + reasoning_accum + "</think>"
cumulative_display += content_buffer
def _looks_like_enabled_bare_json(text: str, enabled_tool_names: set) -> bool:
"""True when ``text`` opens with an ENABLED markerless bare-JSON call; an ordinary JSON answer returns False."""
probe = strip_llama3_leading_sentinels(text.lstrip())
if not (probe.startswith("{") and ('"name"' in probe or '"function"' in probe)):
return False
return strip_leading_bare_json_call(probe, enabled_tool_names) != probe
tool_controller = ToolLoopController(
tools = tools,
auto_heal_tool_calls = auto_heal_tool_calls,
@ -8469,6 +8493,8 @@ class LlamaCppBackend:
)
_MAX_BUFFER_CHARS = 32
# Hold a leading ``{`` well past the 32-char XML cap until it balances (mirrors safetensors).
_MAX_BARE_JSON_BUFFER = 16384
_append_budget_exhausted_nudge = True
# RAG: cap knowledge-base searches per assistant turn. The controller is
# tool-agnostic, so this gate stays in the loop.
@ -8481,6 +8507,9 @@ class LlamaCppBackend:
# "Hello!" won't match. Pattern compiled at module level
# (_INTENT_SIGNAL).
_reprompt_count = 0
# Gates ``max_tool_iterations`` on real tool turns so reserved re-prompt slots don't
# extend the budget. Mirrors the safetensors guard.
_tool_iters_done = 0
_forced_tool_call_pending = False
# Reserve extra iterations for re-prompts so they don't consume the
@ -8489,12 +8518,21 @@ class LlamaCppBackend:
for iteration in range(max_tool_iterations + _extra):
if cancel_event is not None and cancel_event.is_set():
return
# Whether this turn ran a tool; a no-op-only turn stays False and doesn't consume budget.
_turn_executed_real_tool = False
active_tools = tool_controller.active_tools()
if not active_tools:
_append_budget_exhausted_nudge = False
break
_tool_xml_signals = TOOL_XML_SIGNALS
# Gate the markerless bare-JSON form on enabled names so a JSON answer isn't misread as a call.
_enabled_tool_names = {
(tool.get("function") or {}).get("name")
for tool in active_tools
if (tool.get("function") or {}).get("name")
}
# Shared signal tuple so GGUF BUFFERING wakes on every format the parser knows.
_tool_xml_signals = _SHARED_TOOL_XML_SIGNALS
# Build payload -- stream: True so we detect tool signals
# in the first 1-2 chunks without a non-streaming penalty.
@ -8777,7 +8815,36 @@ class LlamaCppBackend:
is_prefix = True
break
if is_match:
# Bare Llama-3.2 {"name":..} has no XML signal: hold an
# incomplete object, drain a complete one (mirrors safetensors).
_hold_buffer = False
# Whole buffer is the call (no visible prefix) -- drain silently.
_drain_silently = False
if not is_match and not is_prefix:
_bare = strip_llama3_leading_sentinels(stripped_buf)
if _bare.startswith("{"):
if _balanced_brace_end(_bare, 0) is None:
if len(stripped_buf) < _MAX_BARE_JSON_BUFFER:
_hold_buffer = True
elif _looks_like_enabled_bare_json(
_bare, _enabled_tool_names
):
# Oversized still-open ENABLED-tool call: stop
# holding (memory bound) but DRAIN, not leak;
# a giant ordinary JSON answer still streams.
_drain_silently = True
elif self._parse_tool_calls_from_text(
content_buffer,
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
):
_drain_silently = True
if _drain_silently:
# No visible prefix -- the buffered text IS
# the call; drain without yielding it.
detect_state = _S_DRAINING
elif is_match:
# Tool signal -- flush any visible
# prefix before DRAINING so the
# route sends it before tool_start.
@ -8794,7 +8861,9 @@ class LlamaCppBackend:
"text": cleaned,
}
detect_state = _S_DRAINING
elif is_prefix and len(stripped_buf) < _MAX_BUFFER_CHARS:
elif _hold_buffer or (
is_prefix and len(stripped_buf) < _MAX_BUFFER_CHARS
):
pass # keep buffering
else:
# Not a tool -- flush buffer
@ -8821,8 +8890,16 @@ class LlamaCppBackend:
# ── Resolve BUFFERING at stream end ──
if detect_state == _S_BUFFERING:
stripped_buf = content_buffer.lstrip()
# A held bare-JSON fragment has no XML signal; route it to DRAINING.
_bare_eos = strip_llama3_leading_sentinels(stripped_buf)
# Gate on enabled names so a JSON answer isn't routed to DRAINING and dropped.
_is_bare_tc = bool(active_tools) and _looks_like_enabled_bare_json(
_bare_eos, _enabled_tool_names
)
if stripped_buf and any(s in stripped_buf for s in _tool_xml_signals):
detect_state = _S_DRAINING
elif _is_bare_tc:
detect_state = _S_DRAINING
elif content_accum or reasoning_accum:
detect_state = _S_STREAMING
if content_buffer:
@ -8848,20 +8925,24 @@ class LlamaCppBackend:
"text": cumulative_display,
}
else:
# No tool signal and no enabled bare-JSON call: a leading ``{`` is an ordinary
# JSON answer and must be shown; any other partial-markup prefix is dropped.
_held = strip_llama3_leading_sentinels(content_buffer.lstrip())
if _held.startswith("{") and not _suppress_visible_output:
yield {"type": "content", "text": _held}
return
# ── STREAMING path: no tool call ──
if detect_state == _S_STREAMING:
# Safety net: check for XML tool signals in content. The
# route layer resets prev_text on tool_start, so post-tool
# synthesis streams correctly even if content was emitted
# before the tool XML.
_safety_tc = None
if any(s in content_accum for s in _tool_xml_signals):
_safety_tc = self._parse_tool_calls_from_text(
content_accum,
allow_incomplete = auto_heal_tool_calls,
)
# Safety net: re-parse the full content for tool calls. The route layer resets
# prev_text on tool_start, so post-tool synthesis streams correctly even if
# content was emitted before the tool XML. Unconditional (not gated on
# _tool_xml_signals): bare-JSON and Gemma wrapper-less calls carry no signal.
_safety_tc = self._parse_tool_calls_from_text(
content_accum,
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
)
if not _safety_tc:
# ── Re-prompt on plan-without-action ──
# If the model described its intent (forward-looking
@ -8978,10 +9059,13 @@ class LlamaCppBackend:
for i in sorted(tool_calls_acc)
if (tool_calls_acc[i].get("function", {}).get("name", "").strip())
] or None
if not tool_calls and any(s in content_accum for s in _tool_xml_signals):
if not tool_calls:
# Unconditional re-parse: DRAINING means the buffer looked like a call, and
# bare-JSON / Gemma wrapper-less calls carry no XML signal to gate on.
tool_calls = self._parse_tool_calls_from_text(
content_accum,
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
)
if tool_calls and not has_structured_tc:
content_text = _strip_tool_markup(
@ -8989,6 +9073,11 @@ class LlamaCppBackend:
final = True,
force = True,
)
# ``_strip_tool_markup`` only knows XML; also drop a leading bare-JSON call
# so the executed call isn't replayed as text or next-turn history.
content_text = strip_leading_bare_json_call(
content_text, _enabled_tool_names
)
if tool_calls:
logger.info(
f"Parsed {len(tool_calls)} tool call(s) from "
@ -9002,6 +9091,13 @@ class LlamaCppBackend:
if content_accum:
# Strip leaked tool-call XML before yielding.
content_accum = _strip_tool_markup(content_accum, final = True)
# A truncated bare-JSON call has no XML to strip and didn't parse. With
# Auto-Heal on drop a leading ENABLED-tool fragment (plain JSON untouched);
# off keeps it visible per the strict contract.
if content_accum and active_tools and auto_heal_tool_calls:
content_accum = strip_leading_bare_json_call(
content_accum, _enabled_tool_names
)
if content_accum:
yield {"type": "content", "text": content_accum}
_meta = _build_metadata_event(
@ -9144,6 +9240,8 @@ class LlamaCppBackend:
_kb_search_count += 1
completion = tool_controller.record_result(decision, result)
resolved_provisional_tool_call_ids.add(decision.tool_call_id)
# A tool ran this turn, so it counts against the caller's budget.
_turn_executed_real_tool = True
yield completion.tool_end_event()
conversation.append(completion.tool_message())
@ -9167,6 +9265,12 @@ class LlamaCppBackend:
if tool_controller.force_final_answer or not tool_controller.active_tools():
_append_budget_exhausted_nudge = False
break
# Count only real tool turns against the cap so reserved re-prompt slots can't
# become extra tool rounds; a no-op turn doesn't consume budget (GGUF parity).
if _turn_executed_real_tool:
_tool_iters_done += 1
if _tool_iters_done >= max_tool_iterations:
break
continue
except httpx.ConnectError:

View file

@ -29,10 +29,23 @@ import os
from collections.abc import Mapping
from typing import Any, Optional
from core.inference.tool_call_parser import TOOL_XML_SIGNALS, has_tool_signal
from core.inference.tool_loop_controller import coerce_tool_arguments
from core.tool_healing import parse_tool_calls_from_text
# Only the formats this healer can promote. The parser's broader list adds Llama
# <|python_tag|> / Mistral [TOOL_CALLS], but buffering those here would flush a
# streamed call as prose, so keep a healer-aligned list.
_HEAL_SIGNALS = (
"<tool_call>",
"<|tool_call>",
"<function=",
)
def _has_heal_signal(text: str) -> bool:
return any(s in text for s in _HEAL_SIGNALS)
# Read once at import (same convention as the other UNSLOTH_* switches).
_HEALING_DISABLED = os.environ.get("UNSLOTH_DISABLE_TOOL_CALL_HEALING", "0") == "1"
# Nudging is OPT-IN: per-request nudge_tool_calls=true, or flip the process
@ -44,7 +57,7 @@ def nudge_enabled(request_flag: Optional[bool]) -> bool:
return _NUDGE_DEFAULT if request_flag is None else bool(request_flag)
_MAX_SIGNAL_LEN = max(len(s) for s in TOOL_XML_SIGNALS)
_MAX_SIGNAL_LEN = max(len(s) for s in _HEAL_SIGNALS)
# A suspected-but-unclosed tool block larger than this is declared a false
# alarm and flushed, bounding memory on a model rambling XML-lookalike text.
_MAX_HOLD_CHARS = 64 * 1024
@ -198,7 +211,7 @@ def heal_openai_message_events(
if not isinstance(msg, dict) or msg.get("tool_calls"):
return None
content = msg.get("content")
if not isinstance(content, str) or not has_tool_signal(content):
if not isinstance(content, str) or not _has_heal_signal(content):
return None
parsed, spans = parse_tool_calls_from_text(content, allow_incomplete = True, with_spans = True)
tool_schemas = _tool_schemas_by_name(tools) if tools is not None else None
@ -248,7 +261,7 @@ def heal_openai_message(
def _earliest_signal(buffer: str) -> int:
best = -1
for signal in TOOL_XML_SIGNALS:
for signal in _HEAL_SIGNALS:
index = buffer.find(signal)
if index >= 0 and (best < 0 or index < best):
best = index
@ -275,7 +288,7 @@ def _partial_signal_suffix(buffer: str) -> int:
"""Length of the longest buffer suffix that is a proper prefix of a signal."""
for length in range(min(len(buffer), _MAX_SIGNAL_LEN - 1), 0, -1):
tail = buffer[-length:]
if any(signal.startswith(tail) for signal in TOOL_XML_SIGNALS):
if any(signal.startswith(tail) for signal in _HEAL_SIGNALS):
return length
return 0
@ -508,7 +521,7 @@ def nudge_should_retry(
if not message or message.get("tool_calls"):
return False
text = message.get("content")
if not isinstance(text, str) or not has_tool_signal(text):
if not isinstance(text, str) or not _has_heal_signal(text):
return False
return not _heal_would_promote(text, allowed_tools, tools)

View file

@ -22,11 +22,17 @@ from loggers import get_logger
from core.inference.tool_call_parser import (
_TOOL_ALL_PATS,
_balanced_brace_end,
_strip_function_xml_calls,
_strip_mistral_closed_calls,
_strip_mistral_reasoning,
BUDGET_EXHAUSTED_NUDGE,
RAG_MAX_SEARCHES_PER_TURN,
RAG_SEARCH_CAP_NUDGE,
TOOL_XML_SIGNALS,
parse_tool_calls_from_text,
strip_leading_bare_json_call,
strip_llama3_leading_sentinels,
strip_tool_markup,
)
from core.inference.tool_loop_controller import (
@ -50,6 +56,34 @@ logger = get_logger(__name__)
# Buffer cap while disambiguating a possible tool-call prefix.
_MAX_BUFFER_CHARS = 32
# Memory bound for holding a leading bare-JSON object whose top-level "{" never balances.
_MAX_BARE_JSON_BUFFER = 16384
# Forward-looking intent ("I'll", "First,", "Step 1:") = planning; nudge a call. Negative
# lookahead drops negated forms ("I will not"). Mirrors GGUF.
_INTENT_SIGNAL = re.compile(
r"(?i)("
r"\b(i['](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall|let me|allow me)\b(?!\s+(?:not|never)\b)"
r"|\b(?:first\b|step \d+:?|here[']?s (?:my |the |a )?(?:plan|approach))"
r"|\b(?:now i|next i)\b"
r")"
)
_MAX_REPROMPTS = 3
_REPROMPT_MAX_CHARS = 2000
# Templated so the nudge names the caller's enabled tools. Mirrors GGUF tool_hint.
_REPROMPT_INSTRUCTION_TEMPLATE = (
"STOP. Do NOT write code or explain. You MUST call a tool NOW. Call {tool_hint} immediately."
)
def _active_tool_names(active_tools: list[dict]) -> list[str]:
names = [
(tool.get("function") or {}).get("name")
for tool in active_tools
if isinstance(tool, dict) and isinstance(tool.get("function"), dict)
]
return [name for name in names if name]
def strip_tool_markup_streaming(
text: str,
@ -60,6 +94,12 @@ def strip_tool_markup_streaming(
"""Strip open-ended tool XML from display text without trimming whitespace."""
if not (auto_heal_tool_calls or tool_protocol_active):
return text
# Mirror the final strip (no final trim): drop a leading Magistral ``[THINK]...[/THINK]``
# block, then Mistral calls, then a parser-accurate function-XML scan before the regex
# arms. An unclosed ``[THINK]`` holds until ``[/THINK]`` so text stays monotonic.
text = _strip_mistral_reasoning(text)
text = _strip_mistral_closed_calls(text)
text = _strip_function_xml_calls(text, final = True)
for pat in _TOOL_ALL_PATS:
text = pat.sub("", text)
return text
@ -81,6 +121,14 @@ def _status_for_tool(tool_name: str, arguments: dict) -> str:
return status_for_tool(tool_name, arguments)
def _looks_like_enabled_bare_json(text: str, enabled_tool_names: Optional[set]) -> bool:
"""True when ``text`` opens with an ENABLED markerless bare-JSON call; an ordinary JSON answer returns False."""
probe = strip_llama3_leading_sentinels(text.lstrip())
if not (probe.startswith("{") and ('"name"' in probe or '"function"' in probe)):
return False
return strip_leading_bare_json_call(probe, enabled_tool_names) != probe
_FUNCTION_SIGNAL_RE = re.compile(r"<function=([\w-]+)>")
_TOOL_CALL_NAME_RE = re.compile(r'"name"\s*:\s*"([\w-]+)"')
@ -198,6 +246,10 @@ def run_safetensors_tool_loop(
kb_search_count = 0
final_attempt_done = False
next_call_id = 0
reprompt_count = 0
# Only turns that executed a tool count against ``max_tool_iterations``; a no-op or
# re-prompt turn must not consume budget (GGUF parity).
_executed_tool_iters = 0
def _tool_succeeded(tool_name: str) -> bool:
key_prefix = f"{tool_name}:"
@ -215,9 +267,13 @@ def run_safetensors_tool_loop(
_state_streaming = 1
_state_draining = 2
for iteration in range(max_tool_iterations + 1):
# Reserve re-prompt slots so they don't eat the caller's tool budget.
_extra_iters = _MAX_REPROMPTS if max_tool_iterations > 0 else 0
for iteration in range(max_tool_iterations + _extra_iters + 1):
if cancel_event is not None and cancel_event.is_set():
return
# Whether this turn ran a tool; a no-op-only turn stays False and doesn't consume budget.
_turn_executed_real_tool = False
if final_attempt_done:
active_tools: list[dict] = []
@ -229,6 +285,8 @@ def run_safetensors_tool_loop(
tool_protocol_active = not final_attempt_done and (unrestricted_tools or bool(active_tools))
tool_xml_signals = TOOL_XML_SIGNALS if tool_protocol_active else ()
# Gate the markerless bare-JSON form on enabled names so a JSON answer isn't misread as a call.
_enabled_tool_names = None if unrestricted_tools else set(_active_tool_names(active_tools))
detect_state = _state_buffering
content_buffer = ""
@ -367,6 +425,34 @@ def run_safetensors_tool_loop(
is_prefix = True
break
# Bare Llama-3.2 ``{"name":..,"parameters":..}`` carries no XML signal. Hold a leading
# ``{`` (after any sentinel) until it closes: drain if it parses as a call, else stream.
bare_probe = strip_llama3_leading_sentinels(stripped)
if (
not is_match
and not is_prefix
and tool_protocol_active
and bare_probe.startswith("{")
):
if _balanced_brace_end(bare_probe, 0) is None:
if len(stripped) < _MAX_BARE_JSON_BUFFER:
continue # object still open -- keep buffering
elif _looks_like_enabled_bare_json(bare_probe, _enabled_tool_names):
# Oversized still-open ENABLED-tool call: stop holding (memory bound) but
# DRAIN, not leak; a giant ordinary JSON answer still streams.
detect_state = _state_draining
continue
elif parse_tool_calls_from_text(
content_buffer,
id_offset = next_call_id,
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
):
# Closed object that parses as a bare-JSON call -- drain silently.
detect_state = _state_draining
continue
# Closed non-call object (or oversized non-call) -- stream as text.
if is_match:
# Tool signal -- flush any visible prefix before DRAINING
# so the route sends it before tool_start.
@ -419,44 +505,74 @@ def run_safetensors_tool_loop(
if detect_state == _state_buffering:
# Buffer never resolved -- tool XML or plain content?
stripped = content_buffer.lstrip()
_bare_eos = strip_llama3_leading_sentinels(stripped)
if (
stripped
and tool_protocol_active
and any(sig in stripped for sig in tool_xml_signals)
):
detect_state = _state_draining
elif tool_protocol_active and _looks_like_enabled_bare_json(
_bare_eos, _enabled_tool_names
):
# Held ENABLED-tool bare-JSON fragment has no XML signal; DRAIN it (a JSON answer
# falls through to the else and streams, GGUF parity).
detect_state = _state_draining
else:
# Drain and fall through to STREAMING so the intent re-prompt + safety-net parser
# still fire on short emissions like "Let me search." that never exit BUFFERING.
if content_buffer:
cumulative_display += content_buffer
yield {
"type": "content",
"text": _strip_tool_markup_final(
cumulative_display,
auto_heal_tool_calls = auto_heal_tool_calls,
tool_protocol_active = False,
),
}
yield {"type": "status", "text": ""}
return
cleaned = strip_tool_markup(cumulative_display, final = True)
if len(cleaned) > len(last_emitted):
last_emitted = cleaned
yield {"type": "content", "text": cleaned}
detect_state = _state_streaming
if detect_state == _state_streaming:
# No tool detected mid-stream -- check for late tool XML.
safety_tc = None
saw_tool_signal = tool_protocol_active and any(
sig in content_accum for sig in tool_xml_signals
# Run the parser even with no XML signal (bare-JSON carries none); it's strict so
# plain answers stay untouched. Mirrors GGUF.
safety_tc = parse_tool_calls_from_text(
content_accum,
id_offset = next_call_id,
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
)
if saw_tool_signal:
safety_tc = parse_tool_calls_from_text(
content_accum,
id_offset = next_call_id,
allow_incomplete = auto_heal_tool_calls,
)
if not safety_tc:
# Final answer: if a literal tool marker in prose was stripped
# during streaming but did not parse as a real call, restore the
# raw cumulative text for core callers. Route-level cleanup can
# still apply the Auto-Heal display policy.
if saw_tool_signal and content_accum:
# Re-prompt only when the model planned without acting (intent signal);
# "4" / "Hello!" never trigger. Mirrors GGUF.
_stripped = content_accum.strip()
if (
tools
and auto_heal_tool_calls
and reprompt_count < _MAX_REPROMPTS
and 0 < len(_stripped) < _REPROMPT_MAX_CHARS
and _INTENT_SIGNAL.search(_stripped)
and not final_attempt_done
):
reprompt_count += 1
logger.info(
"Safetensors re-prompt %d/%d: model planned without "
"calling tools (%d chars)",
reprompt_count,
_MAX_REPROMPTS,
len(_stripped),
)
tool_hint = " or ".join(_active_tool_names(active_tools)) or "an available tool"
conversation.append({"role": "assistant", "content": _stripped})
conversation.append(
{
"role": "user",
"content": _REPROMPT_INSTRUCTION_TEMPLATE.format(tool_hint = tool_hint),
}
)
yield {"type": "status", "text": ""}
continue
# Final answer. If a literal tool marker in prose was buffered but never
# parsed as a call, restore the raw text so the prose surfaces; route
# cleanup still applies the Auto-Heal policy.
if content_accum and any(sig in content_accum for sig in tool_xml_signals):
yield {"type": "content", "text": content_accum}
yield {"type": "status", "text": ""}
return
@ -476,20 +592,24 @@ def run_safetensors_tool_loop(
content_accum,
id_offset = next_call_id,
allow_incomplete = auto_heal_tool_calls,
enabled_tool_names = _enabled_tool_names,
)
if not tool_calls:
# Parser found nothing. Auto-Heal-enabled display cleanup
# strips unparseable tool XML; disabled Auto-Heal preserves
# the raw text so literal/malformed markup stays visible.
if content_accum:
yield {
"type": "content",
"text": _strip_tool_markup_final(
content_accum,
auto_heal_tool_calls = auto_heal_tool_calls,
tool_protocol_active = False,
),
}
_drain_text = _strip_tool_markup_final(
content_accum,
auto_heal_tool_calls = auto_heal_tool_calls,
tool_protocol_active = False,
)
# Drained bare-JSON call that didn't parse: with Auto-Heal on drop the fragment
# (plain JSON untouched); off keeps it visible per the strict contract.
if tool_protocol_active and auto_heal_tool_calls:
_drain_text = strip_leading_bare_json_call(_drain_text, _enabled_tool_names)
if _drain_text:
yield {"type": "content", "text": _drain_text}
if provisional_render_html_started and not provisional_resolved:
provisional_resolved = True
yield {
@ -509,6 +629,9 @@ def run_safetensors_tool_loop(
if tool_calls:
next_call_id += len(tool_calls)
# Strip a leading bare-JSON call so it isn't replayed as text or next-turn history
# (``_strip_tool_markup_final`` only knows XML). No-op for plain JSON answers.
content_text = strip_leading_bare_json_call(content_text, _enabled_tool_names)
if final_attempt_done:
# Final-answer turn re-called a tool -- stop the loop.
@ -634,6 +757,8 @@ def run_safetensors_tool_loop(
completion = tool_controller.record_result(decision, result)
if provisional_match:
provisional_resolved = True
# A tool ran this turn, so it counts against the caller's budget.
_turn_executed_real_tool = True
yield completion.tool_end_event()
conversation.append(completion.tool_message())
@ -646,7 +771,10 @@ def run_safetensors_tool_loop(
if not unrestricted_tools and not tool_controller.active_tools():
final_attempt_done = True
continue
if iteration + 1 >= max_tool_iterations and not final_attempt_done:
# Count only real tool turns against the cap so a no-op turn doesn't consume budget (GGUF parity).
if _turn_executed_real_tool:
_executed_tool_iters += 1
if _executed_tool_iters >= max_tool_iterations and not final_attempt_done:
# Budget exhausted; nudge a final plain answer.
final_attempt_done = True
conversation.append({"role": "user", "content": BUDGET_EXHAUSTED_NUDGE})

File diff suppressed because it is too large Load diff

View file

@ -27,12 +27,15 @@ _TOOL_ALL_PATS = _TOOL_CLOSED_PATS + [
# Pre-compiled patterns for tool-call XML parsing.
_TC_JSON_START_RE = re.compile(r"<tool_call>\s*\{")
_TC_GEMMA_START_RE = re.compile(r"<\|tool_call>call:([\w-]+)\s*\{")
# Name class allows dots/hyphens for dotted Gemma names; whitespace-tolerant around
# ``call`` / ``:`` since drift emits ``call: name{`` and ``call : name{``.
_TC_GEMMA_START_RE = re.compile(r"<\|tool_call>\s*call\s*:\s*([\w.\-]+)\s*\{")
_TC_FUNC_START_RE = re.compile(r"<function=([\w-]+)>\s*")
_TC_END_TAG_RE = re.compile(r"</tool_call>")
_TC_GEMMA_END_TAG_RE = re.compile(r"<tool_call\|>")
_TC_FUNC_CLOSE_RE = re.compile(r"\s*</function>\s*$")
_TC_PARAM_START_RE = re.compile(r"<parameter=([\w-]+)>\s*")
# Horizontal whitespace only so the newline + value indentation survive (_trim_param_value trims one newline).
_TC_PARAM_START_RE = re.compile(r"<parameter=([\w-]+)>[^\S\n]*")
_TC_PARAM_CLOSE_RE = re.compile(r"\s*</parameter>\s*$")
_GEMMA_QUOTE = '<|"|>'
_PARAM_CLOSE_TAG = "</parameter>"
@ -43,7 +46,8 @@ _FUNC_CLOSE_TAG = "</function>"
# must be identifier-shaped (start with a letter or underscore); a comma
# followed by digits-then-colon is value text such as a timestamp or ratio
# (`meet at 10:00, 11:00 tomorrow`), not a new key.
_GEMMA_NEXT_KEY_RE = re.compile(r"\s*[A-Za-z_][\w-]*\s*:")
# Dots match the key-quoting scanner: a dotted key after a bare value must end the value at the comma.
_GEMMA_NEXT_KEY_RE = re.compile(r"\s*[A-Za-z_][\w.\-]*\s*:")
def _balanced_brace_end(
@ -223,7 +227,9 @@ def _quote_gemma_object_keys(src: str) -> str:
while i < len(src) and src[i].isspace():
i += 1
key_name_start = i
while i < len(src) and (src[i].isalnum() or src[i] in "_-"):
# Dots match the parser's key/name charset: Gemma emits dotted argument keys
# (user.name:...) for namespaced schemas.
while i < len(src) and (src[i].isalnum() or src[i] in "_-."):
i += 1
key_name = src[key_name_start:i]
colon_pos = i
@ -267,7 +273,8 @@ def _quote_gemma_object_keys(src: str) -> str:
json.loads(raw.strip())
parts.append(raw)
except (json.JSONDecodeError, ValueError):
parts.append(json.dumps(raw.strip()) if raw.strip() else raw)
# Quote bare value; empty ({k:}) becomes "" so json.loads sees {"k":""} not invalid {"k":}.
parts.append(json.dumps(raw.strip()))
else:
parts.append(src[key_start:i])
return "".join(parts)
@ -291,9 +298,35 @@ def _inside_open_parameter(content: str, pos: int) -> bool:
last_param_start = match.start()
if last_param_start < 0:
return False
last_param_close = content.rfind(_PARAM_CLOSE_TAG, 0, pos)
last_func_close = content.rfind(_FUNC_CLOSE_TAG, 0, pos)
return last_param_start > max(last_param_close, last_func_close)
# The parameter's OWN close tag decides: if it closes after ``pos`` the position is
# argument data (even across literal function closes); an unclosed one falls back to func close.
own_close = content.find(_PARAM_CLOSE_TAG, last_param_start)
if own_close >= 0:
return own_close > pos
func_close = content.find(_FUNC_CLOSE_TAG, last_param_start)
return func_close < 0 or pos < func_close
def _func_close_index(content: str, body_start: int, body: str) -> int:
"""Index in ``body`` of the first ``</function>`` that is not argument
data (not inside an open parameter value); -1 when every close is data.
Taking the LAST close swallowed prose between the real close and a
literal ``</function>`` mentioned later in the answer."""
idx = body.find(_FUNC_CLOSE_TAG)
while idx >= 0:
if not _inside_open_parameter(content, body_start + idx):
return idx
idx = body.find(_FUNC_CLOSE_TAG, idx + 1)
return -1
def _trim_param_value(val: str) -> str:
"""Trim only the wrapping newline (not str.strip) so code/diff argument indentation survives."""
if val.startswith("\n"):
val = val[1:]
if val.endswith("\n"):
val = val[:-1]
return val
def parse_tool_calls_from_text(
@ -349,7 +382,10 @@ def parse_tool_calls_from_text(
if kind == "json":
obj = json.loads(content[m.end() - 1 : end + 1])
name = obj.get("name", "")
arguments = obj.get("arguments", {})
# Accept ``parameters`` alias for ``arguments`` (Llama-3.2 drift inside a Hermes <tool_call>).
arguments = obj.get("arguments")
if arguments is None:
arguments = obj.get("parameters", {})
if isinstance(arguments, dict):
arguments = json.dumps(arguments)
else:
@ -382,7 +418,7 @@ def parse_tool_calls_from_text(
body_end = len(content)
body_end = min(body_end, next_func)
body = content[body_start:body_end]
close_idx = body.rfind(_FUNC_CLOSE_TAG)
close_idx = _func_close_index(content, body_start, body)
if close_idx >= 0:
span_end = body_start + close_idx + len(_FUNC_CLOSE_TAG)
body = body[:close_idx]
@ -404,7 +440,7 @@ def parse_tool_calls_from_text(
val = stripped_val[: -len(_PARAM_CLOSE_TAG)]
else:
val = _TC_PARAM_CLOSE_RE.sub("", val)
arguments[pm.group(1)] = val.strip()
arguments[pm.group(1)] = _trim_param_value(val)
else:
valid_params = True
for pidx, pm in enumerate(param_starts):
@ -422,7 +458,7 @@ def parse_tool_calls_from_text(
val = stripped_val[: -len(_PARAM_CLOSE_TAG)]
else:
val = _TC_PARAM_CLOSE_RE.sub("", val)
arguments[param_name] = val.strip()
arguments[param_name] = _trim_param_value(val)
if not valid_params:
continue
@ -444,6 +480,86 @@ def parse_tool_calls_from_text(
}
)
call_spans.append((start, span_end))
if not tool_calls:
func_starts = [
fm
for fm in _TC_FUNC_START_RE.finditer(content)
if not _inside_open_parameter(content, fm.start())
]
for idx, fm in enumerate(func_starts):
func_name = fm.group(1)
body_start = fm.end()
next_func = func_starts[idx + 1].start() if idx + 1 < len(func_starts) else len(content)
end_tag = _TC_END_TAG_RE.search(content[body_start:])
if end_tag:
body_end = body_start + end_tag.start()
else:
body_end = len(content)
body_end = min(body_end, next_func)
body = content[body_start:body_end]
# Span for with_spans callers: through the </function> close if present, else body end.
span_end = body_end
if not allow_incomplete:
close_idx = _func_close_index(content, body_start, body)
if close_idx < 0:
continue
body = body[:close_idx]
span_end = body_start + close_idx + len(_FUNC_CLOSE_TAG)
else:
# Terminate at the real close so trailing prose doesn't leak in; no close -> whole body.
close_idx = _func_close_index(content, body_start, body)
if close_idx >= 0:
body = body[:close_idx]
span_end = body_start + close_idx + len(_FUNC_CLOSE_TAG)
arguments: dict = {}
param_starts = list(_TC_PARAM_START_RE.finditer(body))
if len(param_starts) == 1:
pm = param_starts[0]
val = body[pm.end() :]
if not allow_incomplete:
stripped_val = val.rstrip()
if not stripped_val.endswith(_PARAM_CLOSE_TAG):
continue
val = stripped_val[: -len(_PARAM_CLOSE_TAG)]
else:
val = _TC_PARAM_CLOSE_RE.sub("", val)
arguments[pm.group(1)] = _trim_param_value(val)
else:
valid_params = True
for pidx, pm in enumerate(param_starts):
param_name = pm.group(1)
val_start = pm.end()
next_param = (
param_starts[pidx + 1].start()
if pidx + 1 < len(param_starts)
else len(body)
)
val = body[val_start:next_param]
if not allow_incomplete:
stripped_val = val.rstrip()
if not stripped_val.endswith(_PARAM_CLOSE_TAG):
valid_params = False
break
val = stripped_val[: -len(_PARAM_CLOSE_TAG)]
else:
val = _TC_PARAM_CLOSE_RE.sub("", val)
arguments[param_name] = _trim_param_value(val)
if not valid_params:
continue
tc = {
"id": f"call_{id_offset + len(tool_calls)}",
"type": "function",
"function": {
"name": func_name,
"arguments": json.dumps(arguments),
},
}
tool_calls.append(tc)
call_spans.append((fm.start(), span_end))
if with_spans:
return tool_calls, call_spans
return tool_calls

View file

@ -603,6 +603,17 @@ def _chat_content_chunk(completion_id, created, model_name, text) -> str:
)
def _chat_reasoning_chunk(completion_id, created, model_name, text) -> str:
"""Like ``_chat_content_chunk`` but on ``reasoning_content`` (renders the UI thinking block)."""
return _chat_chunk_sse(
completion_id,
created,
model_name,
delta = ChoiceDelta(reasoning_content = text),
finish_reason = None,
)
def _chat_final_chunk(completion_id, created, model_name, finish_reason) -> str:
"""Terminal stop chunk (empty delta) carrying the finish reason."""
return _chat_chunk_sse(
@ -1136,6 +1147,7 @@ from core.inference.key_exchange import decrypt_api_key
from core.inference.model_ids import public_model_id
from core.inference.api_monitor import api_monitor
from core.inference.llama_http import nonstreaming_client
from core.inference.tool_call_parser import _strip_function_xml_calls, _strip_mistral_closed_calls
from core.inference.passthrough_healing import (
StreamToolCallHealer,
heal_gate,
@ -1294,6 +1306,11 @@ async def artifact_preview_frame(allow_network: bool = False):
)
# Whitespace/escape-tolerant bare-JSON tool-template detector: matches pretty-printed and
# JSON-escaped ``{"name":`` plus the ``"function"`` alias.
_BARE_JSON_NAME_MARKER_RE = _re.compile(r'\{\s*\\?"(?:name|function)\\?"\s*:')
def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
"""Classify reasoning/tool capabilities via the GGUF classifier so flags
match across backends. gpt-oss is overridden: Harmony routes reasoning and
@ -1304,17 +1321,21 @@ def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
model_identifier = model_id,
log_source = "safetensors",
)
# Our safetensors loop only parses <tool_call>{json}</tool_call>,
# <function=name>...</function>, and Gemma native <|tool_call>...<tool_call|>.
# Llama uses <|python_tag|>, Mistral uses [TOOL_CALLS]; advertising tools for
# those enables a pill the parser can't honour. GGUF is unaffected --
# llama-server normalises every format into structured deltas.
# Markers the parser recognises; drop the pill if a template advertises tools but uses none.
# The bare-JSON ``{"name":`` form is matched whitespace-tolerantly below.
_PARSER_MARKERS = (
"<tool_call>",
"<function=",
"<function name=",
"<|python_tag|>",
"[TOOL_CALLS]",
"<|tool_call>",
)
if (
flags.get("supports_tools")
and chat_template
and "<tool_call>" not in chat_template
and "<function=" not in chat_template
and "<|tool_call>" not in chat_template
and not any(m in chat_template for m in _PARSER_MARKERS)
and not _BARE_JSON_NAME_MARKER_RE.search(chat_template)
):
logger.info(
"safetensors: template advertises tools but uses an "
@ -1335,6 +1356,31 @@ def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
return flags
def _sf_reasoning_prefill_mode(
features: dict,
enable_thinking: Optional[bool],
template: Optional[str] = None,
reasoning_effort: Optional[str] = None,
) -> bool:
"""Whether this request begins inside an unclosed ``<think>`` (Qwen3/GLM prefill it). Gated on the standard markers; bespoke channels, gpt-oss, and thinking-disabled requests are excluded. ``enable_thinking=None`` defaults ON."""
if features.get("reasoning_style") not in ("enable_thinking", "enable_thinking_effort"):
return False
tpl = template or ""
if "</think>" not in tpl and "<think>" not in tpl:
return False
if features.get("reasoning_always_on"):
return True
if not features.get("supports_reasoning"):
return False
if enable_thinking is False:
return False
# reasoning_effort="none" disables thinking on enable_thinking_effort (GLM-5.2) models like
# enable_thinking=False; without this the answer is swallowed into empty reasoning_content.
if features.get("reasoning_style") == "enable_thinking_effort" and reasoning_effort == "none":
return False
return True
def _effective_enable_tools(payload) -> Optional[bool]:
"""Resolve `payload.enable_tools` against the process-level tool policy.
@ -1605,30 +1651,41 @@ def _apply_rag_nudge(nudge: str, tools: list[dict], *, rag_scope) -> str:
return nudge + " " + _RAG_GROUNDING_NUDGE
# Strip tool-call XML the speculative buffer in core/inference/llama_cpp.py
# split across the visible/DRAIN boundary. Four leak shapes:
# 1. well-formed `<tool_call>...</tool_call>` / `<function=...>...</function>`
# 2. orphan opening to EOF (close was DRAINED)
# 3. bare orphan close (open was DRAINED)
# 4. tail-only `</parameter>` (outer close truncated by EOS); anchored to
# `\Z` so mid-text `<parameter>` in user code samples survives.
# Strip leaked tool-call markup: every shared-parser format plus the leak shapes
# ``llama_cpp.py``'s speculative buffer splits across the visible/DRAIN boundary. Mistral
# ``[TOOL_CALLS]`` uses the parser's balanced-brace helper (``\{.*?\}`` would truncate nested JSON).
_TOOL_XML_RE = _re.compile(
# Hyphen in the name char-class matches MCP tool names with dashes
# (mcp__srv__list-issues) that would otherwise leak past this strip.
r"<(?:tool_call|function=[\w-]+)>.*?(?:</(?:tool_call|function)>|\Z)"
# The ``<|python_tag|>`` arm runs to the next REAL Llama sentinel or EOF, so a literal
# ``<|...|>`` token in an argument (e.g. ``<|cite|>``) doesn't truncate the strip.
# ``<function=name>`` plus the ``<function name="name">`` attribute form; name class mirrors the parser.
# A CLOSED ``<function=...>...</function>`` extends to the last ``</function>`` before the next
# opener (so a literal ``</function>`` in a value can't truncate); this arm runs first.
r'<function(?:=[\w.\-]+|\s+name="[\w.\-]+")>(?:(?!<function(?:=[\w.\-]+|\s+name="[\w.\-]+")>).)*</function>'
r'|<(?:tool_call|function(?:=[\w.\-]+|\s+name="[\w.\-]+"))>.*?(?:</(?:tool_call|function)>|\Z)'
r"|<\|tool_call>.*?(?:<tool_call\|>|\Z)"
r"|</(?:tool_call|function)>"
r"|<tool_call\|>"
r"|</parameter>\s*\Z",
r"|<\|python_tag\|>(?:[^<]|<(?!\|(?:eot_id|eom_id|python_tag|start_header_id|end_header_id|begin_of_text|finetune_right_pad_id)\|))*"
# ``</param>`` is the attribute-form alias of ``</parameter>``; strip a tail-only orphan.
r"|</(?:parameter|param)>\s*\Z",
_re.DOTALL,
)
def _strip_tool_xml(text: str) -> str:
"""Mistral balanced-brace helper + guarded function-XML scan + ``_TOOL_XML_RE`` (skips openers inside an open ``<parameter>``)."""
return _TOOL_XML_RE.sub(
"", _strip_function_xml_calls(_strip_mistral_closed_calls(text), final = True)
)
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."""
"""Route-level tool-call leak cleanup (Auto-Heal only) via ``_strip_tool_xml``."""
if not auto_heal_tool_calls:
return text
return _TOOL_XML_RE.sub("", text)
return _strip_tool_xml(text)
logger = get_logger(__name__)
@ -6511,6 +6568,22 @@ async def openai_chat_completions(
_sf_tpl = (_sf_model_info.get("chat_template_info") or {}).get("template")
_sf_features = _detect_safetensors_features(backend, _sf_tpl)
# Split prefilled-``<think>`` output into reasoning_content deltas (GGUF parity) so the UI
# renders the thinking block for safetensors and MLX.
_sf_parse_think = bool(
_sf_features.get("supports_reasoning") or _sf_features.get("reasoning_always_on")
)
# Prefilled-open only for prefill styles with thinking on this request; gpt-oss excluded.
_sf_reasoning_prefilled = _sf_reasoning_prefill_mode(
_sf_features, payload.enable_thinking, _sf_tpl, payload.reasoning_effort
)
def _new_sf_reasoning_extractor():
return _ResponsesReasoningExtractor(
parse_think_markers = _sf_parse_think,
reasoning_prefilled = _sf_reasoning_prefilled,
)
cancel_event = threading.Event()
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created = int(time.time())
@ -6652,6 +6725,19 @@ async def openai_chat_completions(
gen = sf_generate_with_tools()
prev_text = ""
reasoning_extractor = _new_sf_reasoning_extractor()
def _sf_flush_reasoning():
# Drain the extractor at a turn boundary / stream end; only visible text reaches the monitor.
fr, fv = reasoning_extractor.finish()
out = []
if fr:
out.append(_chat_reasoning_chunk(completion_id, created, model_name, fr))
if fv:
api_monitor.append_reply(monitor_id, fv)
out.append(_chat_content_chunk(completion_id, created, model_name, fv))
return out
while True:
if cancel_event.is_set():
backend.reset_generation_state()
@ -6668,7 +6754,11 @@ async def openai_chat_completions(
if event["type"] == "status":
if not event["text"]:
# Turn boundary: flush reasoning, then start a fresh extractor.
for _c in _sf_flush_reasoning():
yield _c
prev_text = ""
reasoning_extractor = _new_sf_reasoning_extractor()
status_data = json.dumps(
{
"type": "tool_status",
@ -6680,7 +6770,11 @@ async def openai_chat_completions(
if event["type"] in ("tool_start", "tool_end"):
if event["type"] == "tool_start":
# Flush reasoning before tool_start so the thinking block closes ahead of the tool card.
for _c in _sf_flush_reasoning():
yield _c
prev_text = ""
reasoning_extractor = _new_sf_reasoning_extractor()
yield f"data: {json.dumps(event)}\n\n"
continue
@ -6694,9 +6788,18 @@ async def openai_chat_completions(
prev_text = clean_cumulative
if not new_text:
continue
api_monitor.append_reply(monitor_id, new_text)
yield _chat_content_chunk(completion_id, created, model_name, new_text)
# Split reasoning vs visible; only visible reaches the monitor.
reasoning_delta, visible_delta = reasoning_extractor.feed(new_text)
if reasoning_delta:
yield _chat_reasoning_chunk(
completion_id, created, model_name, reasoning_delta
)
if visible_delta:
api_monitor.append_reply(monitor_id, visible_delta)
yield _chat_content_chunk(completion_id, created, model_name, visible_delta)
for _c in _sf_flush_reasoning():
yield _c
yield _chat_final_chunk(completion_id, created, model_name, "stop")
# Usage chunk from the last turn, same shape as the
# GGUF tool loop's metadata. Request-scoped holder, so
@ -6774,18 +6877,27 @@ async def openai_chat_completions(
return full_text
content_text = await asyncio.to_thread(_drain_to_text)
api_monitor.set_reply(monitor_id, content_text)
# Split prefilled <think> reasoning from the visible answer; monitor gets visible text only.
_reasoning_text, _visible_text = _extract_responses_reasoning(
content_text,
parse_think_markers = _sf_parse_think,
reasoning_prefilled = _sf_reasoning_prefilled,
)
api_monitor.set_reply(monitor_id, _visible_text)
_stats = _sf_stats_holder.get("stats")
if _stats:
_monitor_usage(monitor_id, _stats.get("usage"))
api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")
_sf_msg_kwargs = {"content": _visible_text}
if _reasoning_text:
_sf_msg_kwargs["reasoning_content"] = _reasoning_text
response = ChatCompletion(
id = completion_id,
created = created,
model = model_name,
choices = [
CompletionChoice(
message = CompletionMessage(content = content_text),
message = CompletionMessage(**_sf_msg_kwargs),
finish_reason = "stop",
)
],
@ -6864,6 +6976,8 @@ async def openai_chat_completions(
yield _chat_role_chunk(completion_id, created, model_name)
prev_text = ""
# Split prefilled <think> into reasoning_content deltas. Single turn (no per-turn reset); also MLX.
reasoning_extractor = _new_sf_reasoning_extractor()
# Run the sync generator in a thread pool to avoid blocking the
# event loop. Critical for compare mode: two SSE requests arrive
# concurrently but the orchestrator serializes them via
@ -6892,9 +7006,21 @@ async def openai_chat_completions(
prev_text = cumulative
if not new_text:
continue
api_monitor.append_reply(monitor_id, new_text)
yield _chat_content_chunk(completion_id, created, model_name, new_text)
reasoning_delta, visible_delta = reasoning_extractor.feed(new_text)
if reasoning_delta:
yield _chat_reasoning_chunk(
completion_id, created, model_name, reasoning_delta
)
if visible_delta:
api_monitor.append_reply(monitor_id, visible_delta)
yield _chat_content_chunk(completion_id, created, model_name, visible_delta)
final_reasoning, final_visible = reasoning_extractor.finish()
if final_reasoning:
yield _chat_reasoning_chunk(completion_id, created, model_name, final_reasoning)
if final_visible:
api_monitor.append_reply(monitor_id, final_visible)
yield _chat_content_chunk(completion_id, created, model_name, final_visible)
yield _chat_final_chunk(completion_id, created, model_name, "stop")
# Usage chunk (choices=[], usage set), same shape as the
# GGUF path so the speed popover works for MLX too.
@ -6956,18 +7082,27 @@ async def openai_chat_completions(
for token in generate():
full_text = token
# Split prefilled <think> reasoning from the visible answer; also covers MLX.
_reasoning_text, _visible_text = _extract_responses_reasoning(
full_text,
parse_think_markers = _sf_parse_think,
reasoning_prefilled = _sf_reasoning_prefilled,
)
_plain_msg_kwargs = {"content": _visible_text}
if _reasoning_text:
_plain_msg_kwargs["reasoning_content"] = _reasoning_text
response = ChatCompletion(
id = completion_id,
created = created,
model = model_name,
choices = [
CompletionChoice(
message = CompletionMessage(content = full_text),
message = CompletionMessage(**_plain_msg_kwargs),
finish_reason = "stop",
)
],
)
api_monitor.set_reply(monitor_id, full_text)
api_monitor.set_reply(monitor_id, _visible_text)
_stats = stats_holder.get("stats")
if _stats:
_monitor_usage(monitor_id, _stats.get("usage"))
@ -7790,10 +7925,18 @@ def _responses_marker_holdback(text: str, markers: tuple[str, ...]) -> int:
class _ResponsesReasoningExtractor:
"""Split local <think> markup into Responses reasoning and visible text."""
def __init__(self, *, parse_think_markers: bool = False) -> None:
def __init__(
self,
*,
parse_think_markers: bool = False,
reasoning_prefilled: bool = False,
) -> None:
self._buffer = ""
self._in_reasoning = False
self._parse_think_markers = parse_think_markers
# ``reasoning_prefilled``: output begins inside an unclosed ``<think>`` (Qwen3/GLM prefill),
# so start in reasoning to capture leading text until the first ``</think>``.
self._in_reasoning = reasoning_prefilled
# Splitting requires marker parsing; a prefilled open implies it.
self._parse_think_markers = parse_think_markers or reasoning_prefilled
def feed(
self,
@ -7816,14 +7959,21 @@ class _ResponsesReasoningExtractor:
if self._in_reasoning:
close_idx = self._buffer.find(_RESPONSES_THINK_CLOSE)
if close_idx != -1:
reasoning_parts.append(self._buffer[:close_idx])
reasoning_parts.append(
self._buffer[:close_idx].replace(_RESPONSES_THINK_OPEN, "")
)
self._buffer = self._buffer[close_idx + len(_RESPONSES_THINK_CLOSE) :]
self._in_reasoning = False
continue
keep = _responses_marker_holdback(self._buffer, (_RESPONSES_THINK_CLOSE,))
# Hold back a trailing partial of either marker: the close (clean chunk-boundary split)
# and a stray open (so a re-emitted ``<think>`` isn't leaked into the reasoning drawer).
keep = _responses_marker_holdback(
self._buffer, (_RESPONSES_THINK_CLOSE, _RESPONSES_THINK_OPEN)
)
if keep == len(self._buffer):
break
reasoning_parts.append(self._buffer[:-keep] if keep else self._buffer)
emit = self._buffer[:-keep] if keep else self._buffer
reasoning_parts.append(emit.replace(_RESPONSES_THINK_OPEN, ""))
self._buffer = self._buffer[-keep:] if keep else ""
break
@ -7860,7 +8010,7 @@ class _ResponsesReasoningExtractor:
return "", remaining
if self._in_reasoning:
self._in_reasoning = False
return remaining, ""
return remaining.replace(_RESPONSES_THINK_OPEN, ""), ""
return "", remaining.replace(_RESPONSES_THINK_CLOSE, "")
@ -7869,8 +8019,12 @@ def _extract_responses_reasoning(
reasoning_content: Any = None,
*,
parse_think_markers: bool = False,
reasoning_prefilled: bool = False,
) -> tuple[str, str]:
extractor = _ResponsesReasoningExtractor(parse_think_markers = parse_think_markers)
extractor = _ResponsesReasoningExtractor(
parse_think_markers = parse_think_markers,
reasoning_prefilled = reasoning_prefilled,
)
reasoning, visible = extractor.feed(text, reasoning_content)
final_reasoning, final_visible = extractor.finish()
return reasoning + final_reasoning, visible + final_visible
@ -9700,7 +9854,7 @@ async def anthropic_messages(
# Strip stale tool-call XML from conversation
for _msg in openai_messages:
if _msg.get("role") == "assistant" and isinstance(_msg.get("content"), str):
_msg["content"] = _TOOL_XML_RE.sub("", _msg["content"]).strip()
_msg["content"] = _strip_tool_xml(_msg["content"]).strip()
def _run_tool_gen():
return llama_backend.generate_chat_completion_with_tools(
@ -9854,7 +10008,7 @@ async def _anthropic_tool_stream(
# content event that was purely tool XML doesn't count as text.
if etype == "content":
event = dict(event)
event["text"] = _TOOL_XML_RE.sub("", event["text"])
event["text"] = _strip_tool_xml(event["text"])
# disable_parallel_tool_use: keep only the first tool_use block,
# dropping every later tool_start and its paired tool_end (robust
# to empty tool-call ids — tracked by state, not id matching).
@ -10040,7 +10194,7 @@ async def _anthropic_tool_non_streaming(
etype = event.get("type", "")
if etype == "content":
# Strip leaked tool-call XML
clean = _TOOL_XML_RE.sub("", event["text"])
clean = _strip_tool_xml(event["text"])
new = clean[len(prev_text) :]
prev_text = clean
if new:
@ -10509,10 +10663,11 @@ async def _anthropic_passthrough_non_streaming(
else:
text = message.get("content") or ""
if text:
# Keep unpromoted bytes when healing is active; legacy stripping is
# only for opted-out or no-client-tool requests.
# Keep unpromoted bytes when healing is active; legacy stripping is only for opted-out
# or no-client-tool requests. _strip_tool_xml also cleans Mistral [TOOL_CALLS] and
# guarded function-XML, not just _TOOL_XML_RE.
if not healing_active:
text = _TOOL_XML_RE.sub("", text)
text = _strip_tool_xml(text)
text = text.strip()
if text:
content_blocks.append(AnthropicResponseTextBlock(text = text))

View file

@ -21,7 +21,10 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
from core.inference.tool_call_parser import parse_tool_calls_from_text
from core.inference.tool_call_parser import (
_gemma_parse_value,
parse_tool_calls_from_text,
)
def _args(call: dict) -> dict:
@ -45,6 +48,17 @@ def test_normal_multi_key_arguments_still_split():
assert _args(calls[0]) == {"a": 1, "b": "hello", "c": "x,y"}
def test_empty_bare_value_becomes_empty_string_not_dropped():
# An empty bare value (``{query:}``) must serialise as ``""`` (``{"query":}`` is invalid JSON).
calls = parse_tool_calls_from_text("<|tool_call>call:search{query:,unit:celsius}<tool_call|>")
assert len(calls) == 1, calls
assert _args(calls[0]) == {"query": "", "unit": "celsius"}
only = parse_tool_calls_from_text("<|tool_call>call:get{q:}<tool_call|>")
assert len(only) == 1, only
assert _args(only[0]) == {"q": ""}
def test_bare_value_with_timestamps_after_comma_is_kept():
# A comma followed by digits-then-colon (a timestamp/ratio) is value text,
# not a new key, so the whole query must be preserved as one argument.
@ -159,3 +173,43 @@ def test_json_marker_inside_xml_parameter_is_not_a_second_call():
)
calls = parse_tool_calls_from_text(content)
assert [c["function"]["name"] for c in calls] == ["python"], calls
def test_gemma_parse_value_always_advances_on_stray_delimiter():
# A stray delimiter (`,`, `}`, `]`) at the primitive position must still advance the
# parser, or a looping caller spins forever (DoS).
for delim in (",", "}", "]"):
text = delim + "rest"
value, nxt = _gemma_parse_value(text, 0)
assert nxt > 0, (delim, value, nxt)
def test_malformed_gemma_array_does_not_hang():
# ``[},]`` (stray ``}`` in a list body) hung the buggy parser; the timeout fails
# the regression loudly instead of blocking CI forever.
import threading
result: dict = {}
def _run():
result["calls"] = parse_tool_calls_from_text("<|tool_call>call:f{a:[},]}<tool_call|>")
t = threading.Thread(target = _run, daemon = True)
t.start()
t.join(timeout = 10.0)
assert not t.is_alive(), "parse_tool_calls_from_text hung on malformed array input"
def test_malformed_gemma_mapping_value_does_not_hang():
# A stray ``}`` where a mapping value is expected must also terminate.
import threading
result: dict = {}
def _run():
result["calls"] = parse_tool_calls_from_text("<|tool_call>call:f{a:}},b:1}<tool_call|>")
t = threading.Thread(target = _run, daemon = True)
t.start()
t.join(timeout = 10.0)
assert not t.is_alive(), "parse_tool_calls_from_text hung on malformed mapping input"

View file

@ -20,7 +20,11 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
from core.inference.llama_cpp import _PROVISIONAL_ARGS_MIN_CHARS, LlamaCppBackend
from core.inference.llama_cpp import (
_MAX_REPROMPTS,
_PROVISIONAL_ARGS_MIN_CHARS,
LlamaCppBackend,
)
from state import tool_approvals
from state.tool_approvals import TOOL_REJECTED_MESSAGE, resolve_tool_decision
@ -1036,9 +1040,11 @@ def test_render_html_success_does_not_reprompt_render_html_intent(monkeypatch):
def test_internal_reprompt_attempts_do_not_duplicate_visible_text(monkeypatch):
"""No-tool re-prompt attempts should not concatenate into the UI."""
streams = [
[_sse({"content": "I will use render_html now."}), _done()],
[_sse({"content": "Understood. I will use render_html now."}), _done()],
# One initial response plus one stream per re-prompt (count from the shared cap).
streams = [[_sse({"content": "I will use render_html now."}), _done()]]
streams += [
[_sse({"content": "Understood. I will use render_html now."}), _done()]
for _ in range(_MAX_REPROMPTS)
]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, streams, payloads)
@ -1073,7 +1079,7 @@ def test_internal_reprompt_attempts_do_not_duplicate_visible_text(monkeypatch):
content_texts = [event.get("text", "") for event in events if event.get("type") == "content"]
assert content_texts == ["I will use render_html now."]
assert len(payloads) == 2
assert len(payloads) == _MAX_REPROMPTS + 1
def test_forced_reprompt_plain_final_answer_is_visible(monkeypatch):
@ -1200,6 +1206,66 @@ def test_auto_heal_disabled_parses_well_formed_xml_when_tools_enabled(monkeypatc
)
def test_textual_mistral_marker_not_leaked_when_inline_with_preface(monkeypatch):
# Inline Mistral ``[TOOL_CALLS]`` after a visible preface: the DRAINING flush must use the
# shared parser patterns (the legacy set leaked the marker to clients).
streams = [
[_sse({"content": 'Let me search. [TOOL_CALLS]web_search{"query":"cats"}'}), _done()],
[_sse({"content": "done"}), _done()],
]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, streams, payloads)
calls: list[tuple[str, dict]] = []
def fake_execute_tool(name, arguments, **_kwargs):
calls.append((name, arguments))
return "result"
monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "search"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
assert calls == [("web_search", {"query": "cats"})]
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert all("[TOOL_CALLS]" not in t for t in content_texts), content_texts
assert any("Let me search." in t for t in content_texts)
def test_textual_llama_python_tag_marker_not_leaked(monkeypatch):
# Same leak class for the Llama-3 built-in ``<|python_tag|>NAME.call(...)`` form.
streams = [
[_sse({"content": '<|python_tag|>web_search.call(query="cats")'}), _done()],
[_sse({"content": "done"}), _done()],
]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, streams, payloads)
calls: list[tuple[str, dict]] = []
def fake_execute_tool(name, arguments, **_kwargs):
calls.append((name, arguments))
return "result"
monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "search"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
assert calls == [("web_search", {"query": "cats"})]
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert all("<|python_tag|>" not in t for t in content_texts), content_texts
def test_reprompted_tool_call_still_streams_final_answer(monkeypatch):
"""Suppression ends once a forced re-prompt actually calls a tool."""
@ -1738,6 +1804,189 @@ def test_empty_tool_call_id_does_not_emit_provisional_card(monkeypatch):
assert calls == [("python", {"code": big_code})]
def _streamed_content(text: str, frag: int = 4) -> list[str]:
"""Stream content token-by-token like llama-server; ``frag`` sets the chunk size."""
chunks = [_sse({"content": text[i : i + frag]}) for i in range(0, len(text), frag)]
chunks.append(_done())
return chunks
def test_bare_json_tool_call_streamed_is_not_leaked_and_executes(monkeypatch):
"""A wrapper-less bare-JSON call must be held while incomplete, drained silently, and executed with nothing leaking."""
bare_call = '{"name": "web_search", "parameters": {"query": "weather in Sydney"}}'
first_stream = _streamed_content(bare_call)
final_stream = [_sse({"content": "It is sunny in Sydney."}), _done()]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [first_stream, final_stream], payloads)
calls: list[tuple[str, dict]] = []
def fake_execute_tool(name, arguments, **_kwargs):
calls.append((name, arguments))
return "Weather: sunny, 22C."
monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "weather in Sydney?"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
assert calls == [("web_search", {"query": "weather in Sydney"})]
assert any(
event.get("type") == "tool_end" and event.get("tool_name") == "web_search"
for event in events
)
# The bare JSON never leaked to the user-visible stream.
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert all('"name"' not in t for t in content_texts), content_texts
assert all("web_search" not in t for t in content_texts), content_texts
# The post-tool synthesis is still streamed.
assert any("sunny in Sydney" in t for t in content_texts), content_texts
def test_ordinary_json_with_name_key_is_shown_not_treated_as_tool_call(monkeypatch):
"""Markerless JSON with a non-enabled name is the answer, not a phantom call."""
answer = '{"name": "Alice", "parameters": {"age": 30}}'
first_stream = _streamed_content(answer)
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [first_stream], payloads)
calls: list[tuple[str, dict]] = []
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda n, a, **_k: (calls.append((n, a)) or "x"),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "give me a person record"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
assert calls == [], calls
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert any("Alice" in t for t in content_texts), content_texts
def test_incomplete_bare_json_truncation_is_not_leaked(monkeypatch):
"""If generation is cut off mid bare-JSON object (no closing brace), the held
fragment must be stripped at stream end rather than dumped to the user."""
truncated = '{"name": "web_search", "parameters": {"query": "weather in S'
stream = _streamed_content(truncated)
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [stream], payloads)
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("no complete call")),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "weather?"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert all('{"name"' not in t for t in content_texts), content_texts
def test_gguf_truncated_disabled_name_json_is_preserved_when_tools_active(monkeypatch):
"""A truncated JSON answer with a non-enabled name must still be shown (resolvers are gated on enabled names)."""
truncated = '{"name": "Alice", "parameters": {"age": 30'
stream = _streamed_content(truncated)
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [stream], payloads)
calls: list[tuple[str, dict]] = []
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda n, a, **_k: (calls.append((n, a)) or "x"),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "give json"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
assert calls == [], calls
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert any("Alice" in t for t in content_texts), content_texts
def test_gguf_truncated_enabled_name_json_is_still_suppressed(monkeypatch):
"""Counterpart guard: a truncated ENABLED-tool bare call (``web_search``) cut off
mid-JSON still must NOT leak -- the gate only spares disabled / non-tool names."""
truncated = '{"name": "web_search", "parameters": {"query": "weather in S'
stream = _streamed_content(truncated)
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [stream], payloads)
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("no complete call")),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "weather?"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert all("web_search" not in t for t in content_texts), content_texts
assert all('{"name"' not in t for t in content_texts), content_texts
def test_gguf_oversized_disabled_name_json_is_preserved(monkeypatch):
"""An oversized still-open JSON answer with a non-enabled name streams as content, not a phantom drain."""
cap = 16384
big = "A" * (cap + 5000)
answer = '{"name":"Alice","parameters":{"bio":"' + big # never closes
first_stream = [_sse({"content": answer[i : i + 2000]}) for i in range(0, len(answer), 2000)]
first_stream.append(_done())
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [first_stream], payloads)
calls: list[tuple[str, dict]] = []
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda n, a, **_k: (calls.append((n, a)) or "x"),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "long json"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
)
)
assert calls == [], calls
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert any("Alice" in t for t in content_texts), content_texts[:1]
def _usage_done(usage: dict, finish_reason: str = "stop") -> str:
"""A terminal SSE chunk carrying llama-server's ``usage`` block, the way the
real server reports it on the final chunk of a completion."""
@ -1813,3 +2062,131 @@ def test_metadata_event_omits_prompt_tokens_details_when_absent(monkeypatch):
metadata = [e for e in events if e.get("type") == "metadata"]
assert metadata, "expected a metadata event"
assert "prompt_tokens_details" not in metadata[-1]["usage"]
def test_gguf_oversized_bare_json_not_leaked_and_executes(monkeypatch):
"""An oversized bare-JSON call drains rather than streams, and still executes via the safety net."""
cap = 16384
big = "A" * (cap + 5000)
full = '{"name":"python","parameters":{"code":"' + big + '"}}'
first_stream = [_sse({"content": full[i : i + 2000]}) for i in range(0, len(full), 2000)]
first_stream.append(_done())
final_stream = [_sse({"content": "done"}), _done()]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [first_stream, final_stream], payloads)
calls: list[tuple[str, dict]] = []
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda name, arguments, **_k: (calls.append((name, arguments)) or "OK"),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "run"}],
tools = [{"type": "function", "function": {"name": "python"}}],
max_tool_iterations = 1,
)
)
content_texts = [e.get("text", "") for e in events if e.get("type") == "content"]
assert not any(t.lstrip().startswith('{"name') for t in content_texts), content_texts[:1]
assert calls and calls[0][0] == "python"
assert len(calls[0][1].get("code", "")) > cap
def test_gguf_bare_json_call_not_replayed_in_next_turn_content(monkeypatch):
"""After a bare-JSON call executes, the kept assistant message must not carry the raw call as content."""
import copy
first_stream = [
_sse({"content": '{"name":"web_search","parameters":{"query":"cats"}}'}),
_done(),
]
final_stream = [_sse({"content": "Found."}), _done()]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, [first_stream, final_stream], payloads)
monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "RESULT")
list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "cats"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 2,
)
)
assert len(payloads) >= 2
asst = [m for m in payloads[1]["messages"] if m.get("role") == "assistant"]
assert asst and not any('"name"' in (m.get("content") or "") for m in asst), asst
def test_gguf_drain_truncated_enabled_name_json_preserved_when_auto_heal_disabled(monkeypatch):
"""Auto-Heal OFF keeps a truncated enabled-name fragment visible; ON suppresses it (strip gated on auto_heal_tool_calls)."""
trunc = '{"name":"web_search","parameters":{"query":"weather'
def _run(auto_heal):
stream = [_sse({"content": trunc}), _done()]
backend = _make_backend(monkeypatch, [stream], [])
calls: list[tuple[str, dict]] = []
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda name, arguments, **_k: (calls.append((name, arguments)) or "result"),
)
events = list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "x"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 1,
auto_heal_tool_calls = auto_heal,
)
)
contents = "".join(e.get("text", "") for e in events if e.get("type") == "content")
return calls, contents
calls_off, contents_off = _run(False)
assert calls_off == [], calls_off
assert "web_search" in contents_off, contents_off
calls_on, contents_on = _run(True)
assert calls_on == [], calls_on
assert "web_search" not in contents_on, contents_on
def test_gguf_valid_tool_calls_respect_max_tool_iterations(monkeypatch):
"""Re-prompt slots must not extend the tool budget: stop after ``max_tool_iterations`` executed rounds."""
# More tool-call streams than the budget: leaked re-prompt slots would run 2+3=5 rounds;
# honouring the budget stops after 2, then a tool-less final-answer pass.
streams = [
_structured_tool_call("web_search", {"query": f"q{i}"}, f"call_{i}") for i in range(6)
]
payloads: list[dict] = []
backend = _make_backend(monkeypatch, streams, payloads)
calls: list[tuple[str, dict]] = []
monkeypatch.setattr(
"core.inference.tools.execute_tool",
lambda name, arguments, **_k: (calls.append((name, arguments)) or "result"),
)
list(
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "search repeatedly"}],
tools = [{"type": "function", "function": {"name": "web_search"}}],
max_tool_iterations = 2,
)
)
# Exactly two executed tool rounds, then one final-answer pass.
assert len(calls) == 2, calls
assert len(payloads) == 3, len(payloads)
# The final pass is the budget-exhausted nudge and carries no tools.
assert _tool_names(payloads[2]) == [], _tool_names(payloads[2])
assert any(
m.get("role") == "user" and "used all available tool calls" in m.get("content", "")
for m in payloads[2]["messages"]
), payloads[2]["messages"]

View file

@ -59,6 +59,7 @@ from models.inference import (
ResponsesUsage,
)
from routes.inference import (
_ResponsesReasoningExtractor,
_SameTaskStreamingResponse,
_build_chat_request,
_chat_tool_calls_to_responses_output,
@ -795,6 +796,7 @@ class TestResponsesNonStreamingAdapter:
def test_monitor_records_translated_visible_text(self, monkeypatch):
import routes.inference as inf_mod
import routes.inference as inf_mod
async def fake_chat_completions(chat_req, request):
assert request.state.skip_api_monitor is True
@ -1988,6 +1990,122 @@ class TestTranslatedMessagesValidate:
ChatMessage(**m.model_dump(exclude_none = True))
# reasoning_prefilled: Qwen3/GLM enable_thinking templates prefill an unclosed <think>, so generation
# begins inside the think block and emits only the closing </think>; extractor starts in reasoning.
class TestReasoningPrefilledExtractor:
def test_prefilled_single_feed_splits_lone_close(self):
# T1: reasoning...</think>answer with a prefilled (unseen) open tag.
reasoning, visible = _extract_responses_reasoning(
"plan</think>answer",
parse_think_markers = True,
reasoning_prefilled = True,
)
assert reasoning == "plan"
assert visible == "answer"
def test_prefilled_never_closed_is_all_reasoning(self):
# T2: truncated mid-thought (no </think>) -> all reasoning (GGUF parity).
reasoning, visible = _extract_responses_reasoning(
"still thinking with no close",
parse_think_markers = True,
reasoning_prefilled = True,
)
assert reasoning == "still thinking with no close"
assert visible == ""
def test_prefilled_close_split_across_feeds(self):
# T3: </think> straddles two feed() calls; holdback resolves it.
ex = _ResponsesReasoningExtractor(parse_think_markers = True, reasoning_prefilled = True)
r1, v1 = ex.feed("plan</th")
r2, v2 = ex.feed("ink>ans")
fr, fv = ex.finish()
assert (r1 + r2 + fr) == "plan"
assert (v1 + v2 + fv) == "ans"
def test_prefilled_close_split_one_char_per_feed(self):
# T4: every char in its own feed still splits correctly.
ex = _ResponsesReasoningExtractor(parse_think_markers = True, reasoning_prefilled = True)
reasoning, visible = "", ""
for ch in "plan</think>x":
r, v = ex.feed(ch)
reasoning += r
visible += v
fr, fv = ex.finish()
assert (reasoning + fr) == "plan"
assert (visible + fv) == "x"
def test_prefilled_empty_generation(self):
# T5: nothing generated.
reasoning, visible = _extract_responses_reasoning(
"",
parse_think_markers = True,
reasoning_prefilled = True,
)
assert reasoning == ""
assert visible == ""
def test_prefilled_whitespace_after_close_is_visible(self):
# T6: Qwen commonly emits </think>\n\n before the answer.
reasoning, visible = _extract_responses_reasoning(
"plan</think>\n\nanswer",
parse_think_markers = True,
reasoning_prefilled = True,
)
assert reasoning == "plan"
assert visible == "\n\nanswer"
def test_prefilled_stray_open_tag_is_suppressed(self):
# T7: a re-emitted literal <think> inside prefilled reasoning is dropped, not leaked.
reasoning, visible = _extract_responses_reasoning(
"a<think>b</think>c",
parse_think_markers = True,
reasoning_prefilled = True,
)
assert reasoning == "ab"
assert visible == "c"
assert "<think>" not in reasoning
def test_prefilled_close_at_start_empty_reasoning(self):
# T8: model closed immediately (empty reasoning) then answered.
reasoning, visible = _extract_responses_reasoning(
"</think>hi",
parse_think_markers = True,
reasoning_prefilled = True,
)
assert reasoning == ""
assert visible == "hi"
def test_not_prefilled_lone_close_preserves_current_behavior(self):
# T9: without prefilled, a lone </think> keeps pre-fix behavior (reasoning stays visible, tag dropped).
reasoning, visible = _extract_responses_reasoning(
"reasoning</think>ans",
parse_think_markers = True,
reasoning_prefilled = False,
)
assert reasoning == ""
assert visible == "reasoningans"
def test_not_prefilled_full_pair_still_splits(self):
# T10: normal explicit <think>..</think> (GGUF / Harmony) unchanged.
reasoning, visible = _extract_responses_reasoning(
"<think>r</think>v",
parse_think_markers = True,
reasoning_prefilled = False,
)
assert reasoning == "r"
assert visible == "v"
def test_prefilled_ignored_when_markers_not_parsed(self):
# T11: a non-reasoning model (parse_think_markers False) passes text straight through.
reasoning, visible = _extract_responses_reasoning(
"just an answer",
parse_think_markers = False,
reasoning_prefilled = False,
)
assert reasoning == ""
assert visible == "just an answer"
# =====================================================================
# Streaming passthrough healing — text-form calls promoted in order
# =====================================================================

View file

@ -127,9 +127,8 @@ def test_detect_safetensors_features_gptoss_disables_tools():
assert flags["supports_tools"] is False
# Llama-3 / Mistral advertise tools but emit <|python_tag|> / [TOOL_CALLS],
# which our parser can't read. The route helper must not flip supports_tools=True
# for them, else the UI enables a pill the agentic loop can't honour.
# Llama-3 / Mistral / Gemma 4 tool-call formats are parser-supported, so supports_tools stays True;
# only templates matching none of the known markers are suppressed.
LLAMA3_TEMPLATE = """
{%- if tools %}
@ -161,27 +160,106 @@ MISTRAL_TEMPLATE = """
{%- endfor %}
"""
GEMMA4_TEMPLATE = """
{%- if tools %}
{{- 'Tools available. Emit calls as ' }}
{{- '<|tool_call>call:NAME{key:<|"|>val<|"|>}<tool_call|>' }}
{%- for tool in tools %}
{{- tool | tojson }}
{%- endfor %}
{%- endif %}
"""
def test_detect_safetensors_features_llama3_template_suppresses_tools():
"""Llama-3 emits <|python_tag|>; safetensors loop cannot parse it."""
def test_detect_safetensors_features_llama3_template_keeps_tools_on():
"""Llama-3 emits <|python_tag|>; parser now supports it."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Llama-3.2-3B-Instruct")
flags = _detect_safetensors_features(backend, LLAMA3_TEMPLATE)
assert flags["supports_tools"] is False
assert flags["supports_tools"] is True
def test_detect_safetensors_features_mistral_template_suppresses_tools():
"""Mistral emits [TOOL_CALLS]; safetensors loop cannot parse it."""
def test_detect_safetensors_features_mistral_template_keeps_tools_on():
"""Mistral emits [TOOL_CALLS]; parser now supports it."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/mistral-7b-instruct-v0.3")
flags = _detect_safetensors_features(backend, MISTRAL_TEMPLATE)
assert flags["supports_tools"] is True
def test_detect_safetensors_features_gemma4_template_keeps_tools_on():
"""Gemma 4 emits <|tool_call>; parser now supports it."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/gemma-4-E2B-it-UD-MLX-4bit")
flags = _detect_safetensors_features(backend, GEMMA4_TEMPLATE)
assert flags["supports_tools"] is True
LLAMA3_2_BARE_JSON_TEMPLATE = """
{%- if tools %}
{{- 'Given the following functions, respond with JSON for a function call.' }}
{{- 'Respond in the format {"name": function name, "parameters": dictionary}.' }}
{%- for tool in tools %}
{{- tool | tojson }}
{%- endfor %}
{%- endif %}
{%- for message in messages %}
{%- if 'tool_calls' in message %}
{{- '{"name": "' + message.tool_calls[0].function.name + '", '}}
{{- '"parameters": ' + (message.tool_calls[0].function.arguments | tojson) + '}' }}
{%- endif %}
{%- endfor %}
"""
def test_detect_safetensors_features_llama3_2_bare_json_keeps_tools_on():
"""Llama-3.2 bare JSON is supported, so the pill stays enabled."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Llama-3.2-3B-Instruct")
flags = _detect_safetensors_features(backend, LLAMA3_2_BARE_JSON_TEMPLATE)
assert flags["supports_tools"] is True
MINICPM5_ATTRIBUTE_TEMPLATE = """
{%- if tools %}
{{- 'Available tools. Emit calls as ' }}
{{- '<function name="NAME"><parameter name="key">value</parameter></function>' }}
{%- for tool in tools %}
{{- tool | tojson }}
{%- endfor %}
{%- endif %}
"""
def test_detect_safetensors_features_attribute_function_form_keeps_tools_on():
"""The attribute form ``<function name="...">`` must be whitelisted or the pill is wrongly suppressed."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "openbmb/MiniCPM-5")
flags = _detect_safetensors_features(backend, MINICPM5_ATTRIBUTE_TEMPLATE)
assert flags["supports_tools"] is True
def test_detect_safetensors_features_unknown_format_suppresses_tools():
"""Tools advertised with no known marker must be suppressed."""
from routes.inference import _detect_safetensors_features
tpl = (
"{%- if tools %}<|im_start|>system\n"
"Emit tool calls as JSON-RPC notifications inside the response."
"<|im_end|>{%- endif %}"
)
backend = SimpleNamespace(active_model_name = "custom/unknown-tool-format")
flags = _detect_safetensors_features(backend, tpl)
assert flags["supports_tools"] is False
def test_detect_safetensors_features_qwen_tool_call_keeps_tools_on():
"""Sanity check: gate only suppresses non-Qwen formats."""
"""Sanity check: Qwen <tool_call> marker still flips supports_tools."""
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Qwen3-0.6B")
@ -454,3 +532,130 @@ def test_route_layer_emits_supports_tools_true_for_qwen3_safetensors():
assert flags["supports_tools"] is True
assert flags["supports_reasoning"] is True
assert flags["supports_preserve_thinking"] is True
# Templates advertising tools whose ``{"name":`` example is pretty-printed or JSON-escaped.
_WHITESPACE_BARE_JSON_TEMPLATE = (
"{%- if tools %}\n"
"To call a tool, output JSON of the form:\n"
'{ "name" : "function_name", "parameters": { } }\n'
"{%- endif %}\n"
"{{ messages }}"
)
_ESCAPED_BARE_JSON_TEMPLATE = (
"{%- if tools %}\n"
'Respond with {\\"name\\": \\"fn\\", \\"parameters\\": {}}\n'
"{%- endif %}\n"
"{{ messages }}"
)
_TOOLS_ADVERTISED_NO_PARSEABLE_FORM = (
"{%- if tools %}\nYou may use the available tools.\n{%- endif %}\n{{ messages }}"
)
def test_detect_safetensors_features_keeps_tools_for_pretty_printed_bare_json():
# Pretty-printed bare-JSON (``{ "name" :``) keeps supports_tools: parser accepts the whitespace.
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Llama-3.2-3B-Instruct")
flags = _detect_safetensors_features(backend, _WHITESPACE_BARE_JSON_TEMPLATE)
assert flags["supports_tools"] is True
def test_detect_safetensors_features_keeps_tools_for_escaped_bare_json():
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Llama-3.2-3B-Instruct")
flags = _detect_safetensors_features(backend, _ESCAPED_BARE_JSON_TEMPLATE)
assert flags["supports_tools"] is True
def test_detect_safetensors_features_drops_tools_when_no_parseable_form():
# Negative control: tools advertised but no parser-recognised emission form -> pill dropped.
from routes.inference import _detect_safetensors_features
backend = SimpleNamespace(active_model_name = "unsloth/Llama-3.2-3B-Instruct")
flags = _detect_safetensors_features(backend, _TOOLS_ADVERTISED_NO_PARSEABLE_FORM)
assert flags["supports_tools"] is False
def test_detect_safetensors_features_keeps_tools_for_function_alias_bare_json():
# The {"function":...} bare-JSON alias keeps supports_tools, mirroring {"name":...}.
from routes.inference import _detect_safetensors_features
tpl = (
"{%- if tools %}\n"
'Respond with {"function": "fn", "parameters": {}}\n'
"{%- endif %}\n"
"{{ messages }}"
)
backend = SimpleNamespace(active_model_name = "unsloth/Llama-3.2-3B-Instruct")
flags = _detect_safetensors_features(backend, tpl)
assert flags["supports_tools"] is True
# _sf_reasoning_prefill_mode gates the prefilled-<think> extractor for enable_thinking models.
class TestSafetensorsReasoningPrefillGate:
# Qwen3-style template with the standard <think>/</think> markers.
_QWEN_TPL = "{% if enable_thinking %}<think>{% endif %}...</think>..."
# gemma-style bespoke reasoning channel -- no standard markers.
_GEMMA_TPL = "{% if enable_thinking %}<|think|>{% endif %}<|channel>thought<channel|>"
def _features(self, **over):
base = {
"supports_reasoning": True,
"reasoning_always_on": False,
"reasoning_style": "enable_thinking",
}
base.update(over)
return base
def test_g1_enable_thinking_true(self):
# G1: Qwen3.5 template + explicit enable_thinking=True -> prefilled.
from routes.inference import _sf_reasoning_prefill_mode
assert _sf_reasoning_prefill_mode(self._features(), True, self._QWEN_TPL) is True
def test_g2_enable_thinking_none_defaults_on(self):
# G2: default request (None) -> prefilled (Qwen3/GLM templates default on).
from routes.inference import _sf_reasoning_prefill_mode
assert _sf_reasoning_prefill_mode(self._features(), None, self._QWEN_TPL) is True
def test_g3_enable_thinking_false(self):
# G3: thinking explicitly off -> not prefilled.
from routes.inference import _sf_reasoning_prefill_mode
assert _sf_reasoning_prefill_mode(self._features(), False, self._QWEN_TPL) is False
def test_g4_gpt_oss_reasoning_effort_excluded(self):
# G4: gpt-oss uses explicit tags via HarmonyTextStreamer -> normal mode.
from routes.inference import _sf_reasoning_prefill_mode
feats = self._features(reasoning_style = "reasoning_effort")
assert _sf_reasoning_prefill_mode(feats, True, self._QWEN_TPL) is False
def test_g5_enable_thinking_effort_included(self):
# G5: GLM-style enable_thinking_effort also prefills.
from routes.inference import _sf_reasoning_prefill_mode
feats = self._features(reasoning_style = "enable_thinking_effort")
assert _sf_reasoning_prefill_mode(feats, None, self._QWEN_TPL) is True
def test_g6_non_reasoning_model(self):
# G6: no reasoning capability -> never prefilled.
from routes.inference import _sf_reasoning_prefill_mode
feats = self._features(supports_reasoning = False, reasoning_style = None)
assert _sf_reasoning_prefill_mode(feats, True, self._QWEN_TPL) is False
def test_g7_reasoning_always_on(self):
# G7: hardcoded-<think> template -> prefilled regardless of the flag.
from routes.inference import _sf_reasoning_prefill_mode
feats = self._features(reasoning_always_on = True)
assert _sf_reasoning_prefill_mode(feats, False, self._QWEN_TPL) is True
def test_g8_gemma_bespoke_channel_excluded(self):
# G8: gemma's <|think|>/<|channel> format has no </think> -> NOT prefilled (else the
# whole answer is swallowed as reasoning). Regression guard.
from routes.inference import _sf_reasoning_prefill_mode
assert _sf_reasoning_prefill_mode(self._features(), True, self._GEMMA_TPL) is False
def test_g9_missing_template_not_prefilled(self):
# G9: no template available -> conservative (not prefilled).
from routes.inference import _sf_reasoning_prefill_mode
assert _sf_reasoning_prefill_mode(self._features(), True, None) is False

View file

@ -0,0 +1,182 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Safetensors/MLX reasoning-block parity with GGUF.
enable_thinking templates prefill an unclosed ``<think>``, so the stream must split the leading
text into ``reasoning_content`` deltas (per turn, monitor gets visible text only). Replays a copy
of ``sf_tool_stream``'s reasoning loop from routes/inference.py against synthetic events.
"""
from __future__ import annotations
import sys
from pathlib import Path
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
from routes.inference import (
_ResponsesReasoningExtractor,
_sf_reasoning_prefill_mode,
_strip_tool_xml_for_display,
)
def _replay_sf_reasoning_stream(events: list[dict], *, prefilled: bool) -> dict:
"""Mirror sf_tool_stream's reasoning loop: diff cumulative snapshots, reset (flushing) on turn end."""
prev_text = ""
extractor = _ResponsesReasoningExtractor(
parse_think_markers = True, reasoning_prefilled = prefilled
)
reasoning_deltas: list[str] = []
visible_deltas: list[str] = []
monitor: list[str] = []
tool_starts: list[dict] = []
order: list[str] = [] # "reasoning" | "visible" | "tool_start" sequence
def _flush():
fr, fv = extractor.finish()
if fr:
reasoning_deltas.append(fr)
order.append("reasoning")
if fv:
visible_deltas.append(fv)
monitor.append(fv)
order.append("visible")
for event in events:
etype = event["type"]
if etype == "status":
if not event["text"]:
_flush()
prev_text = ""
extractor = _ResponsesReasoningExtractor(
parse_think_markers = True, reasoning_prefilled = prefilled
)
continue
if etype in ("tool_start", "tool_end"):
if etype == "tool_start":
_flush()
prev_text = ""
extractor = _ResponsesReasoningExtractor(
parse_think_markers = True, reasoning_prefilled = prefilled
)
tool_starts.append(event)
order.append("tool_start")
continue
clean = _strip_tool_xml_for_display(event.get("text", ""), auto_heal_tool_calls = True)
new_text = clean[len(prev_text) :]
prev_text = clean
if not new_text:
continue
r, v = extractor.feed(new_text)
if r:
reasoning_deltas.append(r)
order.append("reasoning")
if v:
visible_deltas.append(v)
monitor.append(v)
order.append("visible")
_flush()
return {
"reasoning": "".join(reasoning_deltas),
"visible": "".join(visible_deltas),
"monitor": "".join(monitor),
"tool_starts": tool_starts,
"order": order,
}
def test_s1_plain_stream_splits_prefilled_reasoning():
# S1: plain/MLX single turn -> reasoning delta + visible delta; monitor visible-only.
events = [
{"type": "content", "text": "Let me compute 17*23"},
{"type": "content", "text": "Let me compute 17*23 = 391</think>The answer is 391."},
]
out = _replay_sf_reasoning_stream(events, prefilled = True)
assert out["reasoning"] == "Let me compute 17*23 = 391"
assert out["visible"] == "The answer is 391."
assert out["monitor"] == "The answer is 391."
assert "<think>" not in out["reasoning"] and "</think>" not in out["visible"]
def test_s2_reasoning_flushed_before_tool_start():
# S2: reasoning streamed as reasoning_content, then flushed BEFORE tool_start.
events = [
{"type": "content", "text": "I should search"},
{"type": "content", "text": "I should search Sydney weather</think>"},
{"type": "tool_start", "tool_name": "web_search", "tool_call_id": "c0"},
{"type": "tool_end", "tool_name": "web_search", "tool_call_id": "c0"},
{"type": "status", "text": ""},
{"type": "content", "text": "Found it</think>Sydney is 21C today."},
]
out = _replay_sf_reasoning_stream(events, prefilled = True)
# Both turns' reasoning surfaced, answer only from turn 2.
assert "I should search Sydney weather" in out["reasoning"]
assert "Found it" in out["reasoning"]
assert out["visible"] == "Sydney is 21C today."
assert out["monitor"] == "Sydney is 21C today."
# Ordering: the pre-tool reasoning is emitted before the tool_start.
assert out["order"].index("reasoning") < out["order"].index("tool_start")
def test_s3_extractor_resets_each_turn():
# S3: multi-turn -> the two turns' reasoning are distinct (fresh extractor each).
events = [
{"type": "content", "text": "turn1 thoughts</think>partial"},
{"type": "status", "text": ""},
{"type": "content", "text": "turn2 thoughts</think>final answer"},
]
out = _replay_sf_reasoning_stream(events, prefilled = True)
assert out["reasoning"] == "turn1 thoughtsturn2 thoughts"
assert out["visible"] == "partialfinal answer"
def test_s4_harmony_full_tags_normal_mode():
# S4: gpt-oss / explicit-tag models use normal mode (prefilled=False).
events = [{"type": "content", "text": "<think>reasoning here</think>visible answer"}]
out = _replay_sf_reasoning_stream(events, prefilled = False)
assert out["reasoning"] == "reasoning here"
assert out["visible"] == "visible answer"
def test_s5_thinking_off_no_reasoning_deltas():
# S5: thinking disabled -> not prefilled, no </think>, all content is visible.
events = [{"type": "content", "text": "Just the plain answer, no thinking."}]
out = _replay_sf_reasoning_stream(events, prefilled = False)
assert out["reasoning"] == ""
assert out["visible"] == "Just the plain answer, no thinking."
assert out["monitor"] == "Just the plain answer, no thinking."
_THINK_TPL = "...{% if enable_thinking %}<think>{% endif %}...</think>..."
def test_s6_reasoning_effort_none_disables_prefill_for_enable_thinking_effort():
# GLM-5.2 enable_thinking_effort + reasoning_effort="none" disables thinking like
# enable_thinking=False, so prefilled must be OFF (else the answer is swallowed into reasoning).
feats = {"reasoning_style": "enable_thinking_effort", "supports_reasoning": True}
assert _sf_reasoning_prefill_mode(feats, None, _THINK_TPL, "none") is False
# Thinking on (effort level or default) still prefills.
assert _sf_reasoning_prefill_mode(feats, None, _THINK_TPL, "high") is True
assert _sf_reasoning_prefill_mode(feats, None, _THINK_TPL, None) is True
# An explicit enable_thinking=False also disables (unchanged).
assert _sf_reasoning_prefill_mode(feats, False, _THINK_TPL, "high") is False
# reasoning_always_on wins regardless of reasoning_effort.
always = {**feats, "reasoning_always_on": True}
assert _sf_reasoning_prefill_mode(always, None, _THINK_TPL, "none") is True
# Plain enable_thinking models (Qwen) have no "none" sentinel; unaffected.
plain = {"reasoning_style": "enable_thinking", "supports_reasoning": True}
assert _sf_reasoning_prefill_mode(plain, None, _THINK_TPL, "none") is True
# End-to-end: with prefilled=False, a plain no-</think> answer stays visible.
events = [{"type": "content", "text": "The capital of France is Paris."}]
out = _replay_sf_reasoning_stream(events, prefilled = False)
assert out["visible"] == "The capital of France is Paris."
assert out["reasoning"] == ""
# The buggy prefilled=True path is what swallowed the whole answer (guard the delta).
swallowed = _replay_sf_reasoning_stream(events, prefilled = True)
assert swallowed["visible"] == ""
assert swallowed["reasoning"] == "The capital of France is Paris."

File diff suppressed because it is too large Load diff

View file

@ -102,6 +102,22 @@ class TestFunctionStyleTrailingText:
text = "<function=web_search><parameter=query>weather london</function>"
assert parse_tool_calls_from_text(text, allow_incomplete = False) == []
def test_attribute_form_literal_close_tag_is_preserved(self):
# Attribute form ends at the LAST </function>, so a literal close inside code survives.
text = (
'<function name="python"><param name="code">'
'print("</function>")'
"</param></function> all done"
)
call = _only(text)
assert call == {"name": "python", "arguments": {"code": 'print("</function>")'}}
def test_closed_zero_param_attribute_call_is_accepted_in_strict_mode(self):
# A closed zero-param call is valid; strict mode must not treat it as truncated.
assert _only('<function name="ping"></function>') == {"name": "ping", "arguments": {}}
# A no-arg call that never closes is still rejected as truncated.
assert parse_tool_calls_from_text('<function name="ping">', allow_incomplete = False) == []
class TestParityWithJsonStyle:
def test_json_tool_call_with_trailing_prose_is_accepted(self):
@ -176,6 +192,37 @@ class TestGemmaNativeStyle:
}
class TestLlama3PythonTagStrict:
def test_closed_dot_call_is_accepted(self):
text = '<|python_tag|>get_weather.call(location="Tokyo")'
calls = parse_tool_calls_from_text(text, allow_incomplete = False)
assert len(calls) == 1
assert calls[0]["function"]["name"] == "get_weather"
assert json.loads(calls[0]["function"]["arguments"]) == {"location": "Tokyo"}
def test_truncated_dot_call_is_rejected(self):
# No closing paren (depth > 0 at EOF): truncated, reject in strict mode.
text = '<|python_tag|>get_weather.call(location="Tokyo"'
assert parse_tool_calls_from_text(text, allow_incomplete = False) == []
# Auto-Heal still recovers it.
assert len(parse_tool_calls_from_text(text, allow_incomplete = True)) == 1
class TestMistralArrayStrict:
def test_closed_array_is_accepted(self):
text = '[TOOL_CALLS] [{"name":"web_search","arguments":{"q":"x"}}]'
calls = parse_tool_calls_from_text(text, allow_incomplete = False)
assert len(calls) == 1
assert calls[0]["function"]["name"] == "web_search"
def test_unclosed_array_is_rejected(self):
# Missing the closing ]; strict mode must not heal it.
text = '[TOOL_CALLS] [{"name":"web_search","arguments":{"q":"x"}}'
assert parse_tool_calls_from_text(text, allow_incomplete = False) == []
# Auto-Heal still recovers the object by hand.
assert len(parse_tool_calls_from_text(text, allow_incomplete = True)) == 1
class TestHealingPathUnaffected:
def test_auto_heal_still_repairs_unclosed_function(self):
text = "<function=web_search><parameter=query>cats"
@ -197,3 +244,822 @@ class TestHealingPathUnaffected:
assert text[span[0] : span[1]] == (
"<function=web_search><parameter=query>cats</parameter></function>"
)
def test_wrapperless_fallback_calls_carry_spans(self):
# The wrapperless fallback must report spans so consumers strip exactly the markup.
from core.tool_healing import parse_tool_calls_from_text as parse_with_spans
closed = "before <function=web_search><parameter=query>cats</parameter></function> after"
calls, spans = parse_with_spans(closed, allow_incomplete = True, with_spans = True)
(call,) = calls
assert json.loads(call["function"]["arguments"]) == {"query": "cats"}
(span,) = spans
assert closed[span[0] : span[1]] == (
"<function=web_search><parameter=query>cats</parameter></function>"
)
healed = "x <function=web_search><parameter=query>dogs"
calls, spans = parse_with_spans(healed, allow_incomplete = True, with_spans = True)
(call,) = calls
assert json.loads(call["function"]["arguments"]) == {"query": "dogs"}
(span,) = spans
assert healed[span[0] : span[1]] == "<function=web_search><parameter=query>dogs"
class TestParserLinearity:
"""Llama-3 ``.call`` kwargs and Mistral-array healing must stay linear (a regex-per-offset blew up on long truncated bodies)."""
def test_llama3_unterminated_call_arg_is_linear(self):
import time
text = '<|python_tag|>upload.call(data="' + "A" * 200_000 # no closing quote/paren
t0 = time.perf_counter()
parse_tool_calls_from_text(text, allow_incomplete = True)
assert time.perf_counter() - t0 < 2.0
def test_llama3_huge_wordrun_call_arg_is_linear(self):
import time
text = "<|python_tag|>upload.call(" + "a" * 200_000 # giant word run, no '='
t0 = time.perf_counter()
parse_tool_calls_from_text(text, allow_incomplete = True)
assert time.perf_counter() - t0 < 2.0
def test_mistral_unclosed_array_open_braces_is_linear(self):
import time
text = "[TOOL_CALLS] [" + "{" * 200_000 # unclosed array, all open braces
t0 = time.perf_counter()
parse_tool_calls_from_text(text, allow_incomplete = True)
assert time.perf_counter() - t0 < 2.0
def test_llama3_call_kwargs_still_parse(self):
text = '<|python_tag|>do.call(s="hi 😀", n=42, f=1.5, b=true, z=null)'
calls = parse_tool_calls_from_text(text, allow_incomplete = True)
assert len(calls) == 1
assert json.loads(calls[0]["function"]["arguments"]) == {
"s": "hi 😀",
"n": 42,
"f": 1.5,
"b": True,
"z": None,
}
def test_llama3_call_scientific_notation_args_parse(self):
# Scientific notation must decode as float (the old regex truncated 1e-3 -> 1).
text = "<|python_tag|>calc.call(x=1e-3, y=-2E+4, z=0.5e2, n=42)"
calls = parse_tool_calls_from_text(text, allow_incomplete = True)
assert len(calls) == 1
args = json.loads(calls[0]["function"]["arguments"])
assert args == {"x": 1e-3, "y": -2e4, "z": 50.0, "n": 42}
assert isinstance(args["n"], int) and isinstance(args["x"], float)
def test_mistral_unclosed_array_recovers_top_level_objects(self):
text = (
'[TOOL_CALLS] [{"name":"a","arguments":{"k":1}},'
'{"name":"b","arguments":{"j":2}}' # missing closing ]
)
calls = parse_tool_calls_from_text(text, allow_incomplete = True)
assert [c["function"]["name"] for c in calls] == ["a", "b"]
class TestLlamaBuiltinChainAndNesting:
"""Llama-3 ``.call`` built-ins: ``; `` chaining and nested-tag isolation."""
def test_semicolon_chained_builtin_calls_all_parse(self):
# Only the first call is anchored to <|python_tag|>; the rest chain via ';'.
text = "<|python_tag|>alpha.call(x=1); beta.call(y=2); gamma.call(z=3)"
calls = parse_tool_calls_from_text(text, allow_incomplete = True)
assert [c["function"]["name"] for c in calls] == ["alpha", "beta", "gamma"]
assert json.loads(calls[1]["function"]["arguments"]) == {"y": 2}
def test_nested_python_tag_in_json_string_arg_is_not_a_call(self):
# A <|python_tag|> literal inside a code arg is data: the outer "python" call wins.
text = (
'<|python_tag|>{"name":"python","parameters":'
'{"code":"<|python_tag|>os.call(\'rm -rf /\')"}}'
)
calls = parse_tool_calls_from_text(text, allow_incomplete = True)
assert len(calls) == 1
assert calls[0]["function"]["name"] == "python"
args = json.loads(calls[0]["function"]["arguments"])
assert args["code"] == "<|python_tag|>os.call('rm -rf /')"
def test_single_builtin_call_unchanged(self):
text = '<|python_tag|>web_search.call(query="cats")'
calls = parse_tool_calls_from_text(text, allow_incomplete = True)
assert len(calls) == 1
assert calls[0]["function"]["name"] == "web_search"
assert json.loads(calls[0]["function"]["arguments"]) == {"query": "cats"}
def test_strip_leading_bare_json_call_drops_complete_call():
from core.inference.tool_call_parser import strip_leading_bare_json_call
# A complete Llama-3.2 bare-JSON call is removed; trailing prose is kept.
assert strip_leading_bare_json_call('{"name":"web_search","parameters":{"query":"cats"}}') == ""
assert (
strip_leading_bare_json_call('{"name":"python","parameters":{"code":"x"}} done') == "done"
)
def test_strip_leading_bare_json_call_drops_truncated_call():
from core.inference.tool_call_parser import strip_leading_bare_json_call
# A truncated call (no closing brace) collapses to "" -- nothing recoverable.
assert (
strip_leading_bare_json_call('{"name":"web_search","parameters":{"query":"weather in S')
== ""
)
def test_strip_leading_bare_json_call_preserves_plain_json_and_prose():
from core.inference.tool_call_parser import strip_leading_bare_json_call
# No "name" key -> plain JSON answer, left untouched.
assert (
strip_leading_bare_json_call('{"result": 42, "ok": true}') == '{"result": 42, "ok": true}'
)
# Prose before the brace -> not a leading bare call, untouched.
assert strip_leading_bare_json_call('here is {"name":"x"}') == 'here is {"name":"x"}'
# Ordinary text untouched.
assert strip_leading_bare_json_call("just a sentence.") == "just a sentence."
def test_bare_json_gated_on_enabled_tool_names():
from core.inference.tool_call_parser import parse_tool_calls_from_text
alice = '{"name":"Alice","parameters":{"age":30}}'
real = '{"name":"web_search","parameters":{"query":"cats"}}'
# With an enabled set, markerless JSON whose name is not a tool is NOT a call.
assert parse_tool_calls_from_text(alice, enabled_tool_names = {"web_search"}) == []
# A real call (enabled name) still parses.
got = parse_tool_calls_from_text(real, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in got] == ["web_search"]
# No enabled set (None) keeps the name-agnostic behaviour for direct callers.
assert [c["function"]["name"] for c in parse_tool_calls_from_text(alice)] == ["Alice"]
# Marker-based forms are NOT gated (an explicit signal is a real call attempt).
xml = '<tool_call>{"name":"Alice","arguments":{}}</tool_call>'
assert parse_tool_calls_from_text(xml, enabled_tool_names = {"web_search"})
def test_strip_leading_bare_json_call_gated_on_enabled_tool_names():
from core.inference.tool_call_parser import strip_leading_bare_json_call
alice = '{"name":"Alice","parameters":{"age":30}}'
# Not an enabled tool -> ordinary JSON answer, kept verbatim.
assert strip_leading_bare_json_call(alice, {"web_search"}) == alice
# Enabled tool -> a real call, stripped (trailing prose kept).
assert (
strip_leading_bare_json_call(
'{"name":"web_search","parameters":{"q":1}} hi', {"web_search"}
)
== "hi"
)
def test_function_xml_strip_keeps_literal_close_tag_in_param_value():
from core.inference.tool_call_parser import strip_tool_markup
# Strip uses the LAST </function> so a literal in a value survives; calls strip independently.
text = '<function=python><parameter=code>print("</function>")</parameter></function> done'
assert strip_tool_markup(text, final = True) == "done"
two = (
"a <function=f><parameter=x>1</parameter></function> mid "
"<function=g><parameter=y>2</parameter></function> end"
)
assert strip_tool_markup(two, final = True) == "a mid end"
def test_function_xml_strip_keeps_trailing_text_after_literal_open_tag():
from core.inference.tool_call_parser import parse_tool_calls_from_text, strip_tool_markup
# A literal <function=x> opener inside a value is data: the strip keeps " done".
text = '<function=python><parameter=code>print("<function=x>")</parameter></function> done'
assert parse_tool_calls_from_text(text)[0]["function"]["name"] == "python"
assert strip_tool_markup(text, final = True) == "done"
# Non-final (streaming) keeps an unclosed call buffered, does not eat prose early.
open_text = 'pre <function=python><parameter=code>print("<function=x>")'
assert strip_tool_markup(open_text, final = False) == open_text
def test_final_strip_removes_magistral_think_reasoning():
from core.inference.tool_call_parser import strip_tool_markup
# Magistral reasoning is [THINK]...[/THINK]; end-of-turn must drop it.
text = "[THINK]The user greeted me, I should say hi.[/THINK]Hello! How can I help?"
assert strip_tool_markup(text, final = True) == "Hello! How can I help?"
# A [TOOL_CALLS] living inside the reasoning goes with it.
with_call = '[THINK]Maybe I should search.[/THINK][TOOL_CALLS]search{"q":"x"}'
assert strip_tool_markup(with_call, final = True) == ""
def test_streaming_strip_keeps_magistral_think_buffered():
from core.inference.tool_call_parser import strip_tool_markup
# Mid-stream (final=False) leaves the reasoning block intact; only end-of-turn removes it.
text = "[THINK]still thinking"
assert strip_tool_markup(text, final = False) == text
def test_final_strip_leaves_non_magistral_bracket_text_untouched():
from core.inference.tool_call_parser import strip_tool_markup
# Only a LEADING [THINK] block is reasoning; unrelated bracketed prose stays.
text = "See [THINK about it] later"
assert strip_tool_markup(text, final = True) == "See [THINK about it] later"
def test_strip_leading_bare_json_call_ignores_nested_name():
from core.inference.tool_call_parser import strip_leading_bare_json_call
# A nested "name" must NOT gate the strip; the JSON answer is kept verbatim.
nested_trunc = '{"result":{"name":"web_search","age":'
nested_full = '{"result":{"name":"web_search","age":1}}'
assert strip_leading_bare_json_call(nested_trunc, {"web_search"}) == nested_trunc
assert strip_leading_bare_json_call(nested_full, {"web_search"}) == nested_full
# A real top-level call (even with a top-level array before the name) still strips.
assert (
strip_leading_bare_json_call(
'{"data":[1,2],"name":"web_search","parameters":{}}', {"web_search"}
)
== ""
)
def test_mistral_single_object_call_is_stripped_for_display():
from core.inference.tool_call_parser import (
_strip_mistral_closed_calls,
parse_tool_calls_from_text,
)
# The parser accepts single-object [TOOL_CALLS]{...}, so the strip must remove it too.
text = '[TOOL_CALLS]{"name":"web_search","arguments":{"filters":{"date":"2024"}}} tail'
assert [c["function"]["name"] for c in parse_tool_calls_from_text(text)] == ["web_search"]
assert _strip_mistral_closed_calls(text) == " tail"
# A literal [TOOL_CALLS] in prose (no following object) is left untouched.
assert _strip_mistral_closed_calls("See the [TOOL_CALLS] docs") == "See the [TOOL_CALLS] docs"
def test_tool_call_parser_declares_future_annotations_for_py39_import():
# PEP 604 X | None annotations need `from __future__ import annotations` on py3.9; guard it stays.
from pathlib import Path
src = (
Path(__file__).resolve().parent.parent / "core" / "inference" / "tool_call_parser.py"
).read_text()
assert "from __future__ import annotations" in src
def test_bare_json_function_alias_parses_and_strips_symmetrically():
# The "function" alias for the call name must parse and strip symmetrically.
from core.inference.tool_call_parser import (
parse_tool_calls_from_text,
strip_leading_bare_json_call,
_top_level_bare_json_name,
)
enabled = {"web_search"}
text = '{"function":"web_search","parameters":{"query":"cats"}}'
calls = parse_tool_calls_from_text(text, enabled_tool_names = enabled)
assert [c["function"]["name"] for c in calls] == ["web_search"]
assert strip_leading_bare_json_call(text, enabled) == ""
# "name" still takes precedence when both are present; nested aliases are data.
assert _top_level_bare_json_name('{"function":"foo","name":"web_search"}') == "web_search"
assert _top_level_bare_json_name('{"function":"web_search"}') == "web_search"
assert _top_level_bare_json_name('{"result":{"function":"web_search"}}') is None
# A non-enabled function-alias object is ordinary content and is preserved.
assert (
strip_leading_bare_json_call('{"function":"not_a_tool","parameters":{}}', enabled)
== '{"function":"not_a_tool","parameters":{}}'
)
class TestMistralOuterOverXmlLiteral:
"""Quoted tool XML inside a [TOOL_CALLS] call's arguments is data; the outer call executes. Reverse order keeps the XML."""
def test_mistral_v11_arg_quoting_function_xml(self):
text = (
'[TOOL_CALLS]web_search[ARGS]{"query":"literal '
'<function=evil><parameter=x>1</parameter></function>"}'
)
for strict in (True, False):
calls = parse_tool_calls_from_text(text, allow_incomplete = not strict)
assert [c["function"]["name"] for c in calls] == ["web_search"]
assert "<function=evil>" in json.loads(calls[0]["function"]["arguments"])["query"]
def test_mistral_array_arg_quoting_tool_call_json(self):
text = (
'[TOOL_CALLS][{"name":"web_search","arguments":{"query":'
'"see <tool_call>{\\"name\\":\\"evil\\"}</tool_call>"}}]'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_xml_outer_keeps_winning_over_mistral_literal(self):
text = (
'<tool_call>{"name":"web_search","arguments":'
'{"query":"docs say [TOOL_CALLS]evil[ARGS]{}"}}</tool_call>'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
class TestHealerSignalAlignment:
"""The healer buffers only promotable formats; Mistral/Llama text calls stream through."""
def test_heal_signals_subset_of_promotable_formats(self):
from core.inference.passthrough_healing import _HEAL_SIGNALS
assert set(_HEAL_SIGNALS) == {"<tool_call>", "<|tool_call>", "<function="}
def test_stream_healer_does_not_hold_mistral_text(self):
from core.inference.passthrough_healing import StreamToolCallHealer
healer = StreamToolCallHealer(
{"web_search"},
[{"type": "function", "function": {"name": "web_search", "parameters": {}}}],
)
events = list(healer.feed('[TOOL_CALLS]web_search[ARGS]{"query":"cats"}'))
text_out = "".join(v for k, v in events if k == "text")
assert "[TOOL_CALLS]" in text_out # streamed through, not buffered
assert not list(healer.finalize()) or all(k == "text" for k, _v in healer.finalize())
class TestPythonTagLiteralInsideMistralArgs:
"""A python_tag LITERAL inside a leading Mistral call's arguments is data; the outer call executes."""
def test_mistral_arg_quoting_python_tag_call(self):
text = (
'[TOOL_CALLS] [{"name": "web_search", "arguments": '
'{"query": "what is <|python_tag|>evil.call(x=1)"}}]'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
args = json.loads(calls[0]["function"]["arguments"])
assert args["query"] == "what is <|python_tag|>evil.call(x=1)"
class TestPythonTagOuterOverXmlLiteral:
"""A leading Llama-3 ``<|python_tag|>`` call owns the turn: tool XML/Mistral
markup quoted in a ``.call(...)`` string argument (or in trailing prose) is
data, so the outer call executes -- parity with the bare-JSON / Mistral /
attribute-form leading-ownership rules. XML before the tag keeps normal order."""
def test_call_arg_quoting_complete_function_xml(self):
# A closed <function=...> in a .call() code arg must not beat the leading python_tag call.
text = (
'<|python_tag|>python.call(code="<function=render_html>'
'<parameter=x>1</parameter></function>")'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["python"]
args = json.loads(calls[0]["function"]["arguments"])
assert args["code"] == "<function=render_html><parameter=x>1</parameter></function>"
def test_call_arg_quoting_bare_function_tag_in_query(self):
# A query mentioning <function=...> must search, not execute a phantom tool.
text = '<|python_tag|>web_search.call(query="how do I use <function=foo> in llama")'
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
args = json.loads(calls[0]["function"]["arguments"])
assert args["query"] == "how do I use <function=foo> in llama"
def test_call_arg_quoting_tool_call_json(self):
text = (
"<|python_tag|>save_file.call(content="
'"<tool_call>{\\"name\\": \\"delete\\", \\"arguments\\": {}}</tool_call>")'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["save_file"]
def test_json_form_code_arg_quoting_function_xml(self):
# JSON emission: a <function=...> in the code arg is data; the outer "python" call runs.
text = (
'<|python_tag|>{"name":"python","parameters":'
'{"code":"<function=terminal>ls</function>"}}'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["python"]
args = json.loads(calls[0]["function"]["arguments"])
assert args["code"] == "<function=terminal>ls</function>"
def test_call_arg_quoting_mistral_trigger(self):
text = '<|python_tag|>web_search.call(query="see [TOOL_CALLS]evil[ARGS]{}")'
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_leading_call_wins_over_trailing_xml(self):
# A leading python_tag call owns the turn even when a real XML literal follows.
text = (
'<|python_tag|>web_search.call(query="cats") '
"<function=evil><parameter=x>1</parameter></function>"
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_xml_before_python_tag_keeps_xml_order(self):
# A foreign signal BEFORE the tag keeps normal document order (XML wins).
text = (
"<function=web_search><parameter=q>x</parameter></function> "
'<|python_tag|>python.call(code="y")'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
class TestBareJsonOuterOverXmlLiteral:
"""Quoted tool XML inside a leading bare-JSON call is data; XML before the JSON keeps normal order."""
def test_bare_json_code_arg_quoting_function_xml(self):
text = (
'{"name": "python", "arguments": '
'{"code": "run() # <function=terminal>ls</function>"}}'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"python"})
assert [c["function"]["name"] for c in calls] == ["python"]
args = json.loads(calls[0]["function"]["arguments"])
assert args["code"] == "run() # <function=terminal>ls</function>"
def test_bare_json_outer_unrestricted_mode(self):
text = '{"name": "python", "parameters": {"code": "<function=terminal>ls</function>"}}'
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["python"]
def test_xml_before_json_keeps_xml_order(self):
text = (
"<function=web_search><parameter=query>cats</parameter></function>"
' {"name": "python", "arguments": {"code": "x"}}'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
class TestMagistralThinkRehearsal:
"""A call rehearsed inside [THINK]...[/THINK] is reasoning; the real call after wins, and parse agrees with strip."""
def test_function_xml_rehearsal_in_think_is_not_promoted(self):
text = (
'[THINK]I could emit <function=web_search>{"query":"x"}</function>'
' here[/THINK][TOOL_CALLS] [{"name":"terminal","arguments":{"cmd":"ls"}}]'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["terminal"]
def test_hermes_rehearsal_in_think_is_not_promoted(self):
text = (
'[THINK]maybe <tool_call>{"name":"web_search","arguments":'
'{"query":"x"}}</tool_call>[/THINK]'
'[TOOL_CALLS] [{"name":"terminal","arguments":{"cmd":"ls"}}]'
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["terminal"]
def test_unclosed_think_parses_nothing(self):
text = '[THINK]let me try <function=web_search>{"query":"x"}</function>'
assert parse_tool_calls_from_text(text) == []
class TestDisabledBareJsonLiteralNotPromoted:
"""A leading non-enabled-name object is content: nothing inside promotes, and a call after it still parses."""
def test_literal_inside_disabled_json_stays_data(self):
text = (
'{"name": "Alice", "note": "try <function=web_search>'
'<parameter=query>x</parameter></function>"}'
)
assert parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"}) == []
def test_python_tag_literal_inside_disabled_json_stays_data(self):
text = '{"name": "Alice", "note": "<|python_tag|>web_search.call(query=1)"}'
assert parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"}) == []
def test_real_call_after_disabled_json_still_parses(self):
text = (
'{"name": "Alice", "note": "<function=evil>x</function>"} '
'<tool_call>{"name": "web_search", "arguments": {"query": "cats"}}</tool_call>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
class TestMistralLiteralInsideLeadingJson:
"""A [TOOL_CALLS] literal quoted inside a leading JSON object must not be promoted over it."""
def test_outer_json_call_wins_over_mistral_literal(self):
text = '{"name": "python", "arguments": {"code": "[TOOL_CALLS]web_search{}"}}'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"python", "web_search"})
assert [c["function"]["name"] for c in calls] == ["python"]
args = json.loads(calls[0]["function"]["arguments"])
assert args["code"] == "[TOOL_CALLS]web_search{}"
def test_disabled_outer_json_keeps_mistral_literal_as_data(self):
text = '{"name": "Alice", "note": "[TOOL_CALLS]web_search{}"}'
assert parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"}) == []
class TestGemmaWrappedWhitespace:
"""Whitespace drift around ``call``/``:`` in wrapped Gemma calls must still parse (no fallback exists)."""
def test_space_after_call_colon_parses(self):
text = '<|tool_call>call: web_search{query:<|"|>cats<|"|>}<tool_call|>'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
assert json.loads(calls[0]["function"]["arguments"]) == {"query": "cats"}
def test_space_around_colon_parses(self):
text = '<|tool_call>call : web_search{query:<|"|>cats<|"|>}<tool_call|>'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_strict_mode_still_requires_the_closing_tag(self):
text = '<|tool_call>call: web_search{query:<|"|>cats<|"|>}'
assert parse_tool_calls_from_text(text, allow_incomplete = False) == []
class TestGemmaDottedArgumentKeys:
"""Dotted Gemma keys (namespaced schemas) must survive key-quoting or the call is lost."""
def test_dotted_key_parses(self):
text = '<|tool_call>call:web_search{user.name:<|"|>bob<|"|>, query:<|"|>x<|"|>}<tool_call|>'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
args = json.loads(calls[0]["function"]["arguments"])
assert args == {"user.name": "bob", "query": "x"}
class TestLeadingMistralCallOwnsTheTurn:
"""A leading Mistral call wins in document order over literal XML in trailing prose."""
def test_leading_mistral_wins_over_trailing_xml_literal(self):
text = (
'[TOOL_CALLS]web_search[ARGS]{"query":"cats"} '
"Note: <function=evil><parameter=x>1</parameter></function>"
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_xml_leading_keeps_normal_order(self):
text = (
"<function=web_search><parameter=query>x</parameter></function> "
"[TOOL_CALLS]evil[ARGS]{}"
)
calls = parse_tool_calls_from_text(text)
assert [c["function"]["name"] for c in calls] == ["web_search"]
class TestGemmaDottedKeyAfterBareValue:
def test_dotted_key_after_bare_value_is_a_boundary(self):
text = "<|tool_call>call:web_search{query:foo,user.name:bob}<tool_call|>"
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
args = json.loads(calls[0]["function"]["arguments"])
assert args == {"query": "foo", "user.name": "bob"}
class TestNamelessLeadingJsonAnswerIsData:
"""A nameless leading JSON answer is an envelope: quoted markup stays data, and a call after it parses."""
def test_xml_literal_inside_json_answer_stays_data(self):
text = '{"answer": "use <function=web_search><parameter=query>x</parameter></function>"}'
assert parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"}) == []
def test_real_call_after_json_answer_still_parses(self):
text = (
'{"answer": "docs"} <tool_call>{"name": "web_search", '
'"arguments": {"query": "cats"}}</tool_call>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
class TestLeadingBareJsonOwnsTurnOverTrailingXml:
"""Document order: a leading closed bare-JSON call owns the turn even when
tool XML appears AFTER it (inside-or-after, mirroring the Mistral rule)."""
def test_leading_call_wins_over_trailing_xml(self):
text = (
'{"name":"lookup","parameters":{"q":"first"}} Example: '
'<tool_call>{"name":"delete_all","arguments":{}}</tool_call>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"lookup", "delete_all"})
assert [c["function"]["name"] for c in calls] == ["lookup"], calls
assert json.loads(calls[0]["function"]["arguments"]) == {"q": "first"}
def test_chained_leading_calls_win_over_trailing_xml(self):
text = (
'{"name":"lookup","parameters":{"q":"first"}};'
'{"name":"lookup","parameters":{"q":"second"}} '
'<tool_call>{"name":"delete_all","arguments":{}}</tool_call>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"lookup", "delete_all"})
assert [c["function"]["name"] for c in calls] == ["lookup", "lookup"], calls
def test_non_call_leading_object_defers_to_trailing_real_call(self):
# Nameless/disabled-name objects decline: dropped, and the real trailing call still parses.
for lead in ('{"answer": 42}', '{"name":"draft","parameters":{}}'):
text = lead + ' <tool_call>{"name":"delete_all","arguments":{}}</tool_call>'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"delete_all"})
assert [c["function"]["name"] for c in calls] == ["delete_all"], (lead, calls)
def test_leading_xml_call_still_wins_over_trailing_bare_json(self):
text = (
'<tool_call>{"name":"delete_all","arguments":{}}</tool_call> '
'Example: {"name":"lookup","parameters":{"q":"x"}}'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"lookup", "delete_all"})
assert [c["function"]["name"] for c in calls] == ["delete_all"], calls
class TestProseCloseTagAfterClosedFunctionCall:
"""A literal </function> in prose after a closed call is data: the call
ends at its first close that is not parameter data, so arguments never
swallow the prose between the real close and the literal."""
def test_arguments_do_not_swallow_prose(self):
text = (
"<function=web_search><parameter=query>cats</parameter></function>"
" Done. The tag </function> closes a call."
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"], calls
assert json.loads(calls[0]["function"]["arguments"]) == {"query": "cats"}
def test_literal_close_inside_open_parameter_stays_data(self):
text = '<function=python><parameter=code>print("</function>")</parameter></function>'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"python"})
assert [c["function"]["name"] for c in calls] == ["python"], calls
assert json.loads(calls[0]["function"]["arguments"]) == {"code": 'print("</function>")'}
def test_attribute_form_arguments_do_not_swallow_prose(self):
# The attribute form shares the first-balanced-close rule: prose closes never fold in.
text = (
'<function name="web_search"><parameter name="query">cats</parameter></function>'
" Done. The tag </function> closes a call."
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert [c["function"]["name"] for c in calls] == ["web_search"], calls
assert json.loads(calls[0]["function"]["arguments"]) == {"query": "cats"}
def test_attribute_form_literal_close_in_open_parameter_stays_data(self):
text = '<function name="python"><parameter name="code">print("</function>")</parameter></function>'
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"python"})
assert json.loads(calls[0]["function"]["arguments"]) == {"code": 'print("</function>")'}
def test_attribute_form_two_calls_both_parse(self):
text = (
'<function name="web_search"><parameter name="query">cats</parameter></function>'
'<function name="python"><parameter name="code">x=1</parameter></function>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search", "python"})
assert [c["function"]["name"] for c in calls] == ["web_search", "python"], calls
class TestEnabledNameJsonAnswerIsContent:
"""A JSON answer whose top-level name matches an enabled tool but has no
call shape is content: the parser rejects it, so the strip and the drain
gate must keep it visible too."""
def test_answer_survives_strip(self):
from core.inference.tool_call_parser import strip_leading_bare_json_call
ans = '{"name":"web_search","result":"no call"}'
assert strip_leading_bare_json_call(ans, {"web_search"}) == ans
def test_answer_does_not_route_to_draining(self):
from core.inference.safetensors_agentic import _looks_like_enabled_bare_json
assert not _looks_like_enabled_bare_json(
'{"name":"web_search","result":"no call"}', {"web_search"}
)
def test_real_call_still_strips_and_drains(self):
from core.inference.safetensors_agentic import _looks_like_enabled_bare_json
from core.inference.tool_call_parser import strip_leading_bare_json_call
real = '{"name":"web_search","parameters":{"q":"x"}}'
assert strip_leading_bare_json_call(real, {"web_search"}) == ""
assert _looks_like_enabled_bare_json(real, {"web_search"})
def test_arguments_string_call_still_strips(self):
from core.inference.tool_call_parser import strip_leading_bare_json_call
call = '{"name":"web_search","arguments":"{\\"q\\":\\"x\\"}"} tail'
assert strip_leading_bare_json_call(call, {"web_search"}) == "tail"
class TestAttributeFormLeadingContainment:
"""A leading attribute-form call owns the turn: markup quoted inside its
parameter is data, not a call for the shared XML parser to promote."""
def test_quoted_tool_call_inside_param_stays_data(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
'<function name="web_search"><param name="query">find '
'<tool_call>{"name":"delete","arguments":{}}</tool_call></param></function>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search", "delete"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
assert "delete" in json.loads(calls[0]["function"]["arguments"])["query"]
def test_real_xml_call_before_attribute_form_keeps_order(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
'<tool_call>{"name":"delete","arguments":{}}</tool_call> Example: '
'<function name="web_search"><param name="q">x</param></function>'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search", "delete"})
assert calls[0]["function"]["name"] == "delete"
class TestParameterKeepsMultipleLiteralCloses:
"""A parameter that provably closes with its own tag keeps every literal
function close inside it as data (regression: the first literal close was
treated as ending the parameter, truncating the value)."""
def test_two_literal_closes_in_one_parameter(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
'<function name="web_search"><param name="query">'
"a </function> b </function> c </param></function>"
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search"})
assert json.loads(calls[0]["function"]["arguments"]) == {
"query": "a </function> b </function> c"
}
def test_strip_removes_the_whole_call(self):
from core.inference.tool_call_parser import strip_tool_markup
text = (
'<function name="web_search"><param name="query">'
"a </function> b </function> c </param></function> after"
)
assert strip_tool_markup(text, final = True) == "after"
def test_unclosed_parameter_still_heals_at_function_close(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
calls = parse_tool_calls_from_text(
"<function=web_search><parameter=query>val</function>",
enabled_tool_names = {"web_search"},
)
assert json.loads(calls[0]["function"]["arguments"]) == {"query": "val"}
class TestMistralPreambleOwnership:
"""A visible preface before the first Mistral call must not hand the turn
to a later XML literal: the Mistral call is first in document order."""
def test_v11_named_form_after_preface(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
'pref [TOOL_CALLS]web_search[ARGS]{"query":"cats"} Note '
"<function=evil><parameter=x>1</parameter></function>"
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search", "evil"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_array_form_after_preface(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
'pref [TOOL_CALLS][{"name":"web_search","arguments":{"query":"cats"}}] Note '
"<function=evil><parameter=x>1</parameter></function>"
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search", "evil"})
assert [c["function"]["name"] for c in calls] == ["web_search"]
def test_xml_call_before_trigger_keeps_order(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
"<function=evil><parameter=x>1</parameter></function> then "
'[TOOL_CALLS][{"name":"web_search","arguments":{}}]'
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"web_search", "evil"})
assert calls[0]["function"]["name"] == "evil"
def test_prose_mention_without_call_shape_keeps_order(self):
from core.inference.tool_call_parser import parse_tool_calls_from_text
text = (
"See [TOOL_CALLS] docs for details. "
"<function=evil><parameter=x>1</parameter></function>"
)
calls = parse_tool_calls_from_text(text, enabled_tool_names = {"evil"})
assert [c["function"]["name"] for c in calls] == ["evil"]
class TestBareJsonStripRequiresTopLevelName:
"""The strip's shape gate requires the parser's TOP-LEVEL name in every
mode: a JSON answer with only a nested name is content, even name-agnostic."""
def test_nested_name_answer_survives_name_agnostic_strip(self):
from core.inference.tool_call_parser import strip_leading_bare_json_call
ans = '{"parameters":{},"result":{"name":"web_search"}}'
assert strip_leading_bare_json_call(ans) == ans
assert strip_leading_bare_json_call(ans, {"web_search"}) == ans
def test_real_call_still_strips_name_agnostic(self):
from core.inference.tool_call_parser import strip_leading_bare_json_call
assert strip_leading_bare_json_call('{"name":"web_search","parameters":{"q":"x"}}') == ""

View file

@ -24,15 +24,34 @@ import re as _re
_src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text()
_m = _re.search(r"_TOOL_XML_RE = _re\.compile\((.*?)\n\)", _src, _re.DOTALL)
assert _m, "could not extract _TOOL_XML_RE source"
_ns = {"_re": _re}
# Provide both helpers so the extracted _strip_tool_xml_for_display resolves.
from core.inference.tool_call_parser import _strip_function_xml_calls, _strip_mistral_closed_calls
_ns = {
"_re": _re,
"_strip_mistral_closed_calls": _strip_mistral_closed_calls,
"_strip_function_xml_calls": _strip_function_xml_calls,
}
exec(f"_TOOL_XML_RE = _re.compile({_m.group(1)})", _ns)
_TOOL_XML_RE = _ns["_TOOL_XML_RE"]
_xml_helper = _re.search(
r"def _strip_tool_xml\(text: str\) -> str:\n(?: .+\n)+",
_src,
)
assert _xml_helper, "could not extract _strip_tool_xml source"
assert "_strip_mistral_closed_calls" in _xml_helper.group(
0
), "extracted _strip_tool_xml no longer runs the Mistral balanced strip"
exec(_xml_helper.group(0), _ns)
_helper = _re.search(
r"def _strip_tool_xml_for_display\(text: str, \*, auto_heal_tool_calls: bool\) -> str:\n"
r"(?: .+\n)+",
_src,
)
assert _helper, "could not extract _strip_tool_xml_for_display source"
assert "_strip_tool_xml(" in _helper.group(0), "display helper no longer delegates"
exec(_helper.group(0), _ns)
_strip_tool_xml_for_display = _ns["_strip_tool_xml_for_display"]
@ -46,6 +65,15 @@ def test_route_display_strip_respects_disabled_auto_heal_contract():
assert "<tool_call>" not in _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
def test_route_display_strip_removes_mistral_tool_calls_with_nested_json():
# [TOOL_CALLS] with nested JSON needs the Mistral balanced-brace strip, not the regex.
text = 'ok [TOOL_CALLS]web_search{"filters":{"date":"2024"},"query":"cats"} tail'
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = False) == text
out = _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
assert "[TOOL_CALLS]" not in out and "web_search" not in out, out
assert out == "ok tail"
def test_strips_well_formed_tool_call():
text = (
"Let me search.\n"
@ -73,6 +101,25 @@ def test_strips_function_only_well_formed():
assert "Done." in cleaned
def test_strips_function_attribute_form():
# Attribute form <function name="..."> must strip from the route too; dotted/hyphenated names included.
text = (
'Sure.\n<function name="get_weather">\n'
"<parameter=city>\nSydney\n</parameter>\n</function>\nDone."
)
cleaned = _TOOL_XML_RE.sub("", text)
assert "<function name=" not in cleaned
assert "</function>" not in cleaned
assert "Sure." in cleaned and "Done." in cleaned
dotted = 'A <function name="srv.list-issues">x</function> B'
assert _TOOL_XML_RE.sub("", dotted) == "A B"
# Auto-Heal-disabled display contract still preserves literal markup.
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = False) == text
assert "<function name=" not in _strip_tool_xml_for_display(text, auto_heal_tool_calls = True)
# ── Orphan openings ───────────────────────────────────────────────
@ -281,3 +328,109 @@ def test_no_catastrophic_backtracking_on_orphan_opening_spam():
elapsed = time.perf_counter() - t0
assert elapsed < 0.1, f"regex took {elapsed*1000:.0f}ms on 1000x orphan opens"
assert "<tool_call>" not in cleaned
# Llama-3 <|python_tag|> arm bounds on REAL sentinels only
def test_python_tag_strip_consumes_literal_sentinel_in_arg():
# A literal <|...|> token inside the arg must not end the strip early.
text = '<|python_tag|>{"name": "send", "parameters": {"text": "use <|cite|> here"}}'
cleaned = _TOOL_XML_RE.sub("", text)
assert cleaned == "", f"python_tag call leaked at literal sentinel: {cleaned!r}"
@pytest.mark.parametrize(
"sentinel",
[
"<|eot_id|>",
"<|eom_id|>",
"<|start_header_id|>",
"<|end_header_id|>",
],
)
def test_python_tag_strip_stops_at_real_sentinel(sentinel):
# A real control sentinel bounds the strip so following text survives.
text = f'<|python_tag|>{{"name": "x", "parameters": {{}}}}{sentinel}visible answer'
cleaned = _TOOL_XML_RE.sub("", text)
assert (
cleaned == f"{sentinel}visible answer"
), f"strip did not stop at real sentinel {sentinel!r}: {cleaned!r}"
def test_python_tag_strip_restarts_on_second_python_tag():
# A second <|python_tag|> opens a new region; both are stripped.
text = '<|python_tag|>{"name": "a"}<|python_tag|>{"name": "b"}'
cleaned = _TOOL_XML_RE.sub("", text)
assert cleaned == "", f"second python_tag region leaked: {cleaned!r}"
def test_route_strip_removes_param_alias_close_tag():
# Orphan </param> (attribute-form alias of </parameter>) must strip too.
assert _strip_tool_xml_for_display("answer </param>", auto_heal_tool_calls = True) == "answer "
assert (
_strip_tool_xml_for_display("answer </parameter>", auto_heal_tool_calls = True) == "answer "
)
def test_route_strip_uses_guarded_function_scan_for_literal_nested_markup():
# A literal <function=...></function> in a value must not truncate the strip.
text = "<function=python><parameter=code><function=evil></function></parameter></function> tail"
assert _strip_tool_xml_for_display(text, auto_heal_tool_calls = True).strip() == "tail"
def test_strip_keeps_prose_after_closed_function_call_with_literal_close():
# The call ends at its first non-data close; prose after (even a literal </function>) survives.
from core.inference.tool_call_parser import strip_tool_markup
text = (
"<function=web_search><parameter=query>cats</parameter></function>"
" Done. The tag </function> closes a call."
)
assert strip_tool_markup(text, final = True) == "Done. The tag </function> closes a call."
def test_final_strip_keeps_prose_mentioning_bare_markers():
# A false-alarm marker in prose must not drop trailing text; only call-start-shaped text drops.
from core.inference.tool_call_parser import strip_tool_markup
for text in (
"See [TOOL_CALLS] docs for details. More prose after.",
"<|python_tag|> is the Llama marker. Explanation continues.",
"The <|tool_call> opener wraps Gemma calls.",
):
assert strip_tool_markup(text, final = True) == text
# A bare marker at end-of-text is a fragment and still drops.
assert strip_tool_markup("Answer text [TOOL_CALLS]", final = True) == "Answer text"
def test_final_strip_still_drops_truncated_marker_calls():
from core.inference.tool_call_parser import strip_tool_markup
for text in (
'[TOOL_CALLS][{"name":"web_search","argu',
'[TOOL_CALLS]web_search[ARGS]{"q":"x',
'<|python_tag|>{"name":"web_search","par',
'<|python_tag|>foo.call(items=["a',
"<|tool_call>call:web_search{query:tru",
):
assert strip_tool_markup(text, final = True) == ""
def test_chained_bare_json_strip_consumes_all_calls():
# Next-turn history must not keep an executed call, else it replays.
from core.inference.tool_call_parser import strip_leading_bare_json_call
enabled = {"web_search", "python"}
chained = (
'{"name":"web_search","parameters":{"q":"first"}};'
'{"name":"python","parameters":{"code":"x"}}'
)
assert strip_leading_bare_json_call(chained, enabled_tool_names = enabled) == ""
assert (
strip_leading_bare_json_call(chained + " trailing prose", enabled_tool_names = enabled)
== "trailing prose"
)
# The chain stops at a non-call answer object, which stays visible.
call_then_answer = (
'{"name":"web_search","parameters":{"q":"x"}};{"name":"web_search","result":"data"}'
)
assert (
strip_leading_bare_json_call(call_then_answer, enabled_tool_names = enabled)
== '{"name":"web_search","result":"data"}'
)