Skip to content

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.

fix(studio): gate external tool nudges and preserve retry context (#9125)

Kenshi114a4059f3e8
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 41b7759f742..929bcc0e5bf 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -64,6 +64,7 @@ from core.inference.tool_call_parser import (
reprompt_to_act_message,
strip_tool_markup,
)
+from core.tool_healing import _think_spans_outside_tool_markup
from core.inference.tool_loop_controller import (
ToolLoopController,
awaiting_approval_status,
@@ -714,6 +715,10 @@ def _append_user_turn(conversation: list[dict[str, Any]], content: str) -> None:
conversation.append({"role": "user", "content": content})
+def _leading_whitespace(text: str) -> str:
+ return text[: len(text) - len(text.lstrip())]
+
+
def _advance_tool_stream(generator: Any, outcome: dict[str, Any]) -> Any:
try:
return next(generator)
@@ -1043,29 +1048,60 @@ async def stream_with_studio_tools(
# gets one nudge to actually do it, the same recovery the local loops
# give a stalled small model, then the answer stands as written.
visible_answer = "".join(turn.text)
+ # Classify the same text the retry replays, as the local loops do
+ # (_reprompt_intent_text). A turn that is nothing but an unpromotable call
+ # block strips to "", leaving no assistant turn to append and no promise to
+ # continue from, so nudging on the raw text replayed it as user -> user.
+ # Untrimmed: a continuation merges with no separator, so the whitespace a
+ # removed span exposed is all that keeps the partial's last word apart from
+ # the first word replayed, and "not" + " able" is not "notable".
+ stripped_answer = strip_tool_markup(
+ visible_answer,
+ final = True,
+ trim = False,
+ enabled_tool_names = allowed_tool_names,
+ )
+ replayable_answer = stripped_answer.strip()
+ boundary = _leading_whitespace(stripped_answer)
+ if not replayable_answer:
+ # A reasoning-only stall announces the plan inside the think block
+ # and nowhere else. _reprompt_intent_text falls back to that block
+ # rather than dropping the turn, so match it, and replay what was
+ # classified. Ordering matters: the fallback runs on the stripped
+ # text, so a turn that is only an unpromotable call block has no
+ # think span, stays empty, and still does not get nudged.
+ replayable_answer = "\n".join(
+ visible_answer[start:end]
+ for start, end in _think_spans_outside_tool_markup(visible_answer)
+ ).strip()
+ # Only a removed leading [THINK] block empties the strip while leaving a
+ # think span, so the block opens after the turn's own leading run.
+ boundary = _leading_whitespace(visible_answer)
+ if replayable_answer:
+ replayable_answer = boundary + replayable_answer
if (
tools_available
and nudge_enabled(policy.nudge_tool_calls)
and not controller.force_final_answer
and reprompts < max_reprompts
- and is_short_intent_without_action(visible_answer)
- and not is_reprompt_repeat(visible_answer, last_reprompt_text)
+ and is_short_intent_without_action(replayable_answer)
+ and not is_reprompt_repeat(replayable_answer, last_reprompt_text)
):
reprompts += 1
- last_reprompt_text = visible_answer
+ last_reprompt_text = replayable_answer
stalled_hosted = turn.hosted_replay_text()
- if stalled_hosted:
- # A hosted tool did run, the model just did not go on to ask
- # for a local one. The replay below never happens on this
- # path, so the reprompted request would be told to continue
- # from output it can no longer see.
+ stalled_content = (
+ f"{replayable_answer}\n\n{stalled_hosted}"
+ if replayable_answer and stalled_hosted
+ else replayable_answer or stalled_hosted
+ )
+ if stalled_content:
+ # The retry must see the assistant turn it is being asked to
+ # continue from. Without this, plain prose stalls are replayed
+ # as user -> user and the provider answers from scratch.
stalled_message: dict[str, Any] = {
"role": "assistant",
- "content": (
- f"{visible_answer}\n\n{stalled_hosted}"
- if visible_answer
- else stalled_hosted
- ),
+ "content": stalled_content,
}
if turn.reasoning_extra:
# Gemini 3 stows the text part's thoughtSignature here
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.py
index 45986cf72ab..fd2f3d64779 100644
--- a/studio/backend/core/inference/tool_call_parser.py
+++ b/studio/backend/core/inference/tool_call_parser.py
@@ -850,11 +850,16 @@ def strip_tool_markup(
text: str,
*,
final: bool = False,
+ trim: bool = True,
enabled_tool_names: Optional[set] = None,
) -> str:
"""Strip tool-call markup. ``final=False`` keeps in-progress markup buffered;
``final=True`` also drops trailing unclosed runs and trims.
+ ``trim=False`` keeps the whitespace a removed span exposed, which a caller that
+ has to reproduce the boundary the model wrote cannot recover afterwards: the
+ prose can also appear inside the markup, so searching for it is not sound.
+
``enabled_tool_names`` gates the name-conditioned forms so a disabled/example name in
prose is kept (mirrors the parser gate): the bare reasoning-rehearsal ``name[ARGS]{...}``
and the markerless Gemma ``call:NAME{...}`` strip. ``None`` strips every closed call.
@@ -875,7 +880,7 @@ def strip_tool_markup(
# not executed, so it must not be stripped from display either); a literal think marker
# inside a real call's arguments is that call's data and is stripped with the call.
result = _tool_healing.strip_outside_think(text, _strip_segment)
- return result.strip() if final else result
+ return result.strip() if (final and trim) else result
# Every strip arm above is anchored on one of these literals, so text containing none of
diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.json
index 60c66b1e68b..92fd49ad2e6 100644
--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json
+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json
@@ -1739,7 +1739,7 @@
"strip_tool_markup": {
"decorators": [],
"kind": "def",
- "signature": "text: str, *, final: bool=False, enabled_tool_names: Optional[set]=None"
+ "signature": "text: str, *, final: bool=False, trim: bool=True, enabled_tool_names: Optional[set]=None"
},
"thinking_exhausted_message": {
"decorators": [],
diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.json
index 5023eb54285..20e18ea84dc 100644
--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json
+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json
@@ -227,7 +227,7 @@
"strip_leading_bare_json_call": "core.inference.tool_call_parser.strip_leading_bare_json_call(text: 'str', enabled_tool_names: 'Optional[set]' = None) -> 'str'",
"strip_llama3_leading_sentinels": "core.inference.tool_call_parser.strip_llama3_leading_sentinels(content: 'str') -> 'str'",
"strip_segment": "core.inference.tool_call_parser.strip_segment(segment: 'str', *, seg_final: 'bool', enabled_tool_names: 'Optional[set]' = None) -> 'str'",
- "strip_tool_markup": "core.inference.tool_call_parser.strip_tool_markup(text: 'str', *, final: 'bool' = False, enabled_tool_names: 'Optional[set]' = None) -> 'str'",
+ "strip_tool_markup": "core.inference.tool_call_parser.strip_tool_markup(text: 'str', *, final: 'bool' = False, trim: 'bool' = True, enabled_tool_names: 'Optional[set]' = None) -> 'str'",
"thinking_exhausted_message": "core.inference.tool_call_parser.thinking_exhausted_message(context_length: 'Optional[int]' = None) -> 'str'",
"unfinished_thought_progress": "core.inference.tool_call_parser.unfinished_thought_progress(reasoning: 'str') -> 'str'"
}
diff --git a/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py b/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
index 0e3ebeabb87..6fd03b55404 100644
--- a/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
+++ b/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
@@ -279,6 +279,9 @@ def test_the_codex_loop_keeps_its_model_and_nudge_policy(monkeypatch):
)
assert entered["run"].model == "gpt-5.4-codex"
assert entered["policy"].nudge_tool_calls is False
+ # Codex emits structured calls, so text-form healing stays off while the
+ # plan-without-action nudge is still governed by the request flag above.
+ assert entered["policy"].auto_heal is False
def test_the_usage_chunk_falls_back_only_when_no_model_is_known():
diff --git a/studio/backend/tests/test_external_tool_nudge_wiring.py b/studio/backend/tests/test_external_tool_nudge_wiring.py
new file mode 100644
index 00000000000..935a8435c7f
--- /dev/null
+++ b/studio/backend/tests/test_external_tool_nudge_wiring.py
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression guards for external Studio tool-call nudging (#8907 follow-up)."""
+
+import inspect
+from pathlib import Path
+
+from core.inference.studio_tool_loop import ToolLoopPolicy, stream_with_studio_tools
+
+
+def test_external_tool_loop_accepts_and_gates_nudge_flag():
+ assert "nudge_tool_calls" in ToolLoopPolicy.__dataclass_fields__
+ src = inspect.getsource(stream_with_studio_tools)
+ assert "nudge_enabled(policy.nudge_tool_calls)" in src
+
+
+def test_external_route_forwards_request_nudge_flag():
+ from routes import inference as routes_inference
+
+ external_src = inspect.getsource(routes_inference._proxy_to_external_provider)
+ assert external_src.count("nudge_tool_calls = payload.nudge_tool_calls") == 2
+ codex_policy = external_src.split("CodexToolPolicy(", 1)[1].split("if studio_tool_payloads", 1)[
+ 0
+ ]
+ assert "nudge_tool_calls = payload.nudge_tool_calls" in codex_policy
+
+
+def test_frontend_forwards_nudge_setting_to_external_tools():
+ studio = Path(__file__).resolve().parents[2]
+ adapter = (studio / "frontend/src/features/chat/api/chat-adapter.ts").read_text(
+ encoding = "utf-8"
+ )
+ # One local-model request and one external local-tool request.
+ assert adapter.count("nudge_tool_calls: runtime.nudgeToolCalls") >= 2
diff --git a/studio/backend/tests/test_refactor_guard.py b/studio/backend/tests/test_refactor_guard.py
index 156fdd0eb7a..c3b2145db72 100644
--- a/studio/backend/tests/test_refactor_guard.py
+++ b/studio/backend/tests/test_refactor_guard.py
@@ -189,6 +189,10 @@ def test_strip_tool_markup_is_pinned_at_both_final_values():
assert strip_tool_markup(text, final = False, enabled_tool_names = names) == " tail"
assert strip_tool_markup(text, final = True, enabled_tool_names = names) == "tail"
+ # trim = False keeps the boundary the removed span exposed, which the nudge replay
+ # merges onto a resumed partial.
+ untrimmed = strip_tool_markup(text, final = True, trim = False, enabled_tool_names = names)
+ assert untrimmed == " tail"
def test_an_unrelated_addition_elsewhere_does_not_fail_the_guard():
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index 54eebe30655..5da08f3105c 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -111,6 +111,7 @@ def _run(
tools = None,
tool_choice = None,
messages = None,
+ continue_final_message = False,
**policy_kwargs,
):
policy_fields = {
@@ -134,6 +135,7 @@ def _run(
session_id = "s1",
thread_id = "t1",
tool_choice = tool_choice,
+ continue_final_message = continue_final_message,
),
policy = ToolLoopPolicy(**policy_fields),
cancel_event = cancel_event,
@@ -774,13 +776,159 @@ def test_a_stalled_model_is_nudged_to_act(executed):
_run(transport, nudge_tool_calls = True)
assert [c["name"] for c in executed] == ["web_search"]
- # The nudge is a user turn appended after the stall.
+ # The retry sees the assistant stall before the nudge, not user -> user.
second = transport.requests[1]["messages"]
- assert second[-1]["role"] == "user"
+ assert [message["role"] for message in second] == ["user", "assistant", "user"]
+ assert second[-2]["content"] == "I'll search for that now."
-def test_a_stalled_model_is_not_nudged_by_default(executed):
- """The external loop must not invent a retry for an omitted opt-in flag."""
+def test_a_reasoning_only_stall_is_nudged_and_replayed(executed):
+ """Magistral-style stalls put the whole promise inside the think block.
+
+ Stripping tool markup empties such a turn, so classifying the stripped text
+ alone would drop the nudge the local loops still give. The replayed turn must
+ be the text that was classified, or the retry is user -> user again.
+ """
+ stall = "[THINK]I will search now.[/THINK]"
+ transport = FakeTransport(
+ [
+ [_sse({"content": stall}), _sse(finish = "stop"), _DONE],
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "c1",
+ "function": {"name": "web_search", "arguments": "{}"},
+ }
+ ]
+ }
+ ),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ],
+ [_sse({"content": "answer"}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ _run(transport, nudge_tool_calls = True)
+
+ assert [c["name"] for c in executed] == ["web_search"]
+ second = transport.requests[1]["messages"]
+ assert [message["role"] for message in second] == ["user", "assistant", "user"]
+ assert second[-2]["content"] == stall
+
+
+ "stall, merged",
+ [
+ (
+ "[THINK]The user wants a search.[/THINK] I will search now.",
+ "The answer is not I will search now.",
+ ),
+ # Restored as written, not normalised to one space.
+ (
+ "[THINK]The user wants a search.[/THINK]\n\nI will search now.",
+ "The answer is not\n\nI will search now.",
+ ),
+ # No markup to remove, so the model's own boundary is already at index 0.
+ (" I will search now.", "The answer is not I will search now."),
+ # The model wrote none, and inventing one would change what it continued.
+ ("I will search now.", "The answer is notI will search now."),
+ ],
+)
+def test_a_continued_stall_keeps_the_boundary_the_model_wrote(executed, stall, merged):
+ """The merge has no separator, so a trimmed-away space glues two words.
+
+ strip_tool_markup trims, and after a removed [THINK] block that trim sits past
+ index 0, so measuring the leading run of the raw turn reports none.
+ """
+ transport = FakeTransport(
+ [
+ [_sse({"content": stall}), _sse(finish = "stop"), _DONE],
+ [_sse({"content": "done"}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ _run(
+ transport,
+ nudge_tool_calls = True,
+ messages = [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "The answer is not"},
+ ],
+ continue_final_message = True,
+ )
+
+ second = transport.requests[1]["messages"]
+ assert [message["role"] for message in second] == ["user", "assistant", "user"]
+ assert second[-2]["content"] == merged
+
+
+_NOPE_CALL = '<tool_call>{"name": "nope", "arguments": {"q": "I will search now."}}</tool_call>'
+
+
+ "stall, merged",
+ [
+ # The markup quotes the prose back, so searching the raw turn for the surviving
+ # text finds the copy inside the arguments, whose own boundary is the quote.
+ (" I will search now." + _NOPE_CALL, "The answer is not I will search now."),
+ # Stripped at both ends with nothing between the block and the prose, so there
+ # is no boundary to restore and one must not be invented.
+ (
+ "[THINK]plan[/THINK]I will search now." + _NOPE_CALL,
+ "The answer is notI will search now.",
+ ),
+ ],
+)
+def test_the_boundary_is_read_off_the_stripped_turn_not_searched_for(executed, stall, merged):
+ """The surviving prose can also sit inside the markup that was stripped out."""
+ transport = FakeTransport(
+ [
+ [_sse({"content": stall}), _sse(finish = "stop"), _DONE],
+ [_sse({"content": "done"}), _sse(finish = "stop"), _DONE],
+ ],
+ heals = False,
+ )
+ _run(
+ transport,
+ auto_heal = False,
+ nudge_tool_calls = True,
+ messages = [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "The answer is not"},
+ ],
+ continue_final_message = True,
+ )
+
+ second = transport.requests[1]["messages"]
+ assert second[-2]["content"] == merged
+
+
+def test_a_markup_only_stall_is_still_not_nudged(executed):
+ """The reasoning fallback runs on the stripped text, so it must not revive Case G."""
+ transport = FakeTransport(
+ [
+ [
+ _sse({"content": '<tool_call>{"name": "not_enabled"}</tool_call>'}),
+ _sse(finish = "stop"),
+ _DONE,
+ ],
+ [_sse({"content": "SHOULD NOT APPEAR"}), _sse(finish = "stop"), _DONE],
+ ],
+ heals = False,
+ )
+ _run(transport, auto_heal = False, nudge_tool_calls = True)
+
+ assert executed == []
+ assert len(transport.requests) == 1
+
+
+def test_a_stalled_model_is_not_nudged_by_default(executed, monkeypatch):
+ """An API caller that omits the opt-in must not get a hidden retry."""
+ from core.inference import passthrough_healing
+
+ monkeypatch.setattr(passthrough_healing, "_NUDGE_DEFAULT", False)
transport = FakeTransport(
[
[_sse({"content": "I'll search for that now."}), _sse(finish = "stop"), _DONE],
@@ -794,6 +942,33 @@ def test_a_stalled_model_is_not_nudged_by_default(executed):
assert "SHOULD NOT APPEAR" not in _visible_text(lines)
+def test_a_stalled_model_respects_explicit_nudge_off(executed):
+ transport = FakeTransport(
+ [
+ [_sse({"content": "I'll search for that now."}), _sse(finish = "stop"), _DONE],
+ [_sse({"content": "SHOULD NOT APPEAR"}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ _run(transport, nudge_tool_calls = False)
+
+ assert executed == []
+ assert len(transport.requests) == 1
+
+
+def test_nudging_is_independent_of_text_form_healing(executed):
+ """Codex emits structured calls, but still needs plan-without-action recovery."""
+ transport = FakeTransport(
+ [
+ [_sse({"content": "I'll search for that now."}), _sse(finish = "stop"), _DONE],
+ [_sse({"content": "done"}), _sse(finish = "stop"), _DONE],
+ ],
+ heals = False,
+ )
+ _run(transport, auto_heal = False, nudge_tool_calls = True)
+
+ assert len(transport.requests) == 2
+
+
def test_a_finished_answer_is_not_nudged(executed):
"""A real answer must never be re-prompted into calling a tool."""
answer = (
@@ -801,7 +976,7 @@ def test_a_finished_answer_is_not_nudged(executed):
"since the tenth century and remains the largest city in the country."
)
transport = FakeTransport([[_sse({"content": answer}), _sse(finish = "stop"), _DONE]])
- _run(transport)
+ _run(transport, nudge_tool_calls = True)
assert executed == []
assert len(transport.requests) == 1
@@ -913,6 +1088,45 @@ def test_replayed_assistant_content_carries_no_markup(executed):
assert assistant.get("tool_calls")
+def test_truncated_tool_markup_is_not_replayed_during_a_nudge(executed):
+ """A length-truncated call is visible to the user, but not provider context."""
+ markup = '<tool_call>{"name": "web_search", "arguments": {"query": "x"}}</tool_call>'
+ transport = FakeTransport(
+ [
+ [_sse({"content": f"I'll search now. {markup}"}), _sse(finish = "length"), _DONE],
+ [_sse({"content": "done"}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ _run(transport, nudge_tool_calls = True)
+
+ replayed = transport.requests[1]["messages"]
+ assistant = [m for m in replayed if m.get("role") == "assistant"][-1]
+ assert assistant["content"] == "I'll search now."
+
+
+def test_a_markup_only_stall_is_not_nudged(executed):
+ """Nothing to continue from, so the retry would have been user -> user.
+
+ An intent phrase buried in an unpromotable call block reads as a stall to the
+ classifier but strips to nothing, so there is no assistant turn to append and
+ the nudge would merge into the user's own message. Easiest to reach on a
+ transport that does not heal text-form calls, which is the Codex shape.
+ """
+ markup = (
+ '<tool_call>{"name": "nope", "arguments": {"q": "I will look this up now"}}</tool_call>'
+ )
+ transport = FakeTransport(
+ [
+ [_sse({"content": markup}), _sse(finish = "stop"), _DONE],
+ [_sse({"content": "SHOULD NOT APPEAR"}), _sse(finish = "stop"), _DONE],
+ ],
+ heals = False,
+ )
+ _run(transport, auto_heal = False, nudge_tool_calls = True)
+
+ assert len(transport.requests) == 1
+
+
def test_conversation_roles_stay_alternating_for_a_strict_server(executed):
"""A no-op only turn must not leave two user turns in a row."""
transport = FakeTransport(
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 8ed9842587e..05991aa123c 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -1911,8 +1911,8 @@ function NudgeToolCallsToggle() {
Nudge Tool Calls
</span>
<InfoHint>
- When a tool call cannot be repaired, re-ask the model once so the
- intended tool still runs. API requests stay opt-in.
+ When a model stops after promising to use a tool, or its tool call
+ cannot be repaired, ask it to continue. API requests stay opt-in.
</InfoHint>
</div>
<Switch
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 434745eb573..dea34e944e8 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -261,8 +261,9 @@ _TOOL_CALL_NUDGING_OPTION = typer.Option(
None,
"--enable-tool-call-nudging/--disable-tool-call-nudging",
rich_help_panel = _PANEL_SERVER,
- help = "Retry once with a nudge when a non-streaming passthrough tool call can't be healed. "
- "On by default; when the flag is omitted an inherited UNSLOTH_TOOL_CALL_NUDGE is kept.",
+ help = "Allow nudge retries when a tool-enabled model stops after promising to act, or a "
+ "passthrough tool signal can't be healed. On by default; when the flag is omitted an "
+ "inherited UNSLOTH_TOOL_CALL_NUDGE is kept, and an explicit request value wins.",
)
_REASONING_OPTION = typer.Option(
None,
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 2e9f60becce..3580b1057ce 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -2386,9 +2386,9 @@ def run(
"--enable-tool-call-nudging/--disable-tool-call-nudging",
rich_help_panel = _RUN_PANEL_TOOLS,
help = (
- "On the non-streaming client-tool passthrough, retry once with a short "
- "nudge when the model emitted a tool signal that healing could not repair. "
- "Default: on. No effect on streaming requests or the server-side agentic loop."
+ "Allow nudge retries when a tool-enabled model stops after promising to act, "
+ "or when a passthrough tool signal cannot be repaired. Default: on. This sets "
+ "the process default; an explicit request value wins."
),
),
temperature: Optional[float] = typer.Option(