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 <tool_response>. 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.
This commit is contained in:
1 parent
64be7561c5
commit
d6b3f57811
2 files changed
+40
-4
No files matched your search
+10
-4
@@ -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:
|
||||
|
||||
@@ -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("<tool_response>", 1)[1].split("</tool_response>", 1)[0]
|
||||
self.assertEqual("<|vision_start|>" in inside, not isinstance(result, str))
|
||||
self.assertEqual("<|vision_start|>" in prompt.split("</tool_response>", 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,
|
||||
|
||||
Reference in new issue
Block a user