The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vision): accept the image/jpg alias and give the Anthropic converter the same unsupported-subtype downgrade
teknium1d1998c30f7ea
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.pyindex 1397c0cf86f..60e400b1b52 100644--- a/agent/anthropic_message_convert.py+++ b/agent/anthropic_message_convert.py@@ -167,15 +167,24 @@ def convert_tools_to_anthropic(tools: List[Dict]) -> List[Dict]:return result-def _image_source_from_openai_url(url: str) -> Dict[str, str]:- """OpenAI image URL / data URL -> Anthropic image ``source``."""+def _image_block_from_openai_url(url: str) -> Dict[str, Any]:+ """OpenAI image URL / data URL -> Anthropic ``image`` block. An inline subtype the API rejects+ (svg+xml, bmp, tiff) 400s every replay once in history: an SVG is rasterized to PNG when a+ rasterizer is installed, anything else unsupported becomes a text placeholder."""+ from tools.vision_tools_image_prep import rasterize_svg_data_url, unsupported_inline_image_media_typeurl = str(url or "").strip()- if url.startswith("data:"):- header, _, data = url.partition(",")- mime_part = header[len("data:"):].split(";", 1)[0].strip()- media_type = mime_part if mime_part.startswith("image/") else "image/jpeg"- return {"type": "base64", "media_type": media_type, "data": data}- return {"type": "url", "url": url}+ if not url.startswith("data:"):+ return {"type": "image", "source": {"type": "url", "url": url}}+ unsupported = unsupported_inline_image_media_type(url)+ if unsupported == "image/svg+xml" and (png_url := rasterize_svg_data_url(url)) is not None:+ url, unsupported = png_url, None+ if unsupported is not None:+ return _text_block(f"[image omitted: {unsupported} is not a supported image format]")+ header, _, data = url.partition(",")+ mime_part = header[len("data:"):].split(";", 1)[0].strip()+ media_type = mime_part if mime_part.startswith("image/") else "image/jpeg"+ media_type = "image/jpeg" if media_type.lower() == "image/jpg" else media_type+ return {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": data}}def _convert_content_part_to_anthropic(part: Any) -> Optional[Dict[str, Any]]:@@ -192,7 +201,7 @@ def _convert_content_part_to_anthropic(part: Any) -> Optional[Dict[str, Any]]:elif ptype in {"image_url", "input_image"}:image_value = part.get("image_url", {})url = image_value.get("url", "") if isinstance(image_value, dict) else str(image_value or "")- block = {"type": "image", "source": _image_source_from_openai_url(url)}+ block = _image_block_from_openai_url(url)else:block = dict(part)if (cache_control := _cache_control_of(part)) is not None:diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.pyindex dda5da3134e..9f259f12aad 100644--- a/agent/codex_responses_adapter.py+++ b/agent/codex_responses_adapter.py@@ -96,7 +96,6 @@ _ASSISTANT_IMAGE_PLACEHOLDER = "[Assistant image omitted during replay]"# Inline data-URL subtypes the Responses backends accept as ``input_image``. Anything else# (SVG source, BMP, TIFF, ...) 400s the WHOLE request — and, once baked into history, every# later turn too — so it is downgraded to a text placeholder at this converging seam (#29711).-_RESPONSES_INLINE_IMAGE_SUBTYPES = frozenset({"jpeg", "png", "gif", "webp"})_INCOMPLETE_STATUSES = {"queued", "in_progress", "incomplete"}_RESPONSE_MESSAGE_STATUSES = {"completed", "incomplete", "in_progress"}@@ -213,16 +212,6 @@ def _iter_content_parts(content: list) -> Iterator[tuple[str, Any]]:yield "image", part-def _unsupported_inline_image_subtype(url: str) -> Optional[str]:- """``image/<subtype>`` of a ``data:image/...`` URL the Responses backends reject; None for- accepted rasters and for non-data URLs (the provider owns remote-URL validation)."""- header = url.partition(",")[0].lower()- if not header.startswith("data:image/"):- return None- subtype = header[len("data:image/"):].split(";", 1)[0].strip()- return None if subtype in _RESPONSES_INLINE_IMAGE_SUBTYPES else f"image/{subtype or 'unknown'}"--def _input_image_part(part: Dict[str, Any], role: str = "user", *, keep_empty_url: bool) -> Optional[Dict[str, Any]]:"""Responses image part from a chat/Responses image part (``image_url`` may be a str or``{url, detail}``). Assistant → text placeholder (an assistant ``input_image`` 400s every@@ -237,11 +226,12 @@ def _input_image_part(part: Dict[str, Any], role: str = "user", *, keep_empty_urif not _nonempty_str(url) and not keep_empty_url:return Noneurl = str(url or "")- mime = _unsupported_inline_image_subtype(url)+ # Lazy import: the prep module only depends on hermes_constants at import time (no cycle).+ from tools.vision_tools_image_prep import rasterize_svg_data_url, unsupported_inline_image_media_type+ mime = unsupported_inline_image_media_type(url)if mime == "image/svg+xml":# Rasterize so the model still sees the drawing; the placeholder is the fallback only# when no rasterizer (cairosvg / svglib / rsvg-convert / inkscape) is available.- from tools.vision_tools_image_prep import rasterize_svg_data_urlpng_url = rasterize_svg_data_url(url)if png_url is not None:url, mime = png_url, Nonediff --git a/tests/agent/test_anthropic_adapter.py b/tests/agent/test_anthropic_adapter.pyindex c2390dc257b..a66d1d51843 100644--- a/tests/agent/test_anthropic_adapter.py+++ b/tests/agent/test_anthropic_adapter.py@@ -1933,3 +1933,22 @@ def test_oauth_system_prompt_sanitizer_preserves_docs_url():assert "built by claude-code." in system_text # a sentence-final dot is proseassert "claude-code's docs" in system_text # so is a possessiveassert kwargs["system"][-1]["text"].count("claude-code") == 3 # the caller's block, not the CC prefix+++def test_unsupported_inline_image_subtype_downgrades_to_text_for_anthropic(monkeypatch):+ """Sibling of the Responses guard: a data:image/svg+xml (or bmp/tiff) part forwarded verbatim as+ ``media_type`` 400s the Anthropic request on every replay — it must become a text placeholder+ while the valid PNG still goes as an image block and ``image/jpg`` is normalized to JPEG."""+ import tools.vision_tools_image_prep as prep+ monkeypatch.setattr(prep, "_rasterize_svg_to_png", lambda svg_path, out_path: False)+ messages = [{"role": "user", "content": [+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},+ {"type": "image_url", "image_url": {"url": "data:image/svg+xml;base64,PHN2Zy8+"}},+ {"type": "image_url", "image_url": {"url": "data:image/jpg;base64,/9j/4AAQ"}},+ ]}]+ _, result = convert_messages_to_anthropic(messages)+ blocks = result[0]["content"]+ assert [b["type"] for b in blocks] == ["image", "text", "image"]+ assert blocks[0]["source"] == {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo="}+ assert blocks[1]["text"] == "[image omitted: image/svg+xml is not a supported image format]"+ assert blocks[2]["source"]["media_type"] == "image/jpeg"diff --git a/tests/agent/test_codex_responses_adapter.py b/tests/agent/test_codex_responses_adapter.pyindex 04cbf2a474a..95aceb80c12 100644--- a/tests/agent/test_codex_responses_adapter.py+++ b/tests/agent/test_codex_responses_adapter.py@@ -126,6 +126,9 @@ def test_unsupported_inline_image_downgrades_to_text_in_message_and_tool_output(assert tool_output["type"] == "function_call_output"assert [p["type"] for p in tool_output["output"]] == ["input_text", "input_text"]assert "image/svg+xml" in tool_output["output"][1]["text"]+ # ``image/jpg`` is the JPEG alias every other image site accepts — it must still go as input_image.+ jpg = _chat_content_to_responses_parts([{"type": "image_url", "image_url": "data:image/jpg;base64,/9j/4AAQ"}])+ assert jpg == [{"type": "input_image", "image_url": "data:image/jpg;base64,/9j/4AAQ"}]def test_inline_svg_is_rasterized_to_png_when_a_rasterizer_exists(monkeypatch):diff --git a/tools/vision_tools_image_prep.py b/tools/vision_tools_image_prep.pyindex 153a9c954c0..e43f6bf104e 100644--- a/tools/vision_tools_image_prep.py+++ b/tools/vision_tools_image_prep.py@@ -32,6 +32,18 @@ _EXTENSION_MIME_TYPES = {_ANTHROPIC_SUPPORTED_MEDIA_TYPES = frozenset({"image/jpeg", "image/png", "image/gif", "image/webp"})+def unsupported_inline_image_media_type(url: str) -> Optional[str]:+ """``image/<subtype>`` of a ``data:image/...`` URL the inline-image wire paths reject+ (``image/jpg`` counts as JPEG); None for accepted rasters and for non-data URLs (the+ provider owns remote-URL validation)."""+ header = url.partition(",")[0].lower()+ if not header.startswith("data:image/"):+ return None+ subtype = header[len("data:image/"):].split(";", 1)[0].strip() or "unknown"+ media_type = "image/jpeg" if subtype == "jpg" else f"image/{subtype}"+ return None if media_type in _ANTHROPIC_SUPPORTED_MEDIA_TYPES else media_type++_MAGIC_MIME_TYPES = ((b"\xff\xd8\xff", "image/jpeg"), ((b"GIF87a", b"GIF89a"), "image/gif"), (b"BM", "image/bmp"),)