utils.py 25 KB

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