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.

studio: tell the model which tool calls were skipped by the per turn limit (#11154)

Nilayc98e42596bd4
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 4064498d09c..f8056933562 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -462,6 +462,7 @@ from core.inference.tool_loop_controller import (
awaiting_approval_status,
deferred_nudge_text,
provisional_tool_provenance,
+ tool_call_limit_nudge,
)
from state.tool_approvals import (
TOOL_REJECTED_MESSAGE,
@@ -34618,6 +34619,7 @@ class LlamaCppBackend:
# Hold a leading ``{`` well past the 32-char XML cap until it balances (mirrors safetensors).
_MAX_BARE_JSON_BUFFER = 16384
_append_budget_exhausted_nudge = True
+ _limit_notice_in_user_turn = False
# RAG: cap knowledge-base searches per assistant turn. The controller is
# tool-agnostic, so this gate stays in the loop.
_kb_search_count = 0
@@ -36402,6 +36404,8 @@ class LlamaCppBackend:
# Collapse exact-duplicate calls and cap the count for the TEXTUAL
# fallback (mirrors the safetensors loop; see _MAX_TOOL_CALLS_PER_TURN).
+ _over_cap: list = []
+ _limit_notice_in_user_turn = False
if tool_calls and not has_structured_tc and len(tool_calls) > 1:
_seen_keys: set = set()
_last_workspace_key = None
@@ -36427,15 +36431,23 @@ class LlamaCppBackend:
elif _key in _seen_keys:
continue
_seen_keys.add(_key)
- _deduped.append(_tc)
- if len(_deduped) >= _MAX_TOOL_CALLS_PER_TURN:
- break
- if len(_deduped) != len(tool_calls):
+ if len(_deduped) < _MAX_TOOL_CALLS_PER_TURN:
+ _deduped.append(_tc)
+ else:
+ _over_cap.append(_tc)
+ if len(_deduped) + len(_over_cap) != len(tool_calls):
logger.info(
"GGUF textual fallback: collapsed %d repeated tool call(s) "
"in one turn to %d",
len(tool_calls),
- len(_deduped),
+ len(_deduped) + len(_over_cap),
+ )
+ if _over_cap:
+ logger.info(
+ "GGUF textual fallback: skipped %d tool call(s) over the "
+ "per-turn limit of %d",
+ len(_over_cap),
+ _MAX_TOOL_CALLS_PER_TURN,
)
tool_calls = _deduped
@@ -36444,6 +36456,7 @@ class LlamaCppBackend:
# conversation stays consistent and extra calls are never executed.
if disable_parallel_tool_use and tool_calls and len(tool_calls) > 1:
tool_calls = tool_calls[:1]
+ _over_cap = []
assistant_msg: dict = {"role": "assistant", "content": content_text}
if reasoning_accum.strip():
@@ -37012,6 +37025,13 @@ class LlamaCppBackend:
}
for _call in _pending
]
+ # reserve the notice before sharing space among retained results.
+ if _over_cap:
+ _pending_msgs.append(
+ tool_call_limit_nudge(
+ _over_cap, _MAX_TOOL_CALLS_PER_TURN
+ )
+ )
# Measured, not estimated: the estimator charges ASCII
# four characters per token, and a pending call can
# carry base64, minified JSON or a block of code, which
@@ -37312,15 +37332,45 @@ class LlamaCppBackend:
if _forced_tool_call_pending:
_forced_tool_call_pending = False
+ # On the turn that ends the loop no tools are offered again, so the notice
+ # must not ask for a retry and rides the tool result like the budget nudge.
+ _over_cap_final = bool(_over_cap) and (
+ tool_controller.force_final_answer
+ or not tool_controller.active_tools()
+ or (_turn_executed_real_tool and _tool_iters_done + 1 >= max_tool_iterations)
+ # The tool-iteration cap is not the only way out: the loop also stops on
+ # the outer iteration range, which no-op and continuation turns consume
+ # without advancing _tool_iters_done. Missing it asks for a retry and then
+ # tells the model not to call any tools, in adjacent user turns.
+ or iteration + 1 >= max_tool_iterations + _extra + _continuation_credits
+ )
+ _final_over_cap = _over_cap if _over_cap_final else []
+ if _over_cap_final:
+ _over_cap = []
+ if _over_cap:
+ deferred_noop_msgs.append(
+ tool_call_limit_nudge(
+ _over_cap,
+ _MAX_TOOL_CALLS_PER_TURN,
+ unavailable_tools = {
+ _limit_decision.tool_name
+ for _call in _over_cap
+ if (_limit_decision := tool_controller.prepare_call(_call)).action
+ in ("disabled", "render_html_repeat")
+ },
+ )
+ )
# A mixed execute/no-op batch already has a real tool result, so keeping the
# feedback with that result beats appending a newer user turn, which makes
# templates hide this turn's structured reasoning. Only when the result is
# the SAME tool the feedback is about: templates label the whole block with
# the result's own tool name (gemma-4.jinja resolves tool_call_id -> name and
# wraps the body), so folding a note about tool A into tool B's result reads
- # as B's own output. Then the user turn is the lesser loss.
+ # as B's own output. Then the user turn is the lesser loss. A retry notice for
+ # skipped calls is never folded: read as the tail of a result, the calls are not re-issued.
_fold_target_matches = (
- len(deferred_noop_tools) == 1
+ not _over_cap
+ and len(deferred_noop_tools) == 1
and bool(conversation)
and conversation[-1].get("role") == "tool"
and conversation[-1].get("name") in deferred_noop_tools
@@ -37361,6 +37411,33 @@ class LlamaCppBackend:
)
assistant_appended = True
append_deferred_nudges(conversation, deferred_noop_msgs)
+ if _final_over_cap:
+ _limit_text = tool_call_limit_nudge(
+ _final_over_cap, _MAX_TOOL_CALLS_PER_TURN, final = True
+ )["content"]
+ # Same rule as _fold_target_matches above: a template labels the folded
+ # block with the result's own tool name, so a note about tool A inside
+ # tool B's result reads as B's output. Fold only when every skipped call
+ # belongs to the result's own tool.
+ _limit_names = {
+ (_tc.get("function") or {}).get("name") for _tc in _final_over_cap
+ }
+ _limit_foldable = (
+ bool(conversation)
+ and conversation[-1].get("role") == "tool"
+ and _limit_names == {conversation[-1].get("name")}
+ )
+ if not (
+ _limit_foldable and _attach_internal_feedback_to_tool_result(_limit_text)
+ ):
+ if deferred_noop_msgs and conversation[-1].get("role") == "user":
+ conversation[-1] = {
+ **conversation[-1],
+ "content": f"{conversation[-1]['content']}\n\n{_limit_text}",
+ }
+ else:
+ conversation.append({"role": "user", "content": _limit_text})
+ _limit_notice_in_user_turn = True
# Close provisional cards not resolved by execution/no-op handling.
for _pid, _pname in provisional_started_tool_calls.items():
@@ -37427,7 +37504,14 @@ class LlamaCppBackend:
# continuing to request tools.
if max_tool_iterations > 0 and _append_budget_exhausted_nudge:
if not _attach_internal_feedback_to_tool_result(BUDGET_EXHAUSTED_NUDGE):
- conversation.append({"role": "user", "content": BUDGET_EXHAUSTED_NUDGE})
+ # Two user turns in a row break strict templates (Gemma), so ride the notice's turn.
+ if _limit_notice_in_user_turn and conversation[-1].get("role") == "user":
+ conversation[-1] = {
+ **conversation[-1],
+ "content": f"{conversation[-1]['content']}\n\n{BUDGET_EXHAUSTED_NUDGE}",
+ }
+ else:
+ conversation.append({"role": "user", "content": BUDGET_EXHAUSTED_NUDGE})
# Clear status.
yield {"type": "status", "text": ""}
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 576c0cbe77f..24ba0ebcd3e 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -60,6 +60,7 @@ from core.inference.tool_loop_controller import (
awaiting_approval_status,
coerce_tool_arguments,
status_for_tool,
+ tool_call_limit_nudge,
tool_event_provenance,
)
from core.inference.chat_template_helpers import (
@@ -1305,6 +1306,7 @@ def run_safetensors_tool_loop(
return
# Collapse exact-duplicate calls and cap the count (runaway-turn guard).
+ over_cap: list = []
if tool_calls:
seen_keys: set = set()
last_workspace_key = None
@@ -1329,14 +1331,21 @@ def run_safetensors_tool_loop(
elif _key in seen_keys:
continue
seen_keys.add(_key)
- deduped.append(_tc)
- if len(deduped) >= _MAX_TOOL_CALLS_PER_TURN:
- break
- if len(deduped) != len(tool_calls):
+ if len(deduped) < _MAX_TOOL_CALLS_PER_TURN:
+ deduped.append(_tc)
+ else:
+ over_cap.append(_tc)
+ if len(deduped) + len(over_cap) != len(tool_calls):
logger.info(
"Safetensors: collapsed %d repeated tool call(s) in one turn to %d",
len(tool_calls),
- len(deduped),
+ len(deduped) + len(over_cap),
+ )
+ if over_cap:
+ logger.info(
+ "Safetensors: skipped %d tool call(s) over the per-turn limit of %d",
+ len(over_cap),
+ _MAX_TOOL_CALLS_PER_TURN,
)
tool_calls = deduped
@@ -1552,6 +1561,11 @@ def run_safetensors_tool_loop(
{"role": "assistant", "content": json.dumps(call, default = str)}
for call in pending
]
+ # the notice restores skipped arguments after the retained results.
+ if over_cap:
+ pending_args.append(
+ tool_call_limit_nudge(over_cap, _MAX_TOOL_CALLS_PER_TURN)
+ )
kwargs["result_budget_tokens"] = tool_result_budget(
int(context_length),
max_tokens,
@@ -1595,6 +1609,26 @@ def run_safetensors_tool_loop(
yield completion.tool_end_event()
conversation.append(completion.tool_message())
+ # The turn that ends the loop offers no tools again, so do not ask for a retry there.
+ over_cap_final = bool(over_cap) and (
+ tool_controller.force_final_answer
+ or (not unrestricted_tools and not tool_controller.active_tools())
+ or (_turn_executed_real_tool and _executed_tool_iters + 1 >= max_tool_iterations)
+ )
+ if over_cap:
+ deferred_noop_msgs.append(
+ tool_call_limit_nudge(
+ over_cap,
+ _MAX_TOOL_CALLS_PER_TURN,
+ final = over_cap_final,
+ unavailable_tools = {
+ _limit_decision.tool_name
+ for call in over_cap
+ if (_limit_decision := tool_controller.prepare_call(call)).action
+ in ("disabled", "render_html_repeat")
+ },
+ )
+ )
append_deferred_nudges(conversation, deferred_noop_msgs)
yield {"type": "status", "text": ""}
@@ -1611,6 +1645,12 @@ def run_safetensors_tool_loop(
_executed_tool_iters += 1
if _executed_tool_iters >= max_tool_iterations and not final_attempt_done:
final_attempt_done = True
- conversation.append({"role": "user", "content": BUDGET_EXHAUSTED_NUDGE})
+ if over_cap:
+ conversation[-1] = {
+ **conversation[-1],
+ "content": f"{conversation[-1]['content']}\n\n{BUDGET_EXHAUSTED_NUDGE}",
+ }
+ else:
+ conversation.append({"role": "user", "content": BUDGET_EXHAUSTED_NUDGE})
yield {"type": "status", "text": ""}
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index be7802a2184..eba04f01e48 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -1019,6 +1019,50 @@ def append_deferred_nudges(conversation: list, msgs: Sequence[dict]) -> None:
conversation.append({"role": "user", "content": deferred_nudge_text(msgs)})
+def tool_call_limit_nudge(
+ tool_calls: Sequence[Mapping[str, Any]],
+ limit: int,
+ *,
+ final: bool = False,
+ unavailable_tools: Collection[str] = (),
+) -> dict:
+ described = []
+ for tool_call in tool_calls:
+ function = tool_call.get("function") or {}
+ arguments = function.get("arguments", {})
+ if not isinstance(arguments, str):
+ arguments = canonical_arguments_text(arguments)
+ described.append(f"{function.get('name', '')} {arguments}")
+ follow_up = (
+ "Do not describe results you did not receive."
+ if final
+ else "Call them again if you still need their results, and do not describe results "
+ "you did not receive."
+ )
+ if not final and unavailable_tools:
+ retryable_names = sorted(
+ {(call.get("function") or {}).get("name", "") for call in tool_calls}
+ - set(unavailable_tools)
+ )
+ follow_up = (
+ f"Do not retry {', '.join(sorted(unavailable_tools))}; "
+ "these tools are no longer available."
+ )
+ if retryable_names:
+ follow_up += (
+ f" You may retry the skipped calls for {', '.join(retryable_names)} "
+ "if you still need their results."
+ )
+ follow_up += " Do not describe results you did not receive."
+ return {
+ "role": "user",
+ "content": (
+ f"{len(tool_calls)} more tool call(s) in this batch were not executed because "
+ f"at most {limit} tool calls run per turn: {'; '.join(described)}. {follow_up}"
+ ),
+ }
+
+
def _tool_name_from_schema(tool: Mapping[str, Any]) -> str:
function = tool.get("function")
if not isinstance(function, Mapping):
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index abba616520e..32e93c68f73 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -4933,13 +4933,197 @@ def test_gguf_textual_fallback_caps_distinct_tool_calls_per_turn(monkeypatch):
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "go"}],
tools = [{"type": "function", "function": {"name": f"t{i}"}} for i in range(n)],
- max_tool_iterations = 1,
+ max_tool_iterations = 2,
)
)
assert len(calls) == _MAX_TOOL_CALLS_PER_TURN, [c[0] for c in calls]
# The cap keeps the first calls in order (no reordering / drop of leading ones).
assert [c[0] for c in calls] == [f"t{i}" for i in range(_MAX_TOOL_CALLS_PER_TURN)]
+ (notice,) = [
+ m for m in payloads[1]["messages"] if "more tool call(s)" in (m.get("content") or "")
+ ]
+ assert notice["role"] == "user"
+ assert notice["content"].startswith("4 more tool call(s)")
+ for i in range(_MAX_TOOL_CALLS_PER_TURN, n):
+ assert f"t{i} " in notice["content"]
+
+
+def test_gguf_textual_fallback_over_cap_notice_is_not_folded_into_tool_result(monkeypatch):
+ from core.inference.llama_cpp import _MAX_TOOL_CALLS_PER_TURN
+
+ def _call(i):
+ return '<tool_call>{"name":"web_search","arguments":{"query":"q%d"}}</tool_call>' % i
+
+ streams = [
+ [_sse({"content": _call(0)}), _done()],
+ [
+ _sse({"content": "".join(_call(i) for i in range(_MAX_TOOL_CALLS_PER_TURN + 2))}),
+ _done(),
+ ],
+ [_sse({"content": "done"}), _done()],
+ ]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ max_tool_iterations = 3,
+ )
+ )
+
+ last = payloads[2]["messages"][-1]
+ assert last["role"] == "user"
+ assert "2 more tool call(s)" in last["content"]
+ assert not any(
+ "more tool call(s)" in (m.get("content") or "")
+ for m in payloads[2]["messages"]
+ if m.get("role") == "tool"
+ )
+
+
+def test_gguf_textual_fallback_over_cap_on_last_turn_does_not_ask_for_retry(monkeypatch):
+ from core.inference.llama_cpp import _MAX_TOOL_CALLS_PER_TURN
+ from core.inference.tool_call_parser import BUDGET_EXHAUSTED_NUDGE
+
+ blocks = "".join(
+ '<tool_call>{"name":"web_search","arguments":{"query":"q%d"}}</tool_call>' % i
+ for i in range(_MAX_TOOL_CALLS_PER_TURN + 2)
+ )
+ streams = [[_sse({"content": blocks}), _done()], [_sse({"content": "done"}), _done()]]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ max_tool_iterations = 1,
+ )
+ )
+
+ messages = payloads[1]["messages"]
+ last = messages[-1]
+ assert last["role"] == "tool"
+ assert "2 more tool call(s)" in last["content"]
+ assert BUDGET_EXHAUSTED_NUDGE in last["content"]
+ assert not any("Call them again" in (m.get("content") or "") for m in messages)
+ assert not any(
+ a.get("role") == "user" and b.get("role") == "user" for a, b in zip(messages, messages[1:])
+ )
+
+
+def test_gguf_over_cap_notice_is_not_folded_into_an_unrelated_tools_result(monkeypatch):
+ """The final-turn notice must not ride a result whose tool it says nothing about.
+
+ Templates label a folded block with the result's own tool name (gemma-4.jinja resolves
+ tool_call_id -> name and wraps the body), so a note about t8..t11 inside t7's result
+ reads as t7's own output. max_tool_iterations = 1 is the value that routes the notice
+ through the final branch, which is why the cap test above uses 2 and this one does not.
+ """
+ n = 12
+ blocks = "".join(
+ '<tool_call>{"name":"t%d","arguments":{"x":"t%d"}}</tool_call>' % (i, i) for i in range(n)
+ )
+ streams = [[_sse({"content": blocks}), _done()], [_sse({"content": "done"}), _done()]]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": "t%d" % i}} for i in range(n)],
+ max_tool_iterations = 1,
+ )
+ )
+
+ messages = payloads[1]["messages"]
+ holders = [m for m in messages if "more tool call(s)" in (m.get("content") or "")]
+ assert len(holders) == 1
+ holder = holders[0]
+ skipped = {"t8", "t9", "t10", "t11"}
+ if holder["role"] == "tool":
+ assert holder.get("name") in skipped, "a note about %s must not sit inside %r's result" % (
+ sorted(skipped),
+ holder.get("name"),
+ )
+
+
+def test_gguf_over_cap_notice_for_several_tools_is_not_folded_into_one_tools_result(monkeypatch):
+ from core.inference.llama_cpp import _MAX_TOOL_CALLS_PER_TURN
+ from core.inference.tool_call_parser import BUDGET_EXHAUSTED_NUDGE
+
+ blocks = "".join(
+ '<tool_call>{"name":"web_search","arguments":{"query":"q%d"}}</tool_call>' % i
+ for i in range(_MAX_TOOL_CALLS_PER_TURN + 1)
+ )
+ blocks += '<tool_call>{"name":"python","arguments":{"code":"print(1)"}}</tool_call>'
+ streams = [[_sse({"content": blocks}), _done()], [_sse({"content": "done"}), _done()]]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [
+ {"type": "function", "function": {"name": "web_search"}},
+ {"type": "function", "function": {"name": "python"}},
+ ],
+ max_tool_iterations = 1,
+ )
+ )
+
+ messages = payloads[1]["messages"]
+ (holder,) = [m for m in messages if "more tool call(s)" in (m.get("content") or "")]
+ assert holder["role"] == "user"
+ assert "python" in holder["content"] and '"q8"' in holder["content"]
+ assert holder == messages[-1]
+ assert BUDGET_EXHAUSTED_NUDGE in holder["content"]
+ assert not any(
+ a.get("role") == "user" and b.get("role") == "user" for a, b in zip(messages, messages[1:])
+ )
+
+
+def test_gguf_over_cap_does_not_ask_for_a_retry_when_the_range_check_ends_the_loop(monkeypatch):
+ """The iteration range is a second exit; the notice must not ask for a retry there.
+
+ No-op turns burn the range budget without advancing the executed-tool counter, so the
+ loop can stop without the tool-iteration cap ever tripping. Asking for a retry there
+ lands next to the budget nudge that says not to call any more tools.
+ """
+
+ def _call(q):
+ return '<tool_call>{"name":"web_search","arguments":{"query":"%s"}}</tool_call>' % q
+
+ # Six real calls, then five no-op turns each re-issuing a DIFFERENT already-successful
+ # key (repeating one key twice trips the duplicate limit and forces the final answer
+ # through another exit), then a turn that overflows the cap. The no-ops burn the range
+ # without advancing the executed-tool count, so at max_tool_iterations = 3 the loop stops
+ # on the range check with only 2 executed-tool turns behind it.
+ streams = [[_sse({"content": "".join(_call("q%d" % i) for i in range(6))}), _done()]]
+ streams += [[_sse({"content": _call("q%d" % i)}), _done()] for i in range(5)]
+ streams.append([_sse({"content": "".join(_call("z%d" % i) for i in range(10))}), _done()])
+ streams += [[_sse({"content": "done"}), _done()] for _ in range(6)]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ max_tool_iterations = 3,
+ )
+ )
+
+ # Assert the scenario really happened rather than letting the check pass vacuously: the
+ # loop ended without offering tools again, and it did produce exactly one notice.
+ assert not payloads[-1].get("tools")
+ messages = payloads[-1]["messages"]
+ notices = [m for m in messages if "more tool call(s)" in (m.get("content") or "")]
+ assert len(notices) == 1
+ assert "Call them again" not in notices[0]["content"]
def test_gguf_textual_fallback_collapses_duplicate_tool_calls(monkeypatch):
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index efbd70f1ab8..3f959e82a8a 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -10,6 +10,7 @@ calls, tool-result feedback, bad-JSON heal, duplicate-call short-circuit,
``__IMAGES__`` sentinel stripping, executor errors, cancel, and the iteration cap.
"""
+import copy
import json
import threading
from typing import cast
@@ -25,6 +26,7 @@ from core.inference.safetensors_agentic import (
strip_tool_markup_streaming,
)
from core.inference.tool_call_parser import (
+ BUDGET_EXHAUSTED_NUDGE,
NUDGE_TOOL_CALLS_STATUS,
RAG_MAX_SEARCHES_PER_TURN,
has_tool_signal,
@@ -4087,17 +4089,67 @@ class TestGuardrails:
'<tool_call>{"name":"web_search","arguments":{"query":"q%d"}}</tool_call>' % i
for i in range(n)
)
- loop, exec_fn = _make_loop(
- turns = [[turn], ["final"]],
- exec_results = ["r"] * n,
+ seen_messages = []
+ turns = iter([turn, "final"])
+
+ def _gen(messages):
+ seen_messages.append(copy.deepcopy(messages))
+ yield next(turns)
+
+ exec_fn = FakeExecuteTool(["r"] * n)
+ loop = run_safetensors_tool_loop(
+ single_turn = _gen,
+ messages = [{"role": "user", "content": "hi"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ execute_tool = exec_fn,
max_tool_iterations = 2,
)
- _collect_events(loop)
+ events = _collect_events(loop)
assert len(exec_fn.calls) == _MAX_TOOL_CALLS_PER_TURN
# The first N distinct queries executed, in document order.
assert [a["query"] for _name, a in exec_fn.calls] == [
"q%d" % i for i in range(_MAX_TOOL_CALLS_PER_TURN)
]
+ assert len([e for e in events if e.get("type") == "tool_start"]) == _MAX_TOOL_CALLS_PER_TURN
+ (notice,) = [m for m in seen_messages[1] if "more tool call(s)" in m.get("content", "")]
+ assert notice["role"] == "user"
+ assert notice["content"].startswith("4 more tool call(s)")
+ for i in range(_MAX_TOOL_CALLS_PER_TURN, n):
+ assert '"q%d"' % i in notice["content"]
+ assert '"q%d"' % (_MAX_TOOL_CALLS_PER_TURN - 1) not in notice["content"]
+
+ def test_over_cap_on_last_turn_does_not_ask_for_retry(self):
+ from core.inference.safetensors_agentic import _MAX_TOOL_CALLS_PER_TURN
+
+ n = _MAX_TOOL_CALLS_PER_TURN + 2
+ turn = "".join(
+ '<tool_call>{"name":"web_search","arguments":{"query":"q%d"}}</tool_call>' % i
+ for i in range(n)
+ )
+ seen_messages = []
+ turns = iter([turn, "final"])
+
+ def _gen(messages):
+ seen_messages.append(copy.deepcopy(messages))
+ yield next(turns)
+
+ loop = run_safetensors_tool_loop(
+ single_turn = _gen,
+ messages = [{"role": "user", "content": "hi"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ execute_tool = FakeExecuteTool(["r"] * n),
+ max_tool_iterations = 1,
+ )
+ _collect_events(loop)
+ messages = seen_messages[1]
+ last = messages[-1]
+ assert last["role"] == "user"
+ assert last["content"].startswith("2 more tool call(s)")
+ assert BUDGET_EXHAUSTED_NUDGE in last["content"]
+ assert not any("Call them again" in m.get("content", "") for m in messages)
+ assert not any(
+ a["role"] == "user" and b["role"] == "user" for a, b in zip(messages, messages[1:])
+ )
def test_coerce_string_args_python_uses_code_key(self):
assert _coerce_arguments("print(1)", heal = True, tool_name = "python") == {"code": "print(1)"}
diff --git a/studio/backend/tests/test_tool_call_cap_notice_extra.py b/studio/backend/tests/test_tool_call_cap_notice_extra.py
new file mode 100644
index 00000000000..0f229763c71
--- /dev/null
+++ b/studio/backend/tests/test_tool_call_cap_notice_extra.py
@@ -0,0 +1,350 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Edge cases around the over-cap tool-call notice.
+
+The notice is text the model reads, so the load-bearing property is that a turn which
+does NOT overflow the cap reads exactly as it did before. These cover that, plus the
+per-turn reset, the retry actually executing, the dedup boundary, and
+``disable_parallel_tool_use``.
+"""
+
+import copy
+import json
+
+import pytest
+
+from core.inference.safetensors_agentic import (
+ _MAX_TOOL_CALLS_PER_TURN,
+ run_safetensors_tool_loop,
+)
+
+
+def _sibling(name):
+ """Import a sibling test module. conftest puts the backend root on sys.path, not tests/."""
+ import importlib.util
+ import pathlib
+
+ path = pathlib.Path(__file__).with_name(name + ".py")
+ spec = importlib.util.spec_from_file_location("_cap_notice_" + name, path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+_gguf = _sibling("test_llama_cpp_tool_loop")
+_safe = _sibling("test_safetensors_tool_loop")
+
+_backend_and_payloads = _gguf._backend_and_payloads
+_done = _gguf._done
+_record_tool_calls = _gguf._record_tool_calls
+_sse = _gguf._sse
+FakeExecuteTool = _safe.FakeExecuteTool
+_collect_events = _safe._collect_events
+
+NOTICE = "more tool call(s)"
+
+
+def _blocks(queries):
+ return "".join(
+ '<tool_call>{"name":"web_search","arguments":%s}</tool_call>' % json.dumps({"query": q})
+ for q in queries
+ )
+
+
+def _run_safetensors(
+ turn_texts,
+ *,
+ exec_results = None,
+ max_tool_iterations = 4,
+):
+ """Drive the safetensors loop and return (payloads seen by the model, exec_fn)."""
+ seen = []
+ turns = iter(turn_texts)
+
+ def _gen(messages):
+ seen.append(copy.deepcopy(messages))
+ try:
+ yield next(turns)
+ except StopIteration:
+ return
+
+ exec_fn = FakeExecuteTool(exec_results or ["r"] * 64)
+ loop = run_safetensors_tool_loop(
+ single_turn = _gen,
+ messages = [{"role": "user", "content": "hi"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ execute_tool = exec_fn,
+ max_tool_iterations = max_tool_iterations,
+ )
+ _collect_events(loop)
+ return seen, exec_fn
+
+
+def _notices(messages):
+ return [m for m in messages if NOTICE in (m.get("content") or "")]
+
+
+class TestNoticeIsSilentOnNormalTurns:
+ """Daniel's question on the PR: does this wording change a normal tool turn?"""
+
+ def test_a_single_call_turn_carries_no_notice(self):
+ seen, exec_fn = _run_safetensors([_blocks(["a"]), "final"])
+
+ assert len(exec_fn.calls) == 1
+ assert _notices(seen[1]) == []
+
+ def test_a_turn_at_exactly_the_cap_carries_no_notice(self):
+ queries = ["q%d" % i for i in range(_MAX_TOOL_CALLS_PER_TURN)]
+ seen, exec_fn = _run_safetensors([_blocks(queries), "final"])
+
+ assert len(exec_fn.calls) == _MAX_TOOL_CALLS_PER_TURN
+ assert _notices(seen[1]) == []
+
+ def test_gguf_turn_at_exactly_the_cap_carries_no_notice(self, monkeypatch):
+ queries = ["q%d" % i for i in range(_MAX_TOOL_CALLS_PER_TURN)]
+ streams = [
+ [_sse({"content": _blocks(queries)}), _done()],
+ [_sse({"content": "done"}), _done()],
+ ]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ calls = _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ max_tool_iterations = 2,
+ )
+ )
+
+ assert len(calls) == _MAX_TOOL_CALLS_PER_TURN
+ assert _notices(payloads[1]["messages"]) == []
+
+ def test_raw_calls_over_the_cap_that_dedup_under_it_carry_no_notice(self):
+ # 12 raw calls, 4 distinct: the cap is never reached, so this is a dedup turn only.
+ queries = ["a", "b", "c", "d"] * 3
+ seen, exec_fn = _run_safetensors([_blocks(queries), "final"])
+
+ assert [a["query"] for _name, a in exec_fn.calls] == ["a", "b", "c", "d"]
+ assert _notices(seen[1]) == []
+
+
+class TestNoticeIsPerTurn:
+ def test_a_later_normal_turn_does_not_repeat_the_notice(self):
+ over = ["q%d" % i for i in range(_MAX_TOOL_CALLS_PER_TURN + 2)]
+ seen, _exec_fn = _run_safetensors(
+ [_blocks(over), _blocks(["later-1", "later-2"]), "final"],
+ max_tool_iterations = 6,
+ )
+
+ # Turn 2 is told about the 2 skipped calls; turn 3 inherits that one message from
+ # history and gains no new one.
+ assert len(_notices(seen[1])) == 1
+ assert len(_notices(seen[2])) == 1
+
+ def test_the_skipped_calls_execute_when_the_model_reissues_them(self):
+ n = _MAX_TOOL_CALLS_PER_TURN + 2
+ over = ["q%d" % i for i in range(n)]
+ skipped = over[_MAX_TOOL_CALLS_PER_TURN:]
+ _seen, exec_fn = _run_safetensors(
+ [_blocks(over), _blocks(skipped), "final"],
+ max_tool_iterations = 6,
+ )
+
+ # Nothing about the first turn marks the skipped calls as already done, so the
+ # retry the notice asks for is actually honoured.
+ assert [a["query"] for _name, a in exec_fn.calls] == over
+ assert len(exec_fn.calls) == n
+
+
+class TestDisableParallelToolUse:
+ def test_only_one_call_runs_and_no_notice_is_sent(self, monkeypatch):
+ queries = ["q%d" % i for i in range(_MAX_TOOL_CALLS_PER_TURN + 2)]
+ streams = [
+ [_sse({"content": _blocks(queries)}), _done()],
+ [_sse({"content": "done"}), _done()],
+ ]
+ backend, payloads = _backend_and_payloads(monkeypatch, streams)
+ calls = _record_tool_calls(monkeypatch, "OK")
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ max_tool_iterations = 2,
+ disable_parallel_tool_use = True,
+ )
+ )
+
+ assert len(calls) == 1
+ # The 9 dropped calls here are dropped by the caller's own setting, not by the
+ # per-turn cap, so a cap notice would misattribute them.
+ assert _notices(payloads[1]["messages"]) == []
+
+
+class TestSkippedCallsLeaveNoOrphanUi:
+ def test_no_tool_start_or_end_event_for_a_skipped_call(self):
+ n = _MAX_TOOL_CALLS_PER_TURN + 2
+ queries = ["q%d" % i for i in range(n)]
+ turns = iter([_blocks(queries), "final"])
+
+ def _gen(_messages):
+ try:
+ yield next(turns)
+ except StopIteration:
+ return
+
+ loop = run_safetensors_tool_loop(
+ single_turn = _gen,
+ messages = [{"role": "user", "content": "hi"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ execute_tool = FakeExecuteTool(["r"] * n),
+ max_tool_iterations = 2,
+ )
+ events = _collect_events(loop, max_events = 400)
+
+ starts = [e for e in events if e.get("type") == "tool_start"]
+ ends = [e for e in events if e.get("type") == "tool_end"]
+ assert len(starts) == _MAX_TOOL_CALLS_PER_TURN
+ # Every card that opened also closed: a skipped call never leaves a running tool
+ # in the UI.
+ assert {e.get("tool_call_id") for e in starts} == {e.get("tool_call_id") for e in ends}
+
+
[email protected]("backend", ["gguf", "safetensors", "safetensors_unrestricted"])
[email protected]("mixed_skipped", [False, True])
[email protected]("render_result", ["Rendered HTML", "Error: render failed"])
+def test_cap_notice_does_not_invite_a_spent_one_shot_retry(
+ monkeypatch, backend, mixed_skipped, render_result
+):
+ calls = [("render_html", {"code": "<p>first</p>"})]
+ calls += [("web_search", {"query": f"q{i}"}) for i in range(7)]
+ calls.append(("render_html", {"code": "<p>second</p>"}))
+ if mixed_skipped:
+ calls.append(("web_search", {"query": "later"}))
+ text = "".join(
+ "<tool_call>" + json.dumps({"name": name, "arguments": args}) + "</tool_call>"
+ for name, args in calls
+ )
+ tools = [
+ {"type": "function", "function": {"name": name}} for name in ["render_html", "web_search"]
+ ]
+ if backend == "gguf":
+ streams = [[_sse({"content": text}), _done()], [_sse({"content": "done"}), _done()]]
+ engine, payloads = _backend_and_payloads(monkeypatch, streams)
+ executed = _record_tool_calls(
+ monkeypatch, lambda name: render_result if name == "render_html" else "OK"
+ )
+ list(
+ engine.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = tools,
+ max_tool_iterations = 3,
+ )
+ )
+ messages = payloads[1]["messages"]
+ else:
+ payloads = []
+ turns = iter([text, "done"])
+
+ def generate(messages):
+ payloads.append(copy.deepcopy(messages))
+ yield next(turns)
+
+ executor = FakeExecuteTool([render_result] + ["OK"] * 7)
+ list(
+ run_safetensors_tool_loop(
+ single_turn = generate,
+ messages = [{"role": "user", "content": "go"}],
+ tools = None if backend == "safetensors_unrestricted" else tools,
+ execute_tool = executor,
+ max_tool_iterations = 3,
+ )
+ )
+ executed = executor.calls
+ messages = payloads[1]
+ assert len(executed) == 8
+ (notice,) = _notices(messages)
+ content = notice["content"]
+ assert "<p>second</p>" in content
+ if render_result.startswith("Error:"):
+ assert "Call them again" in content
+ else:
+ assert "Call them again" not in content
+ assert "Do not retry render_html" in content
+ if mixed_skipped:
+ assert "retry the skipped calls for web_search" in content
+
+
[email protected]("backend", ["gguf", "safetensors"])
+def test_skipped_arguments_are_reserved_in_result_budgets(monkeypatch, backend):
+ import random
+ import string
+ from core.inference.context_window import (
+ estimate_messages_tokens_conservative,
+ prompt_budget,
+ )
+
+ random_source = random.Random(11154)
+ alphabet = string.ascii_letters + string.digits
+ code = "print(" + json.dumps("".join(random_source.choices(alphabet, k = 4000))) + ")"
+ calls = [{"name": "web_search", "arguments": {"query": f"q{i}"}} for i in range(8)]
+ calls.append({"name": "python", "arguments": {"code": code}})
+ text = "".join("<tool_call>" + json.dumps(call) + "</tool_call>" for call in calls)
+ tools = [{"type": "function", "function": {"name": name}} for name in ["web_search", "python"]]
+ seen = []
+ turns = iter([text, "done"])
+ budgets = []
+
+ def generate(messages):
+ seen.append(copy.deepcopy(messages))
+ yield next(turns)
+
+ def execute(name, arguments, *, result_budget_tokens, **kwargs):
+ budgets.append(result_budget_tokens)
+ return "".join(random_source.choices(alphabet, k = 2 * max(0, result_budget_tokens - 24)))
+
+ if backend == "gguf":
+ streams = [[_sse({"content": text}), _done()], [_sse({"content": "done"}), _done()]]
+ engine, payloads = _backend_and_payloads(monkeypatch, streams)
+
+ def count_tokens(
+ messages,
+ _unused = None,
+ tools = None,
+ **kwargs,
+ ):
+ return estimate_messages_tokens_conservative(
+ messages
+ ) + estimate_messages_tokens_conservative(tools or [])
+
+ monkeypatch.setattr(engine, "count_chat_tokens", count_tokens)
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ engine.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "go"}],
+ tools = tools,
+ max_tool_iterations = 2,
+ max_tokens = 3500,
+ )
+ )
+ seen = [payload["messages"] for payload in payloads]
+ else:
+ list(
+ run_safetensors_tool_loop(
+ single_turn = generate,
+ messages = [{"role": "user", "content": "go"}],
+ tools = tools,
+ execute_tool = execute,
+ max_tool_iterations = 2,
+ context_length = 4096,
+ max_tokens = 3500,
+ )
+ )
+ assert len(budgets) == 8
+ (notice,) = _notices(seen[1])
+ assert json.dumps({"code": code}) in notice["content"]
+ spent = estimate_messages_tokens_conservative(seen[1])
+ spent += estimate_messages_tokens_conservative(tools)
+ assert spent <= prompt_budget(4096, 3500)
diff --git a/studio/backend/tests/test_tool_loop_controller.py b/studio/backend/tests/test_tool_loop_controller.py
index dea6a31b437..75b527f8a3e 100644
--- a/studio/backend/tests/test_tool_loop_controller.py
+++ b/studio/backend/tests/test_tool_loop_controller.py
@@ -32,6 +32,7 @@ from core.inference.tool_loop_controller import (
is_tool_error,
status_for_tool,
strip_result_for_model,
+ tool_call_limit_nudge,
tool_event_provenance,
)
from core.inference.tool_call_parser import TOOL_ERROR_NUDGE, parse_tool_calls_from_text
@@ -719,3 +720,11 @@ def test_failed_workspace_execution_invalidates_previous_reads(tool_name):
controller.record_result(controller.prepare_call(write), "Error: failed after writing")
assert controller.prepare_call(read).action == "execute"
assert controller.prepare_call(write).action == "execute"
+
+
+def test_tool_call_limit_nudge_keeps_long_arguments_whole():
+ code = "print(1)\n" * 60
+ notice = tool_call_limit_nudge(
+ [{"function": {"name": "python", "arguments": json.dumps({"code": code})}}], 8
+ )
+ assert json.dumps({"code": code}) in notice["content"]