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: close refused tool calls under tool_choice none (#12627)
BevKim8706c6e09a72
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex ad95524d78d..9b9d7c720d3 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -133,6 +133,11 @@ _TOOL_TRUNCATED = ("output limit.")+_TOOL_CHOICE_NONE = (+ "Unsloth did not execute this tool call because tool calls are turned off for this request "+ '(tool_choice is "none").'+)+# Card text for a call the controller skipped. The client already painted a card from the provider's own tool_calls# delta, so it needs a short result; the long model-facing nudge stays in the conversation._TOOL_SKIPPED = {@@ -1693,27 +1698,23 @@ async def stream_with_studio_tools(continueturn.text.append(span)yield _sse({"choices": [{"index": 0, "delta": {"content": span}}]})+ # Truncation wins: half-written arguments are never shown.+ unrun_reason = Noneif truncated:- # The other half of the same problem. A call the provider streamed as a tool_calls delta was relayed as it- # arrived, so the client already has a card for it, and refusing to run it leaves that card open for the- # rest of the response. Close it the way every other unrun call is closed. Structured only: a healed call- # was never streamed, and the span released just above is what tells the user about that one. Through- # `calls`, which never executes anything: it is what mints the card id for a call the provider gave none,- # and the client drew its card under that same spelling. Reading the slots directly left every id-less- # call out, so the card the deltas painted spun for the rest of the response. Calls it drops -- nameless,- # or a fork whose object never closed -- have no card of ours to close either.+ unrun_reason = _TOOL_TRUNCATED+ elif tool_choice == "none":+ unrun_reason = _TOOL_CHOICE_NONE+ if unrun_reason is not None:+ # The relayed delta already drew a card: close it like any unrun call, via `calls` (executes nothing), which+ # mints the id the client drew for an id-less call.for raw_call in turn.calls(used_call_ids, painted_card_ids):- truncated_id = (- raw_call.get("card_id") or raw_call.get("stream_id") or raw_call["id"]- )+ unrun_id = raw_call.get("card_id") or raw_call.get("stream_id") or raw_call["id"]name = raw_call["function"]["name"]for card_line in _unrun_call_card(tool_name = name,- tool_call_id = truncated_id,- # The arguments are cut off mid-write, so there is nothing well formed to show; the result says- # what happened.- arguments = {},- result = _TOOL_TRUNCATED,+ tool_call_id = unrun_id,+ arguments = {} if truncated else raw_call.get("arguments"),+ result = unrun_reason,provenance = _unrun_provenance(name, round_id + 1),):yield card_line@@ -1721,11 +1722,7 @@ async def stream_with_studio_tools(# one. Withdrawing the catalog on the way out is not enough on its own: Deep Research sets "none" exactly so# the scraped web text in its prompts cannot reach python or terminal, so a naive or compromised endpoint# echoing a call back must not be able to execute it here.- calls = (- []- if (truncated or tool_choice == "none")- else turn.calls(used_call_ids, painted_card_ids)- )+ calls = [] if unrun_reason is not None else turn.calls(used_call_ids, painted_card_ids)if not calls:# The badge clears between iterations, and this turn is over too. Without it a turn whose only call was# refused never reaches the empty status below, so the client keeps the card it drew for that call opendiff --git a/studio/backend/tests/test_external_tool_refusal_gates.py b/studio/backend/tests/test_external_tool_refusal_gates.pyindex 4bf44c06079..99e0db14b83 100644--- a/studio/backend/tests/test_external_tool_refusal_gates.py+++ b/studio/backend/tests/test_external_tool_refusal_gates.py@@ -146,6 +146,20 @@ def _run(transport, *, tool_choice = None):return asyncio.run(asyncio.wait_for(_collect(), timeout = 30))+def _events(lines, kind):+ events = []+ for line in lines:+ if not line.startswith("data: "):+ continue+ try:+ payload = json.loads(line[6:])+ except ValueError:+ continue+ if isinstance(payload, dict) and payload.get("type") == kind:+ events.append(payload)+ return events++# ── tool_choice: "none" is enforced, not just advertised ─────────────@@ -156,8 +170,59 @@ def test_tool_choice_none_refuses_a_call_the_provider_sent_anyway(executed):endpoint into emitting a python call must not get one executed."""transport = FakeTransport([[_call_line(), _finish("tool_calls")], [_DONE]])- _run(transport, tool_choice = "none")+ lines = _run(transport, tool_choice = "none")++ assert executed == []++ starts = _events(lines, "tool_start")+ ends = _events(lines, "tool_end")++ assert [event["tool_call_id"] for event in starts] == ["c1"]+ assert [event["tool_call_id"] for event in ends] == ["c1"]+ assert starts[0]["arguments"] == {"query": "x"}+ assert ends[0]["tool_name"] == "web_search"+ assert ends[0]["result"] == loop_mod._TOOL_CHOICE_NONE+++def test_a_truncated_call_under_tool_choice_none_closes_once_as_truncated(executed):+ """A turn that is both keeps the truncation reason and closes its call a single time."""+ transport = FakeTransport([[_call_line(), _finish("length")], [_DONE]])+ lines = _run(transport, tool_choice = "none")++ assert executed == []++ starts = _events(lines, "tool_start")+ ends = _events(lines, "tool_end")+ assert [event["tool_call_id"] for event in starts] == ["c1"]+ assert [event["tool_call_id"] for event in ends] == ["c1"]+ assert starts[0]["arguments"] == {}+ assert ends[0]["result"] == loop_mod._TOOL_TRUNCATED+++def test_tool_choice_none_closes_every_refused_card_by_the_id_the_client_drew(executed):+ """Each refused call closes its own card, an id-less one under the minted ``tool_call_<index>``."""+ named = json.loads(_call_line()[6:])+ idless = json.loads(_call_line()[6:])+ idless["choices"][0]["delta"]["tool_calls"][0].update(index = 1)+ del idless["choices"][0]["delta"]["tool_calls"][0]["id"]+ transport = FakeTransport(+ [["data: " + json.dumps(named), "data: " + json.dumps(idless), _DONE], [_DONE]]+ )+ lines = _run(transport, tool_choice = "none")+assert executed == []+ assert len(transport.requests) == 1++ starts = _events(lines, "tool_start")+ ends = _events(lines, "tool_end")+ assert [event["tool_call_id"] for event in starts] == ["c1", "tool_call_1"]+ assert [event["tool_call_id"] for event in ends] == ["c1", "tool_call_1"]+ assert all(event["arguments"] == {"query": "x"} for event in starts)++ # Closed before the empty badge the client ends the provider turn on.+ frames = [json.loads(line[6:]) for line in lines if line.startswith("data: {")]+ last_end = max(at for at, frame in enumerate(frames) if frame.get("type") == "tool_end")+ assert {"type": "tool_status", "content": ""} in frames[last_end:]def test_tool_choice_none_still_withdraws_the_catalog(executed):