utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. import inspect
  2. import json
  3. from collections import deque
  4. from copy import deepcopy
  5. from sys import getsizeof
  6. from typing import TYPE_CHECKING
  7. from sentry_sdk._types import BLOB_DATA_SUBSTITUTE
  8. if TYPE_CHECKING:
  9. from typing import Any, Callable, Dict, List, Optional, Tuple
  10. from sentry_sdk.tracing import Span
  11. import sentry_sdk
  12. from sentry_sdk.utils import logger
  13. MAX_GEN_AI_MESSAGE_BYTES = 20_000 # 20KB
  14. # Maximum characters when only a single message is left after bytes truncation
  15. MAX_SINGLE_MESSAGE_CONTENT_CHARS = 10_000
  16. class GEN_AI_ALLOWED_MESSAGE_ROLES:
  17. SYSTEM = "system"
  18. USER = "user"
  19. ASSISTANT = "assistant"
  20. TOOL = "tool"
  21. GEN_AI_MESSAGE_ROLE_REVERSE_MAPPING = {
  22. GEN_AI_ALLOWED_MESSAGE_ROLES.SYSTEM: ["system"],
  23. GEN_AI_ALLOWED_MESSAGE_ROLES.USER: ["user", "human"],
  24. GEN_AI_ALLOWED_MESSAGE_ROLES.ASSISTANT: ["assistant", "ai"],
  25. GEN_AI_ALLOWED_MESSAGE_ROLES.TOOL: ["tool", "tool_call"],
  26. }
  27. GEN_AI_MESSAGE_ROLE_MAPPING = {}
  28. for target_role, source_roles in GEN_AI_MESSAGE_ROLE_REVERSE_MAPPING.items():
  29. for source_role in source_roles:
  30. GEN_AI_MESSAGE_ROLE_MAPPING[source_role] = target_role
  31. def parse_data_uri(url: str) -> "Tuple[str, str]":
  32. """
  33. Parse a data URI and return (mime_type, content).
  34. Data URI format (RFC 2397): data:[<mediatype>][;base64],<data>
  35. Examples:
  36. data:image/jpeg;base64,/9j/4AAQ... → ("image/jpeg", "/9j/4AAQ...")
  37. data:text/plain,Hello → ("text/plain", "Hello")
  38. data:;base64,SGVsbG8= → ("", "SGVsbG8=")
  39. Raises:
  40. ValueError: If the URL is not a valid data URI (missing comma separator)
  41. """
  42. if "," not in url:
  43. raise ValueError("Invalid data URI: missing comma separator")
  44. header, content = url.split(",", 1)
  45. # Extract mime type from header
  46. # Format: "data:<mime>[;param1][;param2]..." e.g. "data:image/jpeg;base64"
  47. # Remove "data:" prefix, then take everything before the first semicolon
  48. if header.startswith("data:"):
  49. mime_part = header[5:] # Remove "data:" prefix
  50. else:
  51. mime_part = header
  52. mime_type = mime_part.split(";")[0]
  53. return mime_type, content
  54. def get_modality_from_mime_type(mime_type: str) -> str:
  55. """
  56. Infer the content modality from a MIME type string.
  57. Args:
  58. mime_type: A MIME type string (e.g., "image/jpeg", "audio/mp3")
  59. Returns:
  60. One of: "image", "audio", "video", or "document"
  61. Defaults to "image" for unknown or empty MIME types.
  62. Examples:
  63. "image/jpeg" -> "image"
  64. "audio/mp3" -> "audio"
  65. "video/mp4" -> "video"
  66. "application/pdf" -> "document"
  67. "text/plain" -> "document"
  68. """
  69. if not mime_type:
  70. return "image" # Default fallback
  71. mime_lower = mime_type.lower()
  72. if mime_lower.startswith("image/"):
  73. return "image"
  74. elif mime_lower.startswith("audio/"):
  75. return "audio"
  76. elif mime_lower.startswith("video/"):
  77. return "video"
  78. elif mime_lower.startswith("application/") or mime_lower.startswith("text/"):
  79. return "document"
  80. else:
  81. return "image" # Default fallback for unknown types
  82. def transform_openai_content_part(
  83. content_part: "Dict[str, Any]",
  84. ) -> "Optional[Dict[str, Any]]":
  85. """
  86. Transform an OpenAI/LiteLLM content part to Sentry's standardized format.
  87. This handles the OpenAI image_url format used by OpenAI and LiteLLM SDKs.
  88. Input format:
  89. - {"type": "image_url", "image_url": {"url": "..."}}
  90. - {"type": "image_url", "image_url": "..."} (string shorthand)
  91. Output format (one of):
  92. - {"type": "blob", "modality": "image", "mime_type": "...", "content": "..."}
  93. - {"type": "uri", "modality": "image", "mime_type": "", "uri": "..."}
  94. Args:
  95. content_part: A dictionary representing a content part from OpenAI/LiteLLM
  96. Returns:
  97. A transformed dictionary in standardized format, or None if the format
  98. is not OpenAI image_url format or transformation fails.
  99. """
  100. if not isinstance(content_part, dict):
  101. return None
  102. block_type = content_part.get("type")
  103. if block_type != "image_url":
  104. return None
  105. image_url_data = content_part.get("image_url")
  106. if isinstance(image_url_data, str):
  107. url = image_url_data
  108. elif isinstance(image_url_data, dict):
  109. url = image_url_data.get("url", "")
  110. else:
  111. return None
  112. if not url:
  113. return None
  114. # Check if it's a data URI (base64 encoded)
  115. if url.startswith("data:"):
  116. try:
  117. mime_type, content = parse_data_uri(url)
  118. return {
  119. "type": "blob",
  120. "modality": get_modality_from_mime_type(mime_type),
  121. "mime_type": mime_type,
  122. "content": content,
  123. }
  124. except ValueError:
  125. # If parsing fails, return as URI
  126. return {
  127. "type": "uri",
  128. "modality": "image",
  129. "mime_type": "",
  130. "uri": url,
  131. }
  132. else:
  133. # Regular URL
  134. return {
  135. "type": "uri",
  136. "modality": "image",
  137. "mime_type": "",
  138. "uri": url,
  139. }
  140. def transform_anthropic_content_part(
  141. content_part: "Dict[str, Any]",
  142. ) -> "Optional[Dict[str, Any]]":
  143. """
  144. Transform an Anthropic content part to Sentry's standardized format.
  145. This handles the Anthropic image and document formats with source dictionaries.
  146. Input format:
  147. - {"type": "image", "source": {"type": "base64", "media_type": "...", "data": "..."}}
  148. - {"type": "image", "source": {"type": "url", "media_type": "...", "url": "..."}}
  149. - {"type": "image", "source": {"type": "file", "media_type": "...", "file_id": "..."}}
  150. - {"type": "document", "source": {...}} (same source formats)
  151. Output format (one of):
  152. - {"type": "blob", "modality": "...", "mime_type": "...", "content": "..."}
  153. - {"type": "uri", "modality": "...", "mime_type": "...", "uri": "..."}
  154. - {"type": "file", "modality": "...", "mime_type": "...", "file_id": "..."}
  155. Args:
  156. content_part: A dictionary representing a content part from Anthropic
  157. Returns:
  158. A transformed dictionary in standardized format, or None if the format
  159. is not Anthropic format or transformation fails.
  160. """
  161. if not isinstance(content_part, dict):
  162. return None
  163. block_type = content_part.get("type")
  164. if block_type not in ("image", "document") or "source" not in content_part:
  165. return None
  166. source = content_part.get("source")
  167. if not isinstance(source, dict):
  168. return None
  169. source_type = source.get("type")
  170. media_type = source.get("media_type", "")
  171. modality = (
  172. "document"
  173. if block_type == "document"
  174. else get_modality_from_mime_type(media_type)
  175. )
  176. if source_type == "base64":
  177. return {
  178. "type": "blob",
  179. "modality": modality,
  180. "mime_type": media_type,
  181. "content": source.get("data", ""),
  182. }
  183. elif source_type == "url":
  184. return {
  185. "type": "uri",
  186. "modality": modality,
  187. "mime_type": media_type,
  188. "uri": source.get("url", ""),
  189. }
  190. elif source_type == "file":
  191. return {
  192. "type": "file",
  193. "modality": modality,
  194. "mime_type": media_type,
  195. "file_id": source.get("file_id", ""),
  196. }
  197. return None
  198. def transform_google_content_part(
  199. content_part: "Dict[str, Any]",
  200. ) -> "Optional[Dict[str, Any]]":
  201. """
  202. Transform a Google GenAI content part to Sentry's standardized format.
  203. This handles the Google GenAI inline_data and file_data formats.
  204. Input format:
  205. - {"inline_data": {"mime_type": "...", "data": "..."}}
  206. - {"file_data": {"mime_type": "...", "file_uri": "..."}}
  207. Output format (one of):
  208. - {"type": "blob", "modality": "...", "mime_type": "...", "content": "..."}
  209. - {"type": "uri", "modality": "...", "mime_type": "...", "uri": "..."}
  210. Args:
  211. content_part: A dictionary representing a content part from Google GenAI
  212. Returns:
  213. A transformed dictionary in standardized format, or None if the format
  214. is not Google format or transformation fails.
  215. """
  216. if not isinstance(content_part, dict):
  217. return None
  218. # Handle Google inline_data format
  219. if "inline_data" in content_part:
  220. inline_data = content_part.get("inline_data")
  221. if isinstance(inline_data, dict):
  222. mime_type = inline_data.get("mime_type", "")
  223. return {
  224. "type": "blob",
  225. "modality": get_modality_from_mime_type(mime_type),
  226. "mime_type": mime_type,
  227. "content": inline_data.get("data", ""),
  228. }
  229. return None
  230. # Handle Google file_data format
  231. if "file_data" in content_part:
  232. file_data = content_part.get("file_data")
  233. if isinstance(file_data, dict):
  234. mime_type = file_data.get("mime_type", "")
  235. return {
  236. "type": "uri",
  237. "modality": get_modality_from_mime_type(mime_type),
  238. "mime_type": mime_type,
  239. "uri": file_data.get("file_uri", ""),
  240. }
  241. return None
  242. return None
  243. def transform_generic_content_part(
  244. content_part: "Dict[str, Any]",
  245. ) -> "Optional[Dict[str, Any]]":
  246. """
  247. Transform a generic/LangChain-style content part to Sentry's standardized format.
  248. This handles generic formats where the type indicates the modality and
  249. the data is provided via direct base64, url, or file_id fields.
  250. Input format:
  251. - {"type": "image", "base64": "...", "mime_type": "..."}
  252. - {"type": "audio", "url": "...", "mime_type": "..."}
  253. - {"type": "video", "base64": "...", "mime_type": "..."}
  254. - {"type": "file", "file_id": "...", "mime_type": "..."}
  255. Output format (one of):
  256. - {"type": "blob", "modality": "...", "mime_type": "...", "content": "..."}
  257. - {"type": "uri", "modality": "...", "mime_type": "...", "uri": "..."}
  258. - {"type": "file", "modality": "...", "mime_type": "...", "file_id": "..."}
  259. Args:
  260. content_part: A dictionary representing a content part in generic format
  261. Returns:
  262. A transformed dictionary in standardized format, or None if the format
  263. is not generic format or transformation fails.
  264. """
  265. if not isinstance(content_part, dict):
  266. return None
  267. block_type = content_part.get("type")
  268. if block_type not in ("image", "audio", "video", "file"):
  269. return None
  270. # Ensure it's not Anthropic format (which also uses type: "image")
  271. if "source" in content_part:
  272. return None
  273. mime_type = content_part.get("mime_type", "")
  274. modality = block_type if block_type != "file" else "document"
  275. # Check for base64 encoded content
  276. if "base64" in content_part:
  277. return {
  278. "type": "blob",
  279. "modality": modality,
  280. "mime_type": mime_type,
  281. "content": content_part.get("base64", ""),
  282. }
  283. # Check for URL reference
  284. elif "url" in content_part:
  285. return {
  286. "type": "uri",
  287. "modality": modality,
  288. "mime_type": mime_type,
  289. "uri": content_part.get("url", ""),
  290. }
  291. # Check for file_id reference
  292. elif "file_id" in content_part:
  293. return {
  294. "type": "file",
  295. "modality": modality,
  296. "mime_type": mime_type,
  297. "file_id": content_part.get("file_id", ""),
  298. }
  299. return None
  300. def transform_content_part(
  301. content_part: "Dict[str, Any]",
  302. ) -> "Optional[Dict[str, Any]]":
  303. """
  304. Transform a content part from various AI SDK formats to Sentry's standardized format.
  305. This is a heuristic dispatcher that detects the format and delegates to the
  306. appropriate SDK-specific transformer. For direct SDK integration, prefer using
  307. the specific transformers directly:
  308. - transform_openai_content_part() for OpenAI/LiteLLM
  309. - transform_anthropic_content_part() for Anthropic
  310. - transform_google_content_part() for Google GenAI
  311. - transform_generic_content_part() for LangChain and other generic formats
  312. Detection order:
  313. 1. OpenAI: type == "image_url"
  314. 2. Google: "inline_data" or "file_data" keys present
  315. 3. Anthropic: type in ("image", "document") with "source" key
  316. 4. Generic: type in ("image", "audio", "video", "file") with base64/url/file_id
  317. Output format (one of):
  318. - {"type": "blob", "modality": "...", "mime_type": "...", "content": "..."}
  319. - {"type": "uri", "modality": "...", "mime_type": "...", "uri": "..."}
  320. - {"type": "file", "modality": "...", "mime_type": "...", "file_id": "..."}
  321. Args:
  322. content_part: A dictionary representing a content part from an AI SDK
  323. Returns:
  324. A transformed dictionary in standardized format, or None if the format
  325. is unrecognized or transformation fails.
  326. """
  327. if not isinstance(content_part, dict):
  328. return None
  329. # Try OpenAI format first (most common, clear indicator)
  330. result = transform_openai_content_part(content_part)
  331. if result is not None:
  332. return result
  333. # Try Google format (unique keys make it easy to detect)
  334. result = transform_google_content_part(content_part)
  335. if result is not None:
  336. return result
  337. # Try Anthropic format (has "source" key)
  338. result = transform_anthropic_content_part(content_part)
  339. if result is not None:
  340. return result
  341. # Try generic format as fallback
  342. result = transform_generic_content_part(content_part)
  343. if result is not None:
  344. return result
  345. # Unrecognized format
  346. return None
  347. def transform_message_content(content: "Any") -> "Any":
  348. """
  349. Transform message content, handling both string content and list of content blocks.
  350. For list content, each item is transformed using transform_content_part().
  351. Items that cannot be transformed (return None) are kept as-is.
  352. Args:
  353. content: Message content - can be a string, list of content blocks, or other
  354. Returns:
  355. - String content: returned as-is
  356. - List content: list with each transformable item converted to standardized format
  357. - Other: returned as-is
  358. """
  359. if isinstance(content, str):
  360. return content
  361. if isinstance(content, (list, tuple)):
  362. transformed = []
  363. for item in content:
  364. if isinstance(item, dict):
  365. result = transform_content_part(item)
  366. # If transformation succeeded, use the result; otherwise keep original
  367. transformed.append(result if result is not None else item)
  368. else:
  369. transformed.append(item)
  370. return transformed
  371. return content
  372. def _normalize_data(data: "Any", unpack: bool = True) -> "Any":
  373. # convert pydantic data (e.g. OpenAI v1+) to json compatible format
  374. if hasattr(data, "model_dump"):
  375. # Check if it's a class (type) rather than an instance
  376. # Model classes can be passed as arguments (e.g., for schema definitions)
  377. if inspect.isclass(data):
  378. return f"<ClassType: {data.__name__}>"
  379. try:
  380. return _normalize_data(data.model_dump(), unpack=unpack)
  381. except Exception as e:
  382. logger.warning("Could not convert pydantic data to JSON: %s", e)
  383. return data if isinstance(data, (int, float, bool, str)) else str(data)
  384. if isinstance(data, list):
  385. if unpack and len(data) == 1:
  386. return _normalize_data(data[0], unpack=unpack) # remove empty dimensions
  387. return list(_normalize_data(x, unpack=unpack) for x in data)
  388. if isinstance(data, dict):
  389. return {k: _normalize_data(v, unpack=unpack) for (k, v) in data.items()}
  390. return data if isinstance(data, (int, float, bool, str)) else str(data)
  391. def set_data_normalized(
  392. span: "Span", key: str, value: "Any", unpack: bool = True
  393. ) -> None:
  394. normalized = _normalize_data(value, unpack=unpack)
  395. if isinstance(normalized, (int, float, bool, str)):
  396. span.set_data(key, normalized)
  397. else:
  398. span.set_data(key, json.dumps(normalized))
  399. def normalize_message_role(role: str) -> str:
  400. """
  401. Normalize a message role to one of the 4 allowed gen_ai role values.
  402. Maps "ai" -> "assistant" and keeps other standard roles unchanged.
  403. """
  404. return GEN_AI_MESSAGE_ROLE_MAPPING.get(role, role)
  405. def normalize_message_roles(messages: "list[dict[str, Any]]") -> "list[dict[str, Any]]":
  406. """
  407. Normalize roles in a list of messages to use standard gen_ai role values.
  408. Creates a deep copy to avoid modifying the original messages.
  409. """
  410. normalized_messages = []
  411. for message in messages:
  412. if not isinstance(message, dict):
  413. normalized_messages.append(message)
  414. continue
  415. normalized_message = message.copy()
  416. if "role" in message:
  417. normalized_message["role"] = normalize_message_role(message["role"])
  418. normalized_messages.append(normalized_message)
  419. return normalized_messages
  420. def get_start_span_function() -> "Callable[..., Any]":
  421. current_span = sentry_sdk.get_current_span()
  422. transaction_exists = (
  423. current_span is not None and current_span.containing_transaction is not None
  424. )
  425. return sentry_sdk.start_span if transaction_exists else sentry_sdk.start_transaction
  426. def _truncate_single_message_content_if_present(
  427. message: "Dict[str, Any]", max_chars: int
  428. ) -> "Dict[str, Any]":
  429. """
  430. Truncate a message's content to at most `max_chars` characters and append an
  431. ellipsis if truncation occurs.
  432. """
  433. if not isinstance(message, dict) or "content" not in message:
  434. return message
  435. content = message["content"]
  436. if not isinstance(content, str) or len(content) <= max_chars:
  437. return message
  438. message["content"] = content[:max_chars] + "..."
  439. return message
  440. def _find_truncation_index(messages: "List[Dict[str, Any]]", max_bytes: int) -> int:
  441. """
  442. Find the index of the first message that would exceed the max bytes limit.
  443. Compute the individual message sizes, and return the index of the first message from the back
  444. of the list that would exceed the max bytes limit.
  445. """
  446. running_sum = 0
  447. for idx in range(len(messages) - 1, -1, -1):
  448. size = len(json.dumps(messages[idx], separators=(",", ":")).encode("utf-8"))
  449. running_sum += size
  450. if running_sum > max_bytes:
  451. return idx + 1
  452. return 0
  453. def redact_blob_message_parts(
  454. messages: "List[Dict[str, Any]]",
  455. ) -> "List[Dict[str, Any]]":
  456. """
  457. Redact blob message parts from the messages by replacing blob content with "[Filtered]".
  458. This function creates a deep copy of messages that contain blob content to avoid
  459. mutating the original message dictionaries. Messages without blob content are
  460. returned as-is to minimize copying overhead.
  461. e.g:
  462. {
  463. "role": "user",
  464. "content": [
  465. {
  466. "text": "How many ponies do you see in the image?",
  467. "type": "text"
  468. },
  469. {
  470. "type": "blob",
  471. "modality": "image",
  472. "mime_type": "image/jpeg",
  473. "content": "data:image/jpeg;base64,..."
  474. }
  475. ]
  476. }
  477. becomes:
  478. {
  479. "role": "user",
  480. "content": [
  481. {
  482. "text": "How many ponies do you see in the image?",
  483. "type": "text"
  484. },
  485. {
  486. "type": "blob",
  487. "modality": "image",
  488. "mime_type": "image/jpeg",
  489. "content": "[Filtered]"
  490. }
  491. ]
  492. }
  493. """
  494. # First pass: check if any message contains blob content
  495. has_blobs = False
  496. for message in messages:
  497. if not isinstance(message, dict):
  498. continue
  499. content = message.get("content")
  500. if isinstance(content, list):
  501. for item in content:
  502. if isinstance(item, dict) and item.get("type") == "blob":
  503. has_blobs = True
  504. break
  505. if has_blobs:
  506. break
  507. # If no blobs found, return original messages to avoid unnecessary copying
  508. if not has_blobs:
  509. return messages
  510. # Deep copy messages to avoid mutating the original
  511. messages_copy = deepcopy(messages)
  512. # Second pass: redact blob content in the copy
  513. for message in messages_copy:
  514. if not isinstance(message, dict):
  515. continue
  516. content = message.get("content")
  517. if isinstance(content, list):
  518. for item in content:
  519. if isinstance(item, dict) and item.get("type") == "blob":
  520. item["content"] = BLOB_DATA_SUBSTITUTE
  521. return messages_copy
  522. def truncate_messages_by_size(
  523. messages: "List[Dict[str, Any]]",
  524. max_bytes: int = MAX_GEN_AI_MESSAGE_BYTES,
  525. max_single_message_chars: int = MAX_SINGLE_MESSAGE_CONTENT_CHARS,
  526. ) -> "Tuple[List[Dict[str, Any]], int]":
  527. """
  528. Returns a truncated messages list, consisting of
  529. - the last message, with its content truncated to `max_single_message_chars` characters,
  530. if the last message's size exceeds `max_bytes` bytes; otherwise,
  531. - the maximum number of messages, starting from the end of the `messages` list, whose total
  532. serialized size does not exceed `max_bytes` bytes.
  533. In the single message case, the serialized message size may exceed `max_bytes`, because
  534. truncation is based only on character count in that case.
  535. """
  536. serialized_json = json.dumps(messages, separators=(",", ":"))
  537. current_size = len(serialized_json.encode("utf-8"))
  538. if current_size <= max_bytes:
  539. return messages, 0
  540. truncation_index = _find_truncation_index(messages, max_bytes)
  541. if truncation_index < len(messages):
  542. truncated_messages = messages[truncation_index:]
  543. else:
  544. truncation_index = len(messages) - 1
  545. truncated_messages = messages[-1:]
  546. if len(truncated_messages) == 1:
  547. truncated_messages[0] = _truncate_single_message_content_if_present(
  548. deepcopy(truncated_messages[0]), max_chars=max_single_message_chars
  549. )
  550. return truncated_messages, truncation_index
  551. def truncate_and_annotate_messages(
  552. messages: "Optional[List[Dict[str, Any]]]",
  553. span: "Any",
  554. scope: "Any",
  555. max_bytes: int = MAX_GEN_AI_MESSAGE_BYTES,
  556. ) -> "Optional[List[Dict[str, Any]]]":
  557. if not messages:
  558. return None
  559. messages = redact_blob_message_parts(messages)
  560. truncated_messages, removed_count = truncate_messages_by_size(messages, max_bytes)
  561. if removed_count > 0:
  562. scope._gen_ai_original_message_count[span.span_id] = len(messages)
  563. return truncated_messages