Skip to content

Commit 07e31e0

Browse files
jnishiyamaKludex
andauthored
Update handling of ImageUrl for Anthropic Models to use image URLs not binary content (#1318)
Co-authored-by: Marcelo Trylesinski <[email protected]>
1 parent 776a78d commit 07e31e0

File tree

4 files changed

+31
-946
lines changed

4 files changed

+31
-946
lines changed

pydantic_ai_slim/pydantic_ai/models/anthropic.py

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from __future__ import annotations as _annotations
22

3-
import base64
43
import io
54
from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator
65
from contextlib import asynccontextmanager
@@ -354,48 +353,13 @@ async def _map_user_prompt(
354353
else:
355354
raise RuntimeError('Only images and PDFs are supported for binary content')
356355
elif isinstance(item, ImageUrl):
357-
try:
358-
response = await cached_async_http_client().get(item.url)
359-
response.raise_for_status()
360-
yield ImageBlockParam(
361-
source={
362-
'data': io.BytesIO(response.content),
363-
'media_type': item.media_type,
364-
'type': 'base64',
365-
},
366-
type='image',
367-
)
368-
except ValueError:
369-
# Download the file if can't find the mime type.
370-
client = cached_async_http_client()
371-
response = await client.get(item.url, follow_redirects=True)
372-
response.raise_for_status()
373-
base64_encoded = base64.b64encode(response.content).decode('utf-8')
374-
if (mime_type := response.headers['Content-Type']) in (
375-
'image/jpeg',
376-
'image/png',
377-
'image/gif',
378-
'image/webp',
379-
):
380-
yield ImageBlockParam(
381-
source={'data': base64_encoded, 'media_type': mime_type, 'type': 'base64'},
382-
type='image',
383-
)
384-
else: # pragma: no cover
385-
raise RuntimeError(f'Unsupported image type: {mime_type}')
356+
yield ImageBlockParam(source={'type': 'url', 'url': item.url}, type='image')
386357
elif isinstance(item, DocumentUrl):
387-
response = await cached_async_http_client().get(item.url)
388-
response.raise_for_status()
389358
if item.media_type == 'application/pdf':
390-
yield DocumentBlockParam(
391-
source=Base64PDFSourceParam(
392-
data=io.BytesIO(response.content),
393-
media_type=item.media_type,
394-
type='base64',
395-
),
396-
type='document',
397-
)
359+
yield DocumentBlockParam(source={'url': item.url, 'type': 'url'}, type='document')
398360
elif item.media_type == 'text/plain':
361+
response = await cached_async_http_client().get(item.url)
362+
response.raise_for_status()
399363
yield DocumentBlockParam(
400364
source=PlainTextSourceParam(data=response.text, media_type=item.media_type, type='text'),
401365
type='document',

0 commit comments

Comments
 (0)