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: recover a closed tool call whose single code argument has unescaped quotes (#16006)
Daniel Han8d808843e0ba
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex e7fbb157bae..e433b58a768 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -2326,12 +2326,96 @@ def parse_tool_calls_from_text(return calls# Gemma wrapper-less ``call:NAME{...}``: markerless, so the same enabled-name gate applies- return _parse_gemma_tool_calls(+ calls = _parse_gemma_tool_calls(fallback_content,id_offset = id_offset,allow_incomplete = allow_incomplete,enabled_tool_names = enabled_tool_names,)+ if calls or not allow_incomplete:+ return calls+ # Last, and only when nothing parsed: a closed call whose one string argument holds unescaped quotes.+ return _parse_closed_call_unescaped_quotes(content, id_offset = id_offset)+++# ``{"name": N, "arguments"|"parameters": {"KEY": "VALUE"}}`` with nothing after VALUE but the closers.+_ONE_STRING_ARG_CALL_RE = re.compile(+ r'\A\s*\{\s*"name"\s*:\s*"([\w.\-]+)"\s*,\s*"(?:arguments|parameters)"\s*:\s*'+ r'\{\s*"([A-Za-z_][\w\-]*)"\s*:\s*"(.*)"\s*\}\s*\}\s*\Z',+ re.DOTALL,+)+# A lost second argument or outer key (``", "key":``, ``", 'key':``, ``", key:``, ``"}, "key":``): the+# value's end is no longer knowable, so it is refused.+_SECOND_KEY_RE = re.compile(+ r'"[\s}\]]*,\s*(?:"[A-Za-z_][\w\-]*"|\'[A-Za-z_][\w\-]*\'|[A-Za-z_][\w\-]*)\s*:'+)+++def _escape_bare_quotes(raw: str) -> str:+ """Escape the ``"`` no backslash escapes. A model that left bare quotes was not JSON-escaping quotes, so a+ ``\\"`` it wrote next to them is the code's own escape and stays a backslash-quote; other escapes (``\\n``)+ are JSON's. With no bare quote at all, every escape is JSON's."""+ tokens: list[str] = []+ bare = False+ i, n = 0, len(raw)+ while i < n:+ if raw[i] == "\\" and i + 1 < n:+ tokens.append(raw[i : i + 2])+ i += 2+ continue+ bare = bare or raw[i] == '"'+ tokens.append(raw[i])+ i += 1+ if not bare:+ return raw+ return "".join('\\"' if tok == '"' else '\\\\\\"' if tok == '\\"' else tok for tok in tokens)+++def _parse_closed_call_unescaped_quotes(content: str, *, id_offset: int) -> list[dict]:+ """A ``<tool_call>`` closed by ``</tool_call>`` whose single string argument (code, a command) holds+ quotes the model did not escape, so strict JSON and brace matching both lose the call. The closer+ bounds the body, so the value is everything between its opening quote and the final ``"}}``. Only a+ single-argument call, outside reasoning and code fences, with no sign of a second argument."""+ out: list[dict] = []+ if _TC_JSON_START_RE.search(content) is None:+ return out+ think_spans = _tool_healing._think_spans_outside_tool_markup(content)+ code_spans = _tool_healing._code_spans(content)+ # Inside another marker's span (an unclosed call before it) the opener is that call's argument data.+ coverage = _tool_healing.marker_coverage(content)+ pos = 0+ while True:+ start = content.find(_OPEN_CALL_OPENER, pos)+ if start < 0:+ return out+ body_start = start + len(_OPEN_CALL_OPENER)+ end = content.find("</tool_call>", body_start)+ if end < 0:+ return out+ pos = end + len("</tool_call>")+ if (+ any(a <= start < b for a, b in think_spans)+ or any(a < start < b for a, b in coverage)+ or _tool_healing._in_code(code_spans, start)+ ):+ continue+ body = content[body_start:end]+ if _OPEN_CALL_OPENER in body:+ continue+ m = _ONE_STRING_ARG_CALL_RE.match(body)+ if m is None or _SECOND_KEY_RE.search(m.group(3)):+ continue+ try:+ value = json.loads('"' + _escape_bare_quotes(m.group(3)) + '"', strict = False)+ except (json.JSONDecodeError, ValueError):+ continue+ out.append(+ {+ "id": f"call_{id_offset + len(out)}",+ "type": "function",+ "function": {"name": m.group(1), "arguments": json.dumps({m.group(2): value})},+ }+ )def _parse_tool_call_json(diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 2045db750ba..435626a6225 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -1129,11 +1129,13 @@"_LLAMA3_PY_CALL_RE": "'<\\\\|python_tag\\\\|>\\\\s*([\\\\w\\\\.\\\\-]+)\\\\s*\\\\.\\\\s*call\\\\s*\\\\(' flags=32","_LLAMA3_WS_RE": "'\\\\s*' flags=32","_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","_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","_OUTER_ENVELOPE_OPEN_RE": "'<tool_call>|<function(?:=|\\\\s+name=\")|<\\\\|tool_call>|<\\\\|python_tag\\\\|>(?=\\\\s*(?:\\\\{|[A-Za-z_][\\\\w.]*\\\\())' flags=32",+ "_SECOND_KEY_RE": "'\"[\\\\s}\\\\]]*,\\\\s*(?:\"[A-Za-z_][\\\\w\\\\-]*\"|\\\\\\'[A-Za-z_][\\\\w\\\\-]*\\\\\\'|[A-Za-z_][\\\\w\\\\-]*)\\\\s*:' flags=32","_TC_END_TAG_RE": "'</(?:tool_call|function)>' flags=32","_TC_FUNC_CLOSE_RE": "'\\\\s*</function>\\\\s*$' flags=32","_TC_FUNC_START_RE": "'<function(?:=([\\\\w\\\\.\\\\-]+)|\\\\s+name=\"([\\\\w\\\\.\\\\-]+)\")>\\\\s*' flags=32",@@ -1168,6 +1170,7 @@},"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('\"[\\\\s}\\\\]]*,\\\\s*(?:\"[A-Za-z_][\\\\w\\\\-]*\"|\\\\\\'[A-Za-z_][\\\\w\\\\-]*\\\\\\'|[A-Za-z_][\\\\w\\\\-]*)\\\\s*:')": 1,"re.compile('\"name\"\\\\s*:\\\\s*\"([^\"]+)\"')": 1,"re.compile('(?<!\\\\w)call\\\\s*(?::\\\\s*[\\\\w\\\\.\\\\-]*)?$')": 1,"re.compile('(?<!\\\\w)call\\\\s*:\\\\s*([\\\\w\\\\.\\\\-]+)\\\\s*\\\\{')": 1,@@ -1198,6 +1201,7 @@"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('[\\\\w.\\\\-]*[ \\\\t]*\\\\n?[ \\\\t]*`{3,}[a-zA-Z0-9_+-]*')": 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,"re.compile('\\\\[TOOL_CALLS\\\\](?=\\\\s*(?:[\\\\[{]|[A-Za-z_][\\\\w.\\\\-]*(?:[\\\\[{]|\\\\s*$))|\\\\s*$).*$', re.DOTALL)": 1,"re.compile('\\\\[TOOL_CALLS\\\\]\\\\s*[\\\\w\\\\.\\\\-]+\\\\s*(?:\\\\[ARGS\\\\])?\\\\s*\\\\{.*?\\\\}', re.DOTALL)": 1,"re.compile('\\\\[TOOL_CALLS\\\\]\\\\s*\\\\[.*?\\\\](?:\\\\s*</s>)?', re.DOTALL)": 1,@@ -1531,6 +1535,9 @@"_MISTRAL_V11_NAME_RE": {"kind": "assign"},+ "_ONE_STRING_ARG_CALL_RE": {+ "kind": "assign"+ },"_OPEN_CALL_OPENER": {"kind": "assign"},@@ -1555,6 +1562,9 @@"_REPEAT_TRAIL_PUNCT": {"kind": "assign"},+ "_SECOND_KEY_RE": {+ "kind": "assign"+ },"_SENTINEL_MAX_LEN": {"kind": "assign"},@@ -1626,6 +1636,11 @@"kind": "def","signature": "content: str, enabled_tool_names: Optional[set]"},+ "_escape_bare_quotes": {+ "decorators": [],+ "kind": "def",+ "signature": "raw: str"+ },"_escaped_string_content_spans": {"decorators": [],"kind": "def",@@ -1798,6 +1813,11 @@"kind": "def","signature": "content: str, *, id_offset: int=0, enabled_tool_names: Optional[set]=None"},+ "_parse_closed_call_unescaped_quotes": {+ "decorators": [],+ "kind": "def",+ "signature": "content: str, *, id_offset: int"+ },"_parse_deepseek_tool_calls": {"decorators": [],"kind": "def",diff --git a/studio/backend/tests/data/refactor_guard/golden_outputs.json b/studio/backend/tests/data/refactor_guard/golden_outputs.jsonindex 90e9561acf7..5c991f610ff 100644--- a/studio/backend/tests/data/refactor_guard/golden_outputs.json+++ b/studio/backend/tests/data/refactor_guard/golden_outputs.json@@ -6,6 +6,7 @@"_consume_mistral_call": "813544e2d389e368c2d6c77f333ae1d07409d9cf0d3bdad8735c116577bcd380","_decoded_key": "78aa12becfd9bc1f17e0bdb39dfe16824279dc82d4bd5a97c5b511904ad773c0","_disabled_gemma_call_end_containing_signal": "c08417f20bd3f6c67d09c63f750894aa02104faef091f31dba29c57e585ac69a",+ "_escape_bare_quotes": "2166469192d10173d4e11354a52cfdc55b16dc608fe5e74343cd336dfca09a84","_escaped_string_content_spans": "90f2e2f10c8322bd126f413564d9a5e075606cbabe25b47596cfcc9156f7213c","_find_outside_json_strings": "cf83e50f5e7308aae25758d71b706f91c87e690bc6fdddb24605671fb67e3788","_first_foreign_tool_signal": "253f37233f0cd47bb9a1f4e2cb04072d1575b1245d5f0a2c0fc7190dfa138354",@@ -36,6 +37,7 @@"_only_a_code_fence": "986a0b8d0c6d4abe8041da540909357131977dd7ba6a72d537440e44b383a32b","_open_inline_code_run": "2f27bf94223e8b14b8faf656fbe7b59f75a087118c516ff26366865179666517","_parse_bare_rehearsals": "c809e331067827ef1f773b2613bbcb9c9c1138f55e12bd37cbfe35919cceba54",+ "_parse_closed_call_unescaped_quotes": "f5b2cba82abb209bd409fbe327b458c0177a2d09c18b0fab2cd75b6ea64e12bb","_parse_deepseek_tool_calls": "b16631fa1f86628069da6662060cd78f6c2b1edc87e15011bcec5103a450cabd","_parse_function_xml": "8e47d9a73bea635e90c3a8c56b8be91b3e42d1bbf75c36795fad2bdefeb71696","_parse_gemma_tool_calls": "2f1fc545935ef45a31aa2dc32870ee4fc8cfa93d0121f0bcf714c54ac469329f",diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex add8f31aafb..078167e2cb4 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -88,6 +88,7 @@"_MISTRAL_THINK_OPEN","_MISTRAL_TRIGGER","_MISTRAL_V11_NAME_RE",+ "_ONE_STRING_ARG_CALL_RE","_OPEN_CALL_OPENER","_OPEN_CALL_TRIGGERS","_OPEN_CALL_TRIGGER_MAX_LEN",@@ -96,6 +97,7 @@"_OUTER_ENVELOPE_OPEN_RE","_REPEAT_LEAD_PUNCT","_REPEAT_TRAIL_PUNCT",+ "_SECOND_KEY_RE","_SENTINEL_MAX_LEN","_SIGN_OFF","_STRIP_SENTINELS",@@ -115,6 +117,7 @@"_consume_mistral_call","_decoded_key","_disabled_gemma_call_end_containing_signal",+ "_escape_bare_quotes","_escaped_string_content_spans","_find_outside_json_strings","_first_foreign_tool_signal",@@ -151,6 +154,7 @@"_only_a_code_fence","_open_inline_code_run","_parse_bare_rehearsals",+ "_parse_closed_call_unescaped_quotes","_parse_deepseek_tool_calls","_parse_function_xml","_parse_gemma_tool_calls",@@ -224,6 +228,7 @@"_consume_mistral_call": "core.inference.tool_call_parser._consume_mistral_call(obj_text: 'str', out: 'list[dict]', id_offset: 'int') -> 'None'","_decoded_key": "core.inference.tool_call_parser._decoded_key(literal: 'str') -> \"'str | None'\"","_disabled_gemma_call_end_containing_signal": "core.inference.tool_call_parser._disabled_gemma_call_end_containing_signal(content: 'str', enabled_tool_names: 'Optional[set]') -> 'int | None'",+ "_escape_bare_quotes": "core.inference.tool_call_parser._escape_bare_quotes(raw: 'str') -> 'str'","_escaped_string_content_spans": "core.inference.tool_call_parser._escaped_string_content_spans(text: 'str', start: 'int', end: 'int') -> 'list'","_find_outside_json_strings": "core.inference.tool_call_parser._find_outside_json_strings(text: 'str', needle: 'str', start: 'int') -> 'int'","_first_foreign_tool_signal": "core.inference.tool_call_parser._first_foreign_tool_signal(content: 'str') -> 'int | None'",@@ -260,6 +265,7 @@"_only_a_code_fence": "core.inference.tool_call_parser._only_a_code_fence(between: 'str') -> 'bool'","_open_inline_code_run": "core.inference.tool_call_parser._open_inline_code_run(text: 'str', pos: 'int') -> 'bool'","_parse_bare_rehearsals": "core.inference.tool_call_parser._parse_bare_rehearsals(content: 'str', *, id_offset: 'int' = 0, enabled_tool_names: 'Optional[set]' = None) -> 'list[dict]'",+ "_parse_closed_call_unescaped_quotes": "core.inference.tool_call_parser._parse_closed_call_unescaped_quotes(content: 'str', *, id_offset: 'int') -> 'list[dict]'","_parse_deepseek_tool_calls": "core.inference.tool_call_parser._parse_deepseek_tool_calls(content: 'str', *, id_offset: 'int', allow_incomplete: 'bool' = True) -> 'list[dict]'","_parse_function_xml": "core.inference.tool_call_parser._parse_function_xml(content: 'str', *, id_offset: 'int', allow_incomplete: 'bool' = True) -> 'list[dict]'","_parse_gemma_tool_calls": "core.inference.tool_call_parser._parse_gemma_tool_calls(content: 'str', *, id_offset: 'int', allow_incomplete: 'bool' = True, enabled_tool_names: 'Optional[set]' = None) -> 'list[dict]'",diff --git a/studio/backend/tests/test_tool_call_unescaped_quotes_in_code.py b/studio/backend/tests/test_tool_call_unescaped_quotes_in_code.pynew file mode 100644index 00000000000..a9657b1f462--- /dev/null+++ b/studio/backend/tests/test_tool_call_unescaped_quotes_in_code.py@@ -0,0 +1,86 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Small Qwen models writing Python into a Hermes call often leave the code's own double quotes unescaped+(Qwen3-0.6B at temperature 1.2: about a quarter of its python calls). Strict JSON and brace matching both+lose that call; the ``</tool_call>`` closer still bounds it, so a single string argument is recovered.+Anything that could be a different call is left alone."""++from __future__ import annotations++import json++import pytest++from core.inference.tool_call_parser import parse_tool_calls_from_text++ENABLED = {"python", "web_search"}+++def _calls(text, **kw):+ return [+ (c["function"]["name"], json.loads(c["function"]["arguments"]))+ for c in parse_tool_calls_from_text(text, enabled_tool_names = ENABLED, **kw)+ ]+++# Verbatim shape from a real Qwen3-0.6B Q4_K_M sample.+REAL = (+ '\n\n<tool_call>\n{"name": "python", "arguments": {"code": "import json\\njson.dumps({\'a\': {\'b\': [1, '+ "{'c': '}{'}]}, 'msg': \"it's \\\"quoted\\\"\"})\"}}\n</tool_call>"+)+++def test_real_sample_is_recovered_verbatim():+ # The model's own ``\\"`` beside bare quotes is the code's escape, so the recovered code is valid Python.+ code = "import json\njson.dumps({'a': {'b': [1, {'c': '}{'}]}, 'msg': \"it's \\\"quoted\\\"\"})"+ assert _calls(REAL) == [("python", {"code": code})]+ compile(code, "<tool>", "exec")+++def test_escaped_quotes_without_bare_quotes_are_json_escapes():+ text = '<tool_call>\n{"name": "python", "arguments": {"code": "print(\\"a\\")\nprint(\\"b\\")"}}\n</tool_call>'+ assert _calls(text) == [("python", {"code": 'print("a")\nprint("b")'})]++[email protected]("key", ["arguments", "parameters"])+def test_simple_unescaped_quotes(key):+ text = '<tool_call>\n{"name": "python", "' + key + '": {"code": "print("hi")"}}\n</tool_call>'+ assert _calls(text) == [("python", {"code": 'print("hi")'})]+++ "text",+ [+ # a second argument may have been swallowed: the value's end is not knowable+ '<tool_call>\n{"name": "python", "arguments": {"code": "print("hi")", "timeout": "5"}}\n</tool_call>',+ # the same with a single-quoted or unquoted key, and an outer key after the arguments object+ '<tool_call>\n{"name": "terminal", "arguments": {"command": "rm -rf "build"", \'dry_run\': "true"}}\n</tool_call>',+ '<tool_call>\n{"name": "terminal", "arguments": {"command": "rm -rf "build"", dry_run: "true"}}\n</tool_call>',+ '<tool_call>\n{"name": "terminal", "arguments": {"command": "echo "a"}, "parameters": {"command": "rm -rf ~"}}\n</tool_call>',+ # no closer: possibly cut off+ '<tool_call>\n{"name": "python", "arguments": {"code": "print("hi")"}}',+ # a rehearsal inside reasoning, and an example inside a code fence+ '<think>\n<tool_call>\n{"name": "python", "arguments": {"code": "print("hi")"}}\n</tool_call>\n</think>',+ '```\n<tool_call>\n{"name": "python", "arguments": {"code": "print("hi")"}}\n</tool_call>\n```',+ ],+)+def test_ambiguous_shapes_stay_text(text):+ assert _calls(text) == []+++def test_strict_mode_does_not_heal():+ text = '<tool_call>\n{"name": "python", "arguments": {"code": "print("hi")"}}\n</tool_call>'+ assert _calls(text, allow_incomplete = False) == []+++def test_well_formed_call_is_unchanged():+ text = '<tool_call>\n{"name": "python", "arguments": {"code": "print(\\"ok\\")"}}\n</tool_call>'+ assert parse_tool_calls_from_text(text, enabled_tool_names = ENABLED)[0]["function"][+ "arguments"+ ] == json.dumps({"code": 'print("ok")'})+++def test_a_call_inside_an_unclosed_call_body_stays_data():+ text = '<|tool_call>call:python{code:x<tool_call>\n{"name": "python", "arguments": {"code": "print("hi")"}}\n</tool_call>'+ assert _calls(text) == []