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: send tool results to the model in the right order (#10091)
Nilay6153a6f5866f
diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.pyindex f02c2bfa2a2..0a9627fb972 100644--- a/studio/backend/core/inference/anthropic_compat.py+++ b/studio/backend/core/inference/anthropic_compat.py@@ -175,6 +175,9 @@ def anthropic_messages_to_openai(})+ for tr in tool_results:+ result.append(tr)+if has_image:result.append({"role": "user", "content": user_parts})else:@@ -182,12 +185,50 @@ def anthropic_messages_to_openai(text = "\n".join(p["text"] for p in user_parts)if text:result.append({"role": "user", "content": text})- for tr in tool_results:- result.append(tr)return result+def fold_tool_results_into_user(messages: list[dict]) -> list[dict]:+ """Rewrite ``role="tool"`` as user turns: Gemma 2 / 3 have no tool role and+ check alternation by index parity, so one makes llama-server 400 the whole+ request. Shape mirrors minja's ``polyfill_tool_responses``.+ """+ out: list[dict] = []+ call_names: dict[str, str] = {}+ for msg in messages:+ if msg.get("role") == "assistant":+ for tc in msg.get("tool_calls") or []:+ if not isinstance(tc, dict):+ continue+ tc_id = tc.get("id")+ fn = tc.get("function")+ if isinstance(tc_id, str) and tc_id and isinstance(fn, dict):+ name = fn.get("name")+ if isinstance(name, str) and name:+ call_names[tc_id] = name++ if msg.get("role") != "tool":+ out.append(msg)+ continue++ response: dict[str, Any] = {}+ tool_call_id = msg.get("tool_call_id")+ name = msg.get("name") or call_names.get(tool_call_id or "")+ if name:+ response["tool"] = name+ response["content"] = msg.get("content", "")+ if tool_call_id:+ response["tool_call_id"] = tool_call_id+ out.append(+ {+ "role": "user",+ "content": json.dumps({"tool_response": response}, indent = 2),+ }+ )+ return out++_ANTHROPIC_SCHEMA_CLIENT_TOOL_PARAMETERS = {"bash": {"type": "object",diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex e13f7d5f52b..d6829143554 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -2956,6 +2956,7 @@ from models.inference import ()from core.inference.anthropic_compat import (anthropic_messages_to_openai,+ fold_tool_results_into_user,anthropic_schema_client_tool_kind,anthropic_tools_to_openai,anthropic_tool_choice_to_openai,@@ -27437,12 +27438,7 @@ async def anthropic_count_tokens(# Apply the same sanitization /messages does before generation, so the count# matches the prompt the real request would build (otherwise empty-assistant# sentinels / synthetic tool history inflate the count or hit the fallback).- # Coalesce adjacent user turns left behind by dropping an empty / null assistant- # turn, so a strict GGUF chat template does not 400 on non-alternating roles- # (mirrors the GGUF chat path); a no-op for already-alternating histories.- openai_messages = _coalesce_consecutive_user_turns(- _strip_provider_synthetic_tool_history(_drop_empty_assistant_sentinels(openai_messages))- )+ openai_messages = _sanitize_anthropic_openai_messages(openai_messages, llama_backend)openai_tools = anthropic_tools_to_openai(payload.tools or []) or None# Only the client-tool passthrough is forwarded verbatim, so reproduce /messages' own# routing rather than "any tools": a Studio server-tool alias, or a template without@@ -27688,12 +27684,7 @@ async def anthropic_messages(# builders apply the same strip; without it an Anthropic /v1/messages caller# replaying a prior provider-side tool_use forwards fake builtin tool# history to a backend with no matching function declarations.- # Coalesce adjacent user turns left behind by dropping an empty / null assistant- # turn, so a strict GGUF chat template does not 400 on non-alternating roles- # (mirrors the GGUF chat path); a no-op for already-alternating histories.- openai_messages = _coalesce_consecutive_user_turns(- _strip_provider_synthetic_tool_history(_drop_empty_assistant_sentinels(openai_messages))- )+ openai_messages = _sanitize_anthropic_openai_messages(openai_messages, llama_backend)# Enforce vision guard + re-encode embedded images to PNG so the Anthropic# endpoint matches /v1/chat/completions.@@ -29910,6 +29901,32 @@ def _coalesce_consecutive_user_turns(messages: list[dict]) -> list[dict]:return out+def _template_supports_tools(backend) -> bool:+ """Can the loaded template render a ``role="tool"`` message? Not+ ``supports_tools``: same flag with DiffusionGemma forced out of the agentic+ loop, so folding on it strips tool framing from a passthrough request. Same+ order as the client-tool dispatch gate; unreadable backend -> True.+ """+ try:+ for attr in ("supports_tool_passthrough", "supports_tools"):+ if hasattr(backend, attr):+ return bool(getattr(backend, attr))+ return True+ except Exception:+ return True+++def _sanitize_anthropic_openai_messages(messages: list[dict], backend) -> list[dict]:+ """Post-conversion chain shared by /v1/messages and its token counter, so a+ diverging list can never make input_tokens describe a different prompt.+ Fold before coalesce: that is what merges a folded result with its note.+ """+ messages = _strip_provider_synthetic_tool_history(_drop_empty_assistant_sentinels(messages))+ if not _template_supports_tools(backend):+ messages = fold_tool_results_into_user(messages)+ return _coalesce_consecutive_user_turns(messages)++_LOCAL_SERVER_BUILTIN_TOOL_NAMES = frozenset({"web_search", "web_fetch", "code_execution", "image_generation"})diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex 32ef0e0a16a..3647a6c77af 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -728,6 +728,198 @@ class TestAnthropicMessagesToOpenAI:assert result[0]["tool_call_id"] == "tu_1"assert result[0]["content"] == "Result text"+ def test_tool_result_precedes_trailing_user_text(self):+ msgs = [+ {"role": "user", "content": [{"type": "text", "text": "what files are here?"}]},+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Let me look."},+ {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls"}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "tu_1", "content": "README.md\nsrc/"},+ {"type": "text", "text": "<system-reminder>Keep going.</system-reminder>"},+ ],+ },+ ]+ result = anthropic_messages_to_openai(msgs)+ assert [m["role"] for m in result] == ["user", "assistant", "tool", "user"]+ assert result[2]["tool_call_id"] == "tu_1"+ assert result[2]["content"] == "README.md\nsrc/"+ assert result[3]["content"] == "<system-reminder>Keep going.</system-reminder>"++ def test_tool_result_with_image_keeps_user_parts_after_tool(self):+ msgs = [+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "tu_1", "content": "ok"},+ {"type": "text", "text": "and this?"},+ {+ "type": "image",+ "source": {"type": "base64", "media_type": "image/jpeg", "data": "AAAA"},+ },+ ],+ }+ ]+ result = anthropic_messages_to_openai(msgs)+ assert [m["role"] for m in result] == ["tool", "user"]+ parts = result[1]["content"]+ assert parts[0] == {"type": "text", "text": "and this?"}+ assert parts[1]["type"] == "image_url"++ def test_tool_results_fold_into_user_turns_for_a_toolless_template(self):+ """Gemma 2 / 3 have no `tool` role and check alternation by parity, so a+ tool message makes llama-server 400 the whole request."""+ from core.inference.anthropic_compat import fold_tool_results_into_user++ msgs = [+ {"role": "user", "content": "what files are here?"},+ {+ "role": "assistant",+ "content": "Let me look.",+ "tool_calls": [+ {+ "id": "tu_1",+ "type": "function",+ "function": {"name": "Bash", "arguments": '{"command": "ls"}'},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "tu_1", "content": "README.md"},+ {"role": "user", "content": "keep going"},+ ]+ folded = fold_tool_results_into_user(msgs)+ assert [m["role"] for m in folded] == ["user", "assistant", "user", "user"]+ payload = json.loads(folded[2]["content"])+ assert payload == {+ "tool_response": {+ "tool": "Bash",+ "content": "README.md",+ "tool_call_id": "tu_1",+ }+ }+ assert folded[1] is msgs[1] # assistant turn untouched, tool_calls intact++ def test_folding_is_a_no_op_without_tool_messages(self):+ from core.inference.anthropic_compat import fold_tool_results_into_user+ msgs = [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello"},+ ]+ assert fold_tool_results_into_user(msgs) == msgs++ def test_folding_survives_an_orphan_tool_result(self):+ """No tool_calls to resolve the name against: the id still carries."""+ from core.inference.anthropic_compat import fold_tool_results_into_user++ msgs = [{"role": "tool", "tool_call_id": "nope", "content": "R"}]+ folded = fold_tool_results_into_user(msgs)+ assert [m["role"] for m in folded] == ["user"]+ assert json.loads(folded[0]["content"]) == {+ "tool_response": {"content": "R", "tool_call_id": "nope"}+ }++ def test_sanitizer_folds_only_when_the_template_lacks_tool_support(self):+ """A tool-capable template keeps role=tool as the converter emitted it."""+ from routes.inference import _sanitize_anthropic_openai_messages++ class Backend:+ def __init__(self, supports_tools):+ self.supports_tools = supports_tools++ anthropic = [+ {"role": "user", "content": [{"type": "text", "text": "q"}]},+ {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "ls"}}+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "tu_1", "content": "README.md"},+ {"type": "text", "text": "keep going"},+ ],+ },+ ]+ converted = anthropic_messages_to_openai(anthropic)++ tool_capable = _sanitize_anthropic_openai_messages(converted, Backend(True))+ assert [m["role"] for m in tool_capable] == ["user", "assistant", "tool", "user"]++ toolless = _sanitize_anthropic_openai_messages(converted, Backend(False))+ assert [m["role"] for m in toolless] == ["user", "assistant", "user"]+ assert "README.md" in toolless[-1]["content"]+ assert "keep going" in toolless[-1]["content"]++ def test_sanitizer_defaults_to_not_folding_when_the_backend_cannot_answer(self):+ from routes.inference import _sanitize_anthropic_openai_messages++ class Hostile:+ @property+ def supports_tools(self):+ raise RuntimeError("backend not ready")++ msgs = [{"role": "tool", "tool_call_id": "tu_1", "content": "R"}]+ assert _sanitize_anthropic_openai_messages(msgs, Hostile()) == msgs+ assert _sanitize_anthropic_openai_messages(msgs, object()) == msgs++ def test_folding_follows_the_passthrough_capability_not_the_tool_loop_one(self):+ """DiffusionGemma reports supports_tools=False to stay out of the agentic+ loop, but its template renders tool roles and client tools dispatch on+ supports_tool_passthrough; folding on the former strips that framing."""+ from routes.inference import _sanitize_anthropic_openai_messages, _template_supports_tools++ class DiffusionGemma:+ supports_tools = False # forced off: keeps it out of the tool loop+ supports_tool_passthrough = True # the real template capability++ class ToollessTemplate:+ supports_tools = False+ supports_tool_passthrough = False++ assert _template_supports_tools(DiffusionGemma()) is True+ assert _template_supports_tools(ToollessTemplate()) is False++ msgs = [+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "tu_1",+ "type": "function",+ "function": {"name": "Bash", "arguments": "{}"},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "tu_1", "content": "README.md"},+ {"role": "user", "content": "keep going"},+ ]+ kept = _sanitize_anthropic_openai_messages(msgs, DiffusionGemma())+ assert [m["role"] for m in kept] == ["assistant", "tool", "user"]++ folded = _sanitize_anthropic_openai_messages(msgs, ToollessTemplate())+ assert [m["role"] for m in folded] == ["assistant", "user"]++ def test_folding_gate_prefers_passthrough_even_when_supports_tools_raises(self):+ from routes.inference import _template_supports_tools+ class HalfReady:+ supports_tool_passthrough = False++ @property+ def supports_tools(self):+ raise RuntimeError("not ready")++ # Passthrough answers first, so a raising supports_tools cannot skip the fold.+ assert _template_supports_tools(HalfReady()) is False+def test_mixed_text_and_tool_use_blocks(self):msgs = [{