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.

Let a request say whether Search runs locally or at the provider (#8711)

Daniel Han015b4a066851
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index d70ecb5236b..954b451f345 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1331,6 +1331,18 @@ class ChatCompletionRequest(BaseModel):
ge = 1,
description = "[x-unsloth] Timeout in seconds for each tool call execution (9999 = no limit).",
)
+ run_tools_locally: Optional[bool] = Field(
+ None,
+ description = (
+ "[x-unsloth] Execute the selected tools on the Studio host instead of "
+ "asking the provider to run its own hosted builtins. Only meaningful "
+ "for providers that ship hosted tools of the same name (OpenAI, "
+ "Gemini, Kimi, OpenRouter), where 'web_search' alone is ambiguous: "
+ "the same request means hosted search to a client written before "
+ "Studio ran tools for external providers. Omitted keeps the hosted "
+ "behaviour, so an older client is unaffected."
+ ),
+ )
session_id: Optional[str] = Field(
None,
description = "[x-unsloth] Session/thread ID for scoping tool execution sandbox.",
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b3a03b50a55..8ce0755160c 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2367,6 +2367,7 @@ from core.inference.providers import (
get_base_url,
get_provider_info,
hosted_only_tools,
+ LOCAL_STANDINS_FOR_HOSTED_TOOLS,
provider_hosted_tools,
provider_model_runs_local_tools,
provider_runs_local_tools,
@@ -2817,7 +2818,21 @@ def _selects_only_provider_hosted_tools(payload, provider_type: str | None) -> b
# local implementation of those names either, so reading such a request as
# "local" would drop them just the same, only after also replacing the
# provider's search with ours.
- return all(isinstance(name, str) and name in HOSTED_TOOL_NAMES for name in enabled)
+ if not all(isinstance(name, str) and name in HOSTED_TOOL_NAMES for name in enabled):
+ return False
+ # run_tools_locally only decides the ambiguous names, the ones Studio can
+ # also run itself. A selection with no SELECTED local stand-in stays hosted
+ # whatever the flag says: honouring it would enter the loop, find an empty
+ # catalog, fall back to the same passthrough, and skip the confirmation
+ # rejection on the way.
+ if getattr(payload, "run_tools_locally", None) is True:
+ # Intersected with the selection, as hosted_only_tools does: code_execution
+ # maps to python/terminal, but naming it alone selects neither.
+ selected = {name for name in enabled if isinstance(name, str)}
+ return not any(
+ LOCAL_STANDINS_FOR_HOSTED_TOOLS.get(name, frozenset()) & selected for name in selected
+ )
+ return True
def _takes_tool_passthrough(payload, llama_backend) -> bool:
diff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.py
index d75c2d480c0..ed2faf44df5 100644
--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py
+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py
@@ -187,6 +187,46 @@ def test_a_hosted_code_execution_is_not_dropped(monkeypatch):
assert "code_execution" in (FakeExternalClient.last["passthrough"]["enabled_tools"] or [])
+def test_a_code_execution_with_run_tools_locally_still_answers_the_confirm_gate(monkeypatch):
+ """`run_tools_locally` must not smuggle a hosted-only turn past the 400.
+
+ Studio has no `code_execution`, so the local catalog is empty whatever the
+ flag says and the route falls back to the provider. The confirmation
+ rejection keys on the request NOT having taken the loop, so a "local"
+ reading here answers a confirm-me request with an unconfirmed sandbox run.
+ """
+ from fastapi import HTTPException
+
+ inf = _install(monkeypatch, "openai")
+ # Class-level state; the client is built after the guard, so an untouched
+ # record is the evidence nothing was sent.
+ FakeExternalClient.last = {}
+ payload = _payload(
+ enable_tools = True,
+ enabled_tools = ["code_execution"],
+ run_tools_locally = True,
+ confirm_tool_calls = True,
+ )
+ with pytest.raises(HTTPException) as excinfo:
+ _run(inf, payload)
+ assert excinfo.value.status_code == 400
+ assert FakeExternalClient.last.get("passthrough") is None, "ran unconfirmed"
+
+
+def test_a_code_execution_with_run_tools_locally_still_reaches_the_provider(monkeypatch):
+ """And with no confirmation asked for, it proxies exactly as it always did."""
+ inf = _install(monkeypatch, "openai")
+ _run(
+ inf,
+ _payload(
+ enable_tools = True,
+ enabled_tools = ["code_execution"],
+ run_tools_locally = True,
+ ),
+ )
+ assert FakeExternalClient.last["passthrough"]["enabled_tools"] == ["code_execution"]
+
+
@pytest.mark.parametrize("provider_type", SELF_HOSTED_PROVIDERS)
def test_a_self_hosted_provider_still_runs_studios_own_web_search(monkeypatch, provider_type):
"""Shape 2, the PR's primary use case: a self-hosted server has no hosted
diff --git a/studio/backend/tests/test_run_tools_locally_discriminator.py b/studio/backend/tests/test_run_tools_locally_discriminator.py
new file mode 100644
index 00000000000..5a51c2f5235
--- /dev/null
+++ b/studio/backend/tests/test_run_tools_locally_discriminator.py
@@ -0,0 +1,192 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``run_tools_locally`` resolves the one request shape names cannot.
+
+On a provider shipping hosted builtins of the same name, ``enabled_tools:
+["web_search"]`` is byte-identical whether an older bundle means the PROVIDER's
+search or the current composer means the local Search pill. The backend guessed
+hosted, so the newer client silently got hosted search. The flag lets the caller
+say; absent, the hosted reading still wins and old clients are unaffected.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+
+def _drive(coro):
+ return asyncio.new_event_loop().run_until_complete(coro)
+
+
+HOSTED_PROVIDERS = ("openai", "gemini", "kimi", "openrouter")
+SELF_HOSTED_PROVIDERS = ("llama_cpp", "vllm", "ollama", "custom")
+
+
+def _payload(**overrides):
+ from models.inference import ChatCompletionRequest
+
+ base = dict(
+ messages = [{"role": "user", "content": "what is 2+2?"}],
+ provider_id = "saved-1",
+ external_model = "gpt-5.4",
+ stream = True,
+ enable_tools = True,
+ )
+ base.update(overrides)
+ return ChatCompletionRequest(**base)
+
+
+# ── the ambiguous shape, both readings ───────────────────────────────
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_search_only_without_the_flag_stays_hosted(provider_type):
+ """An old cached bundle sends exactly this and means the provider's search."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(enabled_tools = ["web_search"])
+ assert payload.run_tools_locally is None, "the old client does not send it"
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is True
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_search_only_with_the_flag_runs_here(provider_type):
+ """The current composer sends the same names plus the flag, and means us."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(enabled_tools = ["web_search"], run_tools_locally = True)
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is False
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_an_explicit_false_is_not_read_as_a_local_request(provider_type):
+ """Only True flips it. False and None both keep the hosted reading."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(enabled_tools = ["web_search"], run_tools_locally = False)
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is True
+
+
+# ── everything the flag must not change ──────────────────────────────
+
+
[email protected]("provider_type", SELF_HOSTED_PROVIDERS)
+def test_self_hosted_providers_are_unaffected(provider_type):
+ """They declare no hosted tools, so this was never ambiguous for them."""
+ from routes.inference import _selects_only_provider_hosted_tools
+ for flag in (None, True, False):
+ payload = _payload(enabled_tools = ["web_search"], run_tools_locally = flag)
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is False
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_a_local_only_name_never_needed_the_flag(provider_type):
+ """python has no hosted counterpart, so it was always unambiguous."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(enabled_tools = ["python"])
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is False
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_a_hosted_only_name_with_no_local_stand_in_stays_hosted(provider_type):
+ """image_generation has no local implementation, so a local reading would
+ drop it: the flag must not blanket-override the hosted vocabulary."""
+ from core.inference.tools import ALL_TOOLS
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ # The premise: Studio has nothing to substitute.
+ assert "image_generation" not in {tool["function"]["name"] for tool in ALL_TOOLS}
+
+ payload = _payload(enabled_tools = ["image_generation"])
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is True
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_the_flag_cannot_route_a_hosted_only_selection_into_the_loop(provider_type):
+ """The flag decides ambiguous names, it does not override the whole rule.
+
+ Honouring it for image_generation would enter the loop, find nothing to
+ execute, fall back to the same passthrough, and skip the confirmation
+ rejection on the way, since that guard keys on not having taken the loop.
+ """
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(
+ enabled_tools = ["image_generation"],
+ run_tools_locally = True,
+ confirm_tool_calls = True,
+ )
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is True
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_code_execution_alone_stays_hosted_because_its_stand_ins_are_unselected(provider_type):
+ """code_execution has a stand-in mapping, but this request selects neither half.
+
+ Studio ships no code_execution, so the loop has nothing to execute. Reading
+ the flag off the mere existence of the mapping enters the loop, finds an
+ empty catalog, falls back to the same passthrough, and skips the
+ confirmation rejection on the way.
+ """
+ from core.inference.providers import LOCAL_STANDINS_FOR_HOSTED_TOOLS
+ from core.inference.tools import ALL_TOOLS
+ from routes.inference import _select_request_tools, _selects_only_provider_hosted_tools
+
+ # The premise, derived rather than asserted: a mapping exists, nothing it
+ # points at was selected, and Studio has no code_execution of its own.
+ assert LOCAL_STANDINS_FOR_HOSTED_TOOLS["code_execution"] == frozenset({"python", "terminal"})
+ assert "code_execution" not in {tool["function"]["name"] for tool in ALL_TOOLS}
+
+ payload = _payload(
+ enabled_tools = ["code_execution"],
+ run_tools_locally = True,
+ confirm_tool_calls = True,
+ )
+ # The local catalog this request would take into the loop: empty.
+ assert _drive(_select_request_tools(payload, tools_on = True, mcp_allowed = False)) == []
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is True
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_code_execution_beside_a_selected_stand_in_still_takes_the_loop(provider_type):
+ """The other half of the rule: web_search is Studio's to run and
+ code_execution rides along, so the check above must not sweep this up."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(
+ enabled_tools = ["web_search", "code_execution"],
+ run_tools_locally = True,
+ )
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is False
+
+
[email protected]("provider_type", HOSTED_PROVIDERS)
+def test_a_mixed_selection_with_the_flag_still_takes_the_loop(provider_type):
+ """One name Studio can run is enough; the hosted one rides along as a flag."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(
+ enabled_tools = ["web_search", "image_generation"],
+ run_tools_locally = True,
+ )
+ assert _selects_only_provider_hosted_tools(payload, provider_type) is False
+
+
+def test_mcp_still_wins_regardless_of_the_flag():
+ """MCP is unambiguous on its own and predates the flag."""
+ from routes.inference import _selects_only_provider_hosted_tools
+
+ payload = _payload(enabled_tools = ["web_search"], mcp_enabled = True)
+ assert _selects_only_provider_hosted_tools(payload, "openai") is False
+
+
+def test_the_field_defaults_to_absent_not_false():
+ """Same decision as False, but the wire must still distinguish "did not know
+ about this" from "asked for hosted"."""
+ payload = _payload(enabled_tools = ["web_search"])
+ dumped = payload.model_dump(exclude_unset = True)
+ assert "run_tools_locally" not in dumped
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 452f7c645a4..6f0dc4690b4 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -5064,6 +5064,11 @@ export function createOpenAIStreamAdapter(
// non-streaming client-tool passthrough retry, which this
// streaming server-side loop does not perform.
auto_heal_tool_calls: runtime.autoHealToolCalls,
+ // This branch runs the tools here, so say so by name:
+ // enabled_tools ["web_search"] is byte-identical to what an
+ // older bundle sent meaning hosted search, so without this
+ // flag Search silently stayed hosted.
+ run_tools_locally: true,
...(sandboxSessionId ? { session_id: sandboxSessionId } : {}),
...(resolvedThreadId ? { thread_id: resolvedThreadId } : {}),
...(ragEnabled || projectRagEnabled
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index c55913c64ce..bfe6a89aeb2 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -258,6 +258,8 @@ export async function countChatInputTokens(payload: {
mcp_enabled?: boolean;
rag_scope?: Record<string, unknown>;
auto_heal_tool_calls?: boolean;
+ /** Run the selected tools here rather than as the provider's hosted builtins. */
+ run_tools_locally?: boolean;
// `model` is informational: the endpoint counts with whatever is resident and reports which.
}): Promise<{ input_tokens: number; model?: string }> {
const response = await authFetch("/api/inference/chat/count_tokens", {
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index d27aae55a54..44cdb3bf4ab 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -562,6 +562,8 @@ export interface OpenAIChatCompletionsRequest {
context_length?: number;
};
auto_heal_tool_calls?: boolean;
+ /** Run the selected tools here rather than as the provider's hosted builtins. */
+ run_tools_locally?: boolean;
nudge_tool_calls?: boolean;
max_tool_calls_per_message?: number;
tool_call_timeout?: number;