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
Prepare an exhausted call before the budget gate, so its replay parses (#10274)
Shubhankar Tripathya61d6394a660
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex c773fa68482..3883fb65961 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -83,6 +83,7 @@ def _append_mcp_images_owned(from core.inference.tool_loop_controller import (ToolLoopController,+ _reject_json_constant,awaiting_approval_status,canonical_arguments_text,mcp_display_parts,@@ -403,11 +404,6 @@ class ToolLoopPolicy:on_provider_turn_end: Callable[[], None] | None = None-def _reject_json_constant(name: str) -> Any:- """Refuse ``NaN`` / ``Infinity``: ``json.loads`` takes them, ``JSON.parse`` does not."""- raise ValueError(f"{name} is not JSON")--def _split_top_level_json_objects(text: str) -> tuple[list[str], str]:"""The top-level JSON objects in ``text``, and any object still unfinished. A second top-level``{`` means one slot took a second parallel call. Text that is not a run of whole objects@@ -1680,12 +1676,14 @@ async def stream_with_studio_tools(for call in calls:if cancel_event.is_set():break+ # Before the gate: an exhausted call is replayed too, and only the decision's replay is guaranteed to parse.+ decision = controller.prepare_call(call)if not unlimited and remaining <= 0:# Budget spent.for card_line in _unrun_call_card(tool_name = call["function"]["name"],tool_call_id = call.get("card_id") or call.get("stream_id") or call["id"],- arguments = call.get("arguments"),+ arguments = decision.tool_start_payload()["arguments"],result = _TOOL_BUDGET_EXHAUSTED,provenance = _unrun_provenance(call["function"]["name"], round_id),):@@ -1693,13 +1691,7 @@ async def stream_with_studio_tools(# The result below has to be replayed with its call: only the call that spent the last slot reaches# assistant_tool_calls further down, so this one would arrive as an orphan role="tool" message and# OpenAI, Anthropic and Gemini all reject that history instead of answering.- exhausted_call: dict[str, Any] = {- "id": call["id"],- "type": "function",- # Copied: the normalized call also carries a parsed arguments dict that must not reach the- # provider- "function": dict(call["function"]),- }+ exhausted_call = decision.as_assistant_tool_call()exhausted_extra = call.get("extra_content")if isinstance(exhausted_extra, dict) and exhausted_extra:exhausted_call["extra_content"] = exhausted_extra@@ -1713,9 +1705,8 @@ async def stream_with_studio_tools(})continue- decision = controller.prepare_call(call)# The frontend groups a round's reasoning by this id (codexLocalToolRoundId), so every tool card the loop- # emits has to carry it, not just the budget-exhausted one built by hand above.+ # emits has to carry it, including the budget-exhausted card above.decision.provenance["round_id"] = round_idif not decision.should_execute:completion = controller.record_noop(decision)diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex f8db61a608d..1e7b6483ae7 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -48,6 +48,15 @@ UNPARSED_ARGUMENTS_KEY = "__unsloth_unparsed_arguments__"_JSON_STRUCTURAL = frozenset(',:{}[]" \t\n\r')+def _reject_json_constant(name: str) -> Any:+ """Refuse ``NaN`` / ``Infinity``: ``json.loads`` takes them, ``JSON.parse`` does not."""+ raise ValueError(f"{name} is not JSON")+++# Built once: `json.loads` with any keyword constructs a fresh decoder per call.+_STRICT_JSON_DECODER = json.JSONDecoder(parse_constant = _reject_json_constant)++def _looks_like_broken_json(raw: str) -> bool:"""Whether this text was MEANT to be a JSON object and stopped before finishing.@@ -64,7 +73,7 @@ def _looks_like_broken_json(raw: str) -> bool:if not text.startswith(("{", "[")):return Falsetry:- json.loads(text)+ _STRICT_JSON_DECODER.decode(text)except json.JSONDecodeError as error:if error.msg.startswith("Unterminated string") or error.pos >= len(text):return True@@ -81,6 +90,9 @@ def _looks_like_broken_json(raw: str) -> bool:return Falseremainder = text[error.pos :]return bool(remainder) and not any(ch in _JSON_STRUCTURAL for ch in remainder)+ except (ValueError, RecursionError):+ # Digit cap, recursion limit or NaN/Infinity: unreadable is as broken as cut off.+ return Truereturn False@@ -703,12 +715,14 @@ def coerce_tool_arguments()if isinstance(raw_args, str):try:- parsed = json.loads(raw_args)+ # NaN/Infinity would replay as JSON no provider parses.+ parsed = _STRICT_JSON_DECODER.decode(raw_args)if isinstance(parsed, Mapping):return CoercedArguments(coerce_arguments_by_schema(parsed, properties, repair = heal), False)- except (json.JSONDecodeError, ValueError):+ except (ValueError, RecursionError):+ # Must not raise: this runs before the budget gate, so a raise aborts the whole turn.passif heal:# Healing exists for a model that sends its ONE argument as a bare string instead of an object. Text thatdiff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.pyindex 1564595aade..721a5fc3109 100644--- a/studio/backend/tests/test_studio_tool_loop.py+++ b/studio/backend/tests/test_studio_tool_loop.py@@ -24,6 +24,7 @@ from core.inference.studio_tool_loop import (ToolLoopRun,stream_with_studio_tools,)+from core.inference.tool_loop_controller import _reject_json_constantdef _shared_setup_1():@@ -1186,6 +1187,52 @@ def test_budget_exhausted_parallel_call_is_replayed_with_its_call(executed):assert len(_events(lines, "tool_end")) == 2[email protected]("heals", [False, True])+ "fragment",+ [+ '{"query": "b',+ '{"query":' + "1" * 4301 + "}",+ "[" * 100_000,+ '{"query":NaN}',+ ],+ ids = ["cut-off", "digit-limit", "nesting-limit", "nan-constant"],+)+def test_budget_exhausted_call_replays_arguments_a_provider_will_parse(executed, heals, fragment):+ """llama-server parses every replayed tool_call's arguments, so an unparseable one 500s the next turn."""+ transport = FakeTransport(+ [+ [+ _sse(+ {+ "tool_calls": [+ _call_delta(0, "call_a", "web_search", '{"query":"a"}'),+ _call_delta(1, "call_b", "web_search", fragment),+ ]+ }+ ),+ _sse(finish = "tool_calls"),+ _DONE,+ ],+ [_sse({"content": "done"}), _sse(finish = "stop"), _DONE],+ ],+ heals = heals,+ )+ _run(transport, max_calls = 1)++ assert [call["name"] for call in executed] == ["web_search"]+ assert len(transport.requests) == 2+ replayed = transport.requests[1]["messages"]+ exhausted = [+ call+ for message in replayed+ if message.get("role") == "assistant"+ for call in message.get("tool_calls") or []+ if call["id"] == "call_b"+ ][0]+ json.loads(exhausted["function"]["arguments"], parse_constant = _reject_json_constant)++def test_unlimited_budget_runs_past_the_old_fixed_turn_cap(executed):""" "Max" means max: the sentinel used to fall back to 25 provider turns.