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: keep a Codex chat working after a tool returns an image on a text-only model (#11476)
Nilay59ba458d1730
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 9e00a11f635..8c9a00a377e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3472,6 +3472,7 @@ from models.inference import (OpenAIContainerSummary,)from core.inference.anthropic_compat import (+ TOOL_RESULT_IMAGE_OMITTED,anthropic_messages_to_openai,anthropic_reference_block_text,fold_tool_results_into_user,@@ -8533,6 +8534,25 @@ def _messages_have_image(messages) -> bool:)+def _omit_tool_images(messages) -> None:+ for message in messages:+ if message.role != "tool" or not _messages_have_image((message,)):+ continue+ parts = [+ TextContentPart(type = "text", text = TOOL_RESULT_IMAGE_OMITTED)+ if isinstance(part, ImageContentPart)+ else part+ for part in message.content+ ]+ # Text-only is flattened, as _responses_tool_output_content and anthropic_messages_to_openai+ # do: some templates render a part list as an empty tool result.+ message.content = (+ "\n".join(part.text for part in parts)+ if all(isinstance(part, TextContentPart) for part in parts)+ else parts+ )++def _messages_have_remote_image(messages) -> bool:return any(isinstance(m.content, list)@@ -9626,6 +9646,7 @@ async def _maybe_auto_switch_model(image_preflight: Optional[dict] = None,require_speech: bool = False,speech_budget: Optional[dict] = None,+ tool_images_only: bool = False,) -> None:"""Load a downloaded local model named by an OpenAI request when auto-switch is on.@@ -9654,6 +9675,10 @@ async def _maybe_auto_switch_model(:func:`_preflight_audio_for_switch`. ``image_preflight`` does the same fornon-GGUF image count and byte validation."""+ # A text-only GGUF reads tool-result images as a note, so only audio or video needs its mmproj.+ gguf_requires_vision = (+ (require_audio_input or require_video) if tool_images_only else require_vision+ )# The reload-only sentinel means an omitted model, not a name.named_model = requested_model if requested_model != _RELOAD_ONLY_MODEL else Noneif account_access.managed_account():@@ -9823,7 +9848,7 @@ async def _maybe_auto_switch_model(fastapi_request,# GGUF carries both from one mmproj, so the download guard takes# either need; splitting them here would fetch a text-only repo.- require_vision = require_vision or require_audio_input,+ require_vision = gguf_requires_vision or require_audio_input,require_speech = require_speech,current_subject = current_subject,)@@ -10005,14 +10030,17 @@ async def _maybe_auto_switch_model(target_requires_image = require_imageif require_audio_input and not target_is_gguf and audio_preflight is not None:target_requires_image = bool(audio_preflight.get("has_image"))+ target_requires_vision = gguf_requires_vision if target_is_gguf else require_vision+ if tool_images_only and target_is_gguf:+ target_requires_image = Falseif (- (require_vision or require_audio_input)+ (target_requires_vision or require_audio_input)and resolved is not Noneand not await asyncio.to_thread(_target_accepts_request_input,target_id,target_is_gguf,- require_vision,+ target_requires_vision,require_audio_input,variant,target_requires_image,@@ -24608,6 +24636,7 @@ async def produce_openai_chat_completions(_modality_label = "image or audio"_needs_audio_input = False_needs_video = False+ _tool_images_only = False_predecoded_audio = None_preprepared_audio = None_image_preflight = None@@ -24719,6 +24748,11 @@ async def produce_openai_chat_completions(# projector carries no vision tower. A safetensors or MLX checkpoint# declares audio input separately, so it is tracked apart as well._needs_image = bool(_pre_parsed[2]) or _request_has_attached_image(payload)+ _tool_images_only = (+ _needs_image+ and not payload.image_base64+ and not _messages_have_image(m for m in payload.messages if m.role != "tool")+ )# Video rides that projector too. Its own /props gate can only run after# the load, so this at least keeps a text-only target from evicting a# working model to serve a clip it could never take.@@ -24800,6 +24834,7 @@ async def produce_openai_chat_completions(require_video = _needs_video,audio_preflight = _audio_preflight,image_preflight = _image_preflight,+ tool_images_only = _tool_images_only,)if _audio_preflight is not None:_predecoded_audio = _audio_preflight.get("decoded")@@ -25331,6 +25366,10 @@ async def produce_openai_chat_completions(_supports_tool_passthrough = getattr(llama_backend, "supports_tool_passthrough", llama_backend.supports_tools)+ # Before the route split, so the passthrough and the Unsloth tool loop both read a tool+ # result's image as a note on a text-only GGUF, as /v1/messages does.+ if using_gguf and not llama_backend.is_vision:+ _omit_tool_images(payload.messages)# 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)@@ -31998,15 +32037,14 @@ async def _responses_stream()raise HTTPException(status_code = _status, detail = _detail)- # Direct pass-through bypasses the openai_chat_completions image gate.- if not llama_backend.is_vision and any(- isinstance(m.content, list) and any(isinstance(p, ImageContentPart) for p in m.content)- for m in messages- ):- raise HTTPException(- status_code = 400,- detail = "Image provided but current GGUF model does not support vision.",- )+ # Direct pass-through bypasses the openai_chat_completions tool-image note and image gate.+ if not llama_backend.is_vision:+ _omit_tool_images(chat_req.messages)+ if _messages_have_image(chat_req.messages):+ raise HTTPException(+ status_code = 400,+ 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@@ -33171,7 +33209,7 @@ async def openai_responses()if payload.stream:# streaming preflights here; non-streaming delegates its complete preflight to chat.- _responses_has_image = _messages_have_image(messages)+ _responses_has_image = _messages_have_image(m for m in messages if m.role != "tool")_responses_image_b64s = _local_image_payloads_from_messages(messages)await _maybe_auto_switch_model(_switch_model_for_payload(payload),diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex f2a7d3923f9..dcc189f0712 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -4402,6 +4402,7 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):gguf_only = False,audio_preflight = None,image_preflight = None,+ tool_images_only = False,):captured.update(require_vision = require_vision,@@ -9624,6 +9625,7 @@ def test_a_video_request_labels_the_switch_refusal_video(monkeypatch):require_video = False,audio_preflight = None,image_preflight = None,+ tool_images_only = False,):captured.update(require_vision = require_vision,diff --git a/studio/backend/tests/test_responses_tool_images.py b/studio/backend/tests/test_responses_tool_images.pynew file mode 100644index 00000000000..3c0815450df--- /dev/null+++ b/studio/backend/tests/test_responses_tool_images.py@@ -0,0 +1,326 @@+# SPDX-License-Identifier: AGPL-3.0-only++import asyncio+import base64+import contextlib+import inspect+import json+from io import BytesIO++import httpx+import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient+from PIL import Image+from types import SimpleNamespace++from core.inference import local_model_resolver as resolver+from core.inference.anthropic_compat import TOOL_RESULT_IMAGE_OMITTED+from routes import inference as inf+from studio.backend.tests.test_anthropic_messages import _mock_backend+from studio.backend.tests.test_openai_auto_switch import _FakeBackend, _wired+++def image_url():+ buffer = BytesIO()+ Image.new("RGB", (2, 2), "red").save(buffer, format = "PNG")+ return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()+++def payload(stream, *, user_image = False):+ user_content = [{"type": "input_text", "text": "What does the screenshot show?"}]+ if user_image:+ user_content.append({"type": "input_image", "image_url": image_url()})+ return {+ "model": "test",+ "stream": stream,+ "tools": [+ {+ "type": "function",+ "name": "view_image",+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}},+ }+ ],+ "input": [+ {"role": "user", "content": user_content},+ {+ "type": "function_call",+ "call_id": "call_0",+ "name": "view_image",+ "arguments": json.dumps({"path": "."}),+ },+ {"type": "function_call_output", "call_id": "call_0", "output": "shot.png"},+ {+ "type": "function_call",+ "call_id": "call_1",+ "name": "view_image",+ "arguments": json.dumps({"path": "shot.png"}),+ },+ {+ "type": "function_call_output",+ "call_id": "call_1",+ "output": [+ {"type": "input_text", "text": "shot.png"},+ {"type": "input_image", "image_url": image_url()},+ ],+ },+ ],+ }+++def chat_payload(**extra):+ return {+ "model": "test",+ "stream": False,+ "tools": [{"type": "function", "function": {"name": "view_image", "parameters": {}}}],+ "messages": [+ {"role": "user", "content": "What does the screenshot show?"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "view_image", "arguments": "{}"},+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "content": [+ {"type": "text", "text": "shot.png"},+ {"type": "image_url", "image_url": {"url": image_url()}},+ ],+ },+ ],+ **extra,+ }+++def upstream_reply(stream):+ if stream:+ chunks = [+ {"choices": [{"delta": {"content": "A red square."}}]},+ {"choices": [{"delta": {}, "finish_reason": "stop"}]},+ ]+ body = "".join(f"data: {json.dumps(c)}\n\n" for c in chunks) + "data: [DONE]\n\n"+ return httpx.Response(200, text = body, headers = {"content-type": "text/event-stream"})+ return httpx.Response(+ 200,+ json = {+ "choices": [+ {+ "message": {"role": "assistant", "content": "A red square."},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 42, "completion_tokens": 5},+ },+ )+++def post(+ monkeypatch,+ body,+ *,+ vision,+ path = "/v1/responses",+ gguf = True,+):+ seen = {"preflight": []}++ async def switch(*args, **kwargs):+ seen["preflight"].append(kwargs)++ def capture(request):+ seen["wire"] = json.loads(request.content)+ return upstream_reply(body["stream"])++ seen["backend"] = _mock_backend(+ monkeypatch,+ is_vision = vision,+ supports_tool_passthrough = True,+ supports_reasoning = False,+ reasoning_always_on = False,+ _request_reasoning_kwargs = lambda *_a, **_k: None,+ base_url = "http://llama.test",+ effective_parallel_slots = 4,+ is_loaded = gguf,+ )+ monkeypatch.setattr(inf, "_maybe_auto_switch_model", switch)+ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ inf.httpx,+ "AsyncClient",+ lambda *args, **kwargs: real_client(transport = httpx.MockTransport(capture)),+ )+ app = FastAPI()+ app.include_router(inf.router, prefix = "/v1")+ app.dependency_overrides[inf.get_current_subject] = lambda: "test"+ with TestClient(app) as client:+ response = client.post(path, json = body)+ return response, seen+++def tool_contents(messages):+ return [m["content"] for m in messages if m["role"] == "tool"]++[email protected]("stream", [False, True])+def test_text_only_model_answers_after_a_tool_returned_an_image(monkeypatch, stream):+ response, seen = post(monkeypatch, payload(stream), vision = False)++ assert response.status_code == 200, response.text+ assert "A red square." in response.text+ assert tool_contents(seen["wire"]["messages"]) == [+ "shot.png",+ f"shot.png\n{TOOL_RESULT_IMAGE_OMITTED}",+ ]+ if stream:+ assert [p["require_vision"] for p in seen["preflight"]] == [False]++[email protected]("stream", [False, True])+def test_vision_model_still_receives_the_tool_image(monkeypatch, stream):+ response, seen = post(monkeypatch, payload(stream), vision = True)++ assert response.status_code == 200, response.text+ content = tool_contents(seen["wire"]["messages"])[1]+ assert [p["type"] for p in content] == ["text", "image_url"]+ assert content[1]["image_url"]["url"].startswith("data:image/png;base64,")++[email protected]("stream", [False, True])+def test_text_only_model_still_refuses_a_user_image(monkeypatch, stream):+ response, seen = post(monkeypatch, payload(stream, user_image = True), vision = False)++ assert response.status_code == 400, response.text+ assert "does not support vision" in response.text+ assert "wire" not in seen+ if stream:+ assert [p["require_vision"] for p in seen["preflight"]] == [True]++[email protected]("user_image", [False, True])+def test_non_streaming_preflight_marks_tool_only_images(monkeypatch, user_image):+ monkeypatch.setattr(inf, "_should_validate_before_switch", lambda: True)+ response, seen = post(monkeypatch, payload(False, user_image = user_image), vision = True)++ assert response.status_code == 200, response.text+ [preflight] = seen["preflight"]+ assert preflight["require_vision"] is True+ assert preflight["tool_images_only"] is (not user_image)++[email protected]("loop", ["enable_tools", "mcp_enabled"])+def test_text_only_model_runs_the_tool_loop_after_a_tool_returned_an_image(monkeypatch, loop):+ response, seen = post(+ monkeypatch, chat_payload(**{loop: True}), vision = False, path = "/v1/chat/completions"+ )++ assert response.status_code == 200, response.text+ [(_, call)] = seen["backend"].calls+ assert tool_contents(call["messages"]) == [f"shot.png\n{TOOL_RESULT_IMAGE_OMITTED}"]+++def test_text_only_non_gguf_model_still_refuses_a_tool_image(monkeypatch):+ monkeypatch.setattr(+ inf,+ "get_inference_backend",+ lambda: SimpleNamespace(active_model_name = "m", models = {"m": {"is_vision": False}}),+ )+ monkeypatch.setattr(+ inf, "_detect_safetensors_features", lambda *_a, **_k: {"supports_tools": True}+ )+ response, _seen = post(+ monkeypatch, chat_payload(), vision = False, path = "/v1/chat/completions", gguf = False+ )++ assert response.status_code == 400, response.text+ assert "text-only" in response.text+++def test_a_legacy_image_beside_tool_images_still_needs_vision(monkeypatch):+ monkeypatch.setattr(inf, "_should_validate_before_switch", lambda: True)+ body = chat_payload(image_base64 = image_url().partition(",")[2])+ response, seen = post(monkeypatch, body, vision = True, path = "/v1/chat/completions")++ assert response.status_code == 200, response.text+ [preflight] = seen["preflight"]+ assert preflight["tool_images_only"] is False+++def record_probes(monkeypatch):+ signature = inspect.signature(inf._target_accepts_request_input)+ probes = []+ monkeypatch.setattr(+ inf,+ "_target_accepts_request_input",+ lambda *a: probes.append(signature.bind(*a).arguments) or False,+ )+ return probes++[email protected]("target_is_gguf", [True, False])+def test_tool_only_images_need_vision_only_from_a_non_gguf_target(monkeypatch, target_is_gguf):+ _backend, rec = _wired(monkeypatch, _FakeBackend("org/A-GGUF"), ("/local/B", "Q8_0", "org/B"))+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_k: target_is_gguf)+ probes = record_probes(monkeypatch)+ switch = inf._maybe_auto_switch_model(+ "org/B", object(), "t", require_vision = True, tool_images_only = True+ )++ if target_is_gguf:+ asyncio.run(switch)+ assert len(rec.calls) == 1+ else:+ with pytest.raises(HTTPException) as exc:+ asyncio.run(switch)+ assert exc.value.status_code == 400+ assert rec.calls == []+ [probe] = probes+ assert probe["needs_vision"] is True+ assert probe["need_image"] is True++[email protected]("medium", ["require_audio_input", "require_video"])+def test_tool_only_images_leave_a_gguf_target_needing_its_projector(monkeypatch, medium):+ _backend, rec = _wired(monkeypatch, _FakeBackend("org/A-GGUF"), ("/local/B", "Q8_0", "org/B"))+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_k: True)+ probes = record_probes(monkeypatch)+ switch = inf._maybe_auto_switch_model(+ "org/B",+ object(),+ "t",+ require_vision = True,+ require_image = True,+ tool_images_only = True,+ **{medium: True},+ )++ with pytest.raises(HTTPException):+ asyncio.run(switch)+ [probe] = probes+ assert probe["needs_vision"] is True+ assert probe["need_image"] is False+ assert rec.calls == []++[email protected]("tool_images_only", [True, False])+def test_auto_download_needs_an_mmproj_only_for_non_tool_images(monkeypatch, tool_images_only):+ _wired(monkeypatch, _FakeBackend("org/A-GGUF"), None)+ asked = []++ async def download(*_a, require_vision, **_k):+ asked.append(require_vision)++ monkeypatch.setattr(inf, "_maybe_auto_download_model", download)+ switch = inf._maybe_auto_switch_model(+ "org/B-GGUF", object(), "t", require_vision = True, tool_images_only = tool_images_only+ )+ with contextlib.suppress(HTTPException):+ asyncio.run(switch)++ assert asked == [not tool_images_only]