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: heal tool-call arguments sampled as near-JSON instead of passing them whole as text (#16005)
Daniel Han4e955395fc7b
diff --git a/studio/backend/core/inference/relaxed_json.py b/studio/backend/core/inference/relaxed_json.pynew file mode 100644index 00000000000..1a565b34c9d--- /dev/null+++ b/studio/backend/core/inference/relaxed_json.py@@ -0,0 +1,210 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Read a tool-call argument object a model sampled with near-JSON syntax.++Only syntax is repaired, never content: single-quoted strings, unquoted keys, Python literals+(True / False / None), trailing commas, raw newlines and tabs inside strings, and arguments that were+JSON-encoded as a string once or twice. Anything ambiguous (an unescaped quote inside a string, an+unknown bare word, an unterminated string, unbalanced brackets) returns None, so a truncated or garbled+call is never turned into a different one. One linear pass; callers use it only after strict JSON failed.+"""++from __future__ import annotations++import json+from typing import Any, Optional++_LITERALS = {+ "true": "true",+ "True": "true",+ "false": "false",+ "False": "false",+ "null": "null",+ "None": "null",+}+_CONTROL_ESCAPES = {"\n": "\\n", "\r": "\\r", "\t": "\\t"}+_MAX_STRING_LAYERS = 2+++def _reject_constant(name: str) -> Any:+ raise ValueError(f"{name} is not JSON")+++# NaN / Infinity are not JSON and would replay as arguments no provider parses.+_DECODER = json.JSONDecoder(parse_constant = _reject_constant)+++def _strictify(text: str) -> Optional[str]:+ """The strict-JSON spelling of ``text``, or None when the repair would have to guess."""+ out: list[str] = []+ n = len(text)+ i = 0+ pending_comma = False+ pending_space: list[str] = []+ while i < n:+ c = text[i]+ if c in " \t\r\n":+ (pending_space if pending_comma else out).append(c)+ i += 1+ continue+ if pending_comma:+ pending_comma = False+ if c not in "}]":+ out.append(",")+ out.extend(pending_space)+ pending_space = []+ if c == ",":+ pending_comma = True+ i += 1+ continue+ if c == '"' or c == "'":+ quote = c+ j = i + 1+ buf = ['"']+ while True:+ if j >= n:+ return None # unterminated string: truncated, never guessed+ ch = text[j]+ if ch == quote:+ break+ if ch == "\\":+ if j + 1 >= n:+ return None+ nxt = text[j + 1]+ if quote == "'" and nxt == "'":+ buf.append("'")+ else:+ buf.append(text[j : j + 2])+ j += 2+ continue+ if ch == '"':+ buf.append('\\"') # only reachable inside a single-quoted string+ else:+ buf.append(_CONTROL_ESCAPES.get(ch, ch))+ j += 1+ buf.append('"')+ out.append("".join(buf))+ i = j + 1+ continue+ if c.isdigit() or c == "-":+ j = i + 1+ while j < n and text[j] in "0123456789eE+-.":+ j += 1+ out.append(text[i:j])+ i = j+ continue+ if c.isalpha() or c == "_":+ j = i + 1+ while j < n and (text[j].isalnum() or text[j] in "_-"):+ j += 1+ word = text[i:j]+ k = j+ while k < n and text[k] in " \t\r\n":+ k += 1+ if k < n and text[k] == ":":+ out.append(json.dumps(word)) # unquoted key+ elif word in _LITERALS:+ out.append(_LITERALS[word])+ else:+ return None # a bare word that is not a literal: not ours to guess+ i = j+ continue+ out.append(c)+ i += 1+ if pending_comma:+ out.append(",")+ return "".join(out)+++def relaxed_object_end(text: str, start: int) -> Optional[int]:+ """Index of the ``}`` closing the object at ``start``, skipping single- and double-quoted strings as+ ``_strictify`` reads them, so a brace inside a single-quoted argument never ends the call."""+ depth = 0+ quote = None+ i, n = start, len(text)+ while i < n:+ c = text[i]+ if quote:+ if c == "\\":+ i += 1+ elif c == quote:+ quote = None+ elif c == '"' or c == "'":+ quote = c+ elif c in "{[":+ depth += 1+ elif c in "}]":+ depth -= 1+ if depth == 0:+ return i if c == "}" else None+ if depth < 0:+ return None+ i += 1+ return None+++def relaxed_object_starts(text: str) -> frozenset:+ """Positions of the ``{`` that open an object at brace depth 0, quotes honoured inside braces only.+ Near-JSON is read only there: an object nested in another's argument, or after one that never closes,+ is read strictly, as before."""+ starts = []+ depth = 0+ quote = None+ i, n = 0, len(text)+ while i < n:+ c = text[i]+ if quote:+ if c == "\\":+ i += 1+ elif c == quote:+ quote = None+ elif c == "{":+ if depth == 0:+ starts.append(i)+ depth += 1+ elif c == "}":+ depth = max(depth - 1, 0)+ elif depth and (c == '"' or c == "'"):+ quote = c+ i += 1+ return frozenset(starts)+++_TOP_LEVEL_CACHE: tuple = (None, frozenset())+++def relaxed_allowed_at(text: str, pos: int) -> bool:+ global _TOP_LEVEL_CACHE+ cached = _TOP_LEVEL_CACHE+ if cached[0] is not text:+ cached = (text, relaxed_object_starts(text))+ _TOP_LEVEL_CACHE = cached+ return pos in cached[1]+++def relaxed_json_object(text: Any) -> Optional[dict]:+ """The argument object ``text`` spells, or None. Strict JSON first; a JSON string holding an object+ (arguments encoded once or twice) is unwrapped; then the syntax repair above."""+ if not isinstance(text, str):+ return None+ value: Any = text+ for _ in range(_MAX_STRING_LAYERS + 1):+ if not isinstance(value, str):+ break+ stripped = value.strip()+ try:+ value = _DECODER.decode(stripped)+ continue+ except (ValueError, RecursionError):+ pass+ if not stripped.startswith("{"):+ return None+ repaired = _strictify(stripped)+ if repaired is None:+ return None+ try:+ value = _DECODER.decode(repaired)+ except (ValueError, RecursionError):+ return None+ return value if isinstance(value, dict) else Nonediff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex e433b58a768..71a1b644713 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -13,6 +13,7 @@ from typing import Any, Optional# Qwen/Hermes, Qwen3.5 XML and Gemma 4 live in core.tool_healing; this module adds the restfrom core import tool_healing as _tool_healing+from core.inference.relaxed_json import relaxed_allowed_at, relaxed_json_object, relaxed_object_end# Shared with tool_healing so every markerless parse path applies the same guard; wrapped and marker forms are unaffected._markerless_promotable = _tool_healing._markerless_promotable@@ -2418,6 +2419,30 @@ def _parse_closed_call_unescaped_quotes(content: str, *, id_offset: int) -> list)+def _loads_call_object(text: str, *, relaxed: bool = True):+ """A wrapped call's JSON object: strict first; near-JSON a model sampled (single quotes, a trailing comma,+ True/None, unquoted keys) only when strict fails and healing is on. None when neither reads an object."""+ try:+ return json.loads(text)+ except (json.JSONDecodeError, ValueError):+ return relaxed_json_object(text) if relaxed else None+++def _call_object_end(+ text: str,+ start: int,+ relaxed: bool = True,+) -> "tuple[int | None, bool]":+ """The call object's closing brace, and whether near-JSON may still be read. A relaxed read matches+ single-quoted strings too, so a brace in one never ends the call and scanning never resumes inside its+ argument; an object that never closes that way gets JSON brace matching, strict for the rest of the text."""+ if relaxed and relaxed_allowed_at(text, start):+ end = relaxed_object_end(text, start)+ if end is not None:+ return end, True+ return _balanced_brace_end(text, start), False++def _parse_tool_call_json(content: str,*,@@ -2425,17 +2450,17 @@ def _parse_tool_call_json(allow_incomplete: bool = True,) -> list[dict]:out: list[dict] = []+ relaxed = allow_incompletefor m in _TC_JSON_START_RE.finditer(content):brace_start = m.end() - 1- end = _balanced_brace_end(content, brace_start)+ end, relaxed = _call_object_end(content, brace_start, relaxed)if end is None:continue# Strict: a body that never closed ``<tool_call>`` is truncated; trailing prose is tolerated.if not allow_incomplete and not content[end + 1 :].lstrip().startswith("</tool_call>"):continue- try:- obj = json.loads(content[brace_start : end + 1])- except (json.JSONDecodeError, ValueError):+ obj = _loads_call_object(content[brace_start : end + 1], relaxed = relaxed)+ if not isinstance(obj, dict):continuename = obj.get("name", "")args = obj.get("arguments")@@ -2691,6 +2716,8 @@ def _parse_llama3_python_tag(# 2. ``<|python_tag|>{json}``; raw_decode peels ``;``-separated objects.if not out:decoder = json.JSONDecoder()+ # Relaxed spans already tried never overlap, so every char is brace-matched at most once (no O(n^2)).+ relaxed_from = 0 if allow_incomplete else len(content)idx = content.find(_LLAMA3_PYTHON_TAG)while idx >= 0:search_from = idx + len(_LLAMA3_PYTHON_TAG)@@ -2706,8 +2733,16 @@ def _parse_llama3_python_tag(try:obj, end_offset = decoder.raw_decode(content[brace:])except (json.JSONDecodeError, ValueError):- cursor = brace + 1- continue+ obj = None+ if brace >= relaxed_from and relaxed_allowed_at(content, brace):+ close = relaxed_object_end(content, brace)+ relaxed_from = len(content) if close is None else close + 1+ if close is not None:+ obj = relaxed_json_object(content[brace : close + 1])+ if obj is None:+ cursor = brace + 1+ continue+ end_offset = close + 1 - braceif not isinstance(obj, dict):cursor = brace + end_offsetcontinue@@ -2863,14 +2898,15 @@ def _parse_mistral_tool_calls(if content[k] == "[":return _parse_mistral_array(content, k, id_offset, allow_incomplete = allow_incomplete)+ relaxed = allow_incompleteif content[k] == "{":# Pre-v11 single ``{"name":...}``; fall through without a ``name`` so v11+ still runs.- end = _balanced_brace_end(content, k)+ end, relaxed = _call_object_end(content, k, relaxed)if end is not None:try:- obj = json.loads(content[k : end + 1])+ obj = _loads_call_object(content[k : end + 1], relaxed = relaxed)if isinstance(obj, dict) and obj.get("name"):- _consume_mistral_call(content[k : end + 1], out, id_offset)+ _consume_mistral_call(content[k : end + 1], out, id_offset, relaxed = relaxed)return outexcept (json.JSONDecodeError, ValueError):pass@@ -2893,14 +2929,10 @@ def _parse_mistral_tool_calls(if after_name >= len(content) or content[after_name] != "{":pos = content.find(_MISTRAL_TRIGGER, cur)continue- end = _balanced_brace_end(content, after_name)+ end, relaxed = _call_object_end(content, after_name, relaxed)if end is None:break- try:- args = json.loads(content[after_name : end + 1])- except (json.JSONDecodeError, ValueError):- pos = content.find(_MISTRAL_TRIGGER, end + 1)- continue+ args = _loads_call_object(content[after_name : end + 1], relaxed = relaxed)if not isinstance(args, dict):pos = content.find(_MISTRAL_TRIGGER, end + 1)continue@@ -2968,23 +3000,27 @@ def _parse_mistral_array(# Advance past each balanced object instead of rescanning from every ``{`` (ReDoS).pos = 0blen = len(body)+ relaxed = allow_incompletewhile pos < blen:brace = body.find("{", pos)if brace < 0:break- end = _balanced_brace_end(body, brace)+ end, relaxed = _call_object_end(body, brace, relaxed)if end is None:break # truncated mid-object: nothing after it can balance- _consume_mistral_call(body[brace : end + 1], out, id_offset)+ _consume_mistral_call(body[brace : end + 1], out, id_offset, relaxed = relaxed)pos = end + 1return out-def _consume_mistral_call(obj_text: str, out: list[dict], id_offset: int) -> None:- try:- obj = json.loads(obj_text)- except (json.JSONDecodeError, ValueError):- return+def _consume_mistral_call(+ obj_text: str,+ out: list[dict],+ id_offset: int,+ *,+ relaxed: bool = True,+) -> None:+ obj = _loads_call_object(obj_text, relaxed = relaxed)if not isinstance(obj, dict):returnname = obj.get("name") or ""@@ -3776,6 +3812,7 @@ def _parse_deepseek_tool_calls(return outscan_end = end_pos if end_pos >= 0 else len(content)body = content[scan_start:scan_end]+ relaxed = allow_incompletepos = 0while pos < len(body):@@ -3794,14 +3831,10 @@ def _parse_deepseek_tool_calls(if json_start >= len(body) or body[json_start] != "{":pos = json_startcontinue- brace_end = _balanced_brace_end(body, json_start)+ brace_end, relaxed = _call_object_end(body, json_start, relaxed)if brace_end is None:break- try:- args = json.loads(body[json_start : brace_end + 1])- except (json.JSONDecodeError, ValueError):- pos = brace_end + 1- continue+ args = _loads_call_object(body[json_start : brace_end + 1], relaxed = relaxed)if not isinstance(args, dict):pos = brace_end + 1continue@@ -3844,7 +3877,7 @@ def _parse_deepseek_tool_calls(if json_start >= len(body) or body[json_start] != "{":pos = sep_pos + len(_DEEPSEEK_SEP)continue- brace_end = _balanced_brace_end(body, json_start)+ brace_end, relaxed = _call_object_end(body, json_start, relaxed)if brace_end is None:breakif not allow_incomplete:@@ -3854,11 +3887,7 @@ def _parse_deepseek_tool_calls(if not body.startswith(_DEEPSEEK_CALL_END, after):pos = brace_end + 1continue- try:- args = json.loads(body[json_start : brace_end + 1])- except (json.JSONDecodeError, ValueError):- pos = brace_end + 1- continue+ args = _loads_call_object(body[json_start : brace_end + 1], relaxed = relaxed)if not isinstance(args, dict):pos = brace_end + 1continue@@ -4025,6 +4054,7 @@ def _parse_kimi_section_body("""Parse one Kimi K2 section body (between begin / end markers)."""out: list[dict] = []pos = 0+ relaxed = allow_incompletewhile pos < len(body):call_start = body.find(_KIMI_CALL_BEGIN, pos)if call_start < 0:@@ -4059,7 +4089,7 @@ def _parse_kimi_section_body(if json_start >= len(body) or body[json_start] != "{":pos = arg_begin + len(_KIMI_ARG_BEGIN)continue- brace_end = _balanced_brace_end(body, json_start)+ brace_end, relaxed = _call_object_end(body, json_start, relaxed)if brace_end is None:# Skip a malformed call but keep parsing later ones (vLLM recovers them).nxt = body.find(_KIMI_CALL_BEGIN, json_start)@@ -4067,11 +4097,7 @@ def _parse_kimi_section_body(breakpos = nxtcontinue- try:- args = json.loads(body[json_start : brace_end + 1])- except (json.JSONDecodeError, ValueError):- pos = brace_end + 1- continue+ args = _loads_call_object(body[json_start : brace_end + 1], relaxed = relaxed)if not isinstance(args, dict):pos = brace_end + 1continuediff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex 2e6c5ced71f..21e436c6eab 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -674,6 +674,22 @@ def _tool_healing_exec_names() -> "frozenset[str]":return EXECUTION_CLASS_TOOL_NAMES+def _relaxed_arguments(raw_args: str, properties: Any) -> "dict | None":+ """The object near-JSON arguments spell, kept only when it names a declared argument."""+ from core.inference.relaxed_json import relaxed_json_object # noqa: PLC0415 -- failure path only++ repaired = relaxed_json_object(raw_args)+ if not repaired:+ return None+ if (+ isinstance(properties, Mapping)+ and properties+ and not any(k in properties for k in repaired)+ ):+ return None+ return repaired++def coerce_tool_arguments(raw_args: Any,*,@@ -699,6 +715,13 @@ def coerce_tool_arguments(# Must not raise: this runs before the budget gate, so a raise aborts the whole turn.passif heal:+ # Near-JSON (single quotes, a trailing comma, True/None, an object encoded as a string) is the+ # object it spells; wrapping it whole would run the tool on the call's own source text.+ repaired = _relaxed_arguments(raw_args, properties)+ if repaired is not None:+ return CoercedArguments(+ coerce_arguments_by_schema(repaired, properties, repair = heal), True+ )# Text that opens like JSON but fails to parse is a truncated object, not a bare string;# wrapping it whole would pass the fragment as the argument value.key = (diff --git a/studio/backend/core/tool_healing.py b/studio/backend/core/tool_healing.pyindex 734bcdbbfa2..8eedf4032ac 100644--- a/studio/backend/core/tool_healing.py+++ b/studio/backend/core/tool_healing.py@@ -781,6 +781,33 @@ def marker_coverage(content: str) -> list[tuple[int, int]]:return _marker_coverage(content, _build_markers(content))+def _relaxed_allowed_at(content: str, pos: int) -> bool:+ from core.inference.relaxed_json import relaxed_allowed_at # noqa: PLC0415 -- cycle at import time+ return relaxed_allowed_at(content, pos)+++def _relaxed_object_end(content: str, start: int):+ from core.inference.relaxed_json import relaxed_object_end # noqa: PLC0415 -- cycle at import time+ return relaxed_object_end(content, start)+++def _loads_wrapped_call(text: str, *, relaxed: bool = True) -> dict:+ """A wrapped call's JSON object; near-JSON a model sampled (single quotes, a trailing comma, True/None,+ unquoted keys) is read only after strict JSON fails and only when healing is on. Raises ValueError+ when neither reads an object."""+ try:+ return json.loads(text)+ except (json.JSONDecodeError, ValueError):+ if not relaxed:+ raise+ from core.inference.relaxed_json import relaxed_json_object # noqa: PLC0415 -- failure path only++ obj = relaxed_json_object(text)+ if obj is None:+ raise+ return obj++def parse_tool_calls_from_text(content: str,*,@@ -817,11 +844,25 @@ def parse_tool_calls_from_text(]coverage = _marker_coverage(content, markers)covered_until = -1+ relaxed = allow_incompletefor idx, (start, brace_end, kind, m) in enumerate(markers):covered_by_earlier_marker = start < covered_untilcovered_until = max(covered_until, coverage[idx][1])if covered_by_earlier_marker:continue+ relaxed_end = None+ if relaxed and kind == "json" and not _relaxed_allowed_at(content, m.end() - 1):+ relaxed = False+ if relaxed and kind == "json":+ # JSON brace matching ends a single-quoted argument at a brace inside it; markers in that+ # argument are data. An object that never closes this way leaves the rest strict.+ relaxed_end = _relaxed_object_end(content, m.end() - 1)+ if relaxed_end is None:+ relaxed = False+ elif relaxed_end != brace_end:+ brace_end = relaxed_end+ else:+ relaxed_end = Noneif brace_end < 0:continueif not allow_incomplete:@@ -831,7 +872,14 @@ def parse_tool_calls_from_text(continuetry:if kind == "json":- obj = json.loads(content[m.end() - 1 : brace_end + 1])+ try:+ obj = _loads_wrapped_call(content[m.end() - 1 : brace_end + 1], relaxed = relaxed)+ except ValueError:+ if relaxed_end is not None:+ relaxed = False+ raise+ if relaxed_end is not None:+ covered_until = max(covered_until, relaxed_end + 1)name = obj.get("name", "")# Accept "parameters" (Llama-3.2) and "args" (TML Inkling) as aliases.arguments = obj.get("arguments")diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 435626a6225..0f20337c6a8 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -1621,10 +1621,15 @@"kind": "def","signature": "text: str, enabled_tool_names"},+ "_call_object_end": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, start: int, relaxed: bool=True"+ },"_consume_mistral_call": {"decorators": [],"kind": "def",- "signature": "obj_text: str, out: list[dict], id_offset: int"+ "signature": "obj_text: str, out: list[dict], id_offset: int, *, relaxed: bool=True"},"_decoded_key": {"decorators": [],@@ -1759,6 +1764,11 @@"kind": "def","signature": "body: str, p: int, n: int"},+ "_loads_call_object": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, *, relaxed: bool=True"+ },"_marker_inside_leading_envelope": {"decorators": [],"kind": "def",@@ -2371,6 +2381,11 @@"kind": "def","signature": "body: str"},+ "_loads_wrapped_call": {+ "decorators": [],+ "kind": "def",+ "signature": "text: str, *, relaxed: bool=True"+ },"_marker_coverage": {"decorators": [],"kind": "def",@@ -2416,6 +2431,16 @@"kind": "def","signature": "m, pat, text, spans, enabled_tool_names"},+ "_relaxed_allowed_at": {+ "decorators": [],+ "kind": "def",+ "signature": "content: str, pos: int"+ },+ "_relaxed_object_end": {+ "decorators": [],+ "kind": "def",+ "signature": "content: str, start: int"+ },"_split_top_level_commas": {"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 5c991f610ff..67f84c9950e 100644--- a/studio/backend/tests/data/refactor_guard/golden_outputs.json+++ b/studio/backend/tests/data/refactor_guard/golden_outputs.json@@ -3,6 +3,7 @@"_balanced_bracket_end": "19de8fb63babb0861475879bfbc13edd8efde741a2354b8bee9028d598a0c92d","_balanced_paren_end": "f45332aefa427ff956758a2eaac5cb851ba2e86f53a930fe2b99920118f3c7c4","_blocked_markerless_body_spans": "3b9e46336b0bf3b24f00d639e7f891bd4176a9ce7207e694e28524b69245605b",+ "_call_object_end": "1ba933d7c9f25ded793c98ab912d20245809ca0434179d1d225aa0cc47b9aca0","_consume_mistral_call": "813544e2d389e368c2d6c77f333ae1d07409d9cf0d3bdad8735c116577bcd380","_decoded_key": "78aa12becfd9bc1f17e0bdb39dfe16824279dc82d4bd5a97c5b511904ad773c0","_disabled_gemma_call_end_containing_signal": "c08417f20bd3f6c67d09c63f750894aa02104faef091f31dba29c57e585ac69a",@@ -29,6 +30,7 @@"_last_bare_call_word": "6fd7aa3d3e8802e1f11296d2687af0c981eb2237c832f2f3afd6a1dff3909624","_leading_json_value_end": "65730eca2c69dcccfabe521051483c853939c27c91d2ff02e0e10654ab0a65d0","_llama3_kv_value": "9a358426c0018864e7fa5c041eb4b721006aae470456f95be7f8cea2c8314490",+ "_loads_call_object": "4f59718464ebfce224f8df8891c9253619899ea4e797cd9e6751e57c9fcd2ce9","_marker_inside_leading_envelope": "9221375eecada36956b1d2ccc43dca17b34ded6de72c19e424a9902fc3bbe91a","_mask_blocked_bodies": "97cbc2bedcb6749064571cf3b3117e377d0e28b0b8acc3a97ecaae8b627a3aa6","_mistral_region_end": "4319a6b9f647d1623d8cedcfaa1fcdef1e661fde04d42a01ea3bb98f3726f9e1",@@ -104,10 +106,13 @@"_inside_open_parameter": "b94f91fd87588ec8c9dd80f2962c17644d1360ee57c456ea4ab6a90ca12420e7","_iter_bracket_spans": "2def0d358f3aa7790bcc69158040f1e685dde85b870d1b1c8feaa3f179df2188","_json_object_body": "e814b8ed198a73fe7f35306b15d5e796e453449a3d47e369c22732ba32adf18d",+ "_loads_wrapped_call": "bf2c040c5c2e68222d018ecc7fd29a7062bcd12fabaaba7216e7887797d5497e","_marker_coverage": "f2332dd262243358dc4df45b96099bcdb29478cce0430cdacd81f38cce4286d0","_normalise_gemma_quoted_strings": "97fdc0d3c45e32ce3e7749ae1cccbba6bb2a82035dfe05138420684e7fc8fe27","_quote_gemma_array_elements": "d20585abf6d8721545c0a072aa9ae416bcf09aab6dc501c031481234dcb8bb71","_quote_gemma_object_keys": "4872ee71159b48755e78ee5388ce29344eef31f8280dc02b3555a433c20de559",+ "_relaxed_allowed_at": "2952d84242c627b6a044a73947c2fc18db7ea07b3a7ab45a2b2fe99dff3a33c1",+ "_relaxed_object_end": "f1e648a6cd1a53fa2b4c74b9b9033bbb603460de832d80d6f760d49839170c9d","_split_top_level_commas": "dc04334a5d7f2d98d9737d30e2e6ff0b2a163c6e413ec85d7124da441325ba47","_strip_bracket_tag_calls": "2af3b1d6e7c741417b5d2bed967e6417ffd1b7e006b90cdd33c340e5ab9e45ff","_strip_closed_blocks_outside_gemma": "c8e5641bfbd6b5fa3549f9cb5654de8a054af585ac946842b3c1ef4417765823",diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex 078167e2cb4..0e836dfedf8 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -114,6 +114,7 @@"_balanced_paren_end","_bare_json_call_shaped","_blocked_markerless_body_spans",+ "_call_object_end","_consume_mistral_call","_decoded_key","_disabled_gemma_call_end_containing_signal",@@ -142,6 +143,7 @@"_last_bare_call_word","_leading_json_value_end","_llama3_kv_value",+ "_loads_call_object","_marker_inside_leading_envelope","_markerless_blocked_execution","_markerless_execution_class",@@ -209,6 +211,9 @@"promotable_gemma_call_pos","re","reasoning_cap_spent_message",+ "relaxed_allowed_at",+ "relaxed_json_object",+ "relaxed_object_end","repeated_result_message","reprompt_to_act_message","starved_result_message",@@ -225,7 +230,8 @@"_balanced_paren_end": "core.inference.tool_call_parser._balanced_paren_end(text: 'str', paren_start: 'int') -> \"'int | None'\"","_bare_json_call_shaped": "core.inference.tool_call_parser._bare_json_call_shaped(obj) -> 'bool'","_blocked_markerless_body_spans": "core.inference.tool_call_parser._blocked_markerless_body_spans(text: 'str', enabled_tool_names) -> 'list'",- "_consume_mistral_call": "core.inference.tool_call_parser._consume_mistral_call(obj_text: 'str', out: 'list[dict]', id_offset: 'int') -> 'None'",+ "_call_object_end": "core.inference.tool_call_parser._call_object_end(text: 'str', start: 'int', relaxed: 'bool' = True) -> \"'tuple[int | None, bool]'\"",+ "_consume_mistral_call": "core.inference.tool_call_parser._consume_mistral_call(obj_text: 'str', out: 'list[dict]', id_offset: 'int', *, relaxed: 'bool' = True) -> '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'",@@ -253,6 +259,7 @@"_last_bare_call_word": "core.inference.tool_call_parser._last_bare_call_word(text: 'str') -> 'int'","_leading_json_value_end": "core.inference.tool_call_parser._leading_json_value_end(text: 'str') -> 'int | None'","_llama3_kv_value": "core.inference.tool_call_parser._llama3_kv_value(body: 'str', p: 'int', n: 'int') -> 'tuple[Any, int | None]'",+ "_loads_call_object": "core.inference.tool_call_parser._loads_call_object(text: 'str', *, relaxed: 'bool' = True)","_marker_inside_leading_envelope": "core.inference.tool_call_parser._marker_inside_leading_envelope(content: 'str', enabled_tool_names: 'Optional[set]' = None) -> 'bool'","_markerless_blocked_execution": "core.tool_healing._markerless_blocked_execution(name, enabled_tool_names) -> 'bool'","_markerless_execution_class": "core.tool_healing._markerless_execution_class(name) -> 'bool'",@@ -315,6 +322,9 @@"parse_tool_calls_from_text": "core.inference.tool_call_parser.parse_tool_calls_from_text(content: 'str', *, id_offset: 'int' = 0, allow_incomplete: 'bool' = True, enabled_tool_names: 'Optional[set]' = None) -> 'list[dict]'","promotable_gemma_call_pos": "core.inference.tool_call_parser.promotable_gemma_call_pos(text: 'str', enabled_tool_names, start: 'int' = 0, *, floor: 'int' = 0, streaming: 'bool' = False) -> 'int'","reasoning_cap_spent_message": "core.inference.tool_call_parser.reasoning_cap_spent_message(max_tokens: 'Optional[int]' = None) -> 'str'",+ "relaxed_allowed_at": "core.inference.relaxed_json.relaxed_allowed_at(text: 'str', pos: 'int') -> 'bool'",+ "relaxed_json_object": "core.inference.relaxed_json.relaxed_json_object(text: 'Any') -> 'Optional[dict]'",+ "relaxed_object_end": "core.inference.relaxed_json.relaxed_object_end(text: 'str', start: 'int') -> 'Optional[int]'","repeated_result_message": "core.inference.tool_call_parser.repeated_result_message(tool_name: 'str', times: 'int', last_result: 'str') -> 'str'","reprompt_to_act_message": "core.inference.tool_call_parser.reprompt_to_act_message(tool_hint: 'str') -> 'str'","starved_result_message": "core.inference.tool_call_parser.starved_result_message(tool_name: 'str', result: 'str') -> 'str'",@@ -378,6 +388,7 @@"_inside_open_parameter","_iter_bracket_spans","_json_object_body",+ "_loads_wrapped_call","_marker_coverage","_markerless_blocked_execution","_markerless_execution_class",@@ -387,6 +398,8 @@"_quote_gemma_array_elements","_quote_gemma_object_keys","_rehearsal_strip",+ "_relaxed_allowed_at",+ "_relaxed_object_end","_split_top_level_commas","_strip_bracket_tag_calls","_strip_closed_blocks_outside_gemma",@@ -420,6 +433,7 @@"_inside_open_parameter": "core.tool_healing._inside_open_parameter(content: 'str', pos: 'int', *, param_start_re=None, param_closers=('</parameter>',), func_closers=('</function>',)) -> 'bool'","_iter_bracket_spans": "core.tool_healing._iter_bracket_spans(text: 'str', start: 'int' = 0, enabled_tool_names=None)","_json_object_body": "core.tool_healing._json_object_body(body: 'str') -> 'dict | None'",+ "_loads_wrapped_call": "core.tool_healing._loads_wrapped_call(text: 'str', *, relaxed: 'bool' = True) -> 'dict'","_marker_coverage": "core.tool_healing._marker_coverage(content: 'str', markers) -> 'list[tuple[int, int]]'","_markerless_blocked_execution": "core.tool_healing._markerless_blocked_execution(name, enabled_tool_names) -> 'bool'","_markerless_execution_class": "core.tool_healing._markerless_execution_class(name) -> 'bool'",@@ -429,6 +443,8 @@"_quote_gemma_array_elements": "core.tool_healing._quote_gemma_array_elements(body: 'str') -> 'str'","_quote_gemma_object_keys": "core.tool_healing._quote_gemma_object_keys(src: 'str') -> 'str'","_rehearsal_strip": "core.tool_healing._rehearsal_strip(m, pat, text, spans, enabled_tool_names) -> 'str'",+ "_relaxed_allowed_at": "core.tool_healing._relaxed_allowed_at(content: 'str', pos: 'int') -> 'bool'",+ "_relaxed_object_end": "core.tool_healing._relaxed_object_end(content: 'str', start: 'int')","_split_top_level_commas": "core.tool_healing._split_top_level_commas(src: 'str') -> 'list'","_strip_bracket_tag_calls": "core.tool_healing._strip_bracket_tag_calls(text: 'str', enabled_tool_names=None) -> 'str'","_strip_closed_blocks_outside_gemma": "core.tool_healing._strip_closed_blocks_outside_gemma(text: 'str') -> 'str'",diff --git a/studio/backend/tests/test_tool_call_relaxed_arguments.py b/studio/backend/tests/test_tool_call_relaxed_arguments.pynew file mode 100644index 00000000000..81e3c2ac889--- /dev/null+++ b/studio/backend/tests/test_tool_call_relaxed_arguments.py@@ -0,0 +1,215 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A model can sample a call's arguments in near-JSON (single quotes, a trailing comma, True/None, unquoted+keys, raw newlines, an object encoded as a string). Healing reads the object it spells; anything ambiguous or+cut off is not guessed, and a malformed object is never passed whole as a string argument."""++from __future__ import annotations++import json++import pytest++from core.inference.tool_call_parser import parse_tool_calls_from_text+from core.inference.tool_loop_controller import UNPARSED_ARGUMENTS_KEY, coerce_tool_arguments++SEARCH_DOCS = [+ {+ "type": "function",+ "function": {+ "name": "search_docs",+ "parameters": {+ "type": "object",+ "properties": {+ "query": {"type": "string"},+ "limit": {"type": "integer"},+ "exact": {"type": "boolean"},+ },+ "required": ["query"],+ },+ },+ }+]+WANT = {"query": "rope scaling", "limit": 5, "exact": True}+ENABLED = {"web_search", "search_docs", "python"}+++ "raw",+ [+ "{'query': 'rope scaling', 'limit': 5, 'exact': true}",+ '{"query": "rope scaling", "limit": 5, "exact": true,}',+ '{query: "rope scaling", limit: 5, exact: true}',+ '{"query": "rope scaling", "limit": 5, "exact": True}',+ json.dumps(json.dumps(WANT)),+ json.dumps(json.dumps(json.dumps(WANT))),+ ],+)+def test_near_json_arguments_heal_to_the_object(raw):+ coerced = coerce_tool_arguments(+ raw, heal = True, tool_name = "search_docs", tool_schemas = SEARCH_DOCS+ )+ assert coerced.arguments == WANT+++ "raw",+ [+ '{"query": "rope scal', # cut off+ '{"query": "the "best" rope"}', # unescaped quote: ambiguous+ '{"query": "x", "mode": fast}', # unknown bare word+ '{"query": NaN}',+ ],+)+def test_ambiguous_or_cut_off_arguments_are_not_turned_into_an_object(raw):+ coerced = coerce_tool_arguments(+ raw, heal = True, tool_name = "search_docs", tool_schemas = SEARCH_DOCS+ )+ assert coerced.arguments != WANT+ assert set(coerced.arguments) <= {"query", UNPARSED_ARGUMENTS_KEY}+ if "query" in coerced.arguments:+ assert coerced.arguments["query"] == raw # unchanged fallback: the old single-string heal+++def test_plain_string_argument_heal_is_unchanged():+ coerced = coerce_tool_arguments(+ "rope scaling", heal = True, tool_name = "search_docs", tool_schemas = SEARCH_DOCS+ )+ assert coerced.arguments == {"query": "rope scaling"}+++def _parsed(text):+ return [+ (c["function"]["name"], json.loads(c["function"]["arguments"]))+ for c in parse_tool_calls_from_text(text, enabled_tool_names = ENABLED)+ ]+++CODE = "import json\nd = {'a': [1, 2]}\nprint(json.dumps(d))"+++ "text, want",+ [+ (+ "<tool_call>\n{\"name\": \"search_docs\", \"arguments\": {'query': 'rope scaling', 'limit': 5, 'exact': true}}\n</tool_call>",+ WANT,+ ),+ (+ '<tool_call>\n{"name": "search_docs", "arguments": {"query": "rope scaling", "limit": 5, "exact": true},}\n</tool_call>',+ WANT,+ ),+ (+ '<tool_call>\n{name: "search_docs", arguments: {query: "rope scaling", limit: 5, exact: True}}\n</tool_call>',+ WANT,+ ),+ (+ '<tool_call>\n{"name": "python", "arguments": {"code": "'+ + CODE.replace("\n", "\n").replace('"', '\\"')+ + '"}}\n</tool_call>',+ {"code": CODE},+ ),+ (+ '<|python_tag|>{"name": "search_docs", "parameters": {"query": "rope scaling", "limit": 5, "exact": True}}',+ WANT,+ ),+ ("[TOOL_CALLS]search_docs[ARGS]{'query': 'rope scaling', 'limit': 5, 'exact': true}", WANT),+ ],+)+def test_wrapped_calls_with_near_json_parse(text, want):+ assert len(_parsed(text)) == 1+ assert _parsed(text)[0][1] == want+++ "text",+ [+ '{"name": "search_docs", "parameters": {\'query\': \'x\'}}', # markerless bare JSON stays strict+ '<tool_call>\n{"name": "search_docs", "arguments": {\'query\': \'rope scal', # truncated+ "Use {'name': 'search_docs'} in your prompt.",+ ],+)+def test_bare_truncated_and_prose_stay_text(text):+ assert _parsed(text) == []+++def test_well_formed_call_is_identical():+ text = '<tool_call>\n{"name": "search_docs", "arguments": {"query": "rope scaling", "limit": 5, "exact": true}}\n</tool_call>'+ assert parse_tool_calls_from_text(text, enabled_tool_names = ENABLED)[0]["function"][+ "arguments"+ ] == json.dumps(WANT)+++ "text",+ [+ "<tool_call>\n{'name': 'search_docs', 'arguments': {'query': 'rope scaling'}}\n</tool_call>",+ '<tool_call>\n{"name": "search_docs", "arguments": {"query": "rope scaling",}}\n</tool_call>',+ "<|python_tag|>{'name': 'search_docs', 'parameters': {'query': 'rope scaling'}}",+ "[TOOL_CALLS]search_docs[ARGS]{'query': 'rope scaling'}",+ ],+)+def test_auto_heal_off_does_not_repair(text):+ # Auto-Heal off (allow_incomplete=False) is llama-server's strict path: near-JSON is not a call.+ assert len(_parsed(text)) == 1+ assert (+ parse_tool_calls_from_text(text, enabled_tool_names = ENABLED, allow_incomplete = False) == []+ )+++def test_python_tag_unbalanced_braces_stay_linear():+ import time++ text = "<|python_tag|>" + "{" * 20000+ t0 = time.perf_counter()+ assert _parsed(text) == []+ # Brace-matching every ``{`` to the end was O(n^2): about 150 s here, against well under a second.+ assert time.perf_counter() - t0 < 10+++_CODE = (+ '# }}\nexample = {name: "terminal", parameters: {command: "echo unintended"}}\n'+ '[TOOL_CALLS]terminal[ARGS]{command: "echo unintended"}'+)+++ "text",+ [+ "<|python_tag|>{'name': 'python', 'parameters': {'code': '" + _CODE + "'}}",+ "[TOOL_CALLS][{'name': 'python', 'arguments': {'code': '" + _CODE + "'}}]",+ "[TOOL_CALLS]python[ARGS]{'code': '" + _CODE + "'}",+ "<tool_call>{'name':'python','arguments':{'code':'"+ + _CODE+ + '\n<tool_call>{name: "terminal", '+ 'arguments: {command: "echo unintended"}}\'}}</tool_call>',+ "<|tool▁calls▁begin|><|tool▁call▁begin|>python<|tool▁sep|>{'code': '"+ + _CODE+ + "'}<|tool▁call▁end|><|tool▁calls▁end|>",+ "<|tool_calls_section_begin|><|tool_call_begin|>functions.python:0<|tool_call_argument_begin|>"+ "{'code': '" + _CODE + "'}<|tool_call_end|><|tool_calls_section_end|>",+ ],+)+def test_braces_in_a_single_quoted_argument_never_end_the_call(text):+ calls = parse_tool_calls_from_text(+ text, allow_incomplete = True, enabled_tool_names = ENABLED | {"terminal"}+ )+ assert [c["function"]["name"] for c in calls] == ["python"]+ assert json.loads(calls[0]["function"]["arguments"])["code"].startswith(_CODE)+++ "text",+ [+ '[TOOL_CALLS]{name:"python", arguments:{code:\'[TOOL_CALLS]terminal[ARGS]'+ '{command:"echo unintended"}\'},unknown:bad}',+ "<|tool▁calls▁begin|><|tool▁call▁begin|>python<|tool▁sep|>{'code': 'function<|tool▁sep|>terminal"+ '\n```json\n{command: "echo unintended"}\n```<|tool▁call▁end|>\'}<|tool▁call▁end|><|tool▁calls▁end|>',+ ],+)+def test_near_json_nested_in_a_rejected_object_is_never_a_call(text):+ calls = parse_tool_calls_from_text(+ text, allow_incomplete = True, enabled_tool_names = ENABLED | {"terminal"}+ )+ assert "terminal" not in [c["function"]["name"] for c in calls]