1+ from collections .abc import Iterable
12from functools import wraps
23from typing import TYPE_CHECKING
34
45import sentry_sdk
56from sentry_sdk .ai .monitoring import record_token_usage
67from sentry_sdk .ai .utils import (
8+ GEN_AI_ALLOWED_MESSAGE_ROLES ,
79 set_data_normalized ,
810 normalize_message_roles ,
911 truncate_and_annotate_messages ,
3941 raise DidNotEnable ("Anthropic not installed" )
4042
4143if TYPE_CHECKING :
42- from typing import Any , AsyncIterator , Iterator
44+ from typing import Any , AsyncIterator , Iterator , List , Optional , Union
4345 from sentry_sdk .tracing import Span
4446
4547
@@ -122,6 +124,7 @@ def _set_input_data(span, kwargs, integration):
122124 """
123125 Set input data for the span based on the provided keyword arguments for the anthropic message creation.
124126 """
127+ system_prompt = kwargs .get ("system" )
125128 messages = kwargs .get ("messages" )
126129 if (
127130 messages is not None
@@ -130,18 +133,40 @@ def _set_input_data(span, kwargs, integration):
130133 and integration .include_prompts
131134 ):
132135 normalized_messages = []
136+ if system_prompt :
137+ system_prompt_content = None # type: Optional[Union[str, List[dict[str, Any]]]]
138+ if isinstance (system_prompt , str ):
139+ system_prompt_content = system_prompt
140+ elif isinstance (system_prompt , Iterable ):
141+ system_prompt_content = []
142+ for item in system_prompt :
143+ if (
144+ isinstance (item , dict )
145+ and item .get ("type" ) == "text"
146+ and item .get ("text" )
147+ ):
148+ system_prompt_content .append (item .copy ())
149+
150+ if system_prompt_content :
151+ normalized_messages .append (
152+ {
153+ "role" : GEN_AI_ALLOWED_MESSAGE_ROLES .SYSTEM ,
154+ "content" : system_prompt_content ,
155+ }
156+ )
157+
133158 for message in messages :
134159 if (
135- message .get ("role" ) == "user"
160+ message .get ("role" ) == GEN_AI_ALLOWED_MESSAGE_ROLES . USER
136161 and "content" in message
137162 and isinstance (message ["content" ], (list , tuple ))
138163 ):
139164 for item in message ["content" ]:
140165 if item .get ("type" ) == "tool_result" :
141166 normalized_messages .append (
142167 {
143- "role" : "tool" ,
144- "content" : {
168+ "role" : GEN_AI_ALLOWED_MESSAGE_ROLES . TOOL ,
169+ "content" : { # type: ignore[dict-item]
145170 "tool_use_id" : item .get ("tool_use_id" ),
146171 "output" : item .get ("content" ),
147172 },
0 commit comments