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 prose that documents call:NAME{...} in the answer (#8437)
Daniel Hanf59c372056a8
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex 28b544303df..070e5aa3a2d 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -495,11 +495,31 @@ def _strip_mistral_closed_calls(text: str) -> str:return "".join(out)+# A real call may follow a reasoning close directly: the strips run per segment after+# ``strip_outside_think``, so ``</think>call:NAME{..}`` starts its segment.+_GEMMA_ANCHOR_CLOSERS = ("</think>", "[/THINK]", "</thinking>")+++def _gemma_call_is_anchored(text: str, start: int, floor: int) -> bool:+ """Whether a markerless ``call:NAME{...}`` at ``start`` OWNS its position: only+ horizontal whitespace between it and ``floor`` (the scan origin), the start of its+ line, or a reasoning close. Anywhere else it reads as a sentence documenting the+ syntax, so the DISPLAY strip keeps it. The parser is deliberately NOT gated this+ way, so a call it promotes mid-prose stays visible instead of the answer being+ deleted around it."""+ i = start - 1+ while i >= floor and text[i] in " \t\r":+ i -= 1+ if i < floor or text[i] == "\n":+ return True+ return any(text.endswith(closer, floor, i + 1) for closer in _GEMMA_ANCHOR_CLOSERS)++def _strip_gemma_wrapperless_calls(text: str, enabled_tool_names: Optional[set] = None) -> str:"""Strip closed wrapper-less Gemma ``call:NAME{...}`` calls with balanced bracescanning (nested arguments are removed whole). ``enabled_tool_names`` gates thestrip like the parser gate: a disabled/example name stays visible; ``None``- strips every closed call."""+ strips every closed call. An unanchored (mid-sentence) call is prose too."""if _whole_content_is_json_value(text):return textn = len(text)@@ -508,26 +528,32 @@ def _strip_gemma_wrapperless_calls(text: str, enabled_tool_names: Optional[set]cursor = _leading_json_value_end(text) or 0if cursor:out.append(text[:cursor])+ # Anchor origin, advanced only past calls this strip removed, so ``call:a{} call:b{}``+ # stays a pair while prose after a call does not inherit its anchor.+ floor = cursorwhile cursor < n:m = _GEMMA_BARE_TC_RE.search(text, cursor)if not m:out.append(text[cursor:])break- disabled = enabled_tool_names is not None and m.group(1) not in enabled_tool_names+ keep = (enabled_tool_names is not None and m.group(1) not in enabled_tool_names) or (+ not _gemma_call_is_anchored(text, m.start(), floor)+ )brace = m.end() - 1 # _GEMMA_BARE_TC_RE consumes through the opening ``{``# Same boundary scanner as the parser: strip exactly what it consumed.end = _gemma_body_brace_end(text, brace)closed = end is not Nonenext_index = (end + 1) if closed else len(text)if not closed:- # Unclosed call: drop an enabled call to EOS; keep a disabled/example name as prose.- out.append(text[cursor:] if disabled else text[cursor : m.start()])+ # Unclosed: drop an anchored enabled call to EOS, keep prose as written.+ out.append(text[cursor:] if keep else text[cursor : m.start()])break- if disabled:- # Disabled/example name is prose: keep it whole.+ if keep:+ # Prose, not a call.out.append(text[cursor:next_index])else:out.append(text[cursor : m.start()])+ floor = next_indexcursor = next_index # already past the matching ``}``return "".join(out)diff --git a/studio/backend/tests/test_gemma_tool_parse_edge_cases.py b/studio/backend/tests/test_gemma_tool_parse_edge_cases.pyindex e3055d2127d..02a4d70cbee 100644--- a/studio/backend/tests/test_gemma_tool_parse_edge_cases.py+++ b/studio/backend/tests/test_gemma_tool_parse_edge_cases.py@@ -409,3 +409,56 @@ def test_malformed_gemma_mapping_value_does_not_hang():t.start()t.join(timeout = 10.0)assert not t.is_alive(), "parse_tool_calls_from_text hung on malformed mapping input"+++# ── Wrapper-less ``call:NAME{...}``: the display strip removes only a call that OWNS+# its position. The parser is unchanged, so a promoted call is never erased silently.+++def _strip(text: str, enabled = None) -> str:+ from core.inference.tool_call_parser import strip_tool_markup+ return strip_tool_markup(text, final = True, enabled_tool_names = enabled)+++def test_wrapperless_call_in_mid_sentence_prose_is_kept_by_every_display_strip():+ from core.inference.safetensors_agentic import strip_tool_markup_streaming+ from routes.inference import _strip_tool_xml as _routes_strip++ prose = 'Here is the syntax: call:terminal{command: "rm -rf /tmp/x"}. Do not run it.'+ en = {"terminal", "python", "web_search"}+ assert _strip(prose, en) == prose+ assert strip_tool_markup_streaming(prose, enabled_tool_names = en) == prose+ assert _routes_strip(prose, en) == prose+++def test_anchored_wrapperless_calls_are_still_stripped():+ en = {"web_search"}+ # Content start, line start, after a reasoning close, and back-to-back calls.+ assert _strip("call:web_search{query:cats}", en) == ""+ assert _strip("Sure!\ncall:web_search{query:cats}", en) == "Sure!"+ assert "call:web_search" not in _strip("<think>plan</think>call:web_search{query:cats}", en)+ assert _strip("call:web_search{query:hi} call:web_search{query:yo}", en) == ""+ # A leading JSON answer is data; the call after it still owns its line.+ assert "call:web_search" not in _strip('{"summary":"done"}\ncall:web_search{query:cats}', en)+++def test_unclosed_wrapperless_call_strip_follows_the_same_anchor_rule():+ en = {"web_search"}+ # Anchored + enabled: a truncated call is still dropped to EOS (streaming heal).+ assert _strip("Sure!\ncall:web_search{query:weath", en) == "Sure!"+ # Mid-sentence: prose, kept as written.+ inline = "You can run call:web_search{query:weath"+ assert _strip(inline, en) == inline+++def test_streaming_display_of_prose_call_never_shrinks():+ from core.inference.safetensors_agentic import strip_tool_markup_streaming++ prose = "You can run call:web_search{query:cats} to search."+ en = {"web_search"}+ seen = ""+ for i in range(1, len(prose) + 1):+ out = strip_tool_markup_streaming(prose[:i], enabled_tool_names = en)+ assert len(out) >= len(seen), (i, out, seen)+ seen = out+ assert seen == prosediff --git a/studio/backend/tests/test_pr5624_regressions.py b/studio/backend/tests/test_pr5624_regressions.pyindex 4f5471675c7..8f66d7e3173 100644--- a/studio/backend/tests/test_pr5624_regressions.py+++ b/studio/backend/tests/test_pr5624_regressions.py@@ -452,12 +452,16 @@ def test_deepseek_v3_with_call_terminator_parses_in_strict_mode():def test_strip_tool_markup_removes_nested_wrapperless_gemma_call():# Wrapper-less Gemma call with a NESTED object arg: the balanced helper must strip the whole call, not leave a trailing ``}``.- text = "answer: call:f{loc:{city:NYC},n:3} done"+ text = "answer:\ncall:f{loc:{city:NYC},n:3} done"stripped = strip_tool_markup(text, final = True)assert "call:f" not in strippedassert "}" not in strippedassert "answer:" in stripped and "done" in stripped+ # Mid-sentence the same shape is a sentence about the syntax: kept whole.+ prose = "answer: call:f{loc:{city:NYC},n:3} done"+ assert strip_tool_markup(prose, final = True) == prose+# Pass-3 review findings: bare-Kimi streaming (non-final) strip symmetry# and the wrapper-less Gemma route-display strip@@ -482,11 +486,15 @@ def test_routes_layer_strip_removes_wrapperless_gemma_call():# Gemma 4 (skip_special_tokens) emits a wrapper-less ``call:NAME{..}`` with no XML markers.from routes.inference import _strip_tool_xml as _routes_strip- text = 'before call:web_search{query:"weather in Sydney"} after'+ text = 'before\ncall:web_search{query:"weather in Sydney"} after'stripped = _routes_strip(text)assert "call:web_search" not in strippedassert "before" in stripped and "after" in stripped+ # The same call mid-sentence reads as prose, so the route keeps the answer intact.+ prose = 'before call:web_search{query:"weather in Sydney"} after'+ assert _routes_strip(prose) == prose+def test_deepseek_envelope_end_inside_arg_string_is_not_a_truncation():# A DeepSeek V3.1 call whose argument string contains the literal envelope-end token must not be dropped.@@ -536,14 +544,22 @@ def test_wrapperless_gemma_call_gated_by_enabled_tools():assert "call:foo{x:1}" in strip_tool_markup(prose, final = True, enabled_tool_names = {"web_search"})- # An enabled name is still a real call (parsed, and stripped from display).- real = "Answer. call:web_search{query:hi}"+ # An enabled name is still a real call, and a call at a line boundary (the shape+ # Gemma emits) is stripped from display.+ real = "Answer.\ncall:web_search{query:hi}"calls = parse_tool_calls_from_text(real, enabled_tool_names = {"web_search"})assert [c["function"]["name"] for c in calls] == ["web_search"], callsassert "call:web_search" not in strip_tool_markup(real, final = True, enabled_tool_names = {"web_search"})+ # Mid-sentence the strip is deliberately NOT the parser's mirror: the call is still+ # promoted, and its text stays visible instead of the answer being deleted around it.+ inline = "Answer. call:web_search{query:hi}"+ inline_calls = parse_tool_calls_from_text(inline, enabled_tool_names = {"web_search"})+ assert [c["function"]["name"] for c in inline_calls] == ["web_search"], inline_calls+ assert strip_tool_markup(inline, final = True, enabled_tool_names = {"web_search"}) == inline+def test_kimi_section_end_inside_arg_string_is_not_a_truncation():# In a multi-call Kimi section, a later call whose argument holds the literal section-end token must not truncate the section.diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.pyindex 4a7b3ece20c..84ccc22c2c9 100644--- a/studio/backend/tests/test_safetensors_tool_loop.py+++ b/studio/backend/tests/test_safetensors_tool_loop.py@@ -661,11 +661,14 @@ class TestParser:def test_streaming_strip_handles_nested_wrapperless_gemma(self):# Same class of bug for the wrapper-less Gemma call:NAME{...} form with a# nested object argument.- raw = "ok call:f{loc:{city:NYC},n:3} tail"+ raw = "ok\ncall:f{loc:{city:NYC},n:3} tail"out = strip_tool_markup_streaming(raw)assert "call:f" not in outassert "}" not in out- assert "ok " in out and "tail" in out+ assert "ok" in out and "tail" in out+ # Mid-sentence the same shape is prose: streaming display keeps it.+ inline = "ok call:f{loc:{city:NYC},n:3} tail"+ assert strip_tool_markup_streaming(inline) == inlinedef test_streaming_strip_keeps_prose_after_function_xml_with_literal_marker(self):# A literal ``<function=...>`` in a value is data: the strip must close at the REAL@@ -1099,8 +1102,11 @@ class TestParserMultiFormat:assert result == []def test_gemma4_bare_strip_markup_final(self):- text = "Here you go: call:web_search{query:weather today}"+ text = "Here you go:\ncall:web_search{query:weather today}"assert "call:web_search" not in strip_tool_markup(text, final = True)+ # Mid-sentence: prose, kept whole.+ inline = "Here you go: call:web_search{query:weather today}"+ assert strip_tool_markup(inline, final = True) == inline# ── Cross-format sentinels ────────────────────────────────────diff --git a/studio/backend/tests/test_tool_xml_strip.py b/studio/backend/tests/test_tool_xml_strip.pyindex d02638f5899..235260fe3db 100644--- a/studio/backend/tests/test_tool_xml_strip.py+++ b/studio/backend/tests/test_tool_xml_strip.py@@ -831,12 +831,16 @@ def test_route_strip_gates_wrapperless_gemma_by_enabled_tools():# like the parser/loop, so a disabled/example name in prose is preserved in ...prose = "To document syntax you write call:foo{query:example}. That shows the format."assert "call:foo{query:example}" in _strip_tool_xml(prose, {"web_search"})- # An enabled name is still a real call and stripped.+ # An enabled name at a line boundary is still a real call and stripped.assert "call:web_search" not in _strip_tool_xml(- "Answer. call:web_search{query:x}", {"web_search"}+ "Answer.\ncall:web_search{query:x}", {"web_search"}+ )+ # Mid-sentence the shape is prose whatever the name, so the answer is kept whole.+ assert "call:web_search" in _strip_tool_xml("Answer. call:web_search{query:x}", {"web_search"})+ # No gate (legacy) strips every closed call that owns its position.+ assert "call:foo" not in _strip_tool_xml(+ "To document syntax you write\ncall:foo{query:example}")- # No gate (legacy) strips every closed call.- assert "call:foo" not in _strip_tool_xml(prose)def test_gemma_strip_gate_empty_tools_preserves_prose():@@ -850,7 +854,7 @@ def test_gemma_strip_gate_empty_tools_preserves_prose():assert "call:foo{query:example}" in _strip_tool_xml(prose, _gemma_strip_gate(None))# An enabled tool's real call is still stripped.assert "call:web_search" not in _strip_tool_xml(- "Answer. call:web_search{query:x}",+ "Answer.\ncall:web_search{query:x}",_gemma_strip_gate([{"function": {"name": "web_search"}}]),)