Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: return an error when tools are sent to a model that cannot use them (#10314)
Nilay066290ddd317
diff --git a/.github/scripts/agent-guides-drive.sh b/.github/scripts/agent-guides-drive.shindex a3ba87cf7ec..2b96993ff88 100755--- a/.github/scripts/agent-guides-drive.sh+++ b/.github/scripts/agent-guides-drive.sh@@ -625,8 +625,10 @@ case "$MODE" in# hang guard. Nothing here can adjudicate a partial turn either -- the# verdict is a llama-server log slice -- so a cap stays fatal, as it does# for connection and resume.+ # --tools "" and nothing else: gemma-3-270m declares no tools, so /v1/messages now 400s+ # the default 25 schemas. The system prompt stays -- the attribution line lives in it.ab_invoke() {- invoke_via_connect "$@"+ invoke_via_connect "$1" --tools "" "${@:2}"[ "${TIMED_OUT:-0}" = 1 ] && guide_fail "attribution-ab invoke timed out after ${TIMEOUT}s; the A/B cannot be judged from a partial turn"return 0}diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 55bad62893a..55c40c7e2a7 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -28460,6 +28460,30 @@ def _anthropic_selects_server_tools(return payload.enable_tools is True or bool(requested_studio_tools)+def _guard_anthropic_client_tool_catalog(+ openai_client_tools, openai_tool_choice, server_tools, llama_backend+) -> None:+ """400 a live client catalogue the loaded template would drop, else the caller gets prose+ where it asked for a tool_use block. Narrower than the OpenAI gate, which also rejects+ replayed history: _sanitize_anthropic_openai_messages already folded that history for this+ same template, so a history-only turn has no catalogue to drop and still answers. Shared+ with the token counter so a count never describes a request the completion rejects.+ """+ if server_tools or not openai_client_tools or openai_tool_choice == "none":+ return+ if getattr(llama_backend, "supports_tool_passthrough", llama_backend.supports_tools):+ return+ raise HTTPException(+ status_code = 400,+ detail = anthropic_error_body(+ "Client-supplied tools require a GGUF chat template with tool-call support; "+ "the current model/template does not advertise tools.",+ status = 400,+ err_type = "invalid_request_error",+ ),+ )++def _anthropic_requested_studio_tools(tools: Optional[list]) -> set[str]:requested: set[str] = set()for tool in tools or []:@@ -29185,12 +29209,20 @@ async def anthropic_count_tokens(and llama_backend.supports_toolsand not _anthropic_request_has_image(payload))+ _count_openai_client_tools = [+ tool+ for tool in anthropic_tools_to_openai(payload.tools or [])+ if tool.get("function", {}).get("name") not in _count_studio_tools+ ]+ _guard_anthropic_client_tool_catalog(+ _count_openai_client_tools,+ anthropic_tool_choice_to_openai(payload.tool_choice) or "auto",+ _count_server_tools,+ llama_backend,+ )_count_client_tools = (not _count_server_tools- and any(- tool.get("function", {}).get("name") not in _count_studio_tools- for tool in anthropic_tools_to_openai(payload.tools or [])- )+ and bool(_count_openai_client_tools)and getattr(llama_backend, "supports_tool_passthrough", llama_backend.supports_tools))if not _count_client_tools:@@ -29483,12 +29515,18 @@ async def anthropic_messages(# permission gate above: deciding "did this request select server tools"# twice is what let the gate reject requests the router then served.server_tools = _selects_server_tools and llama_backend.supports_tools and not _has_image+ # One short-circuiting chain: a backend whose supports_tools raises must not turn a plain+ # no-tools turn into a 500.client_tools = (not server_toolsand len(openai_client_tools) > 0and getattr(llama_backend, "supports_tool_passthrough", llama_backend.supports_tools))+ _guard_anthropic_client_tool_catalog(+ openai_client_tools, openai_tool_choice, server_tools, llama_backend+ )+# Studio composes the prompt on every branch but the client-tool passthrough, which forwards# the caller's own request verbatim (mirrors the GGUF passthrough gate in /chat/completions).if not client_tools:diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex 00a1f5131ac..6f33a76b4ef 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -2608,6 +2608,213 @@ class TestAnthropicMessagesToolRouting:assert captured["seed"] == 3407+ def test_client_tool_catalog_without_passthrough_is_rejected(self, monkeypatch):+ # /v1/chat/completions 400s this; /v1/messages answered in prose instead.+ backend = _mock_backend(monkeypatch, supports_tools = False, supports_tool_passthrough = False)+ payload = _basic_payload(tools = [{"name": "lookup", "input_schema": {"type": "object"}}])++ with pytest.raises(HTTPException) as excinfo:+ _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))++ assert excinfo.value.status_code == 400+ assert excinfo.value.detail["error"]["type"] == "invalid_request_error"+ assert "does not advertise tools" in excinfo.value.detail["error"]["message"]+ assert backend.calls == []++ def test_replayed_tool_history_without_passthrough_still_answers(self, monkeypatch):+ # fold_tool_results_into_user already handles this template, so a history-only turn+ # still answers. Verified on a real gemma-3-270m-it GGUF.+ backend = _mock_backend(monkeypatch, supports_tools = False, supports_tool_passthrough = False)+ payload = _basic_payload(+ messages = [+ {"role": "user", "content": "hi"},+ {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "t1", "name": "lookup", "input": {}}],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "42"}],+ },+ ]+ )++ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))++ assert response.status_code == 200+ [(path, kwargs)] = backend.calls+ assert path == "plain"+ # The tool_result was folded into a user turn rather than sent as role="tool".+ assert not any(m.get("role") == "tool" for m in kwargs["messages"])+ assert any(+ m.get("role") == "user" and "tool_response" in (m.get("content") or "")+ for m in kwargs["messages"]+ )++ def test_disabled_tool_choice_still_answers_without_passthrough(self, monkeypatch):+ backend = _mock_backend(monkeypatch, supports_tools = False, supports_tool_passthrough = False)+ payload = _basic_payload(+ tools = [{"name": "lookup", "input_schema": {"type": "object"}}],+ tool_choice = {"type": "none"},+ )++ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))++ assert response.status_code == 200+ [(path, _kwargs)] = backend.calls+ assert path == "plain"++ def test_a_plain_turn_survives_a_backend_whose_supports_tools_raises(self, monkeypatch):+ # Reading the passthrough flag on a turn that sent no tools would 500 the half-ready+ # backend test_folding_gate_prefers_passthrough_even_when_supports_tools_raises covers.+ from routes.inference import anthropic_count_tokens++ import routes.inference as inf_mod++ class _Raising:+ is_loaded = True+ is_vision = False+ model_identifier = "half-ready"+ context_length = 4096++ @property+ def supports_tools(self):+ raise RuntimeError("not ready")++ def count_chat_tokens(self, *args, **kwargs):+ return 2++ def generate_chat_completion(self, **kwargs):+ yield "ok"++ def generate_chat_completion_with_tools(self, **kwargs):+ yield {"type": "content", "text": "ok"}++ monkeypatch.setattr(inf_mod, "current_date_prompt_line", lambda **_kwargs: "")+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: _Raising())++ assert (+ _drive(+ anthropic_messages(_basic_payload(), request = self._Request(), current_subject = "t")+ ).status_code+ == 200+ )+ assert (+ _drive(+ anthropic_count_tokens(+ _basic_payload(), request = self._Request(), current_subject = "t"+ )+ ).status_code+ == 200+ )++ def test_count_tokens_rejects_the_catalog_messages_rejects(self, monkeypatch):+ # The template renders no schemas, so the count matched with and without them+ # (27 either way on a real gemma-3-270m) and handed an SDK a budget /messages 400s.+ from routes.inference import anthropic_count_tokens++ _mock_backend(monkeypatch, supports_tools = False, supports_tool_passthrough = False)+ payload = _basic_payload(tools = [{"name": "lookup", "input_schema": {"type": "object"}}])++ with pytest.raises(HTTPException) as excinfo:+ _drive(anthropic_count_tokens(payload, request = self._Request(), current_subject = "t"))++ assert excinfo.value.status_code == 400+ assert "does not advertise tools" in excinfo.value.detail["error"]["message"]++ @pytest.mark.parametrize(+ "fields",+ [+ {},+ {+ "tools": [{"name": "lookup", "input_schema": {"type": "object"}}],+ "tool_choice": {"type": "none"},+ },+ {+ "messages": [+ {"role": "user", "content": "hi"},+ {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "t1", "name": "lookup", "input": {}}+ ],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "42"}],+ },+ ]+ },+ ],+ ids = ["no_tools", "tool_choice_none", "replayed_history"],+ )+ def test_count_tokens_still_counts_what_messages_still_answers(self, monkeypatch, fields):+ from routes.inference import anthropic_count_tokens++ _mock_backend(monkeypatch, supports_tools = False, supports_tool_passthrough = False)++ response = _drive(+ anthropic_count_tokens(+ _basic_payload(**fields), request = self._Request(), current_subject = "t"+ )+ )++ assert response.status_code == 200++ def _v1_client(self, monkeypatch, backend):+ """Mount the real router with the production error handlers installed.++ Every other test here reads ``HTTPException.detail``, the dict BEFORE+ install_api_error_handlers shapes it; an SDK parses the response body, and the two+ agree only while the handler passes a fully-formed envelope through untouched.+ """+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ import routes.inference as inf_mod+ from auth.authentication import get_current_subject+ from utils.api_errors import install_api_error_handlers++ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)+ monkeypatch.setattr(inf_mod, "current_date_prompt_line", lambda **_kwargs: "")++ app = FastAPI()+ app.include_router(inf_mod.router, prefix = "/v1")+ install_api_error_handlers(app)+ app.dependency_overrides[get_current_subject] = lambda: "t"+ return TestClient(app)++ @pytest.mark.parametrize("path", ["/v1/messages", "/v1/messages/count_tokens"])+ @pytest.mark.parametrize("stream", [False, True])+ def test_the_rejection_reaches_the_client_as_an_anthropic_error(+ self, monkeypatch, path, stream+ ):+ # A `detail` wrapper would make the SDKs raise on the missing `error` key instead of+ # surfacing the reason. Streaming too: the gate precedes the generator, so the caller+ # must get JSON, not a 200 SSE stream carrying the error in a frame.+ backend = _mock_backend(monkeypatch, supports_tools = False, supports_tool_passthrough = False)+ client = self._v1_client(monkeypatch, backend)++ resp = client.post(+ path,+ json = {+ "model": "test-model",+ "max_tokens": 16,+ "messages": [{"role": "user", "content": "hi"}],+ "tools": [{"name": "lookup", "input_schema": {"type": "object"}}],+ "stream": stream,+ },+ )++ assert resp.status_code == 400+ assert resp.headers["content-type"].startswith("application/json")+ body = resp.json()+ assert "detail" not in body+ assert body["type"] == "error"+ assert body["error"]["type"] == "invalid_request_error"+ assert "does not advertise tools" in body["error"]["message"]+ assert backend.calls == []+def test_plain_non_streaming_records_api_monitor_entry(self, monkeypatch):import routes.inference as inf_mod@@ -2668,14 +2875,18 @@ class TestAnthropicMessagesToolRouting:_mock_backend(monkeypatch,- supports_tool_passthrough = False,generate_chat_completion = _gen_plain,generate_chat_completion_with_tools = _gen_tools,)monitor = ApiMonitor(max_entries = 3)monkeypatch.setattr(inf_mod, "api_monitor", monitor)fields = (- {"tools": [{"name": "x", "input_schema": {"type": "object"}}]} if with_tools else {}+ {+ "enable_tools": True,+ "tools": [{"type": "web_search_20250305", "name": "web_search"}],+ }+ if with_tools+ else {})response = _drive(