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: fix sending an image with no caption on Anthropic (#10455)

Nilay88888e7f6765
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 44624f657f3..a6e3f270fe3 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -182,6 +182,13 @@ _GEMINI3_FAMILY = re.compile(r"^gemini-3(?:\.\d+)?-")
_GEMINI3_PRO = re.compile(r"^gemini-3(?:\.\d+)?-pro")
+def _anthropic_text_is_sendable(value: Any) -> bool:
+ """Anthropic rejects empty and whitespace-only text; the composer joins with "\\n"."""
+ if isinstance(value, str):
+ return bool(value.strip())
+ return bool(value)
+
+
def _anthropic_sampling_params_removed(model: str) -> bool:
"""Whether Anthropic rejects non-default sampling params for ``model``."""
normalized = model.strip().lower()
@@ -2084,7 +2091,7 @@ class ExternalProviderClient:
# https://platform.claude.com/docs/en/build-with-claude/vision)
anthropic_parts: list[dict[str, Any]] = []
for part in content:
- if part.get("type") == "text":
+ if part.get("type") == "text" and _anthropic_text_is_sendable(part.get("text")):
anthropic_parts.append({"type": "text", "text": part["text"]})
elif part.get("type") == "compaction":
# Round-trip a prior turn's compaction block back onto this
@@ -2238,7 +2245,9 @@ class ExternalProviderClient:
):
_text_content = msg.get("content")
_blocks: list[dict[str, Any]] = []
- if isinstance(_text_content, str) and _text_content:
+ if isinstance(_text_content, str) and _anthropic_text_is_sendable(
+ _text_content
+ ):
_blocks.append({"type": "text", "text": _text_content})
for _tc in msg["tool_calls"]:
if not isinstance(_tc, dict):
@@ -2264,6 +2273,9 @@ class ExternalProviderClient:
if _blocks:
filtered.append({"role": "assistant", "content": _blocks})
continue
+ # A plain string is one text block, so an empty one 400s too.
+ if isinstance(content, str) and not content.strip():
+ continue
filtered.append(msg)
# Newer Claude models removed temperature/top_p/top_k entirely (400
diff --git a/studio/backend/tests/test_anthropic_empty_text_block.py b/studio/backend/tests/test_anthropic_empty_text_block.py
new file mode 100644
index 00000000000..b450a07d7cf
--- /dev/null
+++ b/studio/backend/tests/test_anthropic_empty_text_block.py
@@ -0,0 +1,266 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import json
+
+import httpx
+
+from core.inference import external_provider as ep_mod
+from core.inference.external_provider import ExternalProviderClient
+
+
+def _drive(coro):
+ return asyncio.new_event_loop().run_until_complete(coro)
+
+
+def _capture(
+ monkeypatch,
+ messages,
+ caching = False,
+) -> dict:
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ return httpx.Response(
+ 200,
+ content = b'event: message_stop\ndata: {"type": "message_stop"}\n\n',
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ async def run():
+ client = ExternalProviderClient(
+ provider_type = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ api_key = "sk-ant-test",
+ )
+ async for _ in client._stream_anthropic(
+ messages = messages,
+ model = "claude-opus-4-7",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 32,
+ enable_prompt_caching = caching,
+ ):
+ pass
+ await client.close()
+
+ _drive(run())
+ return captured
+
+
+_IMAGE_DATA_URI = "data:image/png;base64,aGVsbG8="
+
+
+def test_empty_text_block_dropped_from_image_only_turn(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": ""},
+ {"type": "image_url", "image_url": {"url": _IMAGE_DATA_URI}},
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert not [p for p in parts if p.get("type") == "text"], parts
+ assert parts == [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "aGVsbG8=",
+ },
+ }
+ ]
+
+
+def test_captioned_image_keeps_its_text_block(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "what is this?"},
+ {"type": "image_url", "image_url": {"url": _IMAGE_DATA_URI}},
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert parts[0] == {"type": "text", "text": "what is this?"}
+ assert parts[1]["type"] == "image"
+
+
+def test_text_only_empty_block_drops_the_whole_message(monkeypatch):
+ # Nothing usable survives, and an empty content array 400s too.
+ captured = _capture(
+ monkeypatch,
+ [
+ {"role": "user", "content": [{"type": "text", "text": ""}]},
+ {"role": "user", "content": "but THIS one is fine"},
+ ],
+ )
+ assert captured["body"]["messages"] == [{"role": "user", "content": "but THIS one is fine"}]
+
+
+def test_whitespace_only_caption_dropped_from_image_turn(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "\n"},
+ {"type": "image_url", "image_url": {"url": _IMAGE_DATA_URI}},
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert [p["type"] for p in parts] == ["image"], parts
+
+
+def test_caption_keeps_its_own_surrounding_whitespace(monkeypatch):
+ # Only the DECISION uses strip(); a real caption goes out verbatim.
+ captured = _capture(
+ monkeypatch,
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": " what is this? "},
+ {"type": "image_url", "image_url": {"url": _IMAGE_DATA_URI}},
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert parts[0] == {"type": "text", "text": " what is this? "}
+
+
+def test_empty_string_content_message_dropped(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ [
+ {"role": "user", "content": ""},
+ {"role": "user", "content": " "},
+ {"role": "user", "content": "but THIS one is fine"},
+ ],
+ )
+ assert captured["body"]["messages"] == [{"role": "user", "content": "but THIS one is fine"}]
+
+
+def test_dropping_the_last_message_moves_the_cache_breakpoint(monkeypatch):
+ # cache_control on an empty text block is rejected separately.
+ captured = _capture(
+ monkeypatch,
+ [
+ {"role": "user", "content": "keep me"},
+ {"role": "user", "content": [{"type": "text", "text": ""}]},
+ ],
+ caching = True,
+ )
+ messages = captured["body"]["messages"]
+ assert len(messages) == 1
+ last_block = messages[-1]["content"][-1]
+ assert last_block["type"] == "text"
+ assert last_block["text"] == "keep me"
+ assert last_block.get("cache_control") is not None
+
+
+def test_cached_image_only_turn_marks_the_image(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": ""},
+ {"type": "image_url", "image_url": {"url": _IMAGE_DATA_URI}},
+ ],
+ }
+ ],
+ caching = True,
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert [p["type"] for p in parts] == ["image"], parts
+ assert parts[-1].get("cache_control") is not None
+
+
+def test_whitespace_only_assistant_text_beside_a_tool_call(monkeypatch):
+ # The whitespace block 400s and takes the tool_use down with it.
+ captured = _capture(
+ monkeypatch,
+ [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": " \n ",
+ "tool_calls": [
+ {
+ "id": "toolu_1",
+ "type": "function",
+ "function": {"name": "f", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "toolu_1", "content": "42"},
+ ],
+ )
+ blocks = captured["body"]["messages"][1]["content"]
+ assert [b["type"] for b in blocks] == ["tool_use"], blocks
+
+
+def test_real_assistant_text_beside_a_tool_call_survives(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": "calling f",
+ "tool_calls": [
+ {
+ "id": "toolu_1",
+ "type": "function",
+ "function": {"name": "f", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "toolu_1", "content": "42"},
+ ],
+ )
+ blocks = captured["body"]["messages"][1]["content"]
+ assert blocks[0] == {"type": "text", "text": "calling f"}
+ assert blocks[1]["type"] == "tool_use"
+
+
+def test_missing_text_key_does_not_raise(monkeypatch):
+ # `part["text"]` used to KeyError, taking down the whole request.
+ captured = _capture(
+ monkeypatch,
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text"},
+ {"type": "image_url", "image_url": {"url": _IMAGE_DATA_URI}},
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert [p["type"] for p in parts] == ["image"], parts
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 7436465a45b..1341446d5ce 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1194,9 +1194,12 @@ function buildReplayContent(
textContent: string,
imageParts: Array<{ type: "image_url"; image_url: { url: string } }>,
): OpenAIMessageContent {
- return imageParts.length > 0
+ if (imageParts.length === 0) return textContent;
+ // Anthropic rejects whitespace-only text, and collectTextParts joins with "\n".
+ // Spread: the caller's array must not become the message content.
+ return textContent.trim()
? [{ type: "text", text: textContent }, ...imageParts]
- : textContent;
+ : [...imageParts];
}
function collectAssistantTextThoughtSignature(
diff --git a/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts b/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts
new file mode 100644
index 00000000000..e687879d2c4
--- /dev/null
+++ b/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+// chat-adapter.ts drags in the stores, so lift the source; assistant is a stub.
+const adapterSource = readFileSync(
+ fileURLToPath(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ ),
+ "utf8",
+);
+
+function liftAdapterFunction(opener: string): string {
+ const start = adapterSource.indexOf(opener);
+ assert.ok(start >= 0, `${opener} is no longer defined in chat-adapter.ts`);
+ const end = adapterSource.indexOf("\n}", start);
+ assert.ok(end > start, `could not find the end of ${opener}`);
+ return adapterSource.slice(start, end + 2);
+}
+
+const serializeJs = ts.transpileModule(
+ [
+ "function serializeAssistantReplayMessages() { throw new Error('not under test'); }",
+ liftAdapterFunction("function collectTextParts("),
+ liftAdapterFunction("function collectImageParts("),
+ liftAdapterFunction("function buildReplayContent("),
+ liftAdapterFunction("function toOpenAIMessages("),
+ "return { toOpenAIMessages, buildReplayContent };",
+ ].join("\n\n"),
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },
+).outputText;
+
+const { toOpenAIMessages, buildReplayContent } = new Function(
+ serializeJs,
+)() as {
+ toOpenAIMessages: (
+ message: unknown,
+ ) => Array<{ role: string; content: unknown }>;
+ buildReplayContent: (text: string, images: unknown[]) => unknown;
+};
+
+const IMAGE_DATA_URL = "data:image/png;base64,aGVsbG8=";
+
+test("an uncaptioned image sends no empty text block", () => {
+ const [serialized] = toOpenAIMessages({
+ role: "user",
+ content: [{ type: "image", image: IMAGE_DATA_URL }],
+ });
+
+ assert.equal(serialized.role, "user");
+ assert.deepEqual(serialized.content, [
+ { type: "image_url", image_url: { url: IMAGE_DATA_URL } },
+ ]);
+});
+
+test("a captioned image still leads with its text block", () => {
+ const [serialized] = toOpenAIMessages({
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "image", image: IMAGE_DATA_URL },
+ ],
+ });
+
+ assert.deepEqual(serialized.content, [
+ { type: "text", text: "what is this?" },
+ { type: "image_url", image_url: { url: IMAGE_DATA_URL } },
+ ]);
+});
+
+test("a whitespace-only caption sends no text block either", () => {
+ // Two empty text parts join to "\n", which is truthy but still rejected.
+ const [serialized] = toOpenAIMessages({
+ role: "user",
+ content: [
+ { type: "text", text: "" },
+ { type: "text", text: "" },
+ { type: "image", image: IMAGE_DATA_URL },
+ ],
+ });
+
+ assert.deepEqual(serialized.content, [
+ { type: "image_url", image_url: { url: IMAGE_DATA_URL } },
+ ]);
+});
+
+test("a real caption keeps its own surrounding whitespace", () => {
+ const [serialized] = toOpenAIMessages({
+ role: "user",
+ content: [
+ { type: "text", text: " what is this? " },
+ { type: "image", image: IMAGE_DATA_URL },
+ ],
+ });
+
+ assert.deepEqual(serialized.content, [
+ { type: "text", text: " what is this? " },
+ { type: "image_url", image_url: { url: IMAGE_DATA_URL } },
+ ]);
+});
+
+test("the serialised content is not the collected image array itself", () => {
+ const images = [
+ { type: "image_url" as const, image_url: { url: IMAGE_DATA_URL } },
+ ];
+ assert.notEqual(buildReplayContent("", images), images);
+ assert.deepEqual(buildReplayContent("", images), images);
+});
+
+test("a text-only turn still serialises to a plain string", () => {
+ const [serialized] = toOpenAIMessages({
+ role: "user",
+ content: [{ type: "text", text: "no attachments here" }],
+ });
+
+ assert.equal(serialized.content, "no attachments here");
+});