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 Claude session working after an image on text-only GGUFs (#13652)
Nilay7f75c32b7b04
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex a9348c6eb5a..7f9c4032152 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4273,6 +4273,7 @@ class AnthropicMessagesRequest(BaseModel):description = "[x-unsloth] Opt-in tool-call recovery; mirrors the Chat Completions nudge_tool_calls field and defaults off.",)model_config = {"extra": "allow"}+ _message_ordinals: Optional[list[int]] = PrivateAttr(default = None)@model_validator(mode = "after")def _effort_from_output_config(self) -> "AnthropicMessagesRequest":@@ -4329,6 +4330,20 @@ class AnthropicMessagesRequest(BaseModel):normalized["system"] = _merge_anthropic_system(normalized.get("system"), system_additions)return normalized+ @model_validator(mode = "wrap")+ @classmethod+ def _record_message_ordinals(cls, data: Any, handler):+ # Error paths name the client's own message index, not the one left after system folding.+ model = handler(data)+ messages = data.get("messages") if isinstance(data, dict) else None+ if isinstance(messages, list):+ model._message_ordinals = [+ i+ for i, m in enumerate(messages)+ if not (isinstance(m, dict) and m.get("role") == "system")+ ]+ return model+@field_validator("sandbox_level", mode = "before")@classmethoddef _coerce_sandbox_level(cls, value: Any) -> Any:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 87b6260d358..fb7dd4875db 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -10084,6 +10084,16 @@ def _anthropic_request_has_image(payload, *, tool_results: bool = True) -> bool:return next(_anthropic_image_blocks(payload, tool_results = tool_results), None) is not None+def _anthropic_top_level_image_location(payload) -> Optional[str]:+ ordinals = getattr(payload, "_message_ordinals", None) or []+ for i, msg in enumerate(payload.messages):+ if isinstance(msg.content, list):+ for j, block in enumerate(msg.content):+ if block.type == "image":+ return f"messages.{ordinals[i] if i < len(ordinals) else i}.content.{j}.image"+ return None++def _anthropic_local_image_payloads(payload) -> list[str]:encoded_images = []for block in _anthropic_image_blocks(payload):@@ -10364,6 +10374,7 @@ async def _maybe_auto_download_model(require_vision: bool = False,require_speech: bool = False,current_subject: Optional[str] = None,+ rejection_prefix: str = "",) -> None:"""Opt-in: start fetching a named GGUF this server doesn't have.@@ -10397,17 +10408,20 @@ async def _maybe_auto_download_model(returnif refusal is None:return+ message = refusal.message+ if refusal.code == "invalid_value":+ message = f"{rejection_prefix}{message}"path = getattr(getattr(fastapi_request, "url", None), "path", None)detail = (error_body_for_path(path,- refusal.message,+ message,status = refusal.status,code = refusal.code,param = "model",)if isinstance(path, str)- else refusal.message+ else message)_record_refused_request(fastapi_request, requested_model, refusal, current_subject)raise HTTPException(@@ -11099,6 +11113,7 @@ async def _maybe_auto_switch_model(require_vision: bool = False,require_image: bool = True,modality_label: str = "image or audio",+ rejection_prefix: str = "",claim_resident: bool = True,require_audio_input: bool = False,require_video: bool = False,@@ -11321,6 +11336,7 @@ async def _maybe_auto_switch_model(require_vision = gguf_requires_vision or require_audio_input,require_speech = require_speech,current_subject = current_subject,+ rejection_prefix = rejection_prefix,)# Idle-unload may have freed the model; reload exactly what it freed# (path + quant + advertised id) so an alias/unknown name stays servable@@ -11526,7 +11542,7 @@ async def _maybe_auto_switch_model(raise HTTPException(status_code = 400,detail = openai_error_body(- f"The requested model does not support the {modality_label} input in this request.",+ f"{rejection_prefix}The requested model does not support the {modality_label} input in this request.",status = 400,code = "invalid_value",param = "model",@@ -42041,6 +42057,10 @@ async def anthropic_messages(# only top-level images require vision or rule out server tools._anthropic_top_level_image = _anthropic_request_has_image(payload, tool_results = False)_anthropic_image_b64s = _anthropic_local_image_payloads(payload)+ # Anthropic's block path lets clients drop the image instead of resending it every turn.+ _anthropic_image_prefix = (+ f"{_anthropic_top_level_image_location(payload)}: " if _anthropic_top_level_image else ""+ )# Mixing Anthropic server tools with custom client tools is unsupported (the# server-tool loop can't relay client functions back to the caller). Reject@@ -42137,6 +42157,7 @@ async def anthropic_messages(request,current_subject,require_vision = _anthropic_top_level_image,+ rejection_prefix = _anthropic_image_prefix,# The image normalization below can still 400 after this switch, so defer the claim:# the middleware claims on a 2xx, so a rejected request never strands a preview-owned# model.@@ -42167,6 +42188,13 @@ async def anthropic_messages(model_name = _llama_public_model_id(llama_backend, payload.model)message_id = f"msg_{uuid.uuid4().hex[:24]}"+ if _anthropic_top_level_image and not llama_backend.is_vision:+ raise HTTPException(+ status_code = 400,+ detail = f"{_anthropic_image_prefix}"+ "Image provided but current GGUF model does not support vision.",+ )+# ── Translate Anthropic → OpenAI ──────────────────────────openai_messages = anthropic_messages_to_openai([m.model_dump() for m in payload.messages],diff --git a/studio/backend/tests/test_anthropic_native_tool_images.py b/studio/backend/tests/test_anthropic_native_tool_images.pyindex 0d84d89fc48..f5f9b96b793 100644--- a/studio/backend/tests/test_anthropic_native_tool_images.py+++ b/studio/backend/tests/test_anthropic_native_tool_images.py@@ -19,6 +19,7 @@ from core.inference.anthropic_compat import (from models.inference import AnthropicMessagesRequestfrom routes import inference as inffrom studio.backend.tests.test_anthropic_messages import _mock_backend+from utils.api_errors import install_api_error_handlersdef image_block():@@ -190,3 +191,67 @@ def test_text_only_tool_image_keeps_the_server_tool_permission_gate(monkeypatch)assert response.status_code == 400, response.textassert "permission_mode" in response.textassert switched == [] and backend.calls == []++[email protected]("vision", [True, False])+def test_text_only_image_error_names_the_image_block(monkeypatch, vision):+ async def switch(*args, **kwargs):+ pass++ backend = _mock_backend(monkeypatch, is_vision = vision)+ monkeypatch.setattr(inf, "_maybe_auto_switch_model", switch)+ app = FastAPI()+ install_api_error_handlers(app)+ app.include_router(inf.router, prefix = "/v1")+ app.dependency_overrides[inf.get_current_subject] = lambda: "test"+ body = {+ "model": "test-model",+ "max_tokens": 16,+ "messages": [+ {"role": "user", "content": "Hi."},+ {"role": "assistant", "content": "Hello."},+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "What color is this?"},+ image_block(),+ {"type": "text", "text": "Say hi."},+ ],+ },+ ],+ }+ with TestClient(app) as client:+ response = client.post("/v1/messages", json = body)+ if vision:+ assert response.status_code == 200, response.text+ return+ assert response.status_code == 400, response.text+ message = response.json()["error"]["message"]+ assert message.startswith("messages.2.content.1.image: ")+ assert "does not support vision" in message+ assert backend.calls == []+++def test_text_only_image_error_counts_folded_system_messages(monkeypatch):+ async def switch(*args, **kwargs):+ pass++ backend = _mock_backend(monkeypatch, is_vision = False)+ monkeypatch.setattr(inf, "_maybe_auto_switch_model", switch)+ app = FastAPI()+ install_api_error_handlers(app)+ app.include_router(inf.router, prefix = "/v1")+ app.dependency_overrides[inf.get_current_subject] = lambda: "test"+ body = {+ "model": "test-model",+ "max_tokens": 16,+ "messages": [+ {"role": "system", "content": "Be brief."},+ {"role": "user", "content": [{"type": "text", "text": "What color?"}, image_block()]},+ ],+ }+ with TestClient(app) as client:+ response = client.post("/v1/messages", json = body)+ assert response.status_code == 400, response.text+ assert response.json()["error"]["message"].startswith("messages.1.content.1.image: ")+ assert backend.calls == []diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.pyindex 186368f5a6d..1976455c403 100644--- a/studio/backend/tests/test_openai_auto_download.py+++ b/studio/backend/tests/test_openai_auto_download.py@@ -2247,3 +2247,28 @@ def test_the_diagnosis_does_not_report_a_model_this_account_cannot_see(monkeypatmonkeypatch = monkeypatch,)assert "is downloaded, but this server cannot serve it here" in granted+++def test_vision_refusal_names_the_image_block_on_messages(hub, monkeypatch):+ async def _no_mmproj(model, **kwargs):+ return auto_dl.AutoDownloadRefusal(+ status = 400, code = "invalid_value", message = "'x' ships no mmproj companion."+ )++ import utils.openai_auto_switch_settings as s++ monkeypatch.setattr(auto_dl, "maybe_auto_download", _no_mmproj)+ monkeypatch.setattr(s, "get_openai_auto_download_enabled", lambda: True)+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(+ inference_route._maybe_auto_download_model(+ "unsloth/text-GGUF",+ _Req(path = "/v1/messages"),+ require_vision = True,+ rejection_prefix = "messages.0.content.1.image: ",+ )+ )+ assert excinfo.value.status_code == 400+ assert excinfo.value.detail["error"]["message"] == (+ "messages.0.content.1.image: 'x' ships no mmproj companion."+ )diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex ef3db688089..9e84e6cac69 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -4616,6 +4616,32 @@ def test_require_vision_rejects_text_target_before_switch(monkeypatch):assert rec.calls == [] # rejected before the load+def test_anthropic_text_target_rejection_names_the_image_block(monkeypatch):+ from models.inference import AnthropicImageBlock, AnthropicMessage, AnthropicMessagesRequest++ backend, rec = _wired(+ monkeypatch, _FakeBackend("org/A-GGUF"), ("/local/B.gguf", "Q8_0", "org/B-GGUF")+ )+ monkeypatch.setattr(inference_route, "_target_is_vision", lambda _p, _v = None, _i = True: False)+ image = AnthropicImageBlock(+ type = "image", source = {"type": "base64", "media_type": "image/png", "data": "AAAA"}+ )+ payload = AnthropicMessagesRequest(+ model = "org/B-GGUF",+ max_tokens = 16,+ messages = [+ AnthropicMessage(role = "user", content = "hi"),+ AnthropicMessage(role = "assistant", content = "hello"),+ AnthropicMessage(role = "user", content = [{"type": "text", "text": "what?"}, image]),+ ],+ )+ with pytest.raises(HTTPException) as exc:+ asyncio.run(inference_route.anthropic_messages(payload, object(), "tester"))+ assert exc.value.status_code == 400+ assert exc.value.detail["error"]["message"].startswith("messages.2.content.1.image: ")+ assert rec.calls == []++def test_require_vision_allows_vision_target(monkeypatch):backend, rec = _wired(monkeypatch, _FakeBackend("org/A-GGUF"), ("/local/B.gguf", "Q8_0", "org/B-GGUF")