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: support images on /v1/messages (Anthropic-compat) (#5128)

Roland Tannous92cee0ff3e4a
diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.py
index 400e6053e0d..263718c540e 100644
--- a/studio/backend/core/inference/anthropic_compat.py
+++ b/studio/backend/core/inference/anthropic_compat.py
@@ -13,11 +13,44 @@ import json
from typing import Any, Optional, Union
+def _anthropic_image_block_to_openai_part(block: dict) -> Optional[dict]:
+ """Translate one Anthropic ``image`` block to an OpenAI ``image_url`` part.
+
+ Accepts both source shapes:
+ - ``{"type": "base64", "media_type": "image/jpeg", "data": "..."}``
+ - ``{"type": "url", "url": "https://..."}``
+
+ Returns ``None`` when the source is malformed so the caller can skip it.
+ """
+ source = block.get("source") or {}
+ stype = source.get("type")
+ if stype == "base64":
+ data = source.get("data")
+ if not data:
+ return None
+ media_type = source.get("media_type") or "image/jpeg"
+ return {
+ "type": "image_url",
+ "image_url": {"url": f"data:{media_type};base64,{data}"},
+ }
+ if stype == "url":
+ url = source.get("url")
+ if not url:
+ return None
+ return {"type": "image_url", "image_url": {"url": url}}
+ return None
+
+
def anthropic_messages_to_openai(
messages: list[dict],
system: Optional[Union[str, list]] = None,
) -> list[dict]:
- """Convert Anthropic messages + system to OpenAI-format message dicts."""
+ """Convert Anthropic messages + system to OpenAI-format message dicts.
+
+ User messages that carry ``image`` blocks are emitted as OpenAI
+ multimodal content arrays (``[{type: "text", ...}, {type: "image_url", ...}]``)
+ so they flow through llama-server's native vision pathway.
+ """
result: list[dict] = []
# System prompt
@@ -42,54 +75,76 @@ def anthropic_messages_to_openai(
result.append({"role": role, "content": content})
continue
- # Content is a list of blocks
- text_parts: list[str] = []
- tool_calls: list[dict] = []
- tool_results: list[dict] = []
-
- for block in content:
- b = block if isinstance(block, dict) else block.model_dump()
- btype = b.get("type", "")
-
- if btype == "text":
- text_parts.append(b["text"])
- elif btype == "tool_use":
- tool_calls.append(
- {
- "id": b["id"],
- "type": "function",
- "function": {
- "name": b["name"],
- "arguments": json.dumps(b["input"]),
- },
- }
- )
- elif btype == "tool_result":
- tc = b.get("content", "")
- if isinstance(tc, list):
- tc = " ".join(
- p["text"]
- for p in tc
- if isinstance(p, dict) and p.get("type") == "text"
- )
- tool_results.append(
- {
- "role": "tool",
- "tool_call_id": b["tool_use_id"],
- "content": str(tc),
- }
- )
-
if role == "assistant":
+ # Assistant content carries text + tool_use; images aren't
+ # part of Anthropic's assistant content model.
+ text_parts: list[str] = []
+ tool_calls: list[dict] = []
+ for block in content:
+ b = block if isinstance(block, dict) else block.model_dump()
+ btype = b.get("type", "")
+ if btype == "text":
+ text_parts.append(b["text"])
+ elif btype == "tool_use":
+ tool_calls.append(
+ {
+ "id": b["id"],
+ "type": "function",
+ "function": {
+ "name": b["name"],
+ "arguments": json.dumps(b["input"]),
+ },
+ }
+ )
msg_dict: dict[str, Any] = {"role": "assistant"}
if text_parts:
msg_dict["content"] = "\n".join(text_parts)
if tool_calls:
msg_dict["tool_calls"] = tool_calls
result.append(msg_dict)
- elif role == "user":
- if text_parts:
- result.append({"role": "user", "content": "\n".join(text_parts)})
+ continue
+
+ if role == "user":
+ # Build an ordered part list so text/image interleaving is
+ # preserved (e.g. [text, image, text, image]). tool_result
+ # blocks become their own OpenAI "tool" role messages.
+ user_parts: list[dict] = []
+ has_image = False
+ tool_results: list[dict] = []
+ for block in content:
+ b = block if isinstance(block, dict) else block.model_dump()
+ btype = b.get("type", "")
+ if btype == "text":
+ user_parts.append({"type": "text", "text": b["text"]})
+ elif btype == "image":
+ part = _anthropic_image_block_to_openai_part(b)
+ if part is not None:
+ user_parts.append(part)
+ has_image = True
+ elif btype == "tool_result":
+ tc = b.get("content", "")
+ if isinstance(tc, list):
+ tc = " ".join(
+ p["text"]
+ for p in tc
+ if isinstance(p, dict) and p.get("type") == "text"
+ )
+ tool_results.append(
+ {
+ "role": "tool",
+ "tool_call_id": b["tool_use_id"],
+ "content": str(tc),
+ }
+ )
+
+ if has_image:
+ result.append({"role": "user", "content": user_parts})
+ else:
+ # No images — collapse text parts to a plain string so
+ # existing text-only callers keep their simple shape.
+ 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)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 9c84eabd8b2..e17f8f5882e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2866,6 +2866,64 @@ async def openai_responses(
# =====================================================================
+def _normalize_anthropic_openai_images(
+ openai_messages: list[dict], is_vision: bool
+) -> bool:
+ """Enforce the vision guard on translated Anthropic messages and
+ normalize any ``image_url`` parts with base64 data URLs to PNG.
+
+ llama-server's stb_image only handles a few formats (JPEG/PNG/BMP/…);
+ Anthropic clients commonly send JPEG or WebP, and Claude Code sends
+ WebP. Re-encoding everything to PNG mirrors the behavior of
+ `_openai_messages_for_passthrough` / the GGUF branch of
+ `/v1/chat/completions` so the two endpoints agree.
+
+ Mutates ``openai_messages`` in place. Returns ``True`` when any
+ image part was seen (so the caller can skip a second scan). Raises
+ HTTPException(400) when images are present but the active model is
+ not a vision model, or when an image cannot be decoded.
+ """
+ from PIL import Image
+
+ has_image = False
+ for msg in openai_messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if part.get("type") != "image_url":
+ continue
+
+ has_image = True
+ if not is_vision:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Image provided but current GGUF model does not support vision.",
+ )
+
+ url = (part.get("image_url") or {}).get("url", "")
+ if not url.startswith("data:"):
+ # Remote URLs are forwarded as-is; llama-server will
+ # fetch (or fail) per its own support matrix.
+ continue
+
+ try:
+ _, b64data = url.split(",", 1)
+ raw = base64.b64decode(b64data)
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
+ buf = io.BytesIO()
+ img.save(buf, format = "PNG")
+ png_b64 = base64.b64encode(buf.getvalue()).decode("ascii")
+ except Exception as e:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Failed to process image: {e}",
+ )
+ part["image_url"] = {"url": f"data:image/png;base64,{png_b64}"}
+
+ return has_image
+
+
@router.post("/messages")
async def anthropic_messages(
payload: AnthropicMessagesRequest,
@@ -2896,6 +2954,12 @@ async def anthropic_messages(
payload.system,
)
+ # Enforce vision guard + re-encode embedded images to PNG so the
+ # Anthropic endpoint matches the behavior of /v1/chat/completions.
+ _has_image = _normalize_anthropic_openai_images(
+ openai_messages, llama_backend.is_vision
+ )
+
temperature = payload.temperature if payload.temperature is not None else 0.6
top_p = payload.top_p if payload.top_p is not None else 0.95
top_k = payload.top_k if payload.top_k is not None else 20
@@ -2922,7 +2986,11 @@ async def anthropic_messages(
# 1. enable_tools=true → server-side execution of built-in tools (Unsloth shorthand)
# 2. tools=[...] only → client-side pass-through (standard Anthropic behavior)
# 3. neither → plain chat
- server_tools = payload.enable_tools and llama_backend.supports_tools
+ # Server-side agentic loop doesn't support multimodal input — matches
+ # the `not image_b64` gate in /v1/chat/completions.
+ server_tools = (
+ payload.enable_tools and llama_backend.supports_tools and not _has_image
+ )
client_tools = (
not server_tools
and payload.tools
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index ec432df9e62..0825ef9337e 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -10,6 +10,8 @@ import sys
import os
import json
+import pytest
+
_backend = os.path.join(os.path.dirname(__file__), "..")
sys.path.insert(0, _backend)
@@ -32,6 +34,10 @@ from core.inference.anthropic_compat import (
AnthropicStreamEmitter,
AnthropicPassthroughEmitter,
)
+from routes.inference import _normalize_anthropic_openai_images
+from fastapi import HTTPException
+import base64 as _b64
+from io import BytesIO as _BytesIO
# =====================================================================
@@ -246,6 +252,141 @@ class TestAnthropicMessagesToOpenAI:
result = anthropic_messages_to_openai(msgs)
assert result[0]["content"] == "Line 1 Line 2"
+ def test_image_base64_block_becomes_multimodal_part(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What is this?"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/jpeg",
+ "data": "AAAA",
+ },
+ },
+ ],
+ }
+ ]
+ result = anthropic_messages_to_openai(msgs)
+ assert len(result) == 1
+ assert result[0]["role"] == "user"
+ parts = result[0]["content"]
+ assert isinstance(parts, list)
+ assert parts[0] == {"type": "text", "text": "What is this?"}
+ assert parts[1]["type"] == "image_url"
+ assert parts[1]["image_url"]["url"] == "data:image/jpeg;base64,AAAA"
+
+ def test_image_url_block_forwarded_as_url(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Describe it"},
+ {
+ "type": "image",
+ "source": {"type": "url", "url": "https://x/y.png"},
+ },
+ ],
+ }
+ ]
+ result = anthropic_messages_to_openai(msgs)
+ parts = result[0]["content"]
+ assert parts[1] == {
+ "type": "image_url",
+ "image_url": {"url": "https://x/y.png"},
+ }
+
+ def test_image_only_user_message_emits_no_text_part(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "ZZ",
+ },
+ },
+ ],
+ }
+ ]
+ result = anthropic_messages_to_openai(msgs)
+ parts = result[0]["content"]
+ assert len(parts) == 1
+ assert parts[0]["type"] == "image_url"
+
+ def test_image_default_media_type_when_missing(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "source": {"type": "base64", "data": "BB"},
+ },
+ ],
+ }
+ ]
+ result = anthropic_messages_to_openai(msgs)
+ parts = result[0]["content"]
+ assert parts[0]["image_url"]["url"].startswith("data:image/jpeg;base64,")
+
+ def test_image_text_order_preserved(self):
+ # [text1, image1, text2, image2] must not collapse to
+ # [text1+text2, image1, image2].
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "before"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "AA",
+ },
+ },
+ {"type": "text", "text": "after"},
+ {
+ "type": "image",
+ "source": {"type": "url", "url": "https://x/y.png"},
+ },
+ ],
+ }
+ ]
+ result = anthropic_messages_to_openai(msgs)
+ parts = result[0]["content"]
+ assert [p["type"] for p in parts] == [
+ "text",
+ "image_url",
+ "text",
+ "image_url",
+ ]
+ assert parts[0]["text"] == "before"
+ assert parts[2]["text"] == "after"
+ assert parts[1]["image_url"]["url"] == "data:image/png;base64,AA"
+ assert parts[3]["image_url"]["url"] == "https://x/y.png"
+
+ def test_malformed_image_block_is_skipped(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Hi"},
+ {"type": "image", "source": {"type": "base64"}},
+ {"type": "image", "source": {"type": "url"}},
+ ],
+ }
+ ]
+ result = anthropic_messages_to_openai(msgs)
+ # No image parts emitted; message falls back to plain text.
+ assert result[0] == {"role": "user", "content": "Hi"}
+
# =====================================================================
# Tool translation tests
@@ -772,3 +913,101 @@ class TestAnthropicPassthroughEmitter:
parsed = self._parse(events[1])
assert parsed["content_block"]["name"] == "Read"
assert parsed["content_block"]["id"] == "c2"
+
+
+# =====================================================================
+# Vision guard + PNG normalization (/v1/messages)
+# =====================================================================
+
+
+def _jpeg_data_url() -> str:
+ from PIL import Image
+
+ img = Image.new("RGB", (2, 2), (255, 0, 0))
+ buf = _BytesIO()
+ img.save(buf, format = "JPEG")
+ b64 = _b64.b64encode(buf.getvalue()).decode("ascii")
+ return f"data:image/jpeg;base64,{b64}"
+
+
+class TestNormalizeAnthropicOpenAIImages:
+ def test_noop_when_no_images(self):
+ msgs = [{"role": "user", "content": "hi"}]
+ has_image = _normalize_anthropic_openai_images(msgs, is_vision = False)
+ assert has_image is False
+ assert msgs == [{"role": "user", "content": "hi"}]
+
+ def test_returns_true_when_image_present(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"url": _jpeg_data_url()}},
+ ],
+ }
+ ]
+ assert _normalize_anthropic_openai_images(msgs, is_vision = True) is True
+
+ def test_rejects_image_when_model_not_vision(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "?"},
+ {
+ "type": "image_url",
+ "image_url": {"url": _jpeg_data_url()},
+ },
+ ],
+ }
+ ]
+ with pytest.raises(HTTPException) as exc:
+ _normalize_anthropic_openai_images(msgs, is_vision = False)
+ assert exc.value.status_code == 400
+
+ def test_reencodes_jpeg_data_url_to_png(self):
+ original_url = _jpeg_data_url()
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "?"},
+ {"type": "image_url", "image_url": {"url": original_url}},
+ ],
+ }
+ ]
+ _normalize_anthropic_openai_images(msgs, is_vision = True)
+ new_url = msgs[0]["content"][1]["image_url"]["url"]
+ assert new_url.startswith("data:image/png;base64,")
+ assert new_url != original_url
+
+ def test_remote_url_left_unchanged(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "https://x.example/y.png"},
+ },
+ ],
+ }
+ ]
+ _normalize_anthropic_openai_images(msgs, is_vision = True)
+ assert msgs[0]["content"][0]["image_url"]["url"] == "https://x.example/y.png"
+
+ def test_bad_base64_raises_400(self):
+ msgs = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/jpeg;base64,!!!not-b64!!!"},
+ },
+ ],
+ }
+ ]
+ with pytest.raises(HTTPException) as exc:
+ _normalize_anthropic_openai_images(msgs, is_vision = True)
+ assert exc.value.status_code == 400