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: honour forced tool_choice on local gguf tool loops

Souravrajvi050f6ba2af6f2
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 41d7a920eaf..35af433050b 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -25440,6 +25440,7 @@ class LlamaCppBackend:
perf_callback: Optional[Callable[[dict], None]] = None,
reasoning_provenance: Optional[dict] = None,
context_overflow: Optional[str] = None,
+ tool_choice: Any = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -25544,18 +25545,33 @@ class LlamaCppBackend:
# retrieval call would actually prompt (ask mode); auto never gates the
# safe search_knowledge_base tool, so retrieval must still run there.
# off never prompts either, so it also keeps first-pass retrieval.
- from core.inference.chat_template_helpers import trailing_assistant_text
+ from core.inference.chat_template_helpers import forced_tool_name, trailing_assistant_text
+
+ initial_forced_name = forced_tool_name(tool_choice)
+ if initial_forced_name and initial_forced_name not in _gguf_active_tool_names(tools):
+ raise ValueError(
+ f"Forced tool '{initial_forced_name}' is not enabled for this request."
+ )
# A resumed turn must keep the partial trailing: autoinject appends a tool call
# plus its result, moving the boundary so the model opens a fresh answer.
_skip_autoinject = (
- confirm_tool_calls and not bypass_permissions and permission_mode not in ("auto", "off")
+ tool_choice == "none"
+ or (
+ confirm_tool_calls
+ and not bypass_permissions
+ and permission_mode not in ("auto", "off")
+ )
) or bool(continue_final_message and trailing_assistant_text(conversation))
_auto = None if _skip_autoinject else build_rag_autoinject(conversation, rag_scope)
if _auto:
for _ev in _auto["events"]:
yield _ev
conversation.extend(_auto["messages"])
+ _auto_satisfies_forced_choice = bool(_auto) and (
+ tool_choice == "required"
+ or forced_tool_name(tool_choice) == "search_knowledge_base"
+ )
_accumulated_completion_tokens = 0
_accumulated_predicted_ms = 0.0
@@ -25696,8 +25712,13 @@ class LlamaCppBackend:
neutralize_tool_descriptions as _neutralize_tool_descriptions,
)
+ controller_tools = (
+ []
+ if tool_choice == "none"
+ else _neutralize_tool_descriptions(tools, None, self.markup_profile)
+ )
tool_controller = ToolLoopController(
- tools = _neutralize_tool_descriptions(tools, None, self.markup_profile),
+ tools = controller_tools,
auto_heal_tool_calls = auto_heal_tool_calls,
)
@@ -25738,6 +25759,8 @@ class LlamaCppBackend:
from core.inference.chat_template_helpers import sweep_cache as _sweep_cache
_markup_cache = _sweep_cache()
+ # A forced function applies until the model produces it; execution or denial resolves it.
+ _forced_choice_resolved = _auto_satisfies_forced_choice
for iteration in range(max_tool_iterations + _extra):
if cancel_event is not None and cancel_event.is_set():
return
@@ -25748,7 +25771,10 @@ class LlamaCppBackend:
if not active_tools:
_append_budget_exhausted_nudge = False
break
- from core.inference.chat_template_helpers import neutralize_tool_descriptions
+ from core.inference.chat_template_helpers import (
+ neutralize_tool_descriptions,
+ reconciled_tool_choice,
+ )
# An MCP server's description and inputSchema are remote text the template renders
# into the system turn (#7066). Computed above the gate: a tool dropped for unsafe
@@ -25757,6 +25783,22 @@ class LlamaCppBackend:
safe_tools = neutralize_tool_descriptions(
active_tools, _markup_cache, self.markup_profile
)
+ requested_choice = "auto" if tool_choice is None else tool_choice
+ if _forced_choice_resolved and requested_choice not in ("auto", "none"):
+ requested_choice = "auto"
+ requested_choice = (
+ reconciled_tool_choice(requested_choice, tools, safe_tools) or "auto"
+ )
+ forced_name = forced_tool_name(requested_choice)
+ if forced_name:
+ matching_tools = [
+ tool
+ for tool in safe_tools
+ if (tool.get("function") or {}).get("name") == forced_name
+ ]
+ if matching_tools:
+ safe_tools = matching_tools
+ requested_choice = "required"
# Gate the markerless bare-JSON form on enabled names so an ordinary JSON answer isn't misread as a call.
_enabled_tool_names = {
(tool.get("function") or {}).get("name")
@@ -25916,7 +25958,7 @@ class LlamaCppBackend:
# now empty, and "tools": [] would still advertise tool use.
if safe_tools:
payload["tools"] = safe_tools
- payload["tool_choice"] = "auto"
+ payload["tool_choice"] = requested_choice
if _reasoning_kw is not None:
payload["chat_template_kwargs"] = _reasoning_kw
# Re-checked per iteration: once a tool result is appended the partial is
@@ -26259,7 +26301,7 @@ class LlamaCppBackend:
and any(
(tool.get("function") or {}).get("name")
== current_name
- for tool in active_tools
+ for tool in safe_tools
)
):
provisional_started_tool_calls[current_id] = (
@@ -26945,6 +26987,7 @@ class LlamaCppBackend:
tc,
forced = _forced_tool_call_pending,
provisional = provisional_match,
+ allowed_tool_names = {forced_name} if forced_name else None,
)
if not decision.should_execute:
@@ -27034,6 +27077,7 @@ class LlamaCppBackend:
yield {"type": "status", "text": decision.status_text}
if _decision == "deny":
decision_slot = None
+ _forced_choice_resolved = True
resolved_provisional_tool_call_ids.add(decision.tool_call_id)
yield {
"type": "tool_end",
@@ -27278,6 +27322,7 @@ class LlamaCppBackend:
_last_reprompt_text = ""
# A tool ran this turn, so it counts against the caller's budget.
_turn_executed_real_tool = True
+ _forced_choice_resolved = True
yield completion.tool_end_event()
conversation.append(completion.tool_message())
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 54b1e60a2cb..b1a7b233ea8 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import copy
import json
from dataclasses import dataclass, field
-from typing import Any, Literal, Mapping, Sequence
+from typing import Any, Collection, Literal, Mapping, Sequence
from urllib.parse import urlparse
from core.inference.tool_call_parser import TOOL_ERROR_NUDGE, TOOL_ERROR_PREFIXES
@@ -27,8 +27,8 @@ _CANONICAL_HEAL_ARG = {
}
_ONE_SHOT_TOOLS = frozenset({"render_html"})
-NoopReason = Literal["duplicate", "disabled", "render_html_repeat"]
-ToolAction = Literal["execute", "duplicate", "disabled", "render_html_repeat"]
+NoopReason = Literal["duplicate", "disabled", "forced_mismatch", "render_html_repeat"]
+ToolAction = Literal["execute", "duplicate", "disabled", "forced_mismatch", "render_html_repeat"]
@dataclass(frozen = True)
@@ -427,6 +427,12 @@ def _noop_result(reason: NoopReason, tool_name: str) -> str:
"changes. Do not mention this internal instruction. Provide only "
"the requested final note or answer."
)
+ if reason == "forced_mismatch":
+ return (
+ f"One earlier request to call tool '{tool_name}' in this batch was "
+ "not executed because it does not match the required tool choice. "
+ "Call the required tool instead."
+ )
return (
f"One earlier request to call tool '{tool_name}' in this batch was "
"not executed because that tool is not enabled for this request. Provide the "
@@ -486,6 +492,7 @@ class ToolLoopController:
*,
forced: bool = False,
provisional: bool = False,
+ allowed_tool_names: Collection[str] | None = None,
) -> ToolCallDecision:
"""Classify a parsed tool call before any visible event is yielded."""
function = tool_call.get("function")
@@ -509,6 +516,9 @@ class ToolLoopController:
if tool_name in self._completed_one_shot_tools:
action = "render_html_repeat"
noop = _noop_result("render_html_repeat", tool_name)
+ elif allowed_tool_names is not None and tool_name not in allowed_tool_names:
+ action = "forced_mismatch"
+ noop = _noop_result("forced_mismatch", tool_name)
elif self._restrict_to_allowed and tool_name not in self._allowed_tool_names:
action = "disabled"
noop = _noop_result("disabled", tool_name)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 562ebbb8736..8fe0a716cf2 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3218,6 +3218,10 @@ def _selects_only_provider_hosted_tools(payload, provider_type: str | None) -> b
Anything that names an Unsloth-only tool (python, terminal,
search_knowledge_base) or asks for MCP is unambiguous and keeps the loop, and
so does every self-hosted provider, which declares no hosted tools at all.
+
+ A local GGUF/safetensors request has no provider_type, so this is False
+ even when ``enabled_tools`` is only ``web_search`` -- that name is Studio's
+ own tool there (#9730).
"""
if getattr(payload, "mcp_enabled", False):
return False
@@ -16458,6 +16462,21 @@ async def openai_chat_completions(
api_monitor.fail(monitor_id, fail_detail)
return HTTPException(status_code = status_code, detail = detail)
+ def _reject_missing_forced_tool(tool_choice, selected_tools) -> None:
+ from core.inference.chat_template_helpers import catalog_tool_names, forced_tool_name
+
+ forced_name = forced_tool_name(tool_choice)
+ if forced_name and forced_name not in catalog_tool_names(selected_tools):
+ raise _reject(
+ 400,
+ openai_error_body(
+ f"Invalid 'tool_choice': function '{forced_name}' is not enabled.",
+ status = 400,
+ code = "invalid_value",
+ param = "tool_choice",
+ ),
+ )
+
def _reject_unsupported_n(path_label: str) -> "HTTPException":
return _reject(
400,
@@ -16773,6 +16792,7 @@ async def openai_chat_completions(
# reset is POSSIBLE somewhere, not that this request can perform one.
checkpoint_fitted = _rolling_context_policy(payload) is not None,
)
+ _reject_missing_forced_tool(payload.tool_choice, tools_to_use)
# Skip the tool loop when no tool survived, so the safetensors
# loop's "empty = allow all" semantic can't reach built-in tools
# the caller didn't opt into. Callers who omit enabled_tools still
@@ -16900,6 +16920,7 @@ async def openai_chat_completions(
continue_final_message = _continue_final_message(payload),
auto_heal_tool_calls = _gguf_auto_heal_tool_calls,
nudge_tool_calls = payload.nudge_tool_calls,
+ tool_choice = payload.tool_choice,
max_tool_iterations = payload.max_tool_calls_per_message
if payload.max_tool_calls_per_message is not None
else 25,
@@ -18436,6 +18457,7 @@ async def openai_chat_completions(
_sf_tools_to_use = await _select_request_tools(
payload, tools_on = _sf_tools_on, mcp_allowed = _sf_mcp_allowed
)
+ _reject_missing_forced_tool(payload.tool_choice, _sf_tools_to_use)
# Mirror the GGUF path: refuse to enter the tool loop when nothing
# survived, so a model-emitted built-in call can't piggy-back on the
# empty allow-list.
@@ -23658,6 +23680,33 @@ async def anthropic_messages(
if _full_access:
openai_tools = apply_full_access_tool_descriptions(openai_tools)
+ server_tool_choice = openai_tool_choice
+ if isinstance(server_tool_choice, dict):
+ forced_function = server_tool_choice.get("function")
+ forced_name = (
+ forced_function.get("name") if isinstance(forced_function, dict) else None
+ )
+ canonical_name = _STUDIO_ANTHROPIC_TOOL_ALIASES.get(forced_name)
+ if canonical_name:
+ server_tool_choice = {
+ "type": "function",
+ "function": {"name": canonical_name},
+ }
+ from core.inference.chat_template_helpers import catalog_tool_names, forced_tool_name
+
+ forced_name = forced_tool_name(server_tool_choice)
+ if forced_name and forced_name not in catalog_tool_names(openai_tools):
+ message = f"Invalid 'tool_choice': function '{forced_name}' is not enabled."
+ api_monitor.fail(monitor_id, message)
+ raise HTTPException(
+ status_code = 400,
+ detail = anthropic_error_body(
+ message,
+ status = 400,
+ err_type = "invalid_request_error",
+ ),
+ )
+
# Build tool-use system prompt nudge (same logic as /chat/completions)
_nudge = _build_tool_action_nudge(
tools = openai_tools,
@@ -23702,6 +23751,7 @@ async def anthropic_messages(
max_tool_iterations = 25,
auto_heal_tool_calls = True,
nudge_tool_calls = payload.nudge_tool_calls,
+ tool_choice = server_tool_choice,
tool_call_timeout = 300,
session_id = payload.session_id,
thread_id = payload.thread_id,
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 670e2b46cd3..d4e4502686e 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -2722,6 +2722,37 @@ class TestAnthropicMessagesToolRouting:
_drive(anthropic_messages(payload, request = None, current_subject = "t"))
assert backend.calls[0][0] == "tools"
+ def test_server_tool_choice_alias_uses_the_selected_studio_name(self, monkeypatch):
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(
+ tools = [{"type": "web_fetch_20250910", "name": "web_fetch"}],
+ tool_choice = {"type": "tool", "name": "web_fetch"},
+ )
+
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+
+ call_kind, kwargs = backend.calls[0]
+ assert call_kind == "tools"
+ assert kwargs["tool_choice"] == {
+ "type": "function",
+ "function": {"name": "web_search"},
+ }
+ assert [tool["function"]["name"] for tool in kwargs["tools"]] == ["web_search"]
+
+ def test_server_tool_choice_must_be_in_the_selected_catalog(self, monkeypatch):
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(
+ tools = [{"type": "web_search_20250305", "name": "web_search"}],
+ tool_choice = {"type": "tool", "name": "python"},
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+
+ assert exc.value.status_code == 400
+ assert "python" in exc.value.detail["error"]["message"]
+ assert backend.calls == []
+
def test_confirm_tool_calls_rejected_for_server_tools(self, monkeypatch):
backend = _mock_backend(monkeypatch)
payload = _basic_payload(
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index f908763dd70..02516c8f18b 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -17,6 +17,8 @@ import sys
import threading
from pathlib import Path
+import pytest
+
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
@@ -263,6 +265,164 @@ def _structured_tool_call(tool_name: str, arguments: dict, call_id: str) -> list
]
+def test_forced_web_search_tool_choice_is_sent_until_a_tool_runs(monkeypatch):
+ """#9730: a forced web_search must reach llama-server on the first turn.
+
+ After the call executes, the follow-up is auto so the model can answer.
+ """
+ first_stream = _structured_tool_call(
+ "web_search", {"query": "current Linux kernel version"}, "call_search"
+ )
+ second_stream = [_sse({"content": "The current version of the Linux kernel is 6.10."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [first_stream, second_stream], payloads)
+ monkeypatch.setattr(
+ "core.inference.tools.execute_tool",
+ lambda name, arguments, **_kwargs: "Linux kernel 6.10",
+ )
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [
+ {
+ "role": "user",
+ "content": (
+ "Search the web for the current version of the Linux kernel, "
+ "then answer in one sentence."
+ ),
+ }
+ ],
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "python",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ },
+ ],
+ tool_choice = {"type": "function", "function": {"name": "web_search"}},
+ max_tool_iterations = 5,
+ permission_mode = "off",
+ )
+ )
+
+ assert payloads[0]["tool_choice"] == "required"
+ assert [tool["function"]["name"] for tool in payloads[0]["tools"]] == ["web_search"]
+ assert payloads[1]["tool_choice"] == "auto"
+ assert any(
+ event.get("type") == "tool_start" and event.get("tool_name") == "web_search"
+ for event in events
+ )
+
+
+def test_forced_tool_choice_must_exist_in_the_catalog(monkeypatch):
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [], payloads)
+
+ with pytest.raises(ValueError, match="Forced tool 'python' is not enabled"):
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "run python"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ tool_choice = {"type": "function", "function": {"name": "python"}},
+ max_tool_iterations = 1,
+ )
+ )
+
+ assert payloads == []
+
+
+def test_forced_tool_choice_retries_after_other_structured_calls(monkeypatch):
+ wrong_code = "print('wrong tool')\n" * 20
+ streams = [
+ _structured_tool_call("python", {"code": wrong_code}, "call_python"),
+ _structured_tool_call("web_search", {"query": "kernel version"}, "call_search"),
+ [_sse({"content": "The search completed."}), _done()],
+ ]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, streams, payloads)
+ calls: list[tuple[str, dict]] = []
+
+ def fake_execute_tool(name, arguments, **_kwargs):
+ calls.append((name, arguments))
+ return "Linux kernel result"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "search the web"}],
+ tools = [
+ {"type": "function", "function": {"name": "web_search"}},
+ {"type": "function", "function": {"name": "python"}},
+ ],
+ tool_choice = {"type": "function", "function": {"name": "web_search"}},
+ max_tool_iterations = 2,
+ )
+ )
+
+ assert payloads[0]["tool_choice"] == "required"
+ assert [tool["function"]["name"] for tool in payloads[0]["tools"]] == ["web_search"]
+ assert payloads[1]["tool_choice"] == "required"
+ assert [tool["function"]["name"] for tool in payloads[1]["tools"]] == ["web_search"]
+ assert payloads[2]["tool_choice"] == "auto"
+ assert calls == [("web_search", {"query": "kernel version"})]
+ assert [
+ event.get("tool_name") for event in events if event.get("type") == "tool_start"
+ ] == ["web_search"]
+
+
+def test_none_tool_choice_never_executes_model_tool_calls(monkeypatch):
+ stream = [
+ *_structured_tool_call("python", {"code": "print(1)"}, "call_python")[:-1],
+ _sse({"content": "I will answer without tools."}),
+ _done(),
+ ]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [stream], payloads)
+
+ def fail_execute_tool(name, arguments, **_kwargs):
+ raise AssertionError(f"unexpected tool execution: {name} {arguments}")
+
+ def fail_autoinject(*_args, **_kwargs):
+ raise AssertionError("tool_choice=none must not autoinject retrieval")
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", fail_execute_tool)
+ monkeypatch.setattr("core.inference.tools.build_rag_autoinject", fail_autoinject)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "answer directly"}],
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "python",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ],
+ tool_choice = "none",
+ max_tool_iterations = 1,
+ rag_scope = {"thread_id": "t1", "autoinject": True},
+ )
+ )
+
+ assert len(payloads) == 1
+ assert "tools" not in payloads[0]
+ assert "tool_choice" not in payloads[0]
+ assert not [event for event in events if event.get("type") in {"tool_start", "tool_end"}]
+ assert any(event.get("text") == "I will answer without tools." for event in events)
+
+
def test_structured_tool_call_after_visible_preface_is_executed(monkeypatch):
"""llama-server may emit content first and then native delta.tool_calls.
@@ -3261,6 +3421,50 @@ def test_rag_autoinject_counts_as_a_prior_tool_execution(monkeypatch):
assert events
+def test_rag_autoinject_only_resolves_matching_forced_choices(monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.tools.build_rag_autoinject",
+ lambda *_a, **_k: {
+ "events": [],
+ "messages": [{"role": "user", "content": "Retrieved passage: Tokyo."}],
+ },
+ )
+ tools = [
+ {"type": "function", "function": {"name": "search_knowledge_base"}},
+ {"type": "function", "function": {"name": "web_search"}},
+ ]
+
+ def first_payload(tool_choice):
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [[_sse({"content": "The passage describes Tokyo."}), _done()]],
+ payloads,
+ )
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "summarize the docs"}],
+ tools = tools,
+ tool_choice = tool_choice,
+ max_tool_iterations = 1,
+ nudge_tool_calls = False,
+ rag_scope = {"thread_id": "t1"},
+ )
+ )
+ return payloads[0]
+
+ matching = first_payload(
+ {"type": "function", "function": {"name": "search_knowledge_base"}}
+ )
+ required = first_payload("required")
+ unrelated = first_payload({"type": "function", "function": {"name": "web_search"}})
+
+ assert matching["tool_choice"] == "auto"
+ assert required["tool_choice"] == "auto"
+ assert unrelated["tool_choice"] == "required"
+ assert [tool["function"]["name"] for tool in unrelated["tools"]] == ["web_search"]
+
+
def test_confirm_tool_calls_deny_skips_gguf_tool_and_retry_can_execute(monkeypatch):
same_call = _structured_tool_call("python", {"code": "print(1)"}, "call_py")
streams = [
@@ -3295,6 +3499,7 @@ def test_confirm_tool_calls_deny_skips_gguf_tool_and_retry_can_execute(monkeypat
backend.generate_chat_completion_with_tools(
messages = [{"role": "user", "content": "run python"}],
tools = [{"type": "function", "function": {"name": "python"}}],
+ tool_choice = {"type": "function", "function": {"name": "python"}},
max_tool_iterations = 2,
confirm_tool_calls = True,
# Unset defaults to "auto", which would not prompt this safe print(1).
@@ -3308,6 +3513,7 @@ def test_confirm_tool_calls_deny_skips_gguf_tool_and_retry_can_execute(monkeypat
assert len(starts) == 2
assert [event["result"] for event in ends] == [TOOL_REJECTED_MESSAGE, "OK"]
assert calls == [("python", {"code": "print(1)"})]
+ assert [payload.get("tool_choice") for payload in payloads] == ["required", "auto", "auto"]
def _streamed_structured_tool_call(
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 3aa30f97f80..8c34ad727c7 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -2702,6 +2702,107 @@ class TestGgufVisionToolRouting:
assert captured["kwargs"]["disable_parallel_tool_use"] is True
+ def test_enabled_tools_web_search_only_enters_gguf_tool_loop(self, monkeypatch):
+ """#9730: enable_tools + enabled_tools: ["web_search"] on a local GGUF
+ must enter Studio's loop with that catalog, not answer from memory."""
+ import routes.inference as inf_mod
+
+ reset_tool_policy()
+ captured = {}
+
+ def _plain(**kwargs):
+ raise AssertionError("plain GGUF path should not be used")
+
+ def _tools(**kwargs):
+ captured["kwargs"] = kwargs
+ yield {"type": "content", "text": "The current version of the Linux kernel is 6.10."}
+
+ backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ supports_tools = True,
+ model_identifier = "Qwen3.5-2B-MTP-GGUF",
+ context_length = 4096,
+ generate_chat_completion = _plain,
+ generate_chat_completion_with_tools = _tools,
+ )
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [
+ {
+ "role": "user",
+ "content": (
+ "Search the web for the current version of the Linux kernel, "
+ "then answer in one sentence."
+ ),
+ }
+ ],
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ permission_mode = "off",
+ tool_choice = {"type": "function", "function": {"name": "web_search"}},
+ max_tokens = 512,
+ temperature = 0.0,
+ stream = True,
+ )
+
+ response = self._drive(
+ openai_chat_completions(payload, request = self._Request(), current_subject = "test")
+ )
+ self._consume_response(response)
+
+ assert "kwargs" in captured
+ assert [t["function"]["name"] for t in captured["kwargs"]["tools"]] == ["web_search"]
+ assert captured["kwargs"]["tool_choice"] == {
+ "type": "function",
+ "function": {"name": "web_search"},
+ }
+ assert captured["kwargs"]["permission_mode"] == "off"
+
+ def test_forced_tool_choice_must_be_in_the_selected_gguf_catalog(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ reset_tool_policy()
+
+ def _tools(**_kwargs):
+ raise AssertionError("invalid forced choice must not start generation")
+
+ backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ supports_tools = True,
+ model_identifier = "test-gguf",
+ context_length = 4096,
+ generate_chat_completion_with_tools = _tools,
+ )
+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [{"role": "user", "content": "run python"}],
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ permission_mode = "off",
+ tool_choice = {"type": "function", "function": {"name": "python"}},
+ stream = True,
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ self._drive(
+ openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail["error"]["param"] == "tool_choice"
+
def test_confirm_tool_calls_requires_streaming_for_gguf_tools(self, monkeypatch):
import routes.inference as inf_mod
diff --git a/studio/backend/tests/test_run_tools_locally_discriminator.py b/studio/backend/tests/test_run_tools_locally_discriminator.py
index 43d0842f073..2c37a26935b 100644
--- a/studio/backend/tests/test_run_tools_locally_discriminator.py
+++ b/studio/backend/tests/test_run_tools_locally_discriminator.py
@@ -190,3 +190,25 @@ def test_the_field_defaults_to_absent_not_false():
payload = _payload(enabled_tools = ["web_search"])
dumped = payload.model_dump(exclude_unset = True)
assert "run_tools_locally" not in dumped
+
+
+def test_local_gguf_search_only_is_not_a_hosted_request():
+ """#9730: a loaded GGUF has no provider_type; web_search is Studio's tool."""
+ from models.inference import ChatCompletionRequest
+ from routes.inference import _select_request_tools, _selects_only_provider_hosted_tools
+
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "Search the web for the Linux kernel version."}],
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ permission_mode = "off",
+ tool_choice = {"type": "function", "function": {"name": "web_search"}},
+ )
+ assert payload.provider_type is None
+ assert payload.provider_id is None
+ assert _selects_only_provider_hosted_tools(payload, None) is False
+ names = [
+ t["function"]["name"]
+ for t in _drive(_select_request_tools(payload, tools_on = True, mcp_allowed = False))
+ ]
+ assert names == ["web_search"]
diff --git a/studio/backend/tests/test_tool_loop_controller.py b/studio/backend/tests/test_tool_loop_controller.py
index e9ed58b0900..e3e891e7cd3 100644
--- a/studio/backend/tests/test_tool_loop_controller.py
+++ b/studio/backend/tests/test_tool_loop_controller.py
@@ -234,6 +234,23 @@ def test_disabled_tool_is_internal_noop_not_visible_tool_error():
assert controller.active_tools() == []
+def test_forced_mismatch_keeps_the_required_tool_active():
+ controller = ToolLoopController(tools = [_tool("web_search"), _tool("python")])
+ decision = controller.prepare_call(
+ _call("python", {"code": "print(1)"}),
+ allowed_tool_names = {"web_search"},
+ )
+ completion = controller.record_noop(decision)
+
+ assert decision.action == "forced_mismatch"
+ assert "required tool choice" in completion.model_message()["content"]
+ assert not controller.force_final_answer
+ assert [tool["function"]["name"] for tool in controller.active_tools()] == [
+ "web_search",
+ "python",
+ ]
+
+
def test_render_html_success_filters_active_tools_and_repeat_is_internal():
controller = ToolLoopController(tools = [_tool("render_html"), _tool("web_search")])
assert [t["function"]["name"] for t in controller.active_tools()] == [