@@ -53,19 +53,17 @@ def _infer_image_mime_type(raw_bytes: bytes | bytearray | None, mime_type: str |
5353 )
5454
5555
56- def _create_image_content (image_content : ImageContent ) -> dict [str , Any ]:
57- """Create an Anthropic image content block from an ImageContent object."""
58- if image_content .uri :
59- uri_str = str (image_content .uri )
60- if uri_str .startswith (("http://" , "https://" )):
61- return {
62- "type" : "image" ,
63- "source" : {
64- "type" : "url" ,
65- "url" : uri_str ,
66- },
67- }
56+ def _has_inline_image_data (image_content : ImageContent ) -> bool :
57+ """Check whether the ImageContent carries inline image data (not just a remote reference)."""
58+ data = image_content .data
59+ if isinstance (data , (bytes , bytearray )):
60+ # BinaryContent defaults data to b"" when only a URI is given.
61+ return len (data ) > 0
62+ return bool (image_content .data_string ) or data is not None
63+
6864
65+ def _create_base64_image_content (image_content : ImageContent ) -> dict [str , Any ]:
66+ """Create an Anthropic base64 image content block from inline image data."""
6967 raw_bytes = image_content .data if isinstance (image_content .data , (bytes , bytearray )) else None
7068 mime_type = _infer_image_mime_type (raw_bytes , image_content .mime_type )
7169
@@ -95,6 +93,33 @@ def _create_image_content(image_content: ImageContent) -> dict[str, Any]:
9593 }
9694
9795
96+ def _create_image_content (image_content : ImageContent ) -> dict [str , Any ]:
97+ """Create an Anthropic image content block from an ImageContent object.
98+
99+ Inline image data takes precedence over a remote URL: per ImageContent's
100+ contract, its URI may refer to different content than its data, so sending
101+ the URL when bytes are available can send the wrong image (or fail for
102+ URLs requiring authentication).
103+ """
104+ if _has_inline_image_data (image_content ):
105+ return _create_base64_image_content (image_content )
106+
107+ if image_content .uri :
108+ uri_str = str (image_content .uri )
109+ if uri_str .startswith (("http://" , "https://" )):
110+ return {
111+ "type" : "image" ,
112+ "source" : {
113+ "type" : "url" ,
114+ "url" : uri_str ,
115+ },
116+ }
117+
118+ raise ServiceInvalidRequestError (
119+ "ImageContent without data, data_uri, or valid http(s) uri while formatting message for Anthropic."
120+ )
121+
122+
98123def _format_user_message (message : ChatMessageContent ) -> dict [str , Any ]:
99124 """Format a user message to the expected object for the Anthropic client.
100125
0 commit comments