|
1 | 1 | """Utility functions for PydanticAI span instrumentation.""" |
2 | 2 |
|
3 | 3 | import sentry_sdk |
| 4 | +from sentry_sdk._types import BLOB_DATA_SUBSTITUTE |
| 5 | +from sentry_sdk.ai.utils import get_modality_from_mime_type |
4 | 6 | from sentry_sdk.consts import SPANDATA |
5 | 7 |
|
| 8 | +from ..consts import DATA_URL_BASE64_REGEX |
| 9 | + |
6 | 10 | from typing import TYPE_CHECKING |
7 | 11 |
|
8 | 12 | if TYPE_CHECKING: |
9 | | - from typing import Union, Dict, Any, List |
| 13 | + from typing import Union, Dict, Any, List, Optional |
10 | 14 | from pydantic_ai.usage import RequestUsage, RunUsage # type: ignore |
11 | 15 |
|
| 16 | +try: |
| 17 | + from pydantic_ai.messages import BinaryContent, ImageUrl # type: ignore |
| 18 | +except ImportError: |
| 19 | + BinaryContent = None |
| 20 | + ImageUrl = None |
| 21 | + |
| 22 | + |
| 23 | +def _serialize_image_url_item(item: "Any") -> "Dict[str, Any]": |
| 24 | + """Serialize an ImageUrl content item for span data. |
| 25 | +
|
| 26 | + For data URLs containing base64-encoded images, the content is redacted. |
| 27 | + For regular HTTP URLs, the URL string is preserved. |
| 28 | + """ |
| 29 | + data_url_matches = DATA_URL_BASE64_REGEX.match(item.url) |
| 30 | + |
| 31 | + if data_url_matches: |
| 32 | + mime_type = data_url_matches[1] or "image" |
| 33 | + return { |
| 34 | + "type": "image", |
| 35 | + "mime_type": mime_type, |
| 36 | + "content": BLOB_DATA_SUBSTITUTE, |
| 37 | + } |
| 38 | + |
| 39 | + return { |
| 40 | + "type": "image", |
| 41 | + "content": str(item.url), |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | +def _serialize_binary_content_item(item: "Any") -> "Dict[str, Any]": |
| 46 | + """Serialize a BinaryContent item for span data, redacting the blob data.""" |
| 47 | + return { |
| 48 | + "type": "blob", |
| 49 | + "modality": get_modality_from_mime_type(item.media_type), |
| 50 | + "mime_type": item.media_type, |
| 51 | + "content": BLOB_DATA_SUBSTITUTE, |
| 52 | + } |
| 53 | + |
12 | 54 |
|
13 | 55 | def _set_usage_data( |
14 | 56 | span: "sentry_sdk.tracing.Span", usage: "Union[RequestUsage, RunUsage]" |
|
0 commit comments