From d6b3f578114f76383c96b331c8a00243193058da Mon Sep 17 00:00:00 2001 From: sergiywith Date: Fri, 2 Oct 2026 22:16:47 +0300 Subject: [PATCH] serve: an image in an Anthropic tool_result reaches the encoder (Claude Code's Read of a picture) Claude Code returns a picture it opens with Read as an image block inside a tool_result. The Anthropic path turned every tool_result into its text, so the image never reached the encoder and the model described a picture it had not seen. The tool message now carries the image item, as the OpenAI path's tool messages already did; the chat template renders it inside . An image sent beside tool results in the same user turn is kept too. A text-only tool result is still one string, so text prompts are unchanged. --- serve/frontend.py | 14 ++++++++++---- serve/test_server.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/serve/frontend.py b/serve/frontend.py index 31b1fa56..f9f7c2db 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -332,19 +332,25 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d isinstance(b, dict) and b.get("type") == "tool_result" for b in content): messages.append({"role": "user", "content": _parts_of(content)}) continue - text, reasoning, calls = [], [], [] + text, reasoning, calls, parts = [], [], [], [] for block in content or []: kind = block.get("type") if kind == "text": text.append(block.get("text", "")) + parts.append(block) + elif kind in IMAGE_PARTS: + parts.append(block) elif kind == "thinking": reasoning.append(block.get("thinking", "")) elif kind == "tool_use": calls.append({"function": {"name": block.get("name"), "arguments": tool_arguments(block.get("input"))}}) elif kind == "tool_result": - messages.append({"role": "tool", "content": _text_of(block.get("content"))}) - if text or calls or reasoning: - out = {"role": m["role"], "content": "".join(text)} + # A tool's image (Claude Code's Read of a picture) reaches the encoder like a user's, as the OpenAI + # path's tool messages already do; a text-only result is one string, as before. + messages.append({"role": "tool", "content": _parts_of(block.get("content"))}) + if text or calls or reasoning or parts: + # an image sent beside tool results stays in this turn instead of being dropped + out = {"role": m["role"], "content": _parts_of(parts) if _has_image(parts) else "".join(text)} if reasoning: out["reasoning_content"] = "".join(reasoning) if calls: diff --git a/serve/test_server.py b/serve/test_server.py index e1b04c1d..2b6bc674 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -243,6 +243,36 @@ class ImageMarkers(unittest.TestCase): self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) svc.embeddings.path.unlink(missing_ok=True) + def test_anthropic_tool_result_image(self): + """Claude Code's Read of a picture returns it inside a tool_result: it reaches the encoder, in place.""" + import tempfile + from serve.frontend import anthropic_to_messages + tok = ByteTokenizer() + img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}} + call = {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": "a.png"}}]} + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + pad = tok.encode("<|image_pad|>", parse_special=True)[0] + for result, extra, n in (([img], [], 3), ([{"type": "text", "text": "a.png"}, img], [], 3), + ("plain text", [img, {"type": "text", "text": "and this one"}], 3), + ([img], [img], 6)): + with self.subTest(result=str(result)[:30], extra=len(extra)): + msgs = [{"role": "user", "content": "look at a.png"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": result}] + extra}] + m, _, _ = anthropic_to_messages({"messages": msgs}) + ids, _, _ = svc.prepare(m, None, {}) + self.assertEqual(ids.count(pad), n) + prompt = tok.decode(ids) + inside = prompt.split("", 1)[1].split("", 1)[0] + self.assertEqual("<|vision_start|>" in inside, not isinstance(result, str)) + self.assertEqual("<|vision_start|>" in prompt.split("", 1)[1], bool(extra)) + svc.embeddings.path.unlink(missing_ok=True) + # a text-only tool result renders exactly as before: one string + msgs = [{"role": "user", "content": "q"}, call, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "r"}]}]}] + self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r"}) + class ThinkTokenizer(ByteTokenizer): """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special,