Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop re-stripping the whole turn per token once tool markup is open (#16118)
Daniel Hanc45c140927c6
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex ec579d9d305..d227b4d1997 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -1425,16 +1425,21 @@ _OPEN_CALL_TRIGGERS = ()_OPEN_CALL_TRIGGER_MAX_LEN = max(len(trigger) for trigger in _OPEN_CALL_TRIGGERS)_OPEN_CALL_WS_RE = re.compile(r"\s*")+# ``<function=NAME>`` (bare or inside ``<tool_call>``) closes at ``</function>``; other bodies get the same set.+_OPEN_BODY_TRIGGERS = _OPEN_CALL_TRIGGERS + ("</function",)+_OPEN_BODY_TRIGGER_MAX_LEN = max(len(trigger) for trigger in _OPEN_BODY_TRIGGERS)+# The scanner's opener without its trailing ``\s*``, so the body starts at a fixed offset.+_OPEN_FUNCTION_OPENER_RE = re.compile(r'<function(?:=[\w\.\-]+|\s+name="[\w\.\-]+")>')def _promotable_gemma_call_pos(text: str, start: int, enabled_tool_names) -> int:"""The sentinel find is exact, not a heuristic: sweeping call-free prose per chunk was quadratic."""- start = text.find(_GEMMA_BARE_SENTINEL, start)- if start < 0:- return -1- for m in _GEMMA_BARE_TC_RE.finditer(text, start):+ # Every match starts with the literal: same matches as ``finditer``, without sweeping the buffer per chunk.+ m = _search_from_literal(_GEMMA_BARE_TC_RE, _GEMMA_BARE_SENTINEL, text, start)+ while m is not None:if _markerless_promotable(m.group(1), enabled_tool_names):return m.start()+ m = _search_from_literal(_GEMMA_BARE_TC_RE, _GEMMA_BARE_SENTINEL, text, m.end())return -1@@ -1549,6 +1554,7 @@ class StreamingMarkupStripper:"_gate_out","_gate_dead","_gate_from",+ "_gate_triggers","_gate_scanned","_gate_call_ws",)@@ -1586,6 +1592,7 @@ class StreamingMarkupStripper:# (floor, first) the gate can never arm for; append-only growth cannot undo its reason.self._gate_dead = Noneself._gate_from = 0+ self._gate_triggers = _OPEN_CALL_TRIGGERSself._gate_scanned = 0# Where a ``call`` followed only by whitespace so far resumes its colon check, else -1.self._gate_call_ws = -1@@ -1593,10 +1600,16 @@ class StreamingMarkupStripper:def _gate_clean(self, text: str) -> bool:"""Scan only text appended since the last call (plus an overlap) for anything that could change the strip."""n = len(text)- lo = self._gate_scanned - _OPEN_CALL_TRIGGER_MAX_LEN + 1+ triggers = self._gate_triggers+ overlap = (+ _OPEN_CALL_TRIGGER_MAX_LEN+ if triggers is _OPEN_CALL_TRIGGERS+ else _OPEN_BODY_TRIGGER_MAX_LEN+ )+ lo = self._gate_scanned - overlap + 1if lo < self._gate_from:lo = self._gate_from- for trigger in _OPEN_CALL_TRIGGERS:+ for trigger in triggers:if text.find(trigger, lo) >= 0:return Falseat = self._gate_call_ws@@ -1621,20 +1634,17 @@ class StreamingMarkupStripper:return Truedef _gate_try_arm(self, text: str, seg_start: int, out: str, seg_out: str):- """Arm when ``text[seg_start:]`` is ``P + <tool_call> + B``: P without ``<``, ``[``, ``{``, ``call\\s*:``;- B starting ``\\s*{`` without a trigger or ``call\\s*:``. Then only ``<tool_call>.*$`` matches (the masking- walk stops at the opener, GLM needs a name, every other arm needs a ``<`` or ``[`` in P), so the segment- strips to P (``seg_final``) or itself, and so do the cut decisions, until a trigger arrives."""+ """Arm on ``text[seg_start:]`` = ``P + O + B``: P without ``<``, ``[``, ``{``, ``call\\s*:``; O ``<tool_call>``+ and/or ``<function=NAME>``; B without a trigger or ``call\\s*:``. Arms reaching past O run to the end, the rest+ need ``<`` or ``[`` in P, so the segment strips to P (``seg_final``) or itself until a trigger arrives."""key = (self._floor, self._first)if self._gate_dead == key:returnstart = self._floor + self._firstprefix = text[seg_start:start]- body = start + len(_OPEN_CALL_OPENER)if (- not text.startswith(_OPEN_CALL_OPENER, start)# ``<param`` in the kept head makes the cut depend on later text (``_inside_open_parameter``).- or text.find("<param", self._floor, seg_start) >= 0+ text.find("<param", self._floor, seg_start) >= 0or "<" in prefixor "[" in prefixor "{" in prefix@@ -1645,14 +1655,39 @@ class StreamingMarkupStripper:):self._gate_dead = keyreturn- brace = _OPEN_CALL_WS_RE.match(text, body).end()- if brace == len(text):- return+ triggers = _OPEN_BODY_TRIGGERS+ if text.startswith(_OPEN_CALL_OPENER, start):+ body = start + len(_OPEN_CALL_OPENER)+ nxt = _OPEN_CALL_WS_RE.match(text, body).end()+ if nxt == len(text):+ return+ if text[nxt] == "{":+ triggers = _OPEN_CALL_TRIGGERS+ elif text[nxt] == "<":+ fn = _OPEN_FUNCTION_OPENER_RE.match(text, nxt)+ if fn is not None:+ body = fn.end()+ elif text.find(">", nxt) < 0:+ # Possibly a ``<function=NAME>`` still arriving.+ return+ else:+ fn = _OPEN_FUNCTION_OPENER_RE.match(text, start)+ if fn is None:+ rest = len(text) - start+ if text.find(">", start) < 0 and (+ (rest < len(_OPEN_CALL_OPENER) and _OPEN_CALL_OPENER.startswith(text[start:]))+ or text.startswith("<function", start)+ ):+ return+ self._gate_dead = key+ return+ body = fn.end()# Fail closed if the full strip just run disagrees with the reasoning above.- if text[brace] != "{" or seg_out != (prefix if self._seg_final else text[seg_start:]):+ if seg_out != (prefix if self._seg_final else text[seg_start:]):self._gate_dead = keyreturnself._gate_from = body+ self._gate_triggers = triggersself._gate_scanned = bodyself._gate_call_ws = -1if not self._gate_clean(text):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex aeff22ebf9c..fc7a1c671f8 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -6629,15 +6629,45 @@ _DISPLAY_GEMMA_CALL_RE = _re.compile(r"(?<!\w)call\s*:")_DISPLAY_GEMMA_TAIL_RE = _re.compile(r"(?<!\w)c(?:a(?:l(?:l\s*)?)?)?\Z")+# After the first sentinel: ``P + O + B`` with P free of ``<``, ``[``, ``{`` and ``call:``, O one of these openers.+_DISPLAY_HOLD_OPENER_RE = _re.compile(+ r'<tool_call>(?:\s*<function(?:=[\w.\-]+|\s+name="[\w.\-]+")>)?'+ r'|<function(?:=[\w.\-]+|\s+name="[\w.\-]+")>'+)+# Every sentinel but ``</param`` (its end-anchored arm loses to the match at O), plus think and GLM argument tags.+_DISPLAY_HOLD_TRIGGERS = tuple(+ dict.fromkeys(+ tuple(s for s in _DISPLAY_STRIP_SENTINELS if s != "</param")+ + ("<think", "</think", "[THINK", "[/THINK", "<arg_key", "<arg_value", "</arg_value")+ )+)+_DISPLAY_HOLD_OVERLAP = max(len(trigger) for trigger in _DISPLAY_HOLD_TRIGGERS) - 1+# The longest text after a backtick that ``tool_healing.tag_mention_spans`` could still close as a lone-tag mention.+_DISPLAY_HOLD_MENTION_TAG_RE = _re.compile(r"<[^<>`\n]*>?[\w.\-]*[ \t]*")++class _StreamingDisplayStrip:"""``_strip_tool_xml_for_display`` for a cumulative buffer that grows one token at a time.- The full strip rescans the whole buffer per call, quadratic over a turn on the event loop. No arm can edit- text holding none of ``_DISPLAY_STRIP_SENTINELS`` and no ``call:``, so such a buffer is returned as is and the- scan resumes where it stopped. After a sentinel the full strip runs on every call, as before.+ No arm edits text holding no ``_DISPLAY_STRIP_SENTINELS`` and no ``call:``, so such a buffer is returned as is.+ After a sentinel it holds at P while the buffer is ``P + O + B`` (P free of ``<``, ``[``, ``{``, ``call:``; O an+ opener in ``_DISPLAY_HOLD_OPENER_RE``; B free of ``_DISPLAY_HOLD_TRIGGERS`` and ``call:``): every arm either runs+ from O to the end or needs a ``<`` or ``[`` before O. Arms only once the full strip returned exactly P."""- __slots__ = ("_auto_heal", "_names", "_prev", "_scanned", "_gemma_from", "_marked")+ __slots__ = (+ "_auto_heal",+ "_names",+ "_prev",+ "_scanned",+ "_gemma_from",+ "_marked",+ "_hold_out",+ "_hold_dead",+ "_hold_from",+ "_hold_scanned",+ "_hold_gemma_from",+ )def __init__(self,@@ -6654,6 +6684,11 @@ class _StreamingDisplayStrip:self._scanned = 0self._gemma_from = 0self._marked = False+ self._hold_out = None+ self._hold_dead = False+ self._hold_from = 0+ self._hold_scanned = 0+ self._hold_gemma_from = 0def _has_sentinel(self, text: str) -> bool:start = max(0, self._scanned - _DISPLAY_SENTINEL_OVERLAP)@@ -6667,6 +6702,73 @@ class _StreamingDisplayStrip:self._scanned = len(text)return False+ def _hold_clean(self, text: str) -> bool:+ """No trigger and no ``call:`` in B, scanning only what was appended since the last call."""+ lo = max(self._hold_from, self._hold_scanned - _DISPLAY_HOLD_OVERLAP)+ if any(text.find(trigger, lo) >= 0 for trigger in _DISPLAY_HOLD_TRIGGERS):+ return False+ if _DISPLAY_GEMMA_CALL_RE.search(text, self._hold_gemma_from) is not None:+ return False+ tail = _DISPLAY_GEMMA_TAIL_RE.search(+ text, max(self._hold_gemma_from, len(text.rstrip()) - 4)+ )+ self._hold_gemma_from = tail.start() if tail is not None else len(text)+ self._hold_scanned = len(text)+ return True++ def _try_hold(self, text: str, out: str) -> None:+ first = min(+ (at for at in (text.find(s) for s in _DISPLAY_STRIP_SENTINELS) if at >= 0),+ default = -1,+ )+ if first < 0:+ self._hold_dead = True+ return+ prefix = text[:first]+ if (+ "<" in prefix+ or "[" in prefix+ or "{" in prefix+ or _DISPLAY_GEMMA_CALL_RE.search(prefix) is not None+ ):+ self._hold_dead = True+ return+ if prefix.rstrip(" \t").endswith("`"):+ # A backticked tag followed by its closing backticks is a mention the strip keeps; wait until B rules it out.+ tag = _DISPLAY_HOLD_MENTION_TAG_RE.match(text, first)+ if tag is not None and tag.end() == len(text):+ return+ if tag is not None and text[tag.end()] == "`":+ self._hold_dead = True+ return+ opener = _DISPLAY_HOLD_OPENER_RE.match(text, first)+ if opener is not None and opener.group().endswith("<tool_call>"):+ # A wrapped ``<function=NAME>`` may still be arriving after the whitespace.+ nxt = opener.end()+ while nxt < len(text) and text[nxt].isspace():+ nxt += 1+ if nxt == len(text) or (text[nxt] == "<" and text.find(">", nxt) < 0):+ return+ if opener is None:+ # ``<tool_call`` or ``<function=NA`` still arriving.+ if text.find(">", first) < 0 and (+ text.startswith("<function", first)+ or (len(text) - first < 11 and "<tool_call>".startswith(text[first:]))+ ):+ return+ self._hold_dead = True+ return+ if out != prefix:+ self._hold_dead = True+ return+ self._hold_from = opener.end()+ self._hold_scanned = opener.end()+ self._hold_gemma_from = opener.end()+ if not self._hold_clean(text):+ self._hold_dead = True+ return+ self._hold_out = out+def strip(self, text: str) -> str:if not self._auto_heal:return text@@ -6677,11 +6779,19 @@ class _StreamingDisplayStrip:self._marked = Trueif not self._marked:return text- return _strip_tool_xml_for_display(+ if self._hold_out is not None:+ if self._hold_clean(text):+ return self._hold_out+ self._hold_out = None+ self._hold_dead = True+ out = _strip_tool_xml_for_display(text,auto_heal_tool_calls = True,enabled_tool_names = self._names,)+ if not self._hold_dead:+ self._try_hold(text, out)+ return outclass _ReasoningSpanGuard:@@ -6704,6 +6814,8 @@ class _ReasoningSpanGuard:self._consumed = 0self._turn_wrap = Noneself._claimed = False+ self._display = None+ self._display_key = None@propertydef claimed(self) -> bool:@@ -6752,19 +6864,30 @@ class _ReasoningSpanGuard:wrapped_so_far = None,) -> str:wrap = self._wrap_for(text, wrapped_so_far)+ display = self._display_strip(auto_heal_tool_calls, enabled_tool_names)if wrap is None:- return _strip_tool_xml_for_display(- text,+ return display.strip(text)+ # Clamp: mid-stream the close tag has not arrived yet, so the whole text is trace.+ end = min(len(self._OPEN) + int(wrap.get("len", 0)) + len(self._CLOSE), len(text))+ return text[:end] + display.strip(text[end:])++ def _display_strip(+ self, auto_heal_tool_calls: bool, enabled_tool_names+ ) -> "_StreamingDisplayStrip":+ """Returns exactly ``_strip_tool_xml_for_display`` for any input; a buffer that does not extend the last+ one resets it, so a new turn or a moved span start is handled."""+ key = (bool(auto_heal_tool_calls), enabled_tool_names)+ if self._display is None or self._display_key != key:+ self._display = _StreamingDisplayStrip(auto_heal_tool_calls = auto_heal_tool_calls,enabled_tool_names = enabled_tool_names,)- # Clamp: mid-stream the close tag has not arrived yet, so the whole text is trace.- end = min(len(self._OPEN) + int(wrap.get("len", 0)) + len(self._CLOSE), len(text))- return text[:end] + _strip_tool_xml_for_display(- text[end:],- auto_heal_tool_calls = auto_heal_tool_calls,- enabled_tool_names = enabled_tool_names,- )+ # A copy: the caller's set may change between events.+ self._display_key = (+ key[0],+ None if enabled_tool_names is None else frozenset(enabled_tool_names),+ )+ return self._displaydef _strip_tool_xml(text: str, enabled_tool_names: Optional[set] = None) -> str:diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex a5001282933..368d59adfe2 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -1134,6 +1134,7 @@"_MISTRAL_V11_NAME_RE": "'\\\\s*([\\\\w\\\\.\\\\-]+)\\\\s*' flags=32","_ONE_STRING_ARG_CALL_RE": "'\\\\A\\\\s*\\\\{\\\\s*\"name\"\\\\s*:\\\\s*\"([\\\\w.\\\\-]+)\"\\\\s*,\\\\s*\"(?:arguments|parameters)\"\\\\s*:\\\\s*\\\\{\\\\s*\"([A-Za-z_][\\\\w\\\\-]*)\"\\\\s*:\\\\s*\"(.*)\"\\\\s*\\\\}\\\\s*\\\\}\\\\s*\\\\Z' flags=48","_OPEN_CALL_WS_RE": "'\\\\s*' flags=32",+ "_OPEN_FUNCTION_OPENER_RE": "'<function(?:=[\\\\w\\\\.\\\\-]+|\\\\s+name=\"[\\\\w\\\\.\\\\-]+\")>' flags=32","_OUTER_ENVELOPE_CLOSED_PATS[0]": "'<tool_call>(?:(?!<tool_call>).)*</tool_call>' flags=48","_OUTER_ENVELOPE_CLOSED_PATS[1]": "'<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>(?:(?!<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>).)*</function>' flags=48","_OUTER_ENVELOPE_CLOSED_PATS[2]": "'<\\\\|tool_call>.*?<tool_call\\\\|>' flags=48",@@ -1196,6 +1197,7 @@"re.compile('<function(?:=([\\\\w\\\\.\\\\-]+)|\\\\s+name=\"([\\\\w\\\\.\\\\-]+)\")>\\\\s*')": 1,"re.compile('<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>(?:(?!<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>).)*</function>', re.DOTALL)": 1,"re.compile('<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>.*$', re.DOTALL)": 1,+ "re.compile('<function(?:=[\\\\w\\\\.\\\\-]+|\\\\s+name=\"[\\\\w\\\\.\\\\-]+\")>')": 1,"re.compile('<function\\\\s+name=\"')": 1,"re.compile('<tool_call>(?:(?!<tool_call>).)*</tool_call>', re.DOTALL)": 1,"re.compile('<tool_call>.*$', re.DOTALL)": 1,@@ -1562,6 +1564,12 @@"_ONE_STRING_ARG_CALL_RE": {"kind": "assign"},+ "_OPEN_BODY_TRIGGERS": {+ "kind": "assign"+ },+ "_OPEN_BODY_TRIGGER_MAX_LEN": {+ "kind": "assign"+ },"_OPEN_CALL_OPENER": {"kind": "assign"},@@ -1574,6 +1582,9 @@"_OPEN_CALL_WS_RE": {"kind": "assign"},+ "_OPEN_FUNCTION_OPENER_RE": {+ "kind": "assign"+ },"_OUTER_ENVELOPE_CLOSED_PATS": {"kind": "assign"},diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex 0f7753108b1..702463fdd12 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -95,10 +95,13 @@"_MISTRAL_TRIGGER","_MISTRAL_V11_NAME_RE","_ONE_STRING_ARG_CALL_RE",+ "_OPEN_BODY_TRIGGERS",+ "_OPEN_BODY_TRIGGER_MAX_LEN","_OPEN_CALL_OPENER","_OPEN_CALL_TRIGGERS","_OPEN_CALL_TRIGGER_MAX_LEN","_OPEN_CALL_WS_RE",+ "_OPEN_FUNCTION_OPENER_RE","_OUTER_ENVELOPE_CLOSED_PATS","_OUTER_ENVELOPE_OPEN_RE","_REPEAT_LEAD_PUNCT",diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex d04d91e26cf..33e7beda062 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -2041,7 +2041,8 @@ class TestAnthropicToolNonStreaming:monkeypatch.setattr(inf_mod, "_strip_tool_xml_for_display", _slow_strip)def _run_gen():- yield {"type": "content", "text": "ok"}+ # Carries markup: an event without any is returned as is and never reaches the full strip.+ yield {"type": "content", "text": "ok </tool_call>"}async def _run():task = asyncio.create_task(diff --git a/studio/backend/tests/test_stream_strip_open_markup.py b/studio/backend/tests/test_stream_strip_open_markup.pynew file mode 100644index 00000000000..e340e132555--- /dev/null+++ b/studio/backend/tests/test_stream_strip_open_markup.py@@ -0,0 +1,370 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Streaming display strips stay output-identical to the full strip on every prefix, without re-stripping+the whole turn per token once an open call or a markup mention is in it.++Three per-token strips are covered: the generator's ``StreamingMarkupStripper`` (its open-call gate now also+takes ``<function=NAME>`` bodies and non-JSON ``<tool_call>`` bodies), the route's ``_StreamingDisplayStrip``+(holds ``P + <tool_call>|<function=NAME> + B`` at P), and ``_ReasoningSpanGuard`` (the Messages API strip, which+used to run the full strip on every content event)."""++import random+import sys+from pathlib import Path++import pytest++BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(BACKEND_ROOT))++from core.inference import tool_call_parser as parser # noqa: E402+from core.inference.tool_call_parser import StreamingMarkupStripper # noqa: E402+from routes import inference # noqa: E402+from routes.inference import ( # noqa: E402+ _ReasoningSpanGuard,+ _StreamingDisplayStrip,+ _strip_tool_xml_for_display,+)++ENABLED = {"web_search", "python", "terminal", "write_file"}+NAME_GATES = (ENABLED, None, set())+++class _FullStripEveryToken(StreamingMarkupStripper):+ """The generator stripper with its open-call gate off: every token strips the open tail."""++ __slots__ = ()++ def _gate_try_arm(self, *args):+ return None+++class _FullSpanGuard(_ReasoningSpanGuard):+ """The span guard as it was: the full display strip on every event."""++ def _display_strip(self, auto_heal_tool_calls, enabled_tool_names):+ class _Full:+ @staticmethod+ def strip(text):+ return _strip_tool_xml_for_display(+ text,+ auto_heal_tool_calls = auto_heal_tool_calls,+ enabled_tool_names = enabled_tool_names,+ )++ return _Full+++_CODE = (+ "def area(r):\n return 3.14159 * r * r # a < b and c > d\n\n"+ "for i in range(10):\n print(i, area(i), {'k': [i]})\n"+)+_PREFIXES = (+ "",+ "I'll write the file now.\n\n",+ "Sure. ",+ "To call a tool the model wraps JSON in a `",+ "x `y` z\n",+ "call me maybe ",+ " \n",+ "a [link](x) ",+ "brace {x} ",+ "<think>plan it</think>\n",+ "</think>stray ",+ "<parameter=x>v\n",+ "call :",+ "```xml\n",+ "中文 ",+)+_OPENERS = (+ "<tool_call>",+ "<tool_call>\n",+ "<tool_call>\n<function=write_file>\n",+ "<tool_call><function=python>",+ "<function=write_file>\n",+ '<function name="python">',+ "<function=nope>\n",+ "<tool_call>web_search\n",+ '<tool_call>\n{"name": "write_file", "arguments": {"content": "',+ "` tag and ",+)+_BODY_PIECES = (+ "<parameter=path>\nsrc/a.py\n</parameter>\n",+ "<parameter=content>\n",+ _CODE,+ "word ",+ "\n",+ "<",+ "</",+ "<div>",+ "a < b ",+ "{",+ "}",+ "[",+ "]",+ ":",+ "call",+ "call ",+ " :",+ "recall: ",+ "`",+ "```",+ "\\n",+ '\\"',+ "<arg_key>q</arg_key>\n<arg_value>x</arg_value>\n",+ "</parameter>",+ "</param>",+ "<param",+ "中文",+)+_TRIGGER_PIECES = (+ "</function>",+ "</tool_call>",+ "<tool_call>",+ "<function=python>",+ "<|tool_call>call:web_search{q:1}<tool_call|>",+ "[TOOL_CALLS]",+ '[TOOL_CALLS]web_search{"q": 1}',+ "web_search[ARGS]{}",+ "x[ARGS]{",+ "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>python",+ "<|tool▁calls▁end|>",+ "<|tool_calls_section_begin|><|tool_call_begin|>functions.python:0 {}<|tool_call_end|>",+ "<|python_tag|>print(1)",+ "<|content_invoke_tool_json|>",+ "<think>",+ "</think>",+ "[THINK]",+ "[/THINK]",+ "call:web_search{q:1}",+ "call \n\t :python{code:1}",+ "<|channel|>commentary to=functions.python <|message|>{}<|call|>",+ '<minimax:tool_call>\n<invoke name="python">\n<parameter name="code">1</parameter>\n</invoke>\n',+ "</minimax:tool_call>",+ "[/TOOL_CALLS]",+)+_ENDINGS = (+ "",+ "\n</function>\n</tool_call>",+ "\n</parameter>\n</function>\n</tool_call>\nDone.",+ '"}}\n</tool_call> then prose',+ "</tool_call> and <tool_call>\n<function=python>\n<parameter=code>\nx",+ " the end.",+)+++def _corpus(rng: random.Random, n: int):+ for _ in range(n):+ text = rng.choice(_PREFIXES) + rng.choice(_OPENERS)+ trigger_rate = rng.choice((0.0, 0.0, 0.02, 0.1))+ for _ in range(rng.randint(2, 30)):+ pool = _TRIGGER_PIECES if rng.random() < trigger_rate else _BODY_PIECES+ text += rng.choice(pool)+ yield text + rng.choice(_ENDINGS)+++def _prefixes(text: str, rng: random.Random):+ cut = 0+ while cut < len(text):+ cut = min(len(text), cut + rng.choice((1, 2, 3, 4, 5, 6, 8, 16)))+ yield text[:cut]+++def test_generator_strip_matches_on_every_prefix():+ rng = random.Random(20261030)+ engaged = 0+ for text in _corpus(rng, 120):+ for names in NAME_GATES:+ for seg_final in (True, False):+ gated = StreamingMarkupStripper(names, seg_final = seg_final)+ full = _FullStripEveryToken(names, seg_final = seg_final)+ for prefix in _prefixes(text, rng):+ was_on = gated._gate_on+ assert gated.strip(prefix) == full.strip(prefix), (text, len(prefix))+ engaged += was_on and gated._gate_on+ assert engaged > 3000, engaged+++def test_route_display_strip_matches_on_every_prefix():+ rng = random.Random(20261031)+ held = 0+ for text in _corpus(rng, 150):+ for names in NAME_GATES:+ strip = _StreamingDisplayStrip(auto_heal_tool_calls = True, enabled_tool_names = names)+ for prefix in _prefixes(text, rng):+ was_held = strip._hold_out is not None+ assert strip.strip(prefix) == _strip_tool_xml_for_display(+ prefix, auto_heal_tool_calls = True, enabled_tool_names = names+ ), (text, len(prefix))+ held += was_held and strip._hold_out is not None+ assert held > 2000, held+++def test_span_guard_matches_the_full_strip_across_turns():+ rng = random.Random(20261101)+ texts = list(_corpus(rng, 40))+ for names in NAME_GATES:+ for prov in (None, {"wrapped": 2, "wraps": [{"len": 9}, {"len": 4}]}):+ guard, ref = _ReasoningSpanGuard(prov), _FullSpanGuard(prov)+ for turn, text in enumerate(texts[:6]):+ if turn:+ guard.tool_end()+ ref.tool_end()+ if prov is not None and turn < 2:+ text = "<think>" + "r" * (9 if turn == 0 else 4) + "</think>" + text+ for prefix in _prefixes(text, rng):+ kwargs = {"auto_heal_tool_calls": True, "enabled_tool_names": names}+ assert guard.strip(prefix, **kwargs) == ref.strip(prefix, **kwargs), (+ text,+ len(prefix),+ )+ assert _ReasoningSpanGuard().strip("a <tool_call>b", auto_heal_tool_calls = False) == (+ "a <tool_call>b"+ )+++def _count_route_strips(monkeypatch):+ calls = [0]+ real = inference._strip_tool_xml_for_display++ def _counting(*args, **kwargs):+ calls[0] += 1+ return real(*args, **kwargs)++ monkeypatch.setattr(inference, "_strip_tool_xml_for_display", _counting)+ return calls+++def _write_file_stream(tokens: int, prefix: str = "I'll write it.\n\n"):+ text = prefix + "<tool_call>\n<function=write_file>\n<parameter=path>\na.py\n</parameter>\n"+ text += "<parameter=content>\n" + _CODE * (tokens // 20 + 1)+ out, cut = [], len(prefix) + 1+ while len(out) < tokens:+ cut += 4+ out.append(text[:cut])+ return out+++def test_function_xml_write_file_is_not_restripped_per_token():+ seen = {}+ for tokens in (300, 2000):+ calls = [0, 0]++ class _Counting(StreamingMarkupStripper):+ __slots__ = ()++ def _full_strip(self, text):+ calls[0] += 1+ calls[1] += len(text)+ return super()._full_strip(text)++ for seg_final in (True, False):+ stripper = _Counting(ENABLED, seg_final = seg_final)+ full = _FullStripEveryToken(ENABLED, seg_final = seg_final)+ for prefix in _write_file_stream(tokens):+ assert stripper.strip(prefix) == full.strip(prefix)+ seen[tokens] = tuple(calls)+ assert seen[300] == seen[2000], seen+ assert seen[2000][0] < 80, seen+++ "prefix",+ ["To call a tool the model wraps JSON in a `", "I'll write it.\n\n", ""],+)+def test_route_holds_an_open_call_or_mention_to_the_end(monkeypatch, prefix):+ calls = _count_route_strips(monkeypatch)+ seen = {}+ for tokens in (300, 2000):+ calls[0] = 0+ strip = _StreamingDisplayStrip(auto_heal_tool_calls = True, enabled_tool_names = ENABLED)+ for text in _write_file_stream(tokens, prefix):+ got = strip.strip(text)+ seen[tokens] = calls[0]+ assert got == prefix+ assert seen[300] == seen[2000] < 40, seen+++def test_route_hold_releases_on_the_close_split_at_every_offset():+ body = "Writing.\n<tool_call>\n<function=write_file>\n<parameter=content>\n" + _CODE * 3+ close = "</parameter>\n</function>\n</tool_call>\nDone."+ for split in range(1, len(close)):+ for names in NAME_GATES:+ strip = _StreamingDisplayStrip(auto_heal_tool_calls = True, enabled_tool_names = names)+ text = body+ for piece in list("pad words ") + [close[:split], close[split:]]:+ text += piece+ assert strip.strip(text) == _strip_tool_xml_for_display(+ text, auto_heal_tool_calls = True, enabled_tool_names = names+ ), split+ assert strip.strip(text) == "Writing.\n\nDone."+++ "text",+ [+ "Use `<tool_call>` to call a tool.",+ "Use ``<tool_call>` `` here, then more prose follows.",+ "Name it `<function=web_search>` and wait.",+ "Wrap it: ` <function=python> `\n<tool_call>\n<function=python>\n<parameter=code>\n1\n",+ ],+)+def test_route_hold_does_not_arm_on_a_backticked_tag(text):+ # A tag closed by backticks is a mention a mention-aware strip keeps, so the hold must not pin the display.+ for names in NAME_GATES:+ strip = _StreamingDisplayStrip(auto_heal_tool_calls = True, enabled_tool_names = names)+ for cut in range(1, len(text) + 1):+ prefix = text[:cut]+ assert strip.strip(prefix) == _strip_tool_xml_for_display(+ prefix, auto_heal_tool_calls = True, enabled_tool_names = names+ ), (text, cut)+ assert strip._hold_out is None, (text, cut)+++def test_span_guard_skips_the_full_strip_on_plain_prose(monkeypatch):+ calls = _count_route_strips(monkeypatch)+ guard = _ReasoningSpanGuard()+ text = ""+ for i in range(2000):+ text += f"word{i} "+ assert guard.strip(text, auto_heal_tool_calls = True, enabled_tool_names = ENABLED) == text+ assert calls[0] == 0+++def test_gemma_scan_finds_what_finditer_finds():+ """Literal-anchored scan used by ``_needs_whole_buffer``; same first promotable match as the regex sweep."""++ def _reference(text, start, names):+ start = text.find(parser._GEMMA_BARE_SENTINEL, start)+ if start < 0:+ return -1+ for m in parser._GEMMA_BARE_TC_RE.finditer(text, start):+ if parser._markerless_promotable(m.group(1), names):+ return m.start()+ return -1++ rng = random.Random(7)+ alphabet = (+ "call",+ "call:",+ "call :",+ ":",+ "x",+ "web_search",+ "python",+ "{",+ " ",+ "re",+ ".",+ "-",+ "\n",+ )+ for _ in range(3000):+ text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 24)))+ start = rng.randint(0, len(text))+ for names in NAME_GATES:+ assert parser._promotable_gemma_call_pos(text, start, names) == _reference(+ text, start, names+ ), (text, start)