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: keep <function=...> tool-call parsing linear on long output (#16105)
Daniel Hancc9525ae8ed0
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex d227b4d1997..31ab1a22e44 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -886,8 +886,11 @@ def _inference_wrapper_spans(text: str) -> list:spans.append((m.end(), len(text) if end is None else end))# Attribute-form calls have no JSON body; protect the element interior so a genuine call's# arguments are not masked.+ close = -2 # Not yet sought, as ``brace`` above.for m in _ATTR_FUNC_OPEN_RE.finditer(text):- close = text.find("</function>", m.end())+ # Re-seek only once the close falls behind this opener; seeking per opener is quadratic.+ if close != -1 and close < m.end():+ close = text.find("</function>", m.end())spans.append((m.end(), len(text) if close < 0 else close))# A streaming Mistral array has no ``]`` yet but is still parsed; trust the envelope through EOS.pos = text.find(_MISTRAL_TRIGGER)@@ -1176,9 +1179,8 @@ def _strip_function_xml_calls(text: str, *, final: bool) -> str:"""Strip ``<function=...>`` calls by mirroring the parser: an opener inside an open``<parameter>`` is data and each call closes at its first ``</function>`` that is notparameter data; ``final`` drops a trailing unclosed call."""- starts = [- m for m in _TC_FUNC_START_RE.finditer(text) if not _inside_open_parameter(text, m.start())- ]+ inside = _tool_healing._OpenParameterIndex(text, **_OPEN_PARAMETER_TAGS).inside+ starts = [m for m in _TC_FUNC_START_RE.finditer(text) if not inside(m.start())]if not starts:return textout: list[str] = []@@ -1190,7 +1192,7 @@ def _strip_function_xml_calls(text: str, *, final: bool) -> str:next_start = starts[idx + 1].start() if idx + 1 < len(starts) else len(text)close = Nonefor cm in _FUNC_CLOSE_TAG_RE.finditer(text, m.end(), next_start):- if not _inside_open_parameter(text, cm.start()):+ if not inside(cm.start()):close = cm # first close that is not parameter data = the real closebreakif close is not None:@@ -2526,15 +2528,17 @@ _trim_param_value = _tool_healing._trim_param_value_json_object_body = _tool_healing._json_object_body+# Shared by the helper and ``_tool_healing._OpenParameterIndex`` so the two cannot drift.+_OPEN_PARAMETER_TAGS = {+ "param_start_re": _TC_PARAM_START_RE,+ "param_closers": ("</parameter>", "</param>"),+ "func_closers": ("</function>", "</tool_call>"),+}++def _inside_open_parameter(text: str, pos: int) -> bool:"""An opener inside an unclosed parameter block is a literal in an argument value, not a nested call."""- return _tool_healing._inside_open_parameter(- text,- pos,- param_start_re = _TC_PARAM_START_RE,- param_closers = ("</parameter>", "</param>"),- func_closers = ("</function>", "</tool_call>"),- )+ return _tool_healing._inside_open_parameter(text, pos, **_OPEN_PARAMETER_TAGS)def _parse_function_xml(@@ -2545,11 +2549,8 @@ def _parse_function_xml() -> list[dict]:out: list[dict] = []# Skip openers inside an open parameter value, else they become a second call.- func_starts = [- fm- for fm in _TC_FUNC_START_RE.finditer(content)- if not _inside_open_parameter(content, fm.start())- ]+ inside = _tool_healing._OpenParameterIndex(content, **_OPEN_PARAMETER_TAGS).inside+ func_starts = [fm for fm in _TC_FUNC_START_RE.finditer(content) if not inside(fm.start())]for idx, fm in enumerate(func_starts):# group(1) is ``<function=name>``, group(2) is ``<function name="...">``.func_name = fm.group(1) or fm.group(2)@@ -2558,7 +2559,7 @@ def _parse_function_xml(# The first close not inside an open parameter ends the call (mirrors _strip_function_xml_calls).close_match = Nonefor cm in _TC_END_TAG_RE.finditer(content, body_start, next_func):- if not _inside_open_parameter(content, cm.start()):+ if not inside(cm.start()):close_match = cmbreakhas_close = close_match is not None@@ -2576,10 +2577,9 @@ def _parse_function_xml(args: dict = {}param_unclosed = False# A ``<parameter>`` opener inside an open parameter value is literal text.+ body_inside = _tool_healing._OpenParameterIndex(body, **_OPEN_PARAMETER_TAGS).insideparam_starts = [- pm- for pm in _TC_PARAM_START_RE.finditer(body)- if not _inside_open_parameter(body, pm.start())+ pm for pm in _TC_PARAM_START_RE.finditer(body) if not body_inside(pm.start())]if len(param_starts) == 1:pm = param_starts[0]diff --git a/studio/backend/core/tool_healing.py b/studio/backend/core/tool_healing.pyindex 3103b6e94b5..20d835d04e9 100644--- a/studio/backend/core/tool_healing.py+++ b/studio/backend/core/tool_healing.py@@ -3,6 +3,7 @@from __future__ import annotationsimport bisect+import itertoolsimport jsonimport re@@ -200,6 +201,8 @@ _TC_PARAM_CLOSE_RE = re.compile(r"\s*</parameter>\s*$")_GEMMA_QUOTE = '<|"|>'_PARAM_CLOSE_TAG = "</parameter>"_FUNC_CLOSE_TAG = "</function>"+_WRAP_OPEN_RE = re.compile(r"<tool_call>\s*$")+_WRAP_CLOSE_RE = re.compile(r"\s*</tool_call>")# A comma not followed by a key token is part of a bare Gemma value (New York, NY)._GEMMA_NEXT_KEY_RE = re.compile(r"\s*[A-Za-z_][\w.\-]*\s*:")@@ -667,11 +670,100 @@ def _inside_open_parameter(return True-def _func_close_index(content: str, body_start: int, body: str) -> int:+# A few direct scans beat building an index on the per-token streaming strip; past them the index wins.+_OPEN_PARAMETER_SCAN_LIMIT = 16+++class _OpenParameterIndex:+ """``_inside_open_parameter`` for many offsets of one text by bisecting sorted tag offsets (per-call+ scans were quadratic). Valid only for ``<parameter``/``<param`` openers, as the reverse search is."""++ __slots__ = (+ "_content",+ "_param_start_re",+ "_param_closer_tags",+ "_func_closer_tags",+ "_scans",+ "_param_starts",+ "_param_ends",+ "_param_closers",+ "_func_closers",+ )++ def __init__(+ self,+ content: str,+ *,+ param_start_re = None,+ param_closers = (_PARAM_CLOSE_TAG,),+ func_closers = (_FUNC_CLOSE_TAG,),+ ):+ self._content = content+ self._param_start_re = _TC_PARAM_START_RE if param_start_re is None else param_start_re+ self._param_closer_tags = param_closers+ self._func_closer_tags = func_closers+ self._scans = 0+ self._param_starts = None++ def _build(self) -> None:+ content = self._content+ starts = [m.start() for m in self._param_start_re.finditer(content)]+ self._param_starts = starts+ # Bounded at the tag's own ">", as the helper's endpos-limited match is.+ self._param_ends = [content.index(">", start) + 1 for start in starts]+ self._param_closers = self._positions(content, self._param_closer_tags)+ self._func_closers = self._positions(content, self._func_closer_tags)++ @staticmethod+ def _positions(content: str, tags) -> list[int]:+ found: list[int] = []+ for tag in tags:+ at = content.find(tag)+ while at >= 0:+ found.append(at)+ at = content.find(tag, at + 1)+ return sorted(found)++ def inside(self, pos: int) -> bool:+ if self._param_starts is None:+ if self._scans < _OPEN_PARAMETER_SCAN_LIMIT:+ self._scans += 1+ return _inside_open_parameter(+ self._content,+ pos,+ param_start_re = self._param_start_re,+ param_closers = self._param_closer_tags,+ func_closers = self._func_closer_tags,+ )+ self._build()+ idx = bisect.bisect_right(self._param_ends, pos) - 1+ if idx < 0:+ return False+ last = self._param_starts[idx]+ closers = self._param_closers+ i = bisect.bisect_left(closers, last)+ if i < len(closers) and closers[i] <= pos:+ return False+ if closers and closers[-1] > pos:+ return True+ closers = self._func_closers+ i = bisect.bisect_left(closers, last)+ return not (i < len(closers) and closers[i] <= pos)+++def _func_close_index(+ content: str,+ body_start: int,+ body: str,+ *,+ inside = None,+) -> int:"""First close outside a parameter value; taking the last one swallowed prose after the real close."""+ if inside is None:+ inside = lambda pos: _inside_open_parameter(content, pos) # noqa: E731idx = body.find(_FUNC_CLOSE_TAG)while idx >= 0:- if not _inside_open_parameter(content, body_start + idx):+ if not inside(body_start + idx):return idxidx = body.find(_FUNC_CLOSE_TAG, idx + 1)return -1@@ -759,8 +851,9 @@ def _build_markers(content: str):many_candidates = len(candidates) > 1has_parameter = "<parameter=" in content if many_candidates else Truelast_brace = content.rfind("}") if many_candidates else None+ inside = _OpenParameterIndex(content).insidefor m, gemma, kind in candidates:- if has_parameter and _inside_open_parameter(content, m.start()):+ if has_parameter and inside(m.start()):continuebrace_start = m.end() - 1brace_end = (@@ -971,26 +1064,36 @@ def parse_tool_calls_from_text(continueparsed_items.append((start, span_end, name, arguments))+ inside = _OpenParameterIndex(content).inside+ # Coverage is start-sorted: a running max of ends answers each opener by bisect.+ coverage_starts = [s for s, _e in coverage]+ coverage_max_ends = list(itertools.accumulate((e for _s, e in coverage), max))++ def _covered(pos: int) -> bool:+ i = bisect.bisect_right(coverage_starts, pos) - 1+ return i >= 0 and pos < coverage_max_ends[i]+func_starts = [fmfor fm in _TC_FUNC_START_RE.finditer(content)- if not _inside_open_parameter(content, fm.start())+ if not inside(fm.start())and not _in_think(fm.start())and not _in_blocked(fm.start())- and not any(s <= fm.start() < e for s, e in coverage)+ and not _covered(fm.start())]for idx, fm in enumerate(func_starts):func_name = fm.group(1)body_start = fm.end()next_func = func_starts[idx + 1].start() if idx + 1 < len(func_starts) else len(content)- end_tag = _TC_END_TAG_RE.search(content[body_start:])+ # Bounded at the next opener, where body_end is capped anyway.+ end_tag = _TC_END_TAG_RE.search(content, body_start, next_func)if end_tag:- body_end = body_start + end_tag.start()+ body_end = end_tag.start()else:body_end = len(content)body_end = min(body_end, next_func)body = content[body_start:body_end]- close_idx = _func_close_index(content, body_start, body)+ close_idx = _func_close_index(content, body_start, body, inside = inside)if close_idx >= 0:span_end = body_start + close_idx + len(_FUNC_CLOSE_TAG)body = body[:close_idx]@@ -1040,11 +1143,14 @@ def parse_tool_calls_from_text(arguments = _json_object_body(body) or argumentsspan_start = fm.start()- wrap_open = re.search(r"<tool_call>\s*$", content[:span_start])- wrap_close = re.match(r"\s*</tool_call>", content[span_end:])+ ws_start = span_start+ while ws_start > 0 and content[ws_start - 1].isspace():+ ws_start -= 1+ wrap_open = _WRAP_OPEN_RE.search(content, max(0, ws_start - len("<tool_call>")), span_start)+ wrap_close = _WRAP_CLOSE_RE.match(content, span_end)if wrap_open and wrap_close:span_start = wrap_open.start()- span_end += wrap_close.end()+ span_end = wrap_close.end()parsed_items.append((span_start, span_end, func_name, json.dumps(arguments)))parsed_items.sort(key = lambda item: item[0])diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 368d59adfe2..cd508b7100d 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -1102,15 +1102,15 @@},"core.inference.tool_call_parser": {"compiled": {- "INTENT_SIGNAL": "\"(?im)(\\\\b(i['\\\\u2019](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall)\\\\b(?!\\\\s+(?:not|never)\\\\b)(?!\\\\s+(?:do(?:ing)?\\\\s+my\\\\s+best|try\\\\s+my\\\\s+best|be\\\\s+(?:able|happy|glad)\\\\s+to\\\\b|assist\\\\b|help\\\\s+you\\\\b(?!\\\\s+(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render))|give\\\\s+you\\\\s+accurate\\\\b|(?:dig\\\\s+in|help\\\\s+analy[sz]e)\\\\b(?=[^\\\\w]*\\\\Z)))|\\\\b(?:let me|allow me)\\\\b(?!\\\\s+(?:not|never|know)\\\\b)(?!\\\\s+(?:dig\\\\s+in|help\\\\s+analy[sz]e)\\\\b(?=[^\\\\w]*\\\\Z))(?!\\\\s+to\\\\s+(?:do(?:ing)?\\\\s+my\\\\s+best|try\\\\s+my\\\\s+best|be\\\\s+(?:able|happy|glad)\\\\s+to\\\\b|assist\\\\b|help\\\\s+you\\\\b(?!\\\\s+(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render))|give\\\\s+you\\\\s+accurate\\\\b|(?:dig\\\\s+in|help\\\\s+analy[sz]e)\\\\b(?=[^\\\\w]*\\\\Z)))|(?:^|[.!?]\\\\s+)\\\\s*(?:the\\\\s+)?first\\\\s+step\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:–—-]?\\\\s+(?:my|our)\\\\s+(?:plan|approach|step)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:–—-]?\\\\s+(?:i|we|let['’]?s|let us)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:–—-]?\\\\s+(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render)\\\\b|\\\\bstep \\\\d+[ \\\\t*_]*(?::[ \\\\t*_\\\\r]*$|(?:[:,.)\\\\u2013\\\\u2014-][ \\\\t*_]*)?(?:\\\\r?\\\\n(?:[ \\\\t]*\\\\r?\\\\n)?[ \\\\t*_#>-]*(?:\\\\d+[.)][ \\\\t*_]*)?)?(?:(?:let['’]?s|let us)\\\\b|(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render)\\\\b))|\\\\bhere['\\\\u2019]?s (?:my |the |a )?(?:plan|approach)|\\\\b(?:now i|next i)\\\\b)\" flags=42",+ "INTENT_SIGNAL": "\"(?im)(\\\\b(i['\\\\u2019](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall)\\\\b(?!\\\\s+(?:not|never)\\\\b)(?!\\\\s+(?:do(?:ing)?\\\\s+my\\\\s+best|try\\\\s+my\\\\s+best|be\\\\s+(?:able|happy|glad)\\\\s+to\\\\b|assist\\\\b|help\\\\s+you\\\\b(?!\\\\s+(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render))|give\\\\s+you\\\\s+accurate\\\\b|(?:dig\\\\s+in|help\\\\s+analy[sz]e)\\\\b(?=[^\\\\w]*\\\\Z)))|\\\\b(?:let me|allow me)\\\\b(?!\\\\s+(?:not|never|know)\\\\b)(?!\\\\s+(?:dig\\\\s+in|help\\\\s+analy[sz]e)\\\\b(?=[^\\\\w]*\\\\Z))(?!\\\\s+to\\\\s+(?:do(?:ing)?\\\\s+my\\\\s+best|try\\\\s+my\\\\s+best|be\\\\s+(?:able|happy|glad)\\\\s+to\\\\b|assist\\\\b|help\\\\s+you\\\\b(?!\\\\s+(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render))|give\\\\s+you\\\\s+accurate\\\\b|(?:dig\\\\s+in|help\\\\s+analy[sz]e)\\\\b(?=[^\\\\w]*\\\\Z)))|(?:^|[.!?]\\\\s+)\\\\s*(?:the\\\\s+)?first\\\\s+step\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:\u2013\u2014-]?\\\\s+(?:my|our)\\\\s+(?:plan|approach|step)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:\u2013\u2014-]?\\\\s+(?:i|we|let['\u2019]?s|let us)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:\u2013\u2014-]?\\\\s+(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render)\\\\b|\\\\bstep \\\\d+[ \\\\t*_]*(?::[ \\\\t*_\\\\r]*$|(?:[:,.)\\\\u2013\\\\u2014-][ \\\\t*_]*)?(?:\\\\r?\\\\n(?:[ \\\\t]*\\\\r?\\\\n)?[ \\\\t*_#>-]*(?:\\\\d+[.)][ \\\\t*_]*)?)?(?:(?:let['\u2019]?s|let us)\\\\b|(?:search|check|look|find|fetch|get|call|use|run|query|invoke|analy[sz]e|review|inspect|read|gather|examine|retrieve|browse|consult|verify|confirm|compute|calculate|determine|identify|render)\\\\b))|\\\\bhere['\\\\u2019]?s (?:my |the |a )?(?:plan|approach)|\\\\b(?:now i|next i)\\\\b)\" flags=42","_ATTR_FUNC_OPEN_RE": "'<function\\\\s+name=\"' flags=32","_BACKTICK_RUN_RE": "'`+' flags=32","_BARE_JSON_NAME_RE": "'\"name\"\\\\s*:\\\\s*\"([^\"]+)\"' flags=32","_BLOCKED_BODY_MASK_RUN_RE": "'\\ue000+' flags=32",- "_DEEPSEEK_BEGIN_RE": "'<|(?:tool▁calls▁begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool▁calls)|>' flags=32",+ "_DEEPSEEK_BEGIN_RE": "'<\uff5c(?:tool\u2581calls\u2581begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool\u2581calls)\uff5c>' flags=32","_DEEPSEEK_GLUE_GAP_STOP_RE": "'[`<>\\\\[\\\\]{}]' flags=32",- "_DEEPSEEK_R1_CLOSE_RE": "'```[\\\\s\\\\r\\\\n]*<|tool▁call▁end|>' flags=32",- "_EMBEDDED_MARKER_RE": "'<|(?:tool▁calls▁begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool▁calls)|>|<\\\\|tool_calls_section_begin\\\\|>|<\\\\|tool_call_begin\\\\|>' flags=32",+ "_DEEPSEEK_R1_CLOSE_RE": "'```[\\\\s\\\\r\\\\n]*<\uff5ctool\u2581call\u2581end\uff5c>' flags=32",+ "_EMBEDDED_MARKER_RE": "'<\uff5c(?:tool\u2581calls\u2581begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool\u2581calls)\uff5c>|<\\\\|tool_calls_section_begin\\\\|>|<\\\\|tool_call_begin\\\\|>' flags=32","_FENCE_ONLY_RE": "'[\\\\w.\\\\-]*[ \\\\t]*\\\\n?[ \\\\t]*`{3,}[a-zA-Z0-9_+-]*' flags=32","_FUNC_CLOSE_TAG_RE": "'</function>' flags=32","_GEMMA_BARE_TC_PREFIX_RE": "'(?<!\\\\w)call\\\\s*(?::\\\\s*[\\\\w\\\\.\\\\-]*)?$' flags=32",@@ -1150,15 +1150,15 @@"_TOOL_ALL_PATS[10]": "'<\\\\|tool_call>(?=\\\\s*call\\\\s*:|\\\\s*$).*$' flags=48","_TOOL_ALL_PATS[11]": "'\\\\[TOOL_CALLS\\\\](?=\\\\s*(?:[\\\\[{]|[A-Za-z_][\\\\w.\\\\-]*(?:[\\\\[{]|\\\\s*$))|\\\\s*$).*$' flags=48","_TOOL_ALL_PATS[12]": "'<\\\\|python_tag\\\\|>(?=\\\\s*(?:\\\\{|[A-Za-z_][\\\\w.]*\\\\()|\\\\s*$).*$' flags=48",- "_TOOL_ALL_PATS[13]": "'<|(?:tool▁calls▁begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool▁calls)|>(?=\\\\s*(?:<|tool▁call▁begin|>|function)|\\\\s*$).*$' flags=48",- "_TOOL_ALL_PATS[14]": "'<|tool▁call▁begin|>(?=\\\\s*function|\\\\s*$).*$' flags=48",+ "_TOOL_ALL_PATS[13]": "'<\uff5c(?:tool\u2581calls\u2581begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool\u2581calls)\uff5c>(?=\\\\s*(?:<\uff5ctool\u2581call\u2581begin\uff5c>|function)|\\\\s*$).*$' flags=48",+ "_TOOL_ALL_PATS[14]": "'<\uff5ctool\u2581call\u2581begin\uff5c>(?=\\\\s*function|\\\\s*$).*$' flags=48","_TOOL_ALL_PATS[15]": "'<\\\\|tool_calls_section_begin\\\\|>(?=\\\\s*<\\\\|tool_call_begin\\\\|>|\\\\s*$).*$' flags=48","_TOOL_ALL_PATS[16]": "'<\\\\|tool_call_begin\\\\|>(?=\\\\s*[A-Za-z_][\\\\w.\\\\-]*:\\\\d|\\\\s*$).*$' flags=48","_TOOL_ALL_PATS[1]": "'<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>(?:(?!<function(?:=[\\\\w.\\\\-]+|\\\\s+name=\"[\\\\w.\\\\-]+\")>).)*</function>' flags=48","_TOOL_ALL_PATS[2]": "'<\\\\|tool_call>.*?<tool_call\\\\|>' flags=48","_TOOL_ALL_PATS[3]": "'\\\\[TOOL_CALLS\\\\]\\\\s*\\\\[.*?\\\\](?:\\\\s*</s>)?' flags=48","_TOOL_ALL_PATS[4]": "'\\\\[TOOL_CALLS\\\\]\\\\s*[\\\\w\\\\.\\\\-]+\\\\s*(?:\\\\[ARGS\\\\])?\\\\s*\\\\{.*?\\\\}' flags=48",- "_TOOL_ALL_PATS[5]": "'<|(?:tool▁calls▁begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool▁calls)|>.*?<|tool▁calls▁end|>' flags=48",+ "_TOOL_ALL_PATS[5]": "'<\uff5c(?:tool\u2581calls\u2581begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool\u2581calls)\uff5c>.*?<\uff5ctool\u2581calls\u2581end\uff5c>' flags=48","_TOOL_ALL_PATS[6]": "'<\\\\|tool_calls_section_begin\\\\|>.*?<\\\\|tool_calls_section_end\\\\|>' flags=48","_TOOL_ALL_PATS[7]": "'<\\\\|tool_call_begin\\\\|>.*?<\\\\|tool_call_end\\\\|>' flags=48","_TOOL_ALL_PATS[8]": "'<tool_call>.*$' flags=48",@@ -1168,12 +1168,12 @@"_TOOL_CLOSED_PATS[2]": "'<\\\\|tool_call>.*?<tool_call\\\\|>' flags=48","_TOOL_CLOSED_PATS[3]": "'\\\\[TOOL_CALLS\\\\]\\\\s*\\\\[.*?\\\\](?:\\\\s*</s>)?' flags=48","_TOOL_CLOSED_PATS[4]": "'\\\\[TOOL_CALLS\\\\]\\\\s*[\\\\w\\\\.\\\\-]+\\\\s*(?:\\\\[ARGS\\\\])?\\\\s*\\\\{.*?\\\\}' flags=48",- "_TOOL_CLOSED_PATS[5]": "'<|(?:tool▁calls▁begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool▁calls)|>.*?<|tool▁calls▁end|>' flags=48",+ "_TOOL_CLOSED_PATS[5]": "'<\uff5c(?:tool\u2581calls\u2581begin|tool_calls_begin|tool calls begin|tool\\\\\\\\_calls\\\\\\\\_begin|tool\u2581calls)\uff5c>.*?<\uff5ctool\u2581calls\u2581end\uff5c>' flags=48","_TOOL_CLOSED_PATS[6]": "'<\\\\|tool_calls_section_begin\\\\|>.*?<\\\\|tool_calls_section_end\\\\|>' flags=48","_TOOL_CLOSED_PATS[7]": "'<\\\\|tool_call_begin\\\\|>.*?<\\\\|tool_call_end\\\\|>' flags=48"},"regexes": {- "re.compile(\"(?im)(\\\\b(i['\\\\u2019](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall)\\\\b(?!\\\\s+(?:not|never)\\\\b)(?!\\\\s+\" + _HELP_OFFER + ')|\\\\b(?:let me|allow me)\\\\b(?!\\\\s+(?:not|never|know)\\\\b)(?!\\\\s+' + _SIGN_OFF + ')(?!\\\\s+to\\\\s+' + _HELP_OFFER + \")|(?:^|[.!?]\\\\s+)\\\\s*(?:the\\\\s+)?first\\\\s+step\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:–—-]?\\\\s+(?:my|our)\\\\s+(?:plan|approach|step)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:–—-]?\\\\s+(?:i|we|let['’]?s|let us)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:–—-]?\\\\s+\" + _ACTION_VERB + \"\\\\b|\\\\bstep \\\\d+[ \\\\t*_]*(?::[ \\\\t*_\\\\r]*$|(?:[:,.)\\\\u2013\\\\u2014-][ \\\\t*_]*)?(?:\\\\r?\\\\n(?:[ \\\\t]*\\\\r?\\\\n)?[ \\\\t*_#>-]*(?:\\\\d+[.)][ \\\\t*_]*)?)?(?:(?:let['’]?s|let us)\\\\b|\" + _ACTION_VERB + \"\\\\b))|\\\\bhere['\\\\u2019]?s (?:my |the |a )?(?:plan|approach)|\\\\b(?:now i|next i)\\\\b)\")": 1,+ "re.compile(\"(?im)(\\\\b(i['\\\\u2019](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall)\\\\b(?!\\\\s+(?:not|never)\\\\b)(?!\\\\s+\" + _HELP_OFFER + ')|\\\\b(?:let me|allow me)\\\\b(?!\\\\s+(?:not|never|know)\\\\b)(?!\\\\s+' + _SIGN_OFF + ')(?!\\\\s+to\\\\s+' + _HELP_OFFER + \")|(?:^|[.!?]\\\\s+)\\\\s*(?:the\\\\s+)?first\\\\s+step\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:\u2013\u2014-]?\\\\s+(?:my|our)\\\\s+(?:plan|approach|step)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:\u2013\u2014-]?\\\\s+(?:i|we|let['\u2019]?s|let us)\\\\b|(?:^|[.!?]\\\\s+)\\\\s*first\\\\s*[,:\u2013\u2014-]?\\\\s+\" + _ACTION_VERB + \"\\\\b|\\\\bstep \\\\d+[ \\\\t*_]*(?::[ \\\\t*_\\\\r]*$|(?:[:,.)\\\\u2013\\\\u2014-][ \\\\t*_]*)?(?:\\\\r?\\\\n(?:[ \\\\t]*\\\\r?\\\\n)?[ \\\\t*_#>-]*(?:\\\\d+[.)][ \\\\t*_]*)?)?(?:(?:let['\u2019]?s|let us)\\\\b|\" + _ACTION_VERB + \"\\\\b))|\\\\bhere['\\\\u2019]?s (?:my |the |a )?(?:plan|approach)|\\\\b(?:now i|next i)\\\\b)\")": 1,"re.compile('\"[\\\\s}\\\\]]*,\\\\s*(?:\"[A-Za-z_][\\\\w\\\\-]*\"|\\\\\\'[A-Za-z_][\\\\w\\\\-]*\\\\\\'|[A-Za-z_][\\\\w\\\\-]*)\\\\s*:')": 1,"re.compile('\"name\"\\\\s*:\\\\s*\"([^\"]+)\"')": 1,"re.compile('(?:^|[{,\\\\[])\\\\s*[A-Za-z_][\\\\w.\\\\-]*\\\\s*:\\\\s*<\\\\|\"\\\\|>')": 1,@@ -1205,7 +1205,7 @@"re.compile('<tool_call>\\\\s*([\\\\w.\\\\-]+)\\\\s*(?=\\\\n|<arg_key>|</tool_call>)')": 1,"re.compile('<tool_call>\\\\s*\\\\{')": 1,"re.compile('<tool_call>|<function(?:=|\\\\s+name=\")|<\\\\|tool_call>|<\\\\|python_tag\\\\|>(?=\\\\s*(?:\\\\{|[A-Za-z_][\\\\w.]*\\\\())')": 1,- "re.compile('<|tool▁call▁begin|>(?=\\\\s*function|\\\\s*$).*$', re.DOTALL)": 1,+ "re.compile('<\uff5ctool\u2581call\u2581begin\uff5c>(?=\\\\s*function|\\\\s*$).*$', re.DOTALL)": 1,"re.compile('[\\\\w.\\\\-]*[ \\\\t]*\\\\n?[ \\\\t]*`{3,}[a-zA-Z0-9_+-]*')": 1,"re.compile('[`<>\\\\[\\\\]{}]')": 1,"re.compile('\\\\A\\\\s*\\\\{\\\\s*\"name\"\\\\s*:\\\\s*\"([\\\\w.\\\\-]+)\"\\\\s*,\\\\s*\"(?:arguments|parameters)\"\\\\s*:\\\\s*\\\\{\\\\s*\"([A-Za-z_][\\\\w\\\\-]*)\"\\\\s*:\\\\s*\"(.*)\"\\\\s*\\\\}\\\\s*\\\\}\\\\s*\\\\Z', re.DOTALL)": 1,@@ -1225,8 +1225,8 @@"re.compile('`+')": 1,"re.compile('```[\\\\s\\\\r\\\\n]*' + re.escape(_DEEPSEEK_CALL_END))": 1,"re.compile('true|false|null')": 1,- "re.compile(_DEEPSEEK_OPEN_RE_SRC + '(?=\\\\s*(?:<|tool▁call▁begin|>|function)|\\\\s*$).*$', re.DOTALL)": 1,- "re.compile(_DEEPSEEK_OPEN_RE_SRC + '.*?<|tool▁calls▁end|>', re.DOTALL)": 1,+ "re.compile(_DEEPSEEK_OPEN_RE_SRC + '(?=\\\\s*(?:<\uff5ctool\u2581call\u2581begin\uff5c>|function)|\\\\s*$).*$', re.DOTALL)": 1,+ "re.compile(_DEEPSEEK_OPEN_RE_SRC + '.*?<\uff5ctool\u2581calls\u2581end\uff5c>', re.DOTALL)": 1,"re.compile(_DEEPSEEK_OPEN_RE_SRC + '|' + re.escape(_KIMI_SECTION_BEGIN) + '|' + re.escape(_KIMI_CALL_BEGIN))": 1,"re.compile(_DEEPSEEK_OPEN_RE_SRC)": 1,"re.compile(_GEMMA_SLOT + '(\\\\d+)' + _GEMMA_SLOT)": 1@@ -2176,6 +2176,9 @@"decorators": [],"kind": "def","signature": "reasoning: str"+ },+ "_OPEN_PARAMETER_TAGS": {+ "kind": "assign"}}},@@ -2228,7 +2231,9 @@"_TOOL_CLOSED_PATS[6]": "'\\\\[/TOOL_CALLS\\\\]' flags=32","_TOOL_OPEN_XML_TAIL_PATS[0]": "'<tool_call>.*$' flags=48","_TOOL_OPEN_XML_TAIL_PATS[1]": "'<\\\\|tool_call>.*$' flags=48",- "_TOOL_OPEN_XML_TAIL_PATS[2]": "'<function=[\\\\w-]+>.*$' flags=48"+ "_TOOL_OPEN_XML_TAIL_PATS[2]": "'<function=[\\\\w-]+>.*$' flags=48",+ "_WRAP_OPEN_RE": "'<tool_call>\\\\s*$' flags=32",+ "_WRAP_CLOSE_RE": "'\\\\s*</tool_call>' flags=32"},"regexes": {"re.compile('(?:<tool_call>|<\\\\|content_invoke_tool_json\\\\|>)\\\\s*\\\\{')": 1,@@ -2261,9 +2266,9 @@"re.compile('\\\\s*</parameter>\\\\s*$')": 1,"re.compile('\\\\s*[A-Za-z_][\\\\w.\\\\-]*\\\\s*:')": 1,"re.compile('^[ \\\\t]*(?:>[ \\\\t]*)*(?:(?P<bt>```+)[^`\\\\n]*$.*?(?:^[ \\\\t]*(?:>[ \\\\t]*)*(?P=bt)`*[ \\\\t\\\\r]*$|\\\\Z)|(?P<tl>~~~+)[^\\\\n]*$.*?(?:^[ \\\\t]*(?:>[ \\\\t]*)*(?P=tl)~*[ \\\\t\\\\r]*$|\\\\Z))|``(?:[^`]|`(?!`))*?``|`[^`\\\\n]*`', re.DOTALL | re.MULTILINE)": 1,- "re.match('\\\\s*</tool_call>', content[span_end:])": 1,"re.match('\\\\s*\\\\[/TOOL_CALLS\\\\]', content[end:])": 1,- "re.search('<tool_call>\\\\s*$', content[:span_start])": 1+ "re.compile('<tool_call>\\\\s*$')": 1,+ "re.compile('\\\\s*</tool_call>')": 1},"symbols": {"EXECUTION_CLASS_TOOL_NAMES": {@@ -2410,7 +2415,7 @@"_func_close_index": {"decorators": [],"kind": "def",- "signature": "content: str, body_start: int, body: str"+ "signature": "content: str, body_start: int, body: str, *, inside=None"},"_gemma_arguments_to_json": {"decorators": [],@@ -2581,6 +2586,40 @@"decorators": [],"kind": "def","signature": "text: str, patterns"+ },+ "_WRAP_CLOSE_RE": {+ "kind": "assign"+ },+ "_WRAP_OPEN_RE": {+ "kind": "assign"+ },+ "_OpenParameterIndex": {+ "bases": [],+ "decorators": [],+ "kind": "class",+ "methods": {+ "__init__": {+ "decorators": [],+ "signature": "self, content: str, *, param_start_re=None, param_closers=(_PARAM_CLOSE_TAG,), func_closers=(_FUNC_CLOSE_TAG,)"+ },+ "_build": {+ "decorators": [],+ "signature": "self"+ },+ "_positions": {+ "decorators": [+ "staticmethod"+ ],+ "signature": "content: str, tags"+ },+ "inside": {+ "decorators": [],+ "signature": "self, pos: int"+ }+ }+ },+ "_OPEN_PARAMETER_SCAN_LIMIT": {+ "kind": "assign"}}}diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex 702463fdd12..3d6d27e418f 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -102,6 +102,7 @@"_OPEN_CALL_TRIGGER_MAX_LEN","_OPEN_CALL_WS_RE","_OPEN_FUNCTION_OPENER_RE",+ "_OPEN_PARAMETER_TAGS","_OUTER_ENVELOPE_CLOSED_PATS","_OUTER_ENVELOPE_OPEN_RE","_REPEAT_LEAD_PUNCT",@@ -370,6 +371,8 @@"_MCP_TOOL_PREFIX","_MISTRAL_ARRAY_RE","_MISTRAL_BRACKET_RE",+ "_OPEN_PARAMETER_SCAN_LIMIT",+ "_OpenParameterIndex","_PARAM_CLOSE_TAG","_PAT_REQUIRED_TOKEN","_REHEARSAL_CLOSED_STRIP_RE",@@ -394,6 +397,8 @@"_TOOL_CLOSED_BLOCK_PATS","_TOOL_CLOSED_PATS","_TOOL_OPEN_XML_TAIL_PATS",+ "_WRAP_CLOSE_RE",+ "_WRAP_OPEN_RE","_balanced_brace_end","_balanced_bracket_end","_balanced_json_span",@@ -432,6 +437,7 @@"annotations","apply_tool_strip_patterns","bisect",+ "itertools","json","marker_coverage","parse_tool_calls_from_text",@@ -447,7 +453,7 @@"_build_markers": "core.tool_healing._build_markers(content: 'str')","_code_spans": "core.tool_healing._code_spans(text: 'str', start: 'int' = 0) -> 'list[tuple[int, int]]'","_decode_array_items": "core.tool_healing._decode_array_items(text: 'str', body_start: 'int', body_end: 'int')",- "_func_close_index": "core.tool_healing._func_close_index(content: 'str', body_start: 'int', body: 'str') -> 'int'",+ "_func_close_index": "core.tool_healing._func_close_index(content: 'str', body_start: 'int', body: 'str', *, inside=None) -> 'int'","_gemma_arguments_to_json": "core.tool_healing._gemma_arguments_to_json(args_src: 'str') -> 'dict'","_gemma_span_ranges": "core.tool_healing._gemma_span_ranges(text: 'str') -> 'list'","_glued_call_objects": "core.tool_healing._glued_call_objects(content: 'str', pos: 'int', end: 'int')",diff --git a/studio/backend/tests/test_function_xml_linear_scan.py b/studio/backend/tests/test_function_xml_linear_scan.pynew file mode 100644index 00000000000..c7bdc19015b--- /dev/null+++ b/studio/backend/tests/test_function_xml_linear_scan.py@@ -0,0 +1,177 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""``<function=NAME><parameter=KEY>`` parsing asked ``_inside_open_parameter`` once per candidate tag and+each call could rescan the text, so a long value full of tag literals took about a minute per megabyte.+The parser, the strip and the healer now ask one ``_OpenParameterIndex`` per text."""++from __future__ import annotations++import hashlib+import json+import random+import time++import pytest++from core import tool_healing+from core.inference import tool_call_parser+from core.inference.tool_call_parser import (+ StreamingMarkupStripper,+ parse_tool_calls_from_text,+ strip_tool_markup,+)++ENABLED = {"web_search", "write_file", "a", "f"}+PIECES = (+ "<function=a>",+ '<function name="f">',+ "</function>",+ "<tool_call>",+ "</tool_call>",+ "<parameter=p>",+ '<parameter name="q">',+ "<param=r>",+ '<param name="s">',+ "</parameter>",+ "</param>",+ "<param",+ "<parameter=",+ "<function=",+ "{",+ "}",+ '"x"',+ " ",+ "\n",+ "a",+ "<",+ ">",+)+++def _random_texts(+ count,+ seed,+ max_pieces = 24,+):+ rng = random.Random(seed)+ return [+ "".join(rng.choice(PIECES) for _ in range(rng.randint(0, max_pieces))) for _ in range(count)+ ]+++class _HelperIndex:+ """The pre-index behaviour: every query is a fresh ``_inside_open_parameter`` scan of the text."""++ def __init__(self, content, **kwargs):+ self._content = content+ self._kwargs = kwargs++ def inside(self, pos):+ return tool_healing._inside_open_parameter(self._content, pos, **self._kwargs)+++def test_the_index_answers_like_the_shared_helper_at_every_offset(monkeypatch):+ # No warm-up scans, so every query below is answered by the index.+ monkeypatch.setattr(tool_healing, "_OPEN_PARAMETER_SCAN_LIMIT", 0)+ for text in _random_texts(400, seed = 0) + _random_texts(100, seed = 1, max_pieces = 80):+ parser_inside = tool_healing._OpenParameterIndex(+ text, **tool_call_parser._OPEN_PARAMETER_TAGS+ ).inside+ healer_inside = tool_healing._OpenParameterIndex(text).inside+ for pos in range(len(text) + 1):+ assert parser_inside(pos) == tool_call_parser._inside_open_parameter(text, pos), (+ text,+ pos,+ )+ assert healer_inside(pos) == tool_healing._inside_open_parameter(text, pos), (text, pos)+++PROSE = (+ "Each call is `<function=NAME>` with `<parameter=KEY>` blocks closed by `</parameter>`, then `</function>`.\n"+ "```python\nout = [f'<function={name}>', '<parameter=path>a.py</parameter>', '</function>']\n```\n"+)+CALL = "<function=web_search>\n<parameter=query>\nweather in Paris\n</parameter>\n</function>"+WRITE = (+ "<function=write_file>\n<parameter=path>\nparser.py\n</parameter>\n<parameter=content>\n"+ + "t = '<parameter=path>' + p + '</parameter>' # </function> <function=a>\n" * 20+)+CORPUS = _random_texts(200, seed = 2, max_pieces = 40) + [+ PROSE * 20 + CALL,+ WRITE + "\n</parameter>\n</function>",+ WRITE,+ "<tool_call>\n" + CALL + "\n</tool_call>\nDone.",+ "<function=f><parameter=p>" + "<function=a>" * 50 + "</parameter></function>" + CALL,+ ("<tool_call>\n" + CALL + "\n</tool_call>\n") * 5,+ ('<tool_call>{"name": "a", "arguments": {}}</tool_call>\n<function=a></function>\n') * 5,+ '<function name="f"><param name="p">' + '<function name="a">x' * 20 + "</param></function>",+ '<function name="f"><param name="p">1</param></function>\n<function name="a">',+]+# sha256 of the outputs below for CORPUS, recorded on the per-tag scan implementation before the index.+RECORDED_DIGEST = "b0b70a5748fe61c622cf53d1247a53bf78f3150c017940bee3f83b0298ecec2c"+++def _outputs(text):+ return (+ parse_tool_calls_from_text(text, enabled_tool_names = ENABLED),+ parse_tool_calls_from_text(text, enabled_tool_names = ENABLED, allow_incomplete = False),+ strip_tool_markup(text, final = True, enabled_tool_names = ENABLED),+ strip_tool_markup(text, final = False, enabled_tool_names = ENABLED),+ tool_healing.parse_tool_calls_from_text(text, enabled_tool_names = ENABLED),+ tool_healing.parse_tool_calls_from_text(+ text, enabled_tool_names = ENABLED, allow_incomplete = False+ ),+ tool_healing.parse_tool_calls_from_text(text, with_spans = True),+ )+++def _streamed(text, chunk = 5):+ stripper = StreamingMarkupStripper(ENABLED)+ return [stripper.strip(text[:end]) for end in range(chunk, len(text) + chunk, chunk)]+++def _digest(results):+ return hashlib.sha256(json.dumps(results, sort_keys = True).encode()).hexdigest()+++def test_outputs_match_the_per_tag_scan(monkeypatch):+ """Calls, strips (final and mid-stream), heals with Auto-Heal on and off: identical to the helper-backed run."""+ default = [(_outputs(text), _streamed(text)) for text in CORPUS]+ monkeypatch.setattr(tool_healing, "_OPEN_PARAMETER_SCAN_LIMIT", 0)+ indexed = [(_outputs(text), _streamed(text)) for text in CORPUS]+ monkeypatch.setattr(tool_healing, "_OpenParameterIndex", _HelperIndex)+ scanned = [(_outputs(text), _streamed(text)) for text in CORPUS]+ assert indexed == scanned+ assert default == scanned+ # Also covers the bounded wrapper and end-tag searches, which the helper swap above does not reach.+ assert _digest(default) == RECORDED_DIGEST+ # The corpus must reach the function parser, not only fall through it.+ assert sum(len(out[0]) for out, _stream in indexed) >= 50+++ "text",+ [+ "<function=f><parameter=p>" + "<function=a>" * 80000,+ "<function=a><parameter=p>x</parameter></function>" * 20000,+ "<function=f><parameter=p>" + '<tool_call>{"a":1}' * 55000,+ "<parameter=p><function=a>" * 40000,+ '<function name="f"><param name="p">' + '<function name="a">' * 50000,+ ('<tool_call>{"name":"a","arguments":{}}</tool_call>\n<function=a></function>\n') * 6500,+ ],+ ids = [+ "openers_in_a_value",+ "many_calls",+ "json_markers_in_a_value",+ "unclosed_params_and_openers",+ "attribute_openers_in_a_value",+ "json_and_function_calls",+ ],+)+def test_a_megabyte_of_adversarial_markup_parses_in_linear_time(text):+ start = time.perf_counter()+ parse_tool_calls_from_text(text, enabled_tool_names = ENABLED)+ strip_tool_markup(text, final = True, enabled_tool_names = ENABLED)+ tool_healing.parse_tool_calls_from_text(text, enabled_tool_names = ENABLED)+ # Base takes 20 s or more per case; 15 s leaves room for slow CI runners.+ assert time.perf_counter() - start < 15.0