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: keep a chat working after switching to a model without tool support (#10454)

Nilay8d48887d6869
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.py
index 73c27c7ee2a..f7787510a6c 100644
--- a/studio/backend/core/rag/conversation_archive.py
+++ b/studio/backend/core/rag/conversation_archive.py
@@ -273,10 +273,77 @@ def _without_retrieval(group: list[dict]) -> list[dict]:
if str(message.get("role") or "") == "tool":
if str(message.get("tool_call_id") or "") in dropped_ids:
continue
+ message = _without_folded_retrieval(message, dropped_ids)
+ if message is None:
+ continue
out.append(message)
return out
+def _without_folded_retrieval(message: dict, dropped_ids: set):
+ """The message with any folded retrieval result cut out of its text, or None if that was all
+ it was. Matched on the shape the fold emits, since it rewrote the role the id match needs.
+
+ Keyed on ``tool_call_id`` against the calls just dropped, exactly as the role="tool" branch
+ is, and not on the tool name: the fold's output is only a JSON blob in user text, so a user
+ who pastes that shape while discussing the API would otherwise have their own words silently
+ dropped from the archive. An id-less block stays, which is what the role="tool" branch does
+ with an id-less result.
+
+ Cut, not dropped: the coalesce usually merges the passage with the question asked after it.
+ Both content shapes, because that merge yields a string for a plain question and a part list
+ for an image-bearing one. Split on "\\n\\n": ``json.dumps(indent = 2)`` emits no blank line,
+ so one folded block can never contain it.
+ """
+ if str(message.get("role") or "") != "user":
+ return message
+ content = message.get("content")
+ if isinstance(content, str):
+ kept = _text_without_folded_retrieval(content, dropped_ids)
+ if kept is None:
+ return None
+ return {**message, "content": kept}
+ if not isinstance(content, list):
+ return message
+ parts = []
+ for part in content:
+ text = part.get("text") if isinstance(part, dict) and part.get("type") == "text" else None
+ if not isinstance(text, str):
+ parts.append(part)
+ continue
+ kept = _text_without_folded_retrieval(text, dropped_ids)
+ if kept is None:
+ continue
+ parts.append({**part, "text": kept})
+ if not parts:
+ return None
+ return {**message, "content": parts}
+
+
+def _text_without_folded_retrieval(text: str, dropped_ids: set):
+ """``text`` with folded retrieval blocks removed, or None if that was all of it."""
+ if '"tool_response"' not in text:
+ return text
+ kept = []
+ for segment in text.split("\n\n"):
+ try:
+ payload = json.loads(segment)
+ except (ValueError, TypeError):
+ kept.append(segment)
+ continue
+ response = payload.get("tool_response") if isinstance(payload, dict) else None
+ if not isinstance(response, dict):
+ kept.append(segment)
+ continue
+ call_id = str(response.get("tool_call_id") or "")
+ if call_id and call_id in dropped_ids:
+ continue
+ kept.append(segment)
+ if not kept:
+ return None
+ return "\n\n".join(kept)
+
+
def enabled() -> bool:
"""Whether the archive can actually run here.
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a4b872d202e..43c10eadc13 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3967,6 +3967,51 @@ def _takes_tool_passthrough(payload, llama_backend) -> bool:
return _response_format_constrains_decoding(payload)
+def _folds_studio_tool_history(payload, llama_backend) -> bool:
+ """True when Unsloth's own replayed tool turns must be rewritten as user text.
+
+ The client replays that history forever, so refusing it 400s every later turn of the
+ thread. Same ownership test and first guard as ``_takes_tool_passthrough``.
+ """
+ supports_tools = getattr(llama_backend, "supports_tools", False)
+ if supports_tools and _explicit_studio_tool_loop_requested(payload):
+ return False
+ if getattr(llama_backend, "supports_tool_passthrough", supports_tools):
+ return False
+ return _has_openai_tool_history(payload.messages) and _only_studio_tool_history(payload)
+
+
+def _folded_studio_tool_messages(messages) -> list:
+ # _sanitize_anthropic_openai_messages' chain, in its order, and both halves earn their place:
+ # strip first (it ends in _drop_empty_assistant_sentinels, so this drops those too).
+ # A stopped turn left between the result and the next question would block the coalesce,
+ # and the passthrough drops it later without coalescing, so Gemma 400s on role parity.
+ # Downstream a synthetic pair is matched through its role="tool" reply, which folding
+ # destroys, so a Gemini code_execution card would ride on as user prose.
+ # fold before coalesce: what merges a folded result with the note after it.
+ return [
+ ChatMessage.model_validate(_revalidatable(message))
+ for message in _coalesce_consecutive_user_turns(
+ fold_tool_results_into_user(
+ _strip_provider_synthetic_tool_history(
+ [m.model_dump(exclude_none = True) for m in messages]
+ )
+ )
+ )
+ ]
+
+
+def _revalidatable(message: dict) -> dict:
+ """``content = []`` is the placeholder ``_normalise_chat_content_parts`` leaves behind when it
+ lifts an ``input_audio`` part onto ``payload.audio_base64``. ChatMessage rejects it, and until
+ this fold nothing re-validated a message after that lift. ``""`` is the same placeholder in a
+ shape it accepts, and ``_inject_audio_part`` already reads it that way (``content or ""``).
+ """
+ if message.get("content") == [] and message.get("role") != "assistant":
+ return {**message, "content": ""}
+ return message
+
+
def _passthrough_client_tools(payload):
"""The caller's own tool catalog exactly as the passthrough puts it on the wire.
@@ -22345,7 +22390,10 @@ async def produce_openai_chat_completions(
_has_tool_messages = _has_openai_tool_history(payload.messages)
_has_tool_catalog = bool(payload.tools and len(payload.tools) > 0)
_has_active_tool_catalog = _has_tool_catalog and payload.tool_choice != "none"
- _has_client_tool_contract = _has_active_tool_catalog or _has_tool_messages
+ # Read the same way `_takes_tool_passthrough` reads it: history Unsloth's own loop
+ # produced is not a client contract.
+ _has_client_tool_history = _has_tool_messages and not _only_studio_tool_history(payload)
+ _has_client_tool_contract = _has_active_tool_catalog or _has_client_tool_history
# The Unsloth tool loop needs a tool-capable backend, so a request that asks
# for it on a backend that can't run it (DiffusionGemma forces supports_tools
# off) must not steal client tools from the passthrough (#6851).
@@ -22380,6 +22428,10 @@ async def produce_openai_chat_completions(
_supports_tool_passthrough = getattr(
llama_backend, "supports_tool_passthrough", llama_backend.supports_tools
)
+ # Before the passthrough dispatch and the parse, so every later reader sees the fold.
+ if using_gguf and _folds_studio_tool_history(payload, llama_backend):
+ payload.messages = _folded_studio_tool_messages(payload.messages)
+ _pre_parsed = None
if (
using_gguf
and not _studio_tool_loop_requested
@@ -28350,6 +28402,11 @@ def _build_chat_request(
# turn opens a fresh one and restarts the answer.
if isinstance(_extra.get("continue_final_message"), bool):
chat_kwargs["continue_final_message"] = _extra["continue_final_message"]
+ # And for the ownership marker, or every fold below reads a Studio thread as a client's:
+ # only the legacy search_conversation arm could claim one, so a thread that ran terminal
+ # or search_knowledge_base was refused non-streaming and forwarded raw when streamed.
+ if isinstance(_extra.get("studio_tool_history"), bool):
+ chat_kwargs["studio_tool_history"] = _extra["studio_tool_history"]
if isinstance(payload.reasoning, dict):
effort = payload.reasoning.get("effort")
@@ -28642,6 +28699,13 @@ async def _responses_stream(
detail = "Image provided but current GGUF model does not support vision.",
)
+ # Same bypass, same reason as the image gate: without this the non-streaming half of this
+ # very route folds a Studio tool thread and answers while the streaming half still ships
+ # role="tool" to a template that cannot render it, so one thread's replies depend on which
+ # half the client called.
+ if _folds_studio_tool_history(chat_req, llama_backend):
+ chat_req.messages = _folded_studio_tool_messages(chat_req.messages)
+
# Streaming /v1/responses builds the passthrough body directly (bypassing
# openai_chat_completions), so apply recommended sampling here too.
_fill_recommended_sampling_openai(chat_req, getattr(llama_backend, "model_identifier", None))
@@ -30432,8 +30496,11 @@ async def chat_count_tokens(
# does not merge adjacent user turns, so coalescing here would price a prompt it never sends
# (two user turns split by an empty assistant sentinel, after a stopped response).
_takes_passthrough = _takes_tool_passthrough(payload, llama_backend)
+ _count_messages = payload.messages
+ if _folds_studio_tool_history(payload, llama_backend):
+ _count_messages = _folded_studio_tool_messages(_count_messages)
openai_messages = _strip_provider_synthetic_tool_history(
- _drop_empty_assistant_sentinels([m.model_dump(exclude_none = True) for m in payload.messages])
+ _drop_empty_assistant_sentinels([m.model_dump(exclude_none = True) for m in _count_messages])
)
if not _takes_passthrough:
openai_messages = _coalesce_consecutive_user_turns(openai_messages)
diff --git a/studio/backend/tests/test_conversation_archive.py b/studio/backend/tests/test_conversation_archive.py
index 72d8bf77181..40dc79bebfd 100644
--- a/studio/backend/tests/test_conversation_archive.py
+++ b/studio/backend/tests/test_conversation_archive.py
@@ -595,6 +595,116 @@ def test_a_search_the_MODEL_asked_for_is_not_archived_as_new_history():
assert "total 12" in mixed_rendered
+def test_a_folded_retrieval_result_is_still_kept_out_of_the_archive():
+ """A toolless template has its ``role="tool"`` turns rewritten to user text before it ever
+ reaches the archive, so the id match that removes a retrieved passage stops firing and the
+ passage is indexed as fresh conversation -- the nesting above, back by another door.
+
+ The passage usually arrives already merged with the question asked after it, so the cut has
+ to keep that question: dropping the whole turn archives the answer without the ask.
+ """
+ from core.inference.anthropic_compat import fold_tool_results_into_user
+ from core.rag import conversation_archive as archive
+ from routes.inference import _coalesce_consecutive_user_turns
+
+ recalled = [
+ {"role": "user", "content": "what did we say?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_0",
+ "function": {"name": "search_conversation", "arguments": '{"query":"pass"}'},
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_0",
+ "name": "search_conversation",
+ "content": "<chunk>RETRIEVEDPASSAGE</chunk>",
+ },
+ {"role": "user", "content": "ASKEDAFTERWARDS?"},
+ {"role": "assistant", "content": "It was ZQXVARA123."},
+ ]
+ folded = _coalesce_consecutive_user_turns(fold_tool_results_into_user(recalled))
+
+ rendered = archive.render_turn(archive._archivable(folded))
+ assert "RETRIEVEDPASSAGE" not in rendered
+ assert "ASKEDAFTERWARDS?" in rendered
+ assert "ZQXVARA123" in rendered
+
+ # An image on the next question makes the coalesce produce a part list, not a string, and
+ # reading only strings archived the passage on exactly the turns that carry an image.
+ with_image = [
+ {"role": "user", "content": "what did we say?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "call_0", "function": {"name": "search_conversation", "arguments": "{}"}}
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_0",
+ "name": "search_conversation",
+ "content": "<chunk>RETRIEVEDPASSAGE</chunk>",
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "ASKEDWITHIMAGE?"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
+ ],
+ },
+ ]
+ folded_image = _coalesce_consecutive_user_turns(fold_tool_results_into_user(with_image))
+ assert isinstance(folded_image[-1]["content"], list), folded_image[-1]
+ kept_image = archive._archivable(folded_image)
+ dumped = json.dumps(kept_image)
+ assert "RETRIEVEDPASSAGE" not in dumped
+ assert "ASKEDWITHIMAGE?" in dumped
+ assert "image_url" in dumped
+
+ # The fold's output is only JSON in user text, so a user who types that shape while talking
+ # about the API must keep their own words: no retrieval call in the group, nothing to strip.
+ typed = [
+ {
+ "role": "user",
+ "content": "why this shape?\n\n"
+ + json.dumps(
+ {
+ "tool_response": {
+ "tool": "search_conversation",
+ "content": "MYOWNWORDS",
+ "tool_call_id": "call_0",
+ }
+ },
+ indent = 2,
+ ),
+ },
+ {"role": "assistant", "content": "because of the fold."},
+ ]
+ assert "MYOWNWORDS" in json.dumps(archive._archivable(typed))
+
+ # A tool whose result IS conversation keeps it, folded or not.
+ kept = fold_tool_results_into_user(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "call_1", "function": {"name": "terminal", "arguments": '{"cmd":"ls"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "name": "terminal", "content": "total 12"},
+ ]
+ )
+ assert "total 12" in archive.render_turn(archive._archivable(kept))
+
+
def test_swapping_the_tool_retires_the_archived_call():
"""Which tool ran is part of what the turn says, so it has to be part of the probe.
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 0e50e18a0f6..4ca7e3821a0 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -4753,6 +4753,50 @@ def test_chat_count_tokens_keeps_adjacent_user_turns_on_the_passthrough(monkeypa
]
+def test_chat_count_tokens_folds_a_stopped_studio_tool_thread(monkeypatch):
+ """The counter skips its own coalesce on the passthrough, so only the fold helper keeps a
+ Stop-sentinel thread alternating; without it the bar prices a prompt the completion 400s on.
+ Unlike ``..._keeps_adjacent_user_turns_on_the_passthrough`` above, this thread IS folded.
+ """
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99)
+ thread = [
+ {"role": "user", "content": "what did we say about seeds?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "search_conversation", "arguments": '{"query": "s"}'},
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_1",
+ "name": "search_conversation",
+ "content": "we said 3407",
+ },
+ {"role": "assistant", "content": ""},
+ {"role": "user", "content": "and now?"},
+ ]
+
+ _counted_body(
+ _count_request(
+ thread,
+ studio_tool_history = True,
+ response_format = {
+ "type": "json_schema",
+ "json_schema": {"name": "answer", "schema": {"type": "object", "properties": {}}},
+ },
+ )
+ )
+ roles = [message.get("role") for message in counted.get("messages") or []]
+ assert "tool" not in roles, roles
+ assert not any(a == "user" and b == "user" for a, b in zip(roles, roles[1:])), roles
+
+
def test_chat_count_tokens_prices_the_current_date(monkeypatch):
"""The bar has to price what generation sends, and only the passthrough is sent undated."""
_switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 61637ed5eca..ea6f91e5855 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -2025,6 +2025,416 @@ class TestChatCompletionRequestToolFields:
assert entry["reply"] == "plain response"
assert monitor.active_count() == 0
+ def _studio_tool_history_messages(self):
+ return [
+ {"role": "user", "content": "what did we say about seeds?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "search_conversation",
+ "arguments": '{"query": "seeds"}',
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_1",
+ "name": "search_conversation",
+ "content": "we said 3407",
+ },
+ {"role": "user", "content": "and now?"},
+ ]
+
+ def test_studio_tool_history_still_answers_without_a_tool_template(self, monkeypatch):
+ """Switching a thread that already ran a Studio tool to a toolless GGUF used to 400
+ every later turn: the loop's own replayed calls were read as a client tool contract.
+ They are folded into user text instead, exactly as /v1/messages folds them."""
+ import routes.inference as inference_route
+
+ captured = {}
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+
+ def generate_chat_completion(self, **kwargs):
+ captured["messages"] = kwargs["messages"]
+ yield "plain response"
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": self._studio_tool_history_messages(),
+ "studio_tool_history": True,
+ },
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["choices"][0]["message"]["content"] == "plain response"
+ assert not any(m.get("role") == "tool" for m in captured["messages"])
+ assert any(
+ m.get("role") == "user" and "tool_response" in (m.get("content") or "")
+ for m in captured["messages"]
+ )
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert monitor.active_count() == 0
+
+ def test_studio_tool_history_with_a_client_catalog_is_still_rejected(self, monkeypatch):
+ """The catalog is a live client contract whatever produced the history, and a
+ template with no tool markup would drop it and answer in prose instead."""
+ import routes.inference as inference_route
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+
+ def generate_chat_completion(self, **_kwargs):
+ raise AssertionError("a client tool catalog must not fall through")
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": self._studio_tool_history_messages(),
+ "studio_tool_history": True,
+ "tools": [
+ {
+ "type": "function",
+ "function": {"name": "lookup", "parameters": {"type": "object"}},
+ }
+ ],
+ },
+ )
+
+ self._assert_unsupported_param(resp, "tools")
+ assert "does not advertise tools" in resp.json()["error"]["message"]
+ assert monitor.active_count() == 0
+
+ def test_studio_tool_history_keeps_the_passthrough_on_a_tool_capable_gguf(self, monkeypatch):
+ """A backend that can render tools is untouched: the history stays role="tool"."""
+ import routes.inference as inference_route
+
+ captured = {}
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = True
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+
+ def generate_chat_completion(self, **kwargs):
+ captured["messages"] = kwargs["messages"]
+ yield "plain response"
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": self._studio_tool_history_messages(),
+ "studio_tool_history": True,
+ },
+ )
+
+ assert resp.status_code == 200
+ assert any(m.get("role") == "tool" for m in captured["messages"])
+ assert monitor.active_count() == 0
+
+ def test_studio_tool_history_streams_without_a_tool_template(self, monkeypatch):
+ """The composer sends stream=true, and the fold rewrites payload.messages before the
+ generator runs, so the streamed turn needs its own guard: the non-streaming pass
+ cannot show that the folded list is what the stream generates from."""
+ import routes.inference as inference_route
+
+ captured = {}
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+
+ def generate_chat_completion(self, **kwargs):
+ captured["messages"] = kwargs["messages"]
+ yield "plain response"
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": self._studio_tool_history_messages(),
+ "studio_tool_history": True,
+ "stream": True,
+ },
+ )
+
+ assert resp.status_code == 200
+ assert resp.headers["content-type"].startswith("text/event-stream")
+ streamed = "".join(
+ (choice.get("delta") or {}).get("content") or ""
+ for line in resp.text.splitlines()
+ if line.startswith("data: ") and line.removeprefix("data: ") != "[DONE]"
+ for choice in (json.loads(line.removeprefix("data: ")).get("choices") or [])
+ )
+ assert streamed == "plain response"
+ assert not any(m.get("role") == "tool" for m in captured["messages"])
+
+ def test_studio_tool_history_answers_with_studio_tools_left_on(self, monkeypatch):
+ """Switching to a toolless GGUF does not switch Studio's tool toggle off, so the
+ thread's next turn still carries enable_tools. A backend that cannot run the loop
+ must answer in prose rather than reject the turn the toggle cannot undo."""
+ import routes.inference as inference_route
+
+ captured = {}
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+
+ def generate_chat_completion(self, **kwargs):
+ captured["messages"] = kwargs["messages"]
+ yield "plain response"
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": self._studio_tool_history_messages(),
+ "studio_tool_history": True,
+ "enable_tools": True,
+ },
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["choices"][0]["message"]["content"] == "plain response"
+ assert not any(m.get("role") == "tool" for m in captured["messages"])
+ assert monitor.active_count() == 0
+
+ def test_studio_tool_history_under_guided_decoding_has_no_adjacent_user_turns(
+ self, monkeypatch
+ ):
+ """A response_format on this same thread routes to the guided-decoding passthrough,
+ which is the one path that never coalesces. Folding a tool result there leaves it
+ next to the turn that follows it, and Gemma checks alternation by index parity, so
+ llama-server answered 'Unable to generate parser for this template' for the whole
+ request until the fold merged them itself."""
+ import routes.inference as inference_route
+
+ captured = {}
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+ base_url = "http://llama.guided-fold.test"
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None
+
+ def generate_chat_completion(self, **_kwargs):
+ raise AssertionError("a response_format request must use the passthrough")
+
+ async def fake_passthrough(llama_backend, payload, model_name, **kwargs):
+ captured["body"] = inference_route._build_openai_passthrough_body(
+ payload,
+ backend_ctx = llama_backend.context_length,
+ llama_backend = llama_backend,
+ )
+ inference_route.api_monitor.finish(kwargs.get("monitor_id"))
+ return inference_route.JSONResponse({"ok": True, "model": model_name})
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ monkeypatch.setattr(inference_route, "_openai_passthrough_non_streaming", fake_passthrough)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": self._studio_tool_history_messages(),
+ "studio_tool_history": True,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "schema": {"type": "object", "properties": {}},
+ },
+ },
+ },
+ )
+
+ assert resp.status_code == 200
+ roles = [m.get("role") for m in captured["body"]["messages"]]
+ assert "tool" not in roles
+ assert not any(a == "user" and b == "user" for a, b in zip(roles, roles[1:])), roles
+ assert monitor.active_count() == 0
+
+ @pytest.mark.parametrize(
+ "sentinel",
+ [
+ pytest.param({"role": "assistant", "content": None}, id = "explicit_none"),
+ pytest.param({"role": "assistant", "content": ""}, id = "empty_string"),
+ pytest.param({"role": "assistant"}, id = "no_content_key"),
+ pytest.param({"role": "assistant", "content": []}, id = "empty_parts"),
+ ],
+ )
+ def test_studio_tool_history_under_guided_decoding_survives_a_stopped_turn(
+ self, monkeypatch, sentinel
+ ):
+ """Stop leaves an empty assistant turn between the tool result and the next question. The
+ coalesce cannot merge across it and the passthrough drops it downstream without
+ coalescing, so the two user turns land adjacent again -- the failure above, one Stop
+ later. Sanitizing before the fold, not after it, is what holds it."""
+ import routes.inference as inference_route
+
+ captured = {}
+
+ class _GGUFBackend:
+ is_loaded = True
+ model_identifier = "test-gguf"
+ supports_tools = False
+ is_vision = False
+ _is_audio = False
+ context_length = 4096
+ base_url = "http://llama.stopped-fold.test"
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None
+
+ def generate_chat_completion(self, **_kwargs):
+ raise AssertionError("a response_format request must use the passthrough")
+
+ async def fake_passthrough(llama_backend, payload, model_name, **kwargs):
+ captured["body"] = inference_route._build_openai_passthrough_body(
+ payload,
+ backend_ctx = llama_backend.context_length,
+ llama_backend = llama_backend,
+ )
+ inference_route.api_monitor.finish(kwargs.get("monitor_id"))
+ return inference_route.JSONResponse({"ok": True, "model": model_name})
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ monkeypatch.setattr(inference_route, "_openai_passthrough_non_streaming", fake_passthrough)
+ messages = self._studio_tool_history_messages()
+ messages.insert(-1, sentinel)
+ client = self._v1_client(monkeypatch, _GGUFBackend())
+ resp = client.post(
+ "/v1/chat/completions",
+ json = {
+ "messages": messages,
+ "studio_tool_history": True,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "schema": {"type": "object", "properties": {}},
+ },
+ },
+ },
+ )
+
+ assert resp.status_code == 200
+ roles = [m.get("role") for m in captured["body"]["messages"]]
+ assert "tool" not in roles
+ assert not any(a == "user" and b == "user" for a, b in zip(roles, roles[1:])), roles
+ assert monitor.active_count() == 0
+
+ def test_studio_fold_drops_a_provider_synthetic_card_rather_than_folding_it(self):
+ """Downstream a Gemini tool card is dropped by matching its role="tool" reply to the
+ synthetic call, and folding destroys that handle, so a thread switched from Gemini to a
+ local GGUF would carry code_execution on as user prose. Strip before folding."""
+ from routes.inference import _folded_studio_tool_messages
+
+ folded = _folded_studio_tool_messages(
+ [
+ ChatMessage.model_validate(message)
+ for message in [
+ *self._studio_tool_history_messages()[:3],
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_2",
+ "type": "function",
+ "function": {
+ "name": "code_execution",
+ "arguments": '{"_server_tool": true, "code": "print(1)"}',
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_2",
+ "name": "code_execution",
+ "content": "1",
+ },
+ {"role": "user", "content": "and now?"},
+ ]
+ ]
+ )
+
+ rendered = json.dumps([m.model_dump(exclude_none = True) for m in folded])
+ assert "code_execution" not in rendered, rendered
+ # The Studio result is the one that must survive: it is what recall depends on.
+ assert "search_conversation" in rendered
+ roles = [m.role for m in folded]
+ assert not any(a == "user" and b == "user" for a, b in zip(roles, roles[1:])), roles
+
+ def test_studio_fold_keeps_an_audio_only_follow_up_validatable(self):
+ """The audio lift leaves ``content = []`` for ``_inject_audio_part`` to refill, and
+ ChatMessage rejects that placeholder, so speaking the next turn of a folded thread raised
+ out of the route instead of answering."""
+ from routes.inference import _folded_studio_tool_messages
+
+ messages = [
+ ChatMessage.model_validate(message)
+ for message in [
+ *self._studio_tool_history_messages()[:3],
+ {"role": "assistant", "content": "we said 3407"},
+ {"role": "user", "content": [{"type": "text", "text": "placeholder"}]},
+ ]
+ ]
+ # Exactly what the audio lift leaves behind on the latest user turn.
+ messages[-1].content = []
+
+ folded = _folded_studio_tool_messages(messages)
+ assert folded[-1].role == "user"
+ assert folded[-1].content == ""
+
def test_tool_call_history_rejected_when_gguf_template_has_no_tool_support(self, monkeypatch):
import routes.inference as inference_route
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index db788d676c8..5d1533de7ce 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -2720,6 +2720,106 @@ class TestResponsesStreamAdapter:
assert done[0]["item"]["type"] == "function_call"
assert self._payloads(lines, "response.function_call_arguments.done")
+ def test_studio_ownership_marker_reaches_the_chat_request(self):
+ """ResponsesRequest takes the marker as an extra field, and every fold downstream reads
+ it off the ChatCompletionRequest. Dropped in translation, only the legacy
+ search_conversation arm can claim a Studio thread, so one that ran terminal or
+ search_knowledge_base is refused non-streaming and forwarded raw when streamed."""
+ from routes.inference import _build_chat_request
+
+ payload = ResponsesRequest.model_validate(
+ {"input": "hi", "stream": True, "model": "org/M-GGUF", "studio_tool_history": True}
+ )
+ chat_req = _build_chat_request(
+ payload, [ChatMessage(role = "user", content = "hi")], stream = True
+ )
+ assert chat_req.studio_tool_history is True
+
+ # Absent stays absent: a plain client must not be read as Studio's.
+ plain = _build_chat_request(
+ ResponsesRequest.model_validate({"input": "hi", "model": "org/M-GGUF"}),
+ [ChatMessage(role = "user", content = "hi")],
+ stream = False,
+ )
+ assert not plain.studio_tool_history
+
+ def test_studio_tool_history_is_folded_on_the_direct_stream(self, monkeypatch):
+ """This half of /v1/responses builds the passthrough body itself, so it has to fold the
+ way openai_chat_completions does. Otherwise the same thread on the same model answers
+ non-streaming and ships role="tool" to a toolless template when streamed."""
+ import routes.inference as inf_mod
+
+ captured = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode())
+ content = 'data: {"choices": [{"delta": {"content": "ok"}}]}\n\ndata: [DONE]\n\n'
+ return httpx.Response(
+ 200,
+ content = content.encode(),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ transport = httpx.MockTransport(handler)
+ real_async_client = httpx.AsyncClient
+ monkeypatch.setattr(
+ inf_mod.httpx,
+ "AsyncClient",
+ lambda *a, **kw: real_async_client(transport = transport, timeout = kw.get("timeout", 600)),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ context_length = 4096,
+ base_url = "http://llama.test",
+ supports_tools = False,
+ supports_tool_passthrough = False,
+ _request_reasoning_kwargs = (
+ lambda enable_thinking = None, reasoning_effort = None, preserve_thinking = None: None
+ ),
+ ),
+ )
+
+ payload = ResponsesRequest(input = "and now?", stream = True, model = "org/M-GGUF")
+ messages = [
+ ChatMessage(role = "user", content = "what did we say about seeds?"),
+ ChatMessage(
+ role = "assistant",
+ content = None,
+ tool_calls = [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "search_conversation",
+ "arguments": '{"query": "seeds"}',
+ },
+ }
+ ],
+ ),
+ ChatMessage(
+ role = "tool",
+ tool_call_id = "call_1",
+ name = "search_conversation",
+ content = "we said 3407",
+ ),
+ ChatMessage(role = "user", content = "and now?"),
+ ]
+
+ async def run():
+ response = await _responses_stream(payload, messages, self._Request())
+ return await self._collect(response)
+
+ asyncio.run(run())
+
+ roles = [m.get("role") for m in captured["body"]["messages"]]
+ assert "tool" not in roles, roles
+ assert not any(a == "user" and b == "user" for a, b in zip(roles, roles[1:])), roles
+ assert "we said 3407" in json.dumps(captured["body"]["messages"])
+
def test_requests_usage_and_caps_parallel_tool_calls(self, monkeypatch):
import routes.inference as inf_mod
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 4633021235a..7c39e11c86d 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -5211,9 +5211,7 @@ def _reconcile_cuda_integrated_memory(
dev["vram_used_gb"] = pool_used_gb
if dev.get("vram_utilization_pct") is None:
dev["vram_utilization_pct"] = (
- round((min(pool_used_gb, total_gb) / total_gb) * 100, 1)
- if total_gb > 0
- else None
+ round((min(pool_used_gb, total_gb) / total_gb) * 100, 1) if total_gb > 0 else None
)
diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.py
index f5a06720602..1f869d67f37 100644
--- a/tests/studio/test_installer_av_shapes.py
+++ b/tests/studio/test_installer_av_shapes.py
@@ -414,7 +414,7 @@ def _run_watch(tmp_path, action: str) -> tuple[str, list[str]]:
)
assert result.returncode == 0, result.stderr + result.stdout
libraries = [
- line[len("LIB:"):] for line in result.stdout.splitlines() if line.startswith("LIB:")
+ line[len("LIB:") :] for line in result.stdout.splitlines() if line.startswith("LIB:")
]
return result.stdout, libraries