|
| 1 | +import json |
| 2 | + |
1 | 3 | import sentry_sdk |
2 | 4 | from sentry_sdk.ai.utils import ( |
| 5 | + normalize_message_roles, |
3 | 6 | set_data_normalized, |
| 7 | + truncate_and_annotate_messages, |
4 | 8 | ) |
5 | 9 | from sentry_sdk.consts import OP, SPANDATA |
6 | 10 | from sentry_sdk.utils import safe_serialize |
|
16 | 20 | get_is_streaming, |
17 | 21 | ) |
18 | 22 | from .utils import ( |
| 23 | + _serialize_binary_content_item, |
| 24 | + _serialize_image_url_item, |
19 | 25 | _set_usage_data, |
20 | 26 | ) |
21 | 27 |
|
22 | 28 | from typing import TYPE_CHECKING |
23 | 29 |
|
24 | 30 | if TYPE_CHECKING: |
25 | | - from typing import Any |
| 31 | + from typing import Any, List, Dict |
| 32 | + from pydantic_ai.messages import ModelMessage, SystemPromptPart # type: ignore |
| 33 | + from sentry_sdk._types import TextPart as SentryTextPart |
26 | 34 |
|
27 | 35 | try: |
28 | | - from pydantic_ai.messages import ( # type: ignore |
| 36 | + from pydantic_ai.messages import ( |
29 | 37 | BaseToolCallPart, |
| 38 | + BaseToolReturnPart, |
| 39 | + SystemPromptPart, |
| 40 | + UserPromptPart, |
30 | 41 | TextPart, |
| 42 | + ThinkingPart, |
| 43 | + BinaryContent, |
| 44 | + ImageUrl, |
31 | 45 | ) |
32 | 46 | except ImportError: |
33 | 47 | # Fallback if these classes are not available |
34 | 48 | BaseToolCallPart = None |
| 49 | + BaseToolReturnPart = None |
| 50 | + SystemPromptPart = None |
| 51 | + UserPromptPart = None |
35 | 52 | TextPart = None |
| 53 | + ThinkingPart = None |
| 54 | + BinaryContent = None |
| 55 | + ImageUrl = None |
| 56 | + |
| 57 | + |
| 58 | +def _transform_system_instructions( |
| 59 | + permanent_instructions: "list[SystemPromptPart]", |
| 60 | + current_instructions: "list[str]", |
| 61 | +) -> "list[SentryTextPart]": |
| 62 | + text_parts: "list[SentryTextPart]" = [ |
| 63 | + { |
| 64 | + "type": "text", |
| 65 | + "content": instruction.content, |
| 66 | + } |
| 67 | + for instruction in permanent_instructions |
| 68 | + ] |
| 69 | + |
| 70 | + text_parts.extend( |
| 71 | + { |
| 72 | + "type": "text", |
| 73 | + "content": instruction, |
| 74 | + } |
| 75 | + for instruction in current_instructions |
| 76 | + ) |
| 77 | + |
| 78 | + return text_parts |
| 79 | + |
| 80 | + |
| 81 | +def _get_system_instructions( |
| 82 | + messages: "list[ModelMessage]", |
| 83 | +) -> "tuple[list[SystemPromptPart], list[str]]": |
| 84 | + permanent_instructions = [] |
| 85 | + current_instructions = [] |
| 86 | + |
| 87 | + for msg in messages: |
| 88 | + if hasattr(msg, "parts"): |
| 89 | + for part in msg.parts: |
| 90 | + if SystemPromptPart and isinstance(part, SystemPromptPart): |
| 91 | + permanent_instructions.append(part) |
| 92 | + |
| 93 | + if hasattr(msg, "instructions") and msg.instructions is not None: |
| 94 | + current_instructions.append(msg.instructions) |
| 95 | + |
| 96 | + return permanent_instructions, current_instructions |
| 97 | + |
| 98 | + |
| 99 | +def _set_input_messages(span: "sentry_sdk.tracing.Span", messages: "Any") -> None: |
| 100 | + """Set input messages data on a span.""" |
| 101 | + if not _should_send_prompts(): |
| 102 | + return |
| 103 | + |
| 104 | + if not messages: |
| 105 | + return |
| 106 | + |
| 107 | + permanent_instructions, current_instructions = _get_system_instructions(messages) |
| 108 | + if len(permanent_instructions) > 0 or len(current_instructions) > 0: |
| 109 | + span.set_data( |
| 110 | + SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS, |
| 111 | + json.dumps( |
| 112 | + _transform_system_instructions( |
| 113 | + permanent_instructions, current_instructions |
| 114 | + ) |
| 115 | + ), |
| 116 | + ) |
| 117 | + |
| 118 | + try: |
| 119 | + formatted_messages = [] |
| 120 | + |
| 121 | + for msg in messages: |
| 122 | + if hasattr(msg, "parts"): |
| 123 | + for part in msg.parts: |
| 124 | + role = "user" |
| 125 | + # Use isinstance checks with proper base classes |
| 126 | + if SystemPromptPart and isinstance(part, SystemPromptPart): |
| 127 | + continue |
| 128 | + elif ( |
| 129 | + (TextPart and isinstance(part, TextPart)) |
| 130 | + or (ThinkingPart and isinstance(part, ThinkingPart)) |
| 131 | + or (BaseToolCallPart and isinstance(part, BaseToolCallPart)) |
| 132 | + ): |
| 133 | + role = "assistant" |
| 134 | + elif BaseToolReturnPart and isinstance(part, BaseToolReturnPart): |
| 135 | + role = "tool" |
| 136 | + |
| 137 | + content: "List[Dict[str, Any] | str]" = [] |
| 138 | + tool_calls = None |
| 139 | + tool_call_id = None |
| 140 | + |
| 141 | + # Handle ToolCallPart (assistant requesting tool use) |
| 142 | + if BaseToolCallPart and isinstance(part, BaseToolCallPart): |
| 143 | + tool_call_data = {} |
| 144 | + if hasattr(part, "tool_name"): |
| 145 | + tool_call_data["name"] = part.tool_name |
| 146 | + if hasattr(part, "args"): |
| 147 | + tool_call_data["arguments"] = safe_serialize(part.args) |
| 148 | + if tool_call_data: |
| 149 | + tool_calls = [tool_call_data] |
| 150 | + # Handle ToolReturnPart (tool result) |
| 151 | + elif BaseToolReturnPart and isinstance(part, BaseToolReturnPart): |
| 152 | + if hasattr(part, "tool_name"): |
| 153 | + tool_call_id = part.tool_name |
| 154 | + if hasattr(part, "content"): |
| 155 | + content.append({"type": "text", "text": str(part.content)}) |
| 156 | + # Handle regular content |
| 157 | + elif hasattr(part, "content"): |
| 158 | + if isinstance(part.content, str): |
| 159 | + content.append({"type": "text", "text": part.content}) |
| 160 | + elif isinstance(part.content, list): |
| 161 | + for item in part.content: |
| 162 | + if isinstance(item, str): |
| 163 | + content.append({"type": "text", "text": item}) |
| 164 | + elif ImageUrl and isinstance(item, ImageUrl): |
| 165 | + content.append(_serialize_image_url_item(item)) |
| 166 | + elif BinaryContent and isinstance(item, BinaryContent): |
| 167 | + content.append(_serialize_binary_content_item(item)) |
| 168 | + else: |
| 169 | + content.append(safe_serialize(item)) |
| 170 | + else: |
| 171 | + content.append({"type": "text", "text": str(part.content)}) |
| 172 | + # Add message if we have content or tool calls |
| 173 | + if content or tool_calls: |
| 174 | + message: "Dict[str, Any]" = {"role": role} |
| 175 | + if content: |
| 176 | + message["content"] = content |
| 177 | + if tool_calls: |
| 178 | + message["tool_calls"] = tool_calls |
| 179 | + if tool_call_id: |
| 180 | + message["tool_call_id"] = tool_call_id |
| 181 | + formatted_messages.append(message) |
| 182 | + |
| 183 | + if formatted_messages: |
| 184 | + normalized_messages = normalize_message_roles(formatted_messages) |
| 185 | + scope = sentry_sdk.get_current_scope() |
| 186 | + messages_data = truncate_and_annotate_messages( |
| 187 | + normalized_messages, span, scope |
| 188 | + ) |
| 189 | + set_data_normalized( |
| 190 | + span, SPANDATA.GEN_AI_REQUEST_MESSAGES, messages_data, unpack=False |
| 191 | + ) |
| 192 | + except Exception: |
| 193 | + # If we fail to format messages, just skip it |
| 194 | + pass |
36 | 195 |
|
37 | 196 |
|
38 | 197 | def _set_output_data(span: "sentry_sdk.tracing.Span", response: "Any") -> None: |
@@ -77,7 +236,7 @@ def _set_output_data(span: "sentry_sdk.tracing.Span", response: "Any") -> None: |
77 | 236 |
|
78 | 237 |
|
79 | 238 | def ai_client_span( |
80 | | - agent: "Any", model: "Any", model_settings: "Any" |
| 239 | + messages: "Any", agent: "Any", model: "Any", model_settings: "Any" |
81 | 240 | ) -> "sentry_sdk.tracing.Span": |
82 | 241 | """Create a span for an AI client call (model request). |
83 | 242 |
|
@@ -112,6 +271,10 @@ def ai_client_span( |
112 | 271 | agent_obj = agent or get_current_agent() |
113 | 272 | _set_available_tools(span, agent_obj) |
114 | 273 |
|
| 274 | + # Set input messages (full conversation history) |
| 275 | + if messages: |
| 276 | + _set_input_messages(span, messages) |
| 277 | + |
115 | 278 | return span |
116 | 279 |
|
117 | 280 |
|
|
0 commit comments