Skip to content

Commit af7ca37

Browse files
committed
fix(async): walk native Anthropic image and document URL sources in the remote-media inliner
1 parent 08bb7de commit af7ca37

2 files changed

Lines changed: 78 additions & 6 deletions

File tree

‎litellm/litellm_core_utils/prompt_templates/image_handling.py‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,15 @@ class _RemoteFile:
149149
url: str
150150

151151

152+
@dataclass(frozen=True, slots=True)
153+
class _RemoteAnthropicSource:
154+
part: Mapping[str, object]
155+
url: str
156+
157+
158+
_ANTHROPIC_MEDIA_BLOCK_TYPES: Final = frozenset({"image", "document"})
159+
160+
152161
def _as_mapping(value: object) -> Mapping[str, object] | None:
153162
return value if isinstance(value, Mapping) else None # pyright: ignore[reportUnknownVariableType] # fields are parsed one by one
154163

@@ -157,18 +166,27 @@ def _remote_url(candidate: object) -> str | None:
157166
return candidate if isinstance(candidate, str) and candidate.startswith(_REMOTE_URL_PREFIXES) else None
158167

159168

160-
def _parse_remote_part(part: object) -> _RemoteImage | _RemoteFile | None:
169+
def _parse_remote_part(part: object) -> _RemoteImage | _RemoteFile | _RemoteAnthropicSource | None:
161170
fields: Final = _as_mapping(part)
162171
if fields is None:
163172
return None
164-
if fields.get("type") == "image_url":
173+
part_type: Final = fields.get("type")
174+
if part_type == "image_url":
165175
image_url: Final = fields.get("image_url")
166176
image_url_fields: Final = _as_mapping(image_url)
167177
url: Final = _remote_url(image_url_fields.get("url") if image_url_fields is not None else image_url)
168178
return _RemoteImage(fields, image_url_fields, url) if url is not None else None
169-
file: Final = _as_mapping(fields.get("file")) if fields.get("type") == "file" else None
170-
file_url: Final = _remote_url(file.get("file_id")) if file is not None else None
171-
return _RemoteFile(fields, file, file_url) if file is not None and file_url is not None else None
179+
if part_type == "file":
180+
file: Final = _as_mapping(fields.get("file"))
181+
file_url: Final = _remote_url(file.get("file_id")) if file is not None else None
182+
return _RemoteFile(fields, file, file_url) if file is not None and file_url is not None else None
183+
if part_type in _ANTHROPIC_MEDIA_BLOCK_TYPES:
184+
source: Final = _as_mapping(fields.get("source"))
185+
source_url: Final = (
186+
_remote_url(source.get("url")) if source is not None and source.get("type") == "url" else None
187+
)
188+
return _RemoteAnthropicSource(fields, source_url) if source_url is not None else None
189+
return None
172190

173191

174192
_PDF_FORMAT: Final = MappingProxyType({"format": "application/pdf"})
@@ -187,12 +205,19 @@ def _inlined_file(file: Mapping[str, object], url: str, data_url: str) -> Mappin
187205
return {**kept, **_inferred_format(file, url), "file_data": data_url} # mutable-ok: json-serialized part
188206

189207

190-
def _inline(remote: _RemoteImage | _RemoteFile, data_url: str) -> Mapping[str, object]:
208+
def _inlined_anthropic_source(data_url: str) -> Mapping[str, object]:
209+
media_type, _, data = data_url.removeprefix("data:").partition(";base64,")
210+
return {"type": "base64", "media_type": media_type, "data": data} # mutable-ok: json-serialized source block
211+
212+
213+
def _inline(remote: _RemoteImage | _RemoteFile | _RemoteAnthropicSource, data_url: str) -> Mapping[str, object]:
191214
match remote:
192215
case _RemoteImage(part, image_url, _):
193216
return {**part, "image_url": _inlined_image_url(image_url, data_url)} # mutable-ok: json-serialized part
194217
case _RemoteFile(part, file, url):
195218
return {**part, "file": _inlined_file(file, url, data_url)} # mutable-ok: json-serialized message part
219+
case _RemoteAnthropicSource(part, _):
220+
return {**part, "source": _inlined_anthropic_source(data_url)} # mutable-ok: json-serialized message part
196221

197222

198223
def _content_parts(message: Mapping[str, object]) -> tuple[object, ...]:

‎tests/test_litellm/litellm_core_utils/test_image_handling.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,53 @@ async def test_async_inline_remote_media_leaves_messages_without_remote_parts_al
371371
assert async_only_image_fetch.fetched == []
372372

373373

374+
async def test_async_inline_remote_media_inlines_native_anthropic_url_sources(async_only_image_fetch):
375+
"""Native Anthropic ``image`` / ``document`` blocks with ``source.type=url`` must
376+
also be walked, otherwise their URLs leak past the async inliner and get
377+
fetched by the sync fallback on the event loop (Bedrock invoke) or forwarded
378+
to the provider as-is (Mantle)."""
379+
image_source_url = f"http://img.example/{uuid.uuid4()}.png"
380+
document_source_url = f"http://docs.example/{uuid.uuid4()}.png"
381+
messages = [
382+
{
383+
"role": "user",
384+
"content": [
385+
{"type": "image", "source": {"type": "url", "url": image_source_url}},
386+
{
387+
"type": "document",
388+
"source": {"type": "url", "url": document_source_url},
389+
"title": "Doc",
390+
},
391+
{
392+
"type": "image",
393+
"source": {"type": "base64", "media_type": "image/png", "data": "AAA="},
394+
},
395+
],
396+
}
397+
]
398+
snapshot = copy.deepcopy(messages)
399+
400+
inlined = await async_inline_remote_media(messages)
401+
402+
assert inlined[0]["content"] == [
403+
{
404+
"type": "image",
405+
"source": {"type": "base64", "media_type": "image/png", "data": async_only_image_fetch.base64_png},
406+
},
407+
{
408+
"type": "document",
409+
"source": {"type": "base64", "media_type": "image/png", "data": async_only_image_fetch.base64_png},
410+
"title": "Doc",
411+
},
412+
{
413+
"type": "image",
414+
"source": {"type": "base64", "media_type": "image/png", "data": "AAA="},
415+
},
416+
]
417+
assert sorted(async_only_image_fetch.fetched) == sorted([image_source_url, document_source_url])
418+
assert messages == snapshot
419+
420+
374421
async def test_async_inline_remote_media_raises_image_fetch_error_when_the_fetch_fails(monkeypatch):
375422
async def serve_404(client, url, **kwargs):
376423
return Response(404, request=Request("GET", url))

0 commit comments

Comments
 (0)