Repository navigation
studio: tool calling for DeepSeek (R1/V3/V3.1), GLM 4.x, Kimi K2 on safetensors + MLX - #5624
Conversation
…LX (#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.
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.
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.
Adds three more emission-family parsers to tool_call_parser.py so the
shared safetensors / MLX / GGUF agentic loop covers the major open-
weight reasoning families. Patterns ported from llama.cpp
(common/chat-parser.cpp legacy pre-PEG branch), vLLM
(tool_parsers/deepseekv3*, glm4_moe, kimi_k2), and SGLang
(function_call/deepseekv31_detector, glm4_moe_detector, kimik2_detector).
All three references are MIT (llama.cpp) or Apache-2.0 (vLLM, SGLang).
Formats covered:
DeepSeek R1 <|tool▁calls▁begin|><|tool▁call▁begin|>function
<|tool▁sep|>NAME\n```json\n{...}\n```<|tool▁call▁end|>
<|tool▁calls▁end|>
-- args wrapped in a Markdown json fence, ``function``
literal prefix per llama.cpp common_chat_parse_
deepseek_r1 (chat-parser.cpp:801-820)
DeepSeek V3/V3.1
<|tool▁calls▁begin|><|tool▁call▁begin|>NAME
<|tool▁sep|>{json}<|tool▁call▁end|><|tool▁calls▁end|>
-- bare JSON, no code fence, no ``function`` prefix
per llama.cpp common_chat_parse_deepseek_v3_1
(chat-parser.cpp:822-879)
GLM 4.5/4.6/4.7 <tool_call>NAME\n<arg_key>k1</arg_key>
\n<arg_value>v1</arg_value>...</tool_call>
-- strings raw, non-strings JSON-encoded per
chat_template.jinja; multi-call is back-to-back
blocks. Per llama.cpp common_chat_parse_glm_4_5
(chat-parser.cpp:1040-1052)
Kimi K2 <|tool_calls_section_begin|><|tool_call_begin|>
functions.NAME:IDX<|tool_call_argument_begin|>{json}
<|tool_call_end|><|tool_calls_section_end|>
-- bare name recovered by stripping ``functions.``
prefix and ``:IDX`` suffix; full id preserved as
tool_calls[i].id so the roundtrip replays verbatim.
Per llama.cpp common_chat_parse_kimi_k2
(chat-parser.cpp:896-913)
Marker collisions
GLM uses the same ``<tool_call>`` opener as Qwen but with a bare
function name + ``<arg_key>`` body (Qwen has ``\s*{`` after the tag).
The dispatch keeps Qwen first; Qwen's _TC_JSON_START_RE returns no
matches on a GLM emission, so the fall-through to _parse_glm_tool_
calls handles it correctly. Existing Qwen tests confirm zero
regression.
Streaming buffer
TOOL_XML_SIGNALS extended from 5 markers to 12 so the BUFFERING state
machine wakes on every new family's section opener. Added the
DeepSeek alternative markers (ASCII underscores, short ``<|tool▁calls|>``
form) because real checkpoints emit those variants.
Strip patterns
_TOOL_CLOSED_PATS adds DeepSeek envelope (``<|tool▁calls▁begin|>...
<|tool▁calls▁end|>``) and Kimi section (``<|tool_calls_section_begin|>
...<|tool_calls_section_end|>``). _TOOL_ALL_PATS adds the same plus
the unclosed-tail variants so a truncated stream does not leak
markup.
Route gate
_detect_safetensors_features._PARSER_MARKERS grows to include
DeepSeek and Kimi markers plus ``<arg_key>`` (the unique GLM signal).
_TOOL_XML_RE (the route-layer markup-strip regex) gets DeepSeek and
Kimi closed-pair patterns. _TOOL_TEMPLATE_MARKERS in llama_cpp.py
adds ``message['role'] == 'tool'``, ``message['tool_calls']``, and
``tool_calls is defined`` so the classifier recognises DeepSeek's
subscripted-access template style (it has no top-level
``{% if tools %}`` block).
Tests (39 new):
TestParserDeepSeek (7) -- R1 fence, short-form opener, V3.1 bare,
multi-call, with-reasoning, strip,
signal-wakes-streaming
TestParserGLM (6) -- single, mixed types, multi-call,
unclosed-heal, no-Qwen-regression, strip
TestParserKimi (6) -- single, multi-call, dotted-name, unclosed,
strip, signal-wakes-streaming
TestParserCrossFormatRouting (2) -- dispatch routing, signal coverage
TestLoopBasic loop integration (3) -- DeepSeek / GLM / Kimi end-to-end
Capability advertise (3) -- DeepSeek / GLM / Kimi templates flip
supports_tools=True
All 398 targeted tests pass locally (115 safetensors + 27 capability
+ rest of tool / inference / sandbox / model-config suites). Builds
on PR #5620 (parser + healing parity for Llama-3 / Mistral / Gemma 4);
will rebase cleanly onto main once #5620 lands. PR opened as draft -
do not merge until validated against real models for each family.
Sources
- llama.cpp common/chat-parser.cpp lines 801-913, 1040-1052 (MIT)
- vLLM vllm/tool_parsers/deepseekv31_tool_parser.py (Apache-2.0)
- vLLM vllm/tool_parsers/glm4_moe_tool_parser.py (Apache-2.0)
- vLLM vllm/tool_parsers/kimi_k2_tool_parser.py (Apache-2.0)
- SGLang python/sglang/srt/function_call/{deepseekv31,glm4_moe,kimik2}_
detector.py (Apache-2.0)
- Live chat templates: deepseek-ai/DeepSeek-V3.1, zai-org/GLM-4.6,
moonshotai/Kimi-K2-Instruct, unsloth/DeepSeek-V3-0324,
unsloth/GLM-4.5-Air, unsloth/Kimi-K2-Instruct
Mirrors PR unslothai#5624: three more emission-family parsers for the shared tool_call_parser plus CI updates that exercise the new fixtures cross-OS. - DeepSeek R1 / V3 / V3.1: <|tool▁calls▁begin|>...<|tool▁sep|>... - GLM 4.5 / 4.6 / 4.7: <tool_call>NAME\n<arg_key>K</arg_key>\n <arg_value>V</arg_value>...</tool_call> - Kimi K2 / Moonshot: <|tool_calls_section_begin|>...<|tool_call_ argument_begin|>... Ported from llama.cpp common/chat-parser.cpp lines 801-913, 1040-1052 (MIT), vLLM tool_parsers/ {deepseekv31, glm4_moe, kimi_k2}_tool_parser.py (Apache-2.0), and SGLang function_call/ {deepseekv31, glm4_moe, kimik2}_detector.py (Apache-2.0). CI multi-format probe extended from 9 to 13 fixtures so all four new families run on ubuntu / macos-14 / windows.
There was a problem hiding this comment.
Code Review
This pull request adds tool call parsing support for DeepSeek (R1, V3, V3.1), GLM (4.5, 4.6, 4.7), and Kimi K2 models. The implementation includes new regex patterns, specialized parsing functions, and updates to the inference routing logic and test suites. Reviewers suggested making the DeepSeek R1 parser more robust by handling leading whitespace before JSON blocks and recommended moving the ast import to the top level to avoid performance overhead during streaming inference.
| json_start = m.end() | ||
| # Walk a balanced ``{`` even if the trailing fence is truncated. | ||
| if json_start >= len(body) or body[json_start] != "{": |
There was a problem hiding this comment.
The DeepSeek R1 path should skip any leading whitespace between the Markdown code fence and the start of the JSON object, similar to the V3 and Kimi parsers. This makes the parser more robust against variations in model output formatting.
| json_start = m.end() | |
| # Walk a balanced ``{`` even if the trailing fence is truncated. | |
| if json_start >= len(body) or body[json_start] != "{": | |
| json_start = m.end() | |
| # Skip any whitespace before the JSON. | |
| while json_start < len(body) and body[json_start] in " \t\n\r": | |
| json_start += 1 | |
| # Walk a balanced { even if the trailing fence is truncated. | |
| if json_start >= len(body) or body[json_start] != "{": |
| except (json.JSONDecodeError, ValueError): | ||
| pass | ||
| try: | ||
| import ast as _ast |
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).
Four fixes addressing review of the parent commit: 1. GLM <arg_value> coercion: tighten the json.loads -> ast.literal_eval -> raw cascade to only deserialize when the body unambiguously looks like a JSON literal (object, array, JSON-encoded string, true/false/null, or numeric). Strings like ``True`` / ``None`` (Python literals, not JSON) and arbitrary prose now stay raw. The bare-numeric / bare-boolean ambiguity with string args remains an inherent limitation of the template without schema access -- documented in the new comment. Drops the ast import entirely (closes Gemini's :1036 suggestion). 2. Kimi K2 bare-counter ids (e.g. ``<|tool_call_begin|>3``) are now dropped rather than surfaced as a tool literally named "3". Matches vLLM behaviour; SGLang's schema-infer fallback is out of scope at the parse site. Real Kimi K2 emissions use ``functions.NAME:IDX`` so this is the exception path. 3. Restore the elaborate ``<|python_tag|>(?:[^<]|<(?!\|))*`` clause in routes.inference._TOOL_XML_RE -- the simpler ``[^\n<]*`` form regressed PR #5620's multi-line / literal-``<`` python_tag fix. Restore ``TestRoutesPythonTagStrip`` (8 tests) adapted to call ``_TOOL_XML_RE.sub`` directly since the ``_strip_tool_xml`` helper was inlined this PR. 4. Add the spaced and backslash-escaped DeepSeek opener variants (``<|tool calls begin|>``, ``<|tool\_calls\_begin|>``) to ``TOOL_XML_SIGNALS`` for streaming-gate parity with ``_DEEPSEEK_BEGIN_RE``. Also updates the llama.cpp / vLLM citations in the parser docstrings: ``common/chat-parser.cpp`` was split into ``common/chat.cpp`` + ``common/chat-peg-parser.cpp`` by llama.cpp PR #18675, and vLLM moved the tool parsers from ``vllm/entrypoints/openai/tool_parsers/`` to ``vllm/tool_parsers/``. Pin to pre-refactor commit ``51fa458a92d6`` where the cited line numbers still resolve. New regression tests in ``test_pr5624_regressions.py`` cover the GLM coercion heuristic shapes, GLM literal-``<`` in arg_value, Kimi K2 dotted name, Kimi K2 bare-counter drop, DeepSeek V3.1 truncated mid-stream, and routes-layer strip across all three new families. Tests: pytest studio/backend/tests/test_safetensors_tool_loop.py studio/backend/tests/test_safetensors_capability_advertise.py studio/backend/tests/test_pr5624_regressions.py -q -> 170 passed in 1.91s
Conflict in studio/backend/routes/inference.py: combine #5620's multi-format strip (Llama-3 <|python_tag|>, Gemma 4 <|tool_call>... <tool_call|>, Mistral [TOOL_CALLS] via parser helper) with main's speculative-buffer leak fixes (orphan open to EOF, bare orphan close, tail-only </parameter> anchored to \Z so mid-text <parameter> in user code samples survives). pytest studio/backend/tests/test_safetensors_tool_loop.py \ studio/backend/tests/test_safetensors_capability_advertise.py -q -> 118 passed.
…k-glm-kimi Resolves three conflicts against the updated 5620 base (which itself merged main after main moved on with PRs #5735 / #5775 / #5803 etc. touching the same routes/inference.py and tool_call_parser.py surface): * studio/backend/core/inference/tool_call_parser.py ``_TOOL_CLOSED_PATS``: kept 5624's full set (Mistral pre-v11 array, Mistral v11+ name{json}, DeepSeek envelope, Kimi section) on top of the 3-pattern base. New 5620 base reverted to the 3 base patterns because main never carried the tool-format extensions. * studio/backend/routes/inference.py Merged the two regex bodies: kept 5624's elaborate python_tag ``(?:[^<]|<(?!\|))*`` clause and the new-family closed-pair patterns (DeepSeek envelope, Kimi section). DROPPED the inlined Mistral patterns in favour of the base's ``_strip_tool_xml`` helper which delegates Mistral handling to the parser module's ``_strip_mistral_closed_calls`` -- the non-greedy ``\{.*?\}`` form truncates at the first ``}`` of a nested JSON arg, so balanced brace/bracket scanning is correct here. Also kept the base's orphan-close and tail-only ``</parameter>`` patterns from the speculative-buffer split boundary work. Net: 9 call sites continue to use ``_strip_tool_xml(...)`` (Mistral-safe). * studio/backend/tests/test_safetensors_tool_loop.py ``TestRoutesPythonTagStrip``: kept the base's wording for the section header (the two were near-identical) and switched the helper ``_strip`` back to ``_strip_tool_xml`` since the helper is restored. Also retargeted ``test_pr5624_regressions.py``'s routes-layer strip tests to ``_strip_tool_xml`` for consistency with the restored helper. Tests: pytest studio/backend/tests/test_safetensors_tool_loop.py studio/backend/tests/test_safetensors_capability_advertise.py studio/backend/tests/test_pr5624_regressions.py -q -> 170 passed in 1.93s pytest studio/backend/tests/ -q -k 'not gpu and not llama_cpp_integration' -> 2034 passed, 15 failed (pre-existing on the 5620 base; same set as before the merge: test_training_worker_flash_attn, test_desktop_auth, test_studio_api integration shims).
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.
…k-glm-kimi
Second merge pass to absorb the base's "tighten verbose comments in
tool-call parser sections" commit plus pre-commit auto-fixes that
landed on both sides since the previous merge.
Conflicts:
* studio/backend/core/inference/tool_call_parser.py
- Regex prelude: kept 5624's per-family blocks (DeepSeek, GLM,
Kimi) and trimmed comments to the base's tightened style for
Gemma 4. New families need the explicit constants regardless of
comment density.
- parse_tool_calls_from_text: dropped the base's compact for-loop
over the 5 original parsers (it would have double-run Qwen and
function_xml ahead of the explicit chain). Kept 5624's interleaved
dispatch (DeepSeek/Kimi first, Qwen, GLM-after-Qwen,
function_xml, python_tag, Mistral, Gemma, bare-JSON fallback),
with tightened single-line per-family comments.
* studio/backend/routes/inference.py
- _PARSER_MARKERS comment: collapsed to base's tighter style while
keeping the per-family marker list so the next reader knows what
triggers the pill.
- _TOOL_XML_RE comment block: same compression, but the four
speculative-buffer leak shapes and the Mistral balanced-brace
delegation note are preserved.
- _TOOL_XML_RE pattern list: kept all six 5624 alternations
(python_tag elaborate, DeepSeek envelope, Kimi section, plus the
base's orphan-close and tail-only </parameter>) in the order that
matches the comment block.
Tests:
pytest studio/backend/tests/test_safetensors_tool_loop.py
studio/backend/tests/test_safetensors_capability_advertise.py
studio/backend/tests/test_pr5624_regressions.py -q
-> 170 passed in 2.22s
pytest studio/backend/tests/ -q -k 'not gpu and not llama_cpp_integration'
-> 2034 passed, 15 failed (same pre-existing CI gaps on the base:
test_training_worker_flash_attn, test_desktop_auth,
test_studio_api integration shims).
Two fixes surfaced by triple-confirm verification against the live
HF chat templates and upstream llama.cpp / vLLM / SGLang parsers.
1. GLM 4.7 silent drop
``zai-org/GLM-4.7/chat_template.jinja`` line 65 uses
``{{- '<tool_call>' + tc.name -}}`` which Jinja strips trailing
whitespace from, so the first ``<arg_key>`` follows the function
name with NO ``\n`` between them. Real emissions look like
``<tool_call>get_weather<arg_key>city</arg_key><arg_value>London
</arg_value></tool_call>``. The previous ``_GLM_TC_OPEN_RE`` ended
the name with ``\n`` so GLM-4.7 calls were silently dropped
(parser returned ``[]``).
Fix: relax the name terminator to a lookahead that accepts EITHER
``\n`` OR the next ``<arg_key>``:
_GLM_TC_OPEN_RE = re.compile(
r"<tool_call>\s*([^\n<{][^\n<]*?)\s*(?=\n|<arg_key>)"
)
The first-char restriction ``[^\n<{]`` still excludes Qwen's
``<tool_call>{json}`` form so the Qwen-vs-GLM dispatch remains
mutually exclusive.
2. Kimi multi-section parity with vLLM / SGLang
``vllm/tool_parsers/kimi_k2_tool_parser.py`` and SGLang's
``kimik2_detector.py`` both use ``re.findall`` and so collect every
``<|tool_calls_section_begin|>...<|tool_calls_section_end|>`` block
in a single stream. The previous implementation stopped at the
first ``<|tool_calls_section_end|>``. Kimi K2 doesn't emit
multi-section in practice, but parity is cheap.
Fix: wrap the existing per-call body parser in an outer loop that
advances past each ``<|tool_calls_section_end|>`` and continues to
the next ``<|tool_calls_section_begin|>``. Body parsing extracted
to ``_parse_kimi_section_body`` for clarity. Truncated final
section is still surfaced via the existing in-body balanced-brace
walk.
Verified independently against the live HF templates:
* GLM-4.7 emission constructed from the live template parses to the
expected ``{name, arguments}`` shape.
* GLM-4.5 / 4.6 newline shape continues to parse (the lookahead also
matches ``\n``).
* Qwen ``<tool_call>{json}`` still dispatches to the Qwen path -- the
first-char restriction stops the GLM regex from biting JSON bodies.
* Kimi two-section stream surfaces both calls in order with full ids
preserved.
* Bare-counter Kimi ids still drop.
Tests added in ``test_pr5624_regressions.py``:
* ``test_glm_4_7_no_newlines_between_name_and_arg_key``
* ``test_glm_4_7_no_newlines_multi_call``
* ``test_glm_4_7_does_not_break_qwen_path``
* ``test_kimi_two_sections_in_one_stream_both_parse``
pytest studio/backend/tests/test_safetensors_tool_loop.py
studio/backend/tests/test_safetensors_capability_advertise.py
studio/backend/tests/test_pr5624_regressions.py -q
-> 174 passed in 1.93s
pytest studio/backend/tests/ -q -k 'not gpu and not llama_cpp_integration'
-> 2038 passed, 15 failed (pre-existing CI gaps).
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.
Pure comment / docstring tightening on top of the GLM 4.7 + Kimi
multi-section fixes. No behavioural change.
* Drop multi-paragraph prelude and post-refactor citation chatter in
the DeepSeek, GLM and Kimi parser docstrings; keep the shape and
upstream-commit pin.
* Collapse ``parse_tool_calls_from_text``'s 9 per-family blocks into
a single ordered loop with one combined comment.
* Tighten the GLM coercion, Kimi bare-counter and ``_TOOL_XML_RE``
comments to one or two lines each.
* Same trim pass on ``_PARSER_MARKERS`` and the regression-test
docstrings.
Tests:
pytest studio/backend/tests/test_safetensors_tool_loop.py
studio/backend/tests/test_safetensors_capability_advertise.py
studio/backend/tests/test_pr5624_regressions.py -q
-> 174 passed in 2.00s
Two conflicts, both in the tool-call markup-strip plumbing:
* `studio/backend/core/inference/tool_call_parser.py` -- main widened
`<function=NAME>` and `<parameter=NAME>` from `\w+` to `[\w-]+` so
MCP tool ids with hyphens (mcp__srv__list-issues, `repo-name`,
`issue-number`) parse the same as the built-ins. PR-5620 had
broadened the same patterns to `[\w\.\-]+` (also handles dotted
module names) and added the python_tag / Mistral / Gemma 4 strip
families plus the `TOOL_XML_SIGNALS` constant. Resolved by keeping
PR-5620's full pattern set; `[\w\.\-]+` already accepts the hyphens
main was widening to, so no MCP coverage is lost.
* `studio/backend/routes/inference.py` -- `_TOOL_XML_RE` regex on
the route-level scrub path. Same hyphen widening on main vs.
PR-5620's union of (closed pair / orphan open / Gemma 4 /
python_tag / `</parameter>` tail-only). Resolved by unioning all
five patterns and applying main's `[\w-]+` on the `function=` name
char class so hyphenated MCP names get stripped on the route too.
pytest studio/backend/tests/test_safetensors_tool_loop.py
studio/backend/tests/test_safetensors_capability_advertise.py -q
-> 125 passed.
Adversarial input ``<|tool▁calls▁begin|><|tool▁call▁begin|>fn<|tool▁sep|>``
followed by a long body that does NOT contain a closing brace caused
the V3 path's ``([^\n<]+?)<|tool▁sep|>`` regex to backtrack
quadratically: at each position the lazy quantifier extends one char
at a time looking for a sep that isn't there, taking ~19s on 50k
chars.
Replace the regex search with ``str.find`` on the sep marker plus a
left-walk to recover the name. ``str.find`` is O(N); the walk stops
on ``\n`` (turn boundary), ``<`` (start of a tag), or ``>`` (end of
an optional ``<|tool▁call▁begin|>`` prefix). Same observable
behaviour as the regex on every canonical input.
Tests:
test_deepseek_v3_1_huge_truncated_body_is_linear (new) -- 50k chars
must parse in < 1s.
pytest studio/backend/tests/test_safetensors_tool_loop.py
studio/backend/tests/test_safetensors_capability_advertise.py
studio/backend/tests/test_pr5624_regressions.py -q
-> 175 passed in 1.97s
pytest studio/backend/tests/ -q -k 'not gpu and not llama_cpp_integration'
-> 2038 passed, 15 pre-existing failures unchanged.
…all> `_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.
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 615b860. Adds the same 4 regression tests under TestParserMultiFormat. Existing test suite stays green: 127 -> 131 passing.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: adff9073ad
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| re.DOTALL, | ||
| ), | ||
| re.compile( | ||
| r"<\|tool_call_begin\|>(?=\s*[A-Za-z_][\w.\-]*:\d|\s*$).*$", |
There was a problem hiding this comment.
Strip healed Kimi calls without numeric ids
When a section-less Kimi call uses an id that _KIMI_ID_RE accepts without a numeric suffix, e.g. <|tool_call_begin|>functions.web_search<|tool_call_argument_begin|>{"q":"x"}, _parse_kimi_section_body returns a tool call in the default Auto-Heal path even if <|tool_call_end|> is missing. This strip pattern only drops truncated bare Kimi tails when the id is followed by :\d, so the executed tool markup remains in content_text and can be streamed or saved as assistant content. Please align this lookahead with the parser's accepted id forms, or reject those ids in the parser.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Down: malformed and truncated-markup recovery plus display residue, not a real-session bug. The line 118 lookahead deliberately requires the Kimi id to be an identifier followed by colon-digit (the numeric index) or end-of-input, which matches the real Kimi K2 emit format. Per Moonshot's chat template every Kimi call id is functions.NAME:INDEX with a loop index that is always present, e.g. functions.get_weather:0. To reach the gap you describe the model must simultaneously drop the section wrapper, drop the numeric index, and truncate before the call-end marker, a triple deviation the real template never produces. _KIMI_ID_RE makes the index optional only as a lenient healing measure; broadening the strip to accept index-less ids would risk eating ordinary prose that merely names the marker. And even in the hand-crafted case the parser still surfaces the call correctly, so the only effect is leftover markup in display, not a wrong or lost tool call. Keeping as-is.
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Use string-aware DeepSeek and Kimi strip bounds
For DeepSeek/Kimi calls whose JSON arguments contain the literal family terminator text, the parsers correctly ignore that token while inside JSON strings, but these strip regexes stop at the first textual terminator. For example a parsed DeepSeek call with {"query":"what does <|tool▁calls▁end|> mean"} leaves mean"}<|tool▁call▁end|><|tool▁calls▁end|> in the assistant content/history after the tool executes; Kimi has the same leak with <|tool_calls_section_end|> or <|tool_call_end|> inside an argument string. Please mirror the parser's string-aware boundary scan before removing the executed markup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Down: in-string strip plus display residue. This depends on a DeepSeek or Kimi model emitting its own section-terminator special token as literal text inside a JSON argument value (a query string that contains the tool-calls-end token). Those terminators are dedicated special tokens the model uses to close the call block, not argument content; a real single-format session does not place them inside an argument string. Even in that hand-crafted input the parser is string-aware via _find_outside_json_strings and still parses the call with the correct name and arguments and executes the right tool, so the only consequence is a cosmetic markup tail in the displayed or saved assistant text. The tool selection, arguments, and the structured tool_calls stored in history are all correct; this is the in-string-strip and display-residue family already rejected across this PR. Keeping the regex bounds as-is.
| if _GEMMA_TC_RE.search(content): | ||
| return out |
There was a problem hiding this comment.
Do not defer outer wrapperless Gemma calls
When a wrapperless Gemma call has an argument that quotes a wrapped Gemma snippet, e.g. call:web_search{query:"see <|tool_call>call:delete_all{x:1}<tool_call|>"}, the leading-wrapperless guard reaches _parse_gemma_tool_calls, but this global _GEMMA_TC_RE.search returns no outer call; parsing then falls through to tool_healing and executes the quoted inner delete_all call instead. This turns argument text into a different tool invocation whenever the quoted wrapped name is enabled, so the deferral should only apply when the wrapped opener is the actual call to parse, not when it is inside the wrapperless call body.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Down: cross-format plus quoted-example recombination, unreachable from a single real Gemma stream. The input mixes two mutually exclusive modes: a wrapper-less outer call (call:web_search{...}, which only appears once skip_special_tokens has stripped the wrapper and the string markers) whose argument still contains an intact wrapped snippet with the tool_call opener and closer present. In a real generation skip_special_tokens either strips every wrapper marker (so the inner opener is gone too and _GEMMA_TC_RE matches nothing) or keeps them (so the outer call is also wrapped and tool_healing parses web_search correctly in document order). The only way to get a wrapper-less outer with an intact wrapped inner is the model spelling out a full wrapped tool-call as literal argument text, i.e. a quoted example, which is the recombination family this PR rejects. The guard is also deliberately gated on the full _GEMMA_TC_RE pattern (opener plus call:name plus brace) rather than the bare marker, per the comment above it, precisely so a wrapper-less call that merely mentions the marker is not lost. Keeping as-is.
| # Gemma wrapper-less ``call:NAME{...}`` has no tool_xml_signals entry: | ||
| # buffer it here or it streams raw until the end-of-turn safety net. | ||
| # ``(?<!\w)`` keeps "recall:" out; the prefix regex is whitespace-tolerant. |
There was a problem hiding this comment.
Detect prose-prefaced wrapperless Gemma before streaming
This wrapperless-Gemma buffering only runs while the turn is still in BUFFERING. If the model first emits visible prose and later emits an enabled call such as Here: call:web_search{query:x}, the loop is already in STREAMING, where it scans only tool_xml_signals; because call: has no signal, partial bytes like call:web_search can be sent to the client before the {...} arrives, and the later cumulative strip cannot retract them before the safety-net parser executes the tool. Please add the same prefix/drain handling to the streaming-state signal scan.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Down: streaming display residue, not a correctness bug. You are right that the wrapper-less Gemma buffering only runs in the leading BUFFERING state and that the STREAMING signal scan has no call-colon entry, so a prose-prefaced call:NAME can transiently show a partial name before the brace body arrives. But it resolves correctly on finalization: the end-of-turn safety-net parser (parse_tool_calls_from_text over content_accum) still parses the wrapper-less call and executes the right tool with the right arguments, and the saved assistant content is cleaned by _strip_tool_markup_final, so history has no leak and no tool is lost or mis-selected. The only artifact is a transient partial display mid-stream, which is the streaming-residue family already rejected here. Adding call-colon to the STREAMING signal scan would force ordinary prose that contains the word call followed by a colon to buffer or drain mid-stream, which is worse than a transient partial. Keeping as-is.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: adff9073ad
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| elif len(stripped_buf) < _MAX_BUFFER_CHARS: | ||
| _hold_buffer = True |
There was a problem hiding this comment.
Buffer long Gemma call prefixes before streaming
When a Gemma GGUF stream emits wrapper-less call:NAME{...} text and NAME is longer than the 32-character buffer cap (common for MCP names like mcp__server__long-tool-name), this branch stops holding the prefix before the { arrives and falls back to STREAMING. Since call: has no TOOL_XML_SIGNALS marker, the later {...} cannot move the stream into DRAINING, so the raw call:... prefix/body can be emitted to the client before the end-of-turn safety net parses and executes the tool. The safetensors path added a larger prefix hold for this same case; the GGUF textual fallback needs the same treatment.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Streaming display residue family, and this re-frames the streaming-buffer angle rejected last round. Traced against the GGUF path: content_accum accumulates every content token unconditionally (llama_cpp.py line 8806), so a long-name Gemma bare call:NAME{...} that exceeds the 32-char BUFFERING hold and drops to STREAMING is still fully present in content_accum at end-of-turn. The STREAMING safety net re-parses content_accum unconditionally (llama_cpp.py line 8980), so _parse_gemma_tool_calls catches the call and it executes; the finalized content is _strip_tool_markup(content_accum, final=True, force=True), which runs _strip_gemma_wrapperless_calls and leaves history clean. No call is lost, no wrong tool, no wrong args, no data loss. The only effect is a transient partial call:... display before the safety net fires, and tool_start resets prev_text at the route level. The safetensors 16384 vs GGUF 32 hold is a real asymmetry, but it changes only transient streaming presentation, not correctness or history, so it does not meet the bar.
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Strip DeepSeek/Kimi calls with balanced scanning
When a DeepSeek or Kimi argument string legitimately contains the literal envelope terminator (for example <|tool▁calls▁end|> or <|tool_calls_section_end|>), the parser skips it as JSON string data, but these lazy strip regexes stop at that first occurrence. After the tool executes, strip_tool_markup leaves the remainder of the JSON and closing markers in the assistant content/display/history; use the same outside-JSON scanning for the strip path (and its route-level mirror) instead of matching the first terminator.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
In-string strip family (matching inside JSON string literals), and this re-frames the line-84 string-aware-strip item rejected last round. The premise requires a DeepSeek or Kimi argument JSON string to legitimately contain the literal envelope terminator (the DeepSeek tool-calls-end token or the Kimi tool-calls-section-end token) as string data. Those terminators are dedicated special tokens in the model vocabulary, not literal argument text: a real single-format DeepSeek V3.1 or Kimi K2 generation emits the terminator only as the structural close of the tool-calls region, never inside an argument value. The parser's _find_outside_json_strings scan (lines 2295 and 2554) is defensive belt-and-suspenders, not evidence that legitimate output ever places the terminator inside a string. Because the triggering input cannot arise from well-formed single-format generation, the lazy strip leaves nothing behind on real model output, so there is no reachable correctness bug.
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), | ||
| # Kimi K2 section-less closed call; without this arm the unclosed catch-all | ||
| # below eats trailing prose to EOS. | ||
| re.compile(r"<\|tool_call_begin\|>.*?<\|tool_call_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Preserve Kimi snippets inside JSON answers
When a structured JSON answer contains a complete section-less Kimi snippet as a string value (for example documenting <|tool_call_begin|>functions.web_search:0...<|tool_call_end|>), the parser correctly treats it as data, but strip_tool_markup(final=True) still applies this closed-call regex and deletes the string contents. This corrupts response-format/JSON answers even though no tool call was parsed; the strip path needs the same whole-JSON/data guard used for markerless Gemma examples before removing Kimi markup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Quoted-example / in-string strip family, and this re-frames the Kimi-in-JSON angle rejected last round. The scenario needs a structured JSON answer that carries a section-less Kimi snippet (the tool_call_begin and tool_call_end markers) as literal string content. Those are Kimi special tokens: in a real single-format Kimi K2 generation, emitting tool_call_begin means the model is structurally making a tool call, not documenting syntax inside a JSON answer, so this cannot arise from legitimate output. The _whole_content_is_json_value / _leading_json_value_end guard exists for the MARKERLESS forms (Gemma bare call:NAME{...} and bare JSON) precisely because those shapes can appear verbatim as ordinary answer text; a marker-based special-token form cannot, which is why the strip does not carry that guard. Also, for a COMPLETE embedded Kimi call (with tool_call_argument_begin and a JSON body) the parse path parses it via _parse_kimi_section_body rather than treating it as data, so parse and strip agree; the described parse-vs-strip divergence exists only for an incomplete snippet, which is even further from legitimate output. No reachable corruption on real single-format answers.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: adff9073ad
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Strip DeepSeek/Kimi calls with JSON-aware end scanning
When a DeepSeek or Kimi argument string contains the literal section/end marker (for example a search query or code snippet documenting <|tool▁calls▁end|> / <|tool_calls_section_end|>), the parser deliberately finds the envelope end outside JSON strings, but these new strip regexes stop at the first marker text. After the tool is executed, strip_tool_markup(..., final=True) leaves the remainder of the JSON and closing tags in the visible assistant content / next-turn history, e.g. marker"}<|tool▁call▁end|>..., which can leak tool markup and corrupt subsequent turns. The strip path needs the same JSON-aware scan used by _parse_deepseek_tool_calls / _parse_kimi_tool_calls rather than a lazy .*? close.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same JSON string-literal strip-bounds concern as the prior two rounds on this line (string-aware parse vs lazy strip regex). Traced again: the divergence only triggers if a DeepSeek or Kimi argument JSON string literally contains the section terminator, which is a dedicated special token used to close the call block, never argument text in a real single-format generation. The parse path still executes the correct tool with correct args; only cosmetic markup residue differs. Unreachable on legitimate output, so leaving as is.
| nt = AutoTokenizer.from_pretrained( | ||
| template_source, | ||
| token = hf_token if hf_token and hf_token.strip() else None, | ||
| ) |
There was a problem hiding this comment.
Pass trust_remote_code when reloading native tokenizers
When a model was loaded with trust_remote_code=True and this fallback is needed because the active override template dropped tools, the secondary AutoTokenizer.from_pretrained call omits the same trust setting used for the actual load. For custom-code tokenizer repos this raises and is caught here, so render_native_template returns None and the request silently keeps the tool-dropping prompt even though the user already consented to remote code for the model load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 72354db.
Confirmed against transformers 4.57.6: AutoTokenizer.from_pretrained sets has_remote_code from the tokenizer auto_map and, when has_remote_code and not has_local_code and not trust_remote_code, resolve_trust_remote_code raises ValueError (in a non-interactive server it raises immediately rather than prompting). So the secondary reload of a custom-code tokenizer repo raised, the except returned None, and the request kept the tool-dropping prompt.
Change: render_native_template now sources trust_remote_code from model_info (bool(model_info.get('trust_remote_code', False))) and threads it into the secondary AutoTokenizer.from_pretrained, mirroring how hf_token is handled. Both backends now persist the flag on their per-model info dict at load time (InferenceBackend and MLXInferenceBackend), so the read lands on the value the model was actually loaded with.
Consent is scoped to the stored flag, not a hard-coded True: for a base model template_source is the loaded model itself; for a LoRA adapter template_source is the base model, which worker.py gates and loads under that same single trust_remote_code, so re-passing it executes no code the user did not already consent to. A falsy stored flag reproduces the prior behaviour (no new code execution).
Regression test: studio/backend/tests/test_native_template_trust_remote_code.py monkeypatches AutoTokenizer.from_pretrained to raise unless trust_remote_code is truthy. test_native_reload_passes_stored_trust_remote_code asserts the tools-advertising native prompt is returned; it fails before the fix (returns None) and passes after. A second test asserts None is returned without stored consent, and a third pins that both backend model_info dicts persist the flag.
| re.DOTALL, | ||
| ), | ||
| re.compile( | ||
| r"<\|tool_call_begin\|>(?=\s*[A-Za-z_][\w.\-]*:\d|\s*$).*$", |
There was a problem hiding this comment.
Strip incomplete section-less Kimi calls without numeric ids
The Kimi parser accepts section-less ids without a :IDX suffix and, with Auto-Heal on, will execute a call once its JSON object is balanced even if <|tool_call_end|> is missing. This unclosed-strip lookahead only matches ids followed by :\d, so an emitted fragment like <|tool_call_begin|>functions.web_search<|tool_call_argument_begin|>{"q":"x"} is parsed as a tool call but then remains in the assistant content/history after execution. The strip pattern should mirror _KIMI_ID_RE's optional suffix.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same section-less Kimi without numeric id concern rejected in the first round on this line. Real Kimi K2 always emits functions.NAME:INDEX with an always-present loop.index per the Moonshot chat template; reaching this needs no section wrapper, no numeric index, and truncation before the end marker all at once, which the real template never produces. Even in the crafted case the parser surfaces the call with allow_incomplete, leaving only markup residue. Leaving as is.
The native-template fallback re-fetches a model's native chat template from its repo when an Unsloth override template drops the tools schema. The secondary AutoTokenizer.from_pretrained threaded hf_token but not trust_remote_code, so for a model loaded with trust_remote_code=True whose tokenizer repo carries custom code the reload raised, was swallowed, and the request silently kept the tool-dropping prompt for a model that supports tools. Store the loaded trust_remote_code on each backend's per-model info dict and source it in render_native_template, so the reload re-uses exactly the consent granted at load. For a LoRA adapter the reload targets the base model, whose remote code was gated and loaded under the same stored flag, so re-passing it executes no unconsented code. Falsy stored flag preserves the prior behaviour. Adds a regression test that fails without the flag (custom-code reload raises, returns None) and passes with it (tools-advertising native prompt returned).
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 72354db0c4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Strip DeepSeek/Kimi calls past quoted end markers
When a DeepSeek or Kimi argument string contains the literal protocol end token, the parsers correctly ignore that quoted marker via _find_outside_json_strings, but these display-strip regexes stop at the first textual end marker. In that case the tool call is executed, while strip_tool_markup(..., final=True) leaves the remainder (for example token"}<|tool▁call▁end|>...) in visible output and in the assistant message that is fed into the next turn; use the same string-aware scan for stripping these envelopes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Traced fresh against both the parser and the strip. This is the in-string strip family and stays below the bar, same as the prior three passes on this line, with the same reasoning now covering the DeepSeek arm it has been extended to.
The DeepSeek section terminator (tool calls end) and the Kimi section terminator (tool_calls_section_end) are dedicated special tokens. In real single-format output a model emits them structurally as the terminator, not as literal characters inside a JSON argument string, so the non-greedy strip and a string-aware scan land on the same offset. The _find_outside_json_strings guard in the parser is defensive coverage for a hand-constructed input, not evidence the input is reachable.
And on that constructed input the call still parses and executes correctly, because the parser is string-aware, so the worst case is a trailing display fragment for output a real model does not generate. No wrong tool, no dropped or truncated call, no wrong args. The simple display regex here is intentional.
| r"|" | ||
| + _DS_OPEN_SRC | ||
| + r"(?=\s*(?:<|tool▁call▁begin|>|function)|\s*$).*?(?:<|tool▁calls▁end|>|\Z)" | ||
| r"|<\|tool_calls_section_begin\|>(?=\s*<\|tool_call_begin\|>|\s*$).*?(?:<\|tool_calls_section_end\|>|\Z)" | ||
| r"|<\|tool_call_begin\|>(?=\s*[A-Za-z_][\w.\-]*:\d|\s*$).*?(?:<\|tool_call_end\|>|\Z)" |
There was a problem hiding this comment.
Make route cleanup string-aware for new envelopes
This route-level fallback has the same quoted-end-token problem for raw/stale DeepSeek and Kimi markup: _TOOL_XML_RE consumes only up to the first <|tool▁calls▁end|> or <|tool_calls_section_end|>, even when that token appears inside the JSON argument string. Prior assistant history or streamed content passed directly through _strip_tool_xml_for_display can therefore leak the remaining raw tool-call tail; this path needs to delegate to a string-aware DeepSeek/Kimi stripper rather than the non-greedy regex.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same in-string strip family as the parser-side item, now at the route-level _TOOL_XML_RE. Traced fresh against this path.
_TOOL_XML_RE closes its DeepSeek and Kimi arms at the section terminator, which is a dedicated special token. A real single-format model never emits that token as literal characters inside a JSON argument value, so the non-greedy close and a string-aware scan agree. _strip_tool_xml_for_display is an Auto-Heal display safety net, and the underlying call is parsed and executed by the string-aware parser regardless, so even on a hand-built in-string input the only effect is a trailing display fragment, not a wrong or lost call. Below the bar.
| elif len(stripped_buf) < _MAX_BUFFER_CHARS: | ||
| _hold_buffer = True |
There was a problem hiding this comment.
Keep long wrapperless Gemma names buffered
In the GGUF textual fallback, when Gemma emits the wrapperless call:NAME form and the tool name is longer than _MAX_BUFFER_CHARS before the { arrives in a later SSE chunk (common for MCP-style names), this branch stops holding the prefix and falls through to streaming, so the raw call:... text is sent to the client before the end-of-turn parser executes it. The safetensors path already holds _GEMMA_BARE_TC_PREFIX_RE up to the larger bare-JSON cap; the GGUF path needs the same treatment for long enabled tool names.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Traced fresh against the streaming path. Same conclusion as the prior pass: streaming display residue, below the bar.
When the wrapperless Gemma name is longer than the 32-char hold and the brace has not arrived yet, the buffer does drain to the client as raw call:NAME text. But content_accum keeps every content token, and at end of turn the safety-net parser re-parses content_accum and executes the call. The Gemma name class is unbounded, so a 54-char MCP-style name parses fine, verified locally. content_text is then rebuilt with strip_tool_markup(final=True), which runs the gated Gemma wrapperless strip and removes the call, verified to yield an empty history string. So the executed call and the assistant message written to history are both correct. The only artifact is a transient raw prefix in the live stream, which is the display-residue family. No wrong tool, no lost call, no corrupted history.
| # An enabled call that CLOSES before the signal still owns the turn | ||
| # (inside-or-after rule, as for closed bare-JSON/Mistral envelopes); | ||
| # the ownership claim stays gated on an enabled name. | ||
| return enabled_tool_names is not None and end < first |
There was a problem hiding this comment.
Let unrestricted Gemma calls keep document order
When enabled_tool_names is None (the documented name-agnostic/unrestricted mode used by direct parser callers and the tools=[] safetensors loop contract), a leading wrapperless Gemma call that closes before a later XML/Kimi/Mistral marker should still own the turn. This guard returns False in exactly that case, so call:web_search{...}<tool_call>... can skip the first call and execute the later marked call instead; the inside-or-after ownership check should also apply when names are unrestricted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Traced fresh against the leading-call guards, the dispatch, and the pinned control tests. Below the bar: the scenario is cross-format, and the gate is a deliberate, tested design.
The example, a wrapperless Gemma call:web_search{...} followed by a Qwen tool_call marker, mixes two different tool-call formats in one output. A single real model emits one format, so a wrapperless Gemma call followed by a genuine Qwen, Kimi, or Mistral call is not legitimate single-format session output. The only single-format variant is a marker quoted inside a later Gemma call's JSON string argument, which is the in-string quoted-arg family and is already handled by the inside branch.
The inside branch returns True unconditionally, including when names are unrestricted, because a marker inside the leading call's balanced body is unambiguously argument data. The after branch is gated on an enabled name on purpose: the wrapperless form is markerless, so when names are unrestricted we cannot confirm a leading call:NAME is a real call rather than prose, and claiming ownership over a later explicit marker in that mode would let a false-positive call:NAME in prose suppress a genuine trailing call. The bare-JSON sibling can be name-agnostic there because its name-and-parameters object shape is self-identifying. test_multi_gemma_ownership_reverse_controls pins exactly this: with names unrestricted, call:foo{} followed by a real tool_call delete_all resolves to delete_all. So the asymmetry is intentional, and dropping the gate trades a cross-format non-case for a real false-positive regression on a case the suite already locks in.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 72354db0c4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _GEMMA_BARE_TC_RE.match(stripped_buf): | ||
| _drain_silently = True | ||
| elif len(stripped_buf) < _MAX_BUFFER_CHARS: | ||
| _hold_buffer = True |
There was a problem hiding this comment.
Keep long Gemma tool names buffered in GGUF
In the GGUF textual fallback, a wrapper-less Gemma call is held only while the call:NAME prefix is shorter than _MAX_BUFFER_CHARS (32). When an enabled tool has a longer name (for example an MCP-style mcp__github__list_repository_issues) and the { has not streamed yet, this branch falls through to STREAMING and emits the raw call:... prefix; later stripping cannot retract already-sent content, even though the parser will still execute the tool once the body completes. The safetensors loop handles this by buffering the name prefix up to the larger bare-JSON cap, so the GGUF path should use the same behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining. This is the Gemma GGUF streaming-residue family, raised a third time. content_accum retains every content token, and the end-of-turn safety net re-parses content_accum with _parse_tool_calls_from_text, so the tool still executes once the body completes even when a long call:NAME prefix crosses the 32-char buffer window and streams raw. Nothing is dropped or mis-called; the only artifact is that the raw call:NAME prefix was already displayed and later stripping cannot retract sent bytes. That is streaming display residue, not a lost or wrong call, so it stays below the correctness bar.
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Skip sentinel matches inside DeepSeek/Kimi arguments
These strip regexes stop at the first DeepSeek/Kimi section-end token, even when that token is inside the parsed JSON argument string. For inputs like a DeepSeek search query asking what <|tool▁calls▁end|> means (or a Kimi argument mentioning <|tool_calls_section_end|>), the parser correctly ignores the literal marker, but final display/history cleanup leaves the remainder of the JSON and closing tags visible (for example mean"}<|tool▁call▁end|>...). The strip path needs the same outside-JSON-string scan used by the parser.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining. This is the in-string-strip / display-residue family, now raised a fifth time. The parse path already scans for the DeepSeek and Kimi section-end tokens outside JSON strings via _find_outside_json_strings (the DeepSeek and Kimi parsers), so a real call is bounded and executed correctly regardless of a marker quoted in its arguments. In a real single-format session the section-end token is a dedicated special token the model emits only as the structural terminator, never as literal argument text, so the lazy strip regex and the string-aware scan land on the same offset. They differ only for a contrived query that literally quotes the section-end token inside its arguments, and even there the call parses and executes correctly; only trailing display and history residue differs. That is cosmetic strip residue, not a lost, dropped, or mis-parsed call, so it stays below the correctness bar.
| ) | ||
| # Covers both ``<function=NAME>`` and the attribute form; an attribute-form call | ||
| # embedding a DeepSeek/Kimi marker must not be hijacked by the marker pre-pass. | ||
| _OUTER_ENVELOPE_OPEN_RE = re.compile(r'<tool_call>|<function(?:=|\s+name=")|<\|tool_call>') |
There was a problem hiding this comment.
Treat python_tag as an outer marker envelope
When a Llama-3 <|python_tag|> tool call has an argument string that quotes a complete DeepSeek or Kimi example, the new marker pre-pass is not suppressed because this leading-envelope guard only recognizes <tool_call>, <function...>, and Gemma wrappers. In that scenario the embedded DeepSeek/Kimi snippet is promoted and executed instead of the outer Llama tool call, so python_tag calls need to participate in the same before-the-first-marker guard.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 79fb8ca. python_tag is Llama-3's tool-call envelope (the built-in NAME.call(...) form and the custom JSON form), so I added it to _OUTER_ENVELOPE_OPEN_RE with a call-shaped lookahead that mirrors the _TOOL_ALL_PATS python_tag arm. When a python_tag call opens before the first DeepSeek/Kimi marker, _marker_inside_leading_envelope now suppresses the marker pre-pass, so the quoted example stays argument data and the real outer call runs. The lookahead keeps a bare prose python_tag mention from being treated as an envelope.
Reproduced before the fix: an enabled python_tag web_search call whose query quotes a complete Kimi example (or a DeepSeek example with empty-args) parsed the embedded delete_all instead of web_search, in both the NAME.call(...) and custom-JSON shapes. The regression test test_python_tag_call_with_embedded_marker_runs_outer_call in test_pr5624_regressions.py fails without the change (asserts web_search, gets delete_all) and passes with it; it also pins the prose-mention case so a real Kimi call after a bare python_tag token still parses. Full tool-parsing suites: 571 passed.
| if _GEMMA_BARE_TC_PREFIX_RE.match(stripped) is not None: | ||
| if len(stripped) < _MAX_BARE_JSON_BUFFER: | ||
| continue |
There was a problem hiding this comment.
Drop held Gemma prefixes at EOF
This branch now buffers a wrapper-less Gemma prefix such as call:web_search until the { arrives, but the end-of-stream resolver below only recognizes XML signals and bare JSON. If generation stops after the enabled call:NAME prefix but before {, the held buffer falls through as normal content and the raw tool prefix is sent to the user instead of being dropped like the analogous truncated bare-JSON call.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining. This is the Gemma truncated-prefix display-residue variant at end-of-stream. The scenario stops after an enabled call:NAME prefix but before the opening brace, so there is no complete Gemma call: no arguments, no body, nothing the parser can execute either before or after any change. Both paths execute zero calls; the only difference is whether the residual call:NAME text is dropped from the final display, exactly the truncated-markup-recovery and display-residue class. No real call is lost or mis-parsed (there is no call, only a truncated prefix), so it stays below the correctness bar.
A Llama-3 <|python_tag|> tool call (built-in NAME.call(...) or custom
{json} form) whose argument quotes a complete DeepSeek/Kimi example was
hijacked by the DeepSeek/Kimi marker pre-pass: the embedded example (for
example delete_all) executed instead of the real outer call. python_tag
is Llama-3's tool-call envelope, so a marker quoted inside its arguments
is data, the same as for <tool_call>, <function=...>, bare JSON, Mistral
and wrapper-less Gemma, which the guard already covers.
Add <|python_tag|> to _OUTER_ENVELOPE_OPEN_RE with a call-shaped
lookahead (mirroring the _TOOL_ALL_PATS python_tag arm) so the marker
pre-pass is suppressed when a python_tag call opens before the first
marker, while a bare prose <|python_tag|> mention is left untouched.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 79fb8cafdb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # Mistral v11+ ``[TOOL_CALLS]name{json}`` (may chain), close at ``}``. | ||
| re.compile(r"\[TOOL_CALLS\]\s*[\w\.\-]+\s*(?:\[ARGS\])?\s*\{.*?\}", re.DOTALL), | ||
| # DeepSeek R1 / V3 / V3.1: full envelope (any opener variant) ... end. | ||
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), |
There was a problem hiding this comment.
Strip DeepSeek/Kimi envelopes with string-aware scanning
When a valid DeepSeek or Kimi call has an argument string containing the literal section terminator (for example asking what <|tool▁calls▁end|> means), this lazy regex stops at the terminator inside the JSON string and leaves the rest of the tool markup in the visible assistant text/history after the call is parsed. The parser already uses _find_outside_json_strings for these envelopes, so the strip path needs the same string-aware boundary logic (the Kimi section regex just below has the same issue).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The parse path for these envelopes already scans for the section-end terminator outside JSON strings via _find_outside_json_strings, so a valid call whose argument literally quotes the DeepSeek end terminator still parses with full, correct arguments. Only the lazy display-strip regex differs, leaving at most a cosmetic residue of already-consumed markup; no call is dropped, truncated, or given wrong args. The DeepSeek section terminators are dedicated special tokens in the model vocabulary, not literal argument text a real session emits. This is the in-string-strip and display-residue family, rejected across roughly six prior re-frames. Rejecting.
| # An enabled call that CLOSES before the signal still owns the turn | ||
| # (inside-or-after rule, as for closed bare-JSON/Mistral envelopes); | ||
| # the ownership claim stays gated on an enabled name. | ||
| return enabled_tool_names is not None and end < first |
There was a problem hiding this comment.
Treat name-agnostic Gemma calls as owning the turn
With the default enabled_tool_names=None (documented as name-agnostic), a leading wrapper-less Gemma call that closes before a later foreign marker returns False here, so the pre-pass can parse a later [TOOL_CALLS]/Kimi/DeepSeek snippet instead of the earlier call:...{...}. This breaks the default parser/unrestricted-tool mode for outputs like call:web_search{query:hi} [TOOL_CALLS]evil{}, where the later marker is selected even though the Gemma call appears first.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified fresh against the live tree. In the name-agnostic default the guard deliberately returns False when a markerless leading Gemma call closes before a later foreign marker, so an explicitly-marked trailing call is selected. That behaviour is pinned by test_multi_gemma_ownership_reverse_controls, whose agnostic control asserts that call:foo{} followed by a marked XML tool_call block yields the marked call, not foo. A markerless Gemma call carries no special-token signal and can be a false positive from prose, so letting it own the turn would let a spurious call:foo{} suppress a genuine marked call. The cited example mixes Gemma call syntax with a Mistral TOOL_CALLS marker, which is cross-format and not legitimate single-format real-session output. Rejecting as deliberate and test-pinned; the near-line variant was rejected last round.
| re.DOTALL, | ||
| ), | ||
| re.compile( | ||
| r"<\|tool_call_begin\|>(?=\s*[A-Za-z_][\w.\-]*:\d|\s*$).*$", |
There was a problem hiding this comment.
Strip bare Kimi calls without call indexes
The Kimi parser accepts section-less IDs without a :0 suffix (functions.web_search is valid because _KIMI_ID_RE makes the index optional), but this unclosed-strip lookahead only recognizes names followed by :\d. When Auto-Heal parses a truncated bare Kimi call without the optional index, the call executes and the raw <|tool_call_begin|>... text remains in the assistant content/history because the final strip does not match it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed the residue is real for that exact shape, but it only appears for a bare tool-call opener with no section wrapper and no call index at the same time. Moonshot Kimi K2 always emits functions.NAME:idx, where idx is a mandatory global counter starting at 0, wrapped in the tool-calls section markers; I re-confirmed this against the official Kimi K2 tool-call guidance. A real truncated Kimi call therefore carries the section wrapper, which the section-begin arm strips, and the index, which the unclosed call arm colon-digit lookahead matches, and it strips cleanly. The optional-index and section-less leniency are supersets of the real format kept for llama.cpp parity; the no-wrapper-plus-no-index shape the residue needs is not something the real template produces, so it is not legitimate single-format real-session output. Rejecting.
| # DeepSeek R1 / V3 / V3.1: full envelope (any opener variant) ... end. | ||
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Require real Kimi call shape before stripping sections
This closed-section regex strips any text between <|tool_calls_section_begin|> and <|tool_calls_section_end|> even when it is only explanatory prose and not a parseable Kimi call. In a tool-enabled conversation where the assistant answers a question about the Kimi template markers, strip_tool_markup(..., final=True) deletes the documented marker text despite the parser returning no tool call; the closed-strip arm needs the same call-shape/argument-marker guard used by the unclosed arms.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The closed-section strip removing prose between the section markers is cosmetic over-stripping, not a dropped or corrupted call: the parser returns no call, so nothing is lost, at most documentation text is trimmed from the display. For this to fire the assistant must emit both the Kimi section-begin and section-end special tokens as literal display text while answering a question about the markers, which is the quoted-example-about-the-markers case. That is the in-string-strip, display-residue and quoted-example family, rejected across roughly six prior re-frames on this line. Rejecting.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 79fb8cafdb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| re.compile(_DEEPSEEK_OPEN_RE_SRC + r".*?<|tool▁calls▁end|>", re.DOTALL), | ||
| # Kimi K2: ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``. | ||
| re.compile(r"<\|tool_calls_section_begin\|>.*?<\|tool_calls_section_end\|>", re.DOTALL), |
There was a problem hiding this comment.
Strip DeepSeek/Kimi blocks with string-aware boundaries
When an argument string itself contains the family end marker, these non-greedy strip patterns stop inside the JSON even though the new parsers deliberately find the envelope end outside JSON strings. For example, a DeepSeek call whose query is what does <|tool▁calls▁end|> mean parses successfully, but strip_tool_markup(..., final=True) leaves the tail (mean"}<|tool▁call▁end|>...) in display/history; Kimi has the same issue with <|tool_calls_section_end|>. The strip path needs the same string-aware boundary scan as the parser.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting. This is the in-string display-strip family again (7th re-frame). The parse path already locates the envelope terminator OUTSIDE JSON strings via _find_outside_json_strings, so the call and its arguments are extracted correctly; only strip_tool_markup's non-greedy display regex stops at an in-string marker. And the DeepSeek tool-calls-end and Kimi section-end tokens are dedicated special tokens: a real model never emits them as literal text inside an argument value, so a query like 'what does (the end token) mean' is not legitimate single-format output. No wrong tool, no lost or truncated call, no wrong args, only cosmetic display residue on a fabricated input. Below the STRICT BAR.
| # An enabled call that CLOSES before the signal still owns the turn | ||
| # (inside-or-after rule, as for closed bare-JSON/Mistral envelopes); | ||
| # the ownership claim stays gated on an enabled name. | ||
| return enabled_tool_names is not None and end < first |
There was a problem hiding this comment.
Let ungated Gemma calls own later foreign markers
In the enabled_tool_names=None mode documented above as name-agnostic, a balanced wrapper-less Gemma call that closes before a later foreign marker does not own the turn because this returns False. That makes parse_tool_calls_from_text('call:web_search{query:x} ... <tool_call>{"name":"evil","arguments":{}}</tool_call>') return the later XML example instead of the first Gemma call, while the same input with an enabled-name set returns web_search; unrestricted/no-gate callers can therefore execute the wrong tool.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting. The enabled_tool_names is None gate here is deliberate and test-pinned, not an oversight. In name-agnostic mode a wrapper-less Gemma call is indistinguishable from prose, so it must not own the turn against a MARKED Qwen/Hermes tool_call that carries an explicit signal. test_multi_gemma_ownership_reverse_controls pins exactly this: the agnostic input 'call:foo{} ' plus a marked tool_call for delete_all returns delete_all, not foo. Letting a markerless call own the turn would let false-positive prose that merely looks like call:NAME{...} suppress a genuine marked call. This is the theoretical enabled_tool_names is None gate reject family. Below the STRICT BAR.
| text = _strip_mistral_closed_calls(text) | ||
| # Scan-strip the function-XML form first (parser-accurate: a literal | ||
| # ``<function=...>`` inside a value is data, not a call), then the regex arms | ||
| # cover the other formats (they no-op here once the scan ran). | ||
| if final: | ||
| text = _strip_gemma_wrapperless_calls(text, enabled_tool_names) |
There was a problem hiding this comment.
Preserve disabled Gemma prose before stripping nested markers
The Mistral strip runs before the gated wrapper-less Gemma strip, so a disabled/example Gemma snippet can still be mutated by markers inside its quoted text. With enabled tools {'web_search'}, call:foo{query:"[TOOL_CALLS]web_search{}"} is correctly not parsed as a call, but final display becomes call:foo{query:""}, contradicting the gate that disabled/example call:NAME{...} prose stays visible; protect those spans before applying generic marker strips.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting after a fresh single-format trace. parse_tool_calls_from_text of the string call:foo{query:"[TOOL_CALLS]web_search{}"} with enabled={web_search} returns [] (foo is disabled, correctly not treated as a call), so no call is lost and no wrong tool runs. The only effect is that strip_tool_markup(final=True) rewrites the display to call:foo{query:""}. That mutation only happens because the value quotes a Mistral [TOOL_CALLS] trigger, which is FOREIGN to Gemma. A legitimate single-format Gemma stream never contains a Mistral trigger, and Gemma's own tool_call wrapper is a dedicated special/control token that skip_special_tokens strips uniformly across the whole decode (Google Gemma 4 function-calling docs). So this is cross-format display-strip residue on a disabled example, not a parse-correctness bug. Below the STRICT BAR. Source: ai.google.dev Gemma 4 function calling.
| re.DOTALL, | ||
| ), | ||
| re.compile( | ||
| r"<\|tool_call_begin\|>(?=\s*[A-Za-z_][\w.\-]*:\d|\s*$).*$", |
There was a problem hiding this comment.
Strip healed Kimi calls without an index suffix
The parser accepts Kimi ids without a :IDX suffix (functions.web_search) and, with Auto-Heal on, will execute a balanced call even if <|tool_call_end|> was truncated. This final-strip catch-all only matches ids followed by :\d, so a healed bare Kimi call like <|tool_call_begin|>functions.web_search<|tool_call_argument_begin|>{"q":"x"} executes but remains in the assistant display/history as raw markup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting. Real Kimi K2 always emits functions.NAME:idx with a MANDATORY numeric index. Moonshot's official tool_call_guidance.md documents the id format as functions.func_name:idx and its reference parser matches an id of word-chars-and-dots then :digits, with the index incrementing per call (:0, :1, :2). A bare functions.web_search with no index is not valid Kimi output, so the final-strip arm that matches an id followed by :digit already covers every real Kimi call. _KIMI_ID_RE makes the suffix optional only for parser robustness, not because real sessions omit it. Even in the fabricated bare-id case the effect is display residue, never a lost call or wrong tool. Below the STRICT BAR. Source: moonshotai Kimi-K2 tool_call_guidance.md.
| begin = _DEEPSEEK_BEGIN_RE.search(content) | ||
| if not begin: | ||
| return out | ||
| scan_start = begin.end() |
There was a problem hiding this comment.
Continue scanning after non-call DeepSeek envelopes
This parser only inspects the first DeepSeek opener in the text. If the model includes a closed non-call/example envelope before the real tool block, e.g. Example: <|tool▁calls▁begin|>not a call<|tool▁calls▁end|> ... <|tool▁calls▁begin|><|tool▁call▁begin|>function..., the first body produces no calls and the later valid call is never considered; loop past envelopes that do not yield a call, as the Kimi parser already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting after a fresh trace. Empirically the first envelope does shadow a later one: a string with a leading 'Example:' tool-calls-begin ... tool-calls-end envelope containing non-call text, followed by a real tool-calls-begin / call-begin web_search / sep / json / call-end / tool-calls-end envelope, parses to []. But this is unreachable on legitimate single-format DeepSeek output. Per the DeepSeek-V3.1 model card, one assistant turn emits a SINGLE tool-calls-begin ... tool-calls-end envelope and chains multiple calls directly INSIDE it with no separators; it does not emit two envelopes, and those section markers are special tokens the model produces only around real calls, never as a prose 'Example:' envelope. I verified the controls: a single real envelope parses to web_search and two real calls in one envelope parse to a and b. The only way a first envelope yields zero calls is a quoted-example or malformed-markup first envelope, both reject families. The Kimi-parity argument is a code-symmetry preference, not a reachable single-format correctness bug. Below the STRICT BAR. Source: DeepSeek-V3.1 model card.
| if _GEMMA_TC_RE.search(content): | ||
| return out |
There was a problem hiding this comment.
Parse leading wrapper-less Gemma before wrapped examples
This unconditional defer fires when a wrapped Gemma marker appears anywhere in the text, even inside or after an enabled leading wrapper-less Gemma call. In that case the leading-call guard invokes _parse_gemma_tool_calls, gets an empty result, and the later tool_healing pass can promote the quoted/trailing wrapped example instead (for example executing evil from a <|tool_call>call:evil... string inside call:web_search{query:"..."}). Only defer to the wrapped parser when the wrapped opener actually precedes the wrapper-less call being considered.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting after a fresh trace. Empirically parse of a leading bare call:web_search{...} whose argument value quotes a wrapped Gemma tool_call marker followed by call:evil{} returns evil, a wrong tool, because _parse_gemma_tool_calls defers unconditionally whenever any wrapped Gemma tool_call literal is present and tool_healing then promotes the quoted inner call. But that input mixes two mutually exclusive Gemma decode modes and cannot arise in a real single-format stream. Gemma's tool_call wrapper is a dedicated special/control token (Google Gemma 4 function-calling docs). With skip_special_tokens=True the whole sequence is decoded uniformly, so a bare-form leading call:web_search{...} carries NO wrapped tool_call literal anywhere in its arguments; with skip_special_tokens=False the leading call is ITSELF wrapped and tool_healing parses it correctly. A bare leading call plus a wrapped tool_call literal inside its argument is mixed-mode / quoted-example, unlike the FOREIGN markup (Qwen tool_call, Mistral trigger, Kimi markers) the ownership guards already handle, which can legitimately survive as literal text. This is the already-rejected :1726 / :831 Gemma-ordering family. Below the STRICT BAR. Source: ai.google.dev Gemma 4 function calling.
| if m is not None and m.start() < first_marker.start(): | ||
| return True |
There was a problem hiding this comment.
Do not let XML examples suppress later marker calls
This guard treats any closed outer XML span before the first DeepSeek/Kimi marker as owning the turn, even when that span is just prose that no parser will turn into a call. With text like <tool_call>not a call</tool_call> <|tool▁calls▁begin|>...real call..., the pre-pass is skipped, tool_healing returns no call for the example, and the later valid DeepSeek/Kimi call is never parsed; only parseable outer calls should block the marker pre-pass.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejecting after a fresh trace. Empirically parse of a leading closed Qwen/Hermes tool_call span containing non-call text ('not a call'), followed by a real DeepSeek tool-calls-begin / call-begin web_search envelope, returns [] (the Kimi variant too), so the closed foreign span does shadow the marker pre-pass. But for the guard to fire on a NON-call span the content must contain a foreign Qwen/Hermes tool_call, function-xml, or wrapped-Gemma span BEFORE a DeepSeek or Kimi marker. Those XML tags are not DeepSeek or Kimi tokens, so in a real single-format DeepSeek or Kimi session they can appear only as a quoted example of a foreign tool-call dialect. On genuine single-format marker output there is no foreign XML span, so the guard never fires on a non-call span and no real marker call is ever lost. This is the cross-format quoted-example family; the guard deliberately lets a closed outer envelope own the turn to protect a real outer call's arguments and trailing examples. Below the STRICT BAR.
commented
Jul 6, 2026
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
DRAFT - do not merge. Stacked on PR #5620 (Llama-3 / Mistral / Gemma 4 + healing parity). Validate against real models before merging.