2727 get_llm_url ,
2828 get_span_name ,
2929 set_event_completion ,
30- set_event_completion_chunk ,
3130 set_usage_attributes ,
32- set_span_attribute
31+ set_span_attribute ,
3332)
3433from opentelemetry .trace import Span , Tracer , SpanKind
3534from opentelemetry .trace .status import StatusCode
36- from src .langtrace_python_sdk .constants .instrumentation .anthropic import APIS
37- from src .langtrace_python_sdk .constants .instrumentation .common import SERVICE_PROVIDERS
38- from src .langtrace_python_sdk .instrumentation .anthropic .types import StreamingResult , ResultType , MessagesCreateKwargs , ContentItem , Usage
39-
40- def handle_streaming_response (result : StreamingResult , span : Span ) -> Iterator [str ]:
41- result_content : List [str ] = []
42- span .add_event (Event .STREAM_START .value )
43- input_tokens : int = 0
44- output_tokens : int = 0
45- try :
46- for chunk in result :
47- if chunk ['message' ]["model" ] is not None :
48- span .set_attribute (
49- SpanAttributes .LLM_RESPONSE_MODEL , chunk ["message" ]["model" ]
50- )
51- content : str = ""
52- if chunk ["delta" ].get ("text" ) is not None :
53- content = chunk ["delta" ]["text" ] or ""
54- result_content .append (content if len (content ) > 0 else "" )
55-
56- if chunk ["message" ]["usage" ] is not None :
57- usage = chunk ["message" ]["usage" ]
58- input_tokens += usage .get ("input_tokens" , 0 )
59- output_tokens += usage .get ("output_tokens" , 0 )
60-
61- if content :
62- set_event_completion_chunk (span , "" .join (content ))
63-
64- yield content
65- finally :
66- span .add_event (Event .STREAM_END .value )
67- set_usage_attributes (
68- span , {"input_tokens" : input_tokens , "output_tokens" : output_tokens }
69- )
70- completion : List [Dict [str , str ]] = [{"role" : "assistant" , "content" : "" .join (result_content )}]
71- set_event_completion (span , completion )
35+ from langtrace_python_sdk .constants .instrumentation .anthropic import APIS
36+ from langtrace_python_sdk .constants .instrumentation .common import SERVICE_PROVIDERS
37+ from langtrace_python_sdk .instrumentation .anthropic .types import (
38+ StreamingResult ,
39+ ResultType ,
40+ MessagesCreateKwargs ,
41+ ContentItem ,
42+ Usage ,
43+ )
7244
73- span .set_status (StatusCode .OK )
74- span .end ()
7545
7646def messages_create (version : str , tracer : Tracer ) -> Callable [..., Any ]:
7747 """Wrap the `messages_create` method."""
7848
79- def traced_method (wrapped : Callable [..., Any ], instance : Any , args : List [Any ], kwargs : MessagesCreateKwargs ) -> Any :
49+ def traced_method (
50+ wrapped : Callable [..., Any ],
51+ instance : Any ,
52+ args : List [Any ],
53+ kwargs : MessagesCreateKwargs ,
54+ ) -> Any :
8055 service_provider = SERVICE_PROVIDERS ["ANTHROPIC" ]
8156
8257 # Extract system from kwargs and attach as a role to the prompts
8358 prompts = kwargs .get ("messages" , [])
8459 system = kwargs .get ("system" )
8560 if system :
86- prompts = [{"role" : "system" , "content" : system }] + kwargs .get ("messages" , [])
61+ prompts = [{"role" : "system" , "content" : system }] + kwargs .get (
62+ "messages" , []
63+ )
8764 extraAttributes = get_extra_attributes ()
8865 span_attributes = {
8966 ** get_langtrace_attributes (version , service_provider ),
9067 ** get_llm_request_attributes (kwargs , prompts = prompts ),
9168 ** get_llm_url (instance ),
9269 SpanAttributes .LLM_PATH : APIS ["MESSAGES_CREATE" ]["ENDPOINT" ],
93- ** extraAttributes ,
70+ ** extraAttributes , # type: ignore
9471 }
9572
9673 attributes = LLMSpanAttributes (** span_attributes )
@@ -103,7 +80,7 @@ def traced_method(wrapped: Callable[..., Any], instance: Any, args: List[Any], k
10380 try :
10481 # Attempt to call the original method
10582 result = wrapped (* args , ** kwargs )
106- return set_response_attributes (result , span , kwargs )
83+ return set_response_attributes (result , span )
10784
10885 except Exception as err :
10986 # Record the exception in the span
@@ -114,77 +91,36 @@ def traced_method(wrapped: Callable[..., Any], instance: Any, args: List[Any], k
11491 span .end ()
11592 raise
11693
117- def handle_streaming_response (result : StreamingResult , span : Span ) -> Iterator [str ]:
118- """Process and yield streaming response chunks."""
119- result_content : List [str ] = []
120- span .add_event (Event .STREAM_START .value )
121- input_tokens : int = 0
122- output_tokens : int = 0
123- try :
124- for chunk in result :
125- span .set_attribute (
126- SpanAttributes .LLM_RESPONSE_MODEL , chunk ["message" ]["model" ] or ""
127- )
128- content : str = ""
129- if hasattr (chunk , "delta" ) and chunk ["delta" ] is not None :
130- content = chunk ["delta" ]["text" ] or ""
131- result_content .append (content if len (content ) > 0 else "" )
132- if chunk ["message" ]["usage" ] is not None :
133- input_tokens += (
134- chunk ["message" ]["usage" ]["input_tokens" ]
135- if hasattr (chunk ["message" ]["usage" ], "input_tokens" )
136- else 0
137- )
138- output_tokens += (
139- chunk ["message" ]["usage" ]["output_tokens" ]
140- if hasattr (chunk ["message" ]["usage" ], "output_tokens" )
141- else 0
142- )
143-
144- if content :
145- set_event_completion_chunk (span , "" .join (content ))
146-
147- yield content
148- finally :
149- span .add_event (Event .STREAM_END .value )
150- set_usage_attributes (
151- span , {"input_tokens" : input_tokens , "output_tokens" : output_tokens }
152- )
153- completion = [{"role" : "assistant" , "content" : "" .join (result_content )}]
154- set_event_completion (span , completion )
155-
156- span .set_status (StatusCode .OK )
157- span .end ()
158-
159- def set_response_attributes (result : Union [ResultType , StreamingResult ], span : Span , kwargs : MessagesCreateKwargs ) -> Any :
94+ def set_response_attributes (
95+ result : Union [ResultType , StreamingResult ], span : Span
96+ ) -> Any :
16097 if not isinstance (result , Iterator ):
161- if result [ "content" ] is not None :
98+ if hasattr ( result , "content" ) and result . content is not None :
16299 set_span_attribute (
163- span , SpanAttributes .LLM_RESPONSE_MODEL , result [ " model" ]
100+ span , SpanAttributes .LLM_RESPONSE_MODEL , result . model
164101 )
165- content_item = result [ " content" ] [0 ]
166- completion : List [ ContentItem ] = [
102+ content_item = result . content [0 ]
103+ completion = [
167104 {
168- "role" : result [ " role" ] or "assistant" ,
169- "content" : content_item .get ( " text" , "" ) ,
170- "type" : content_item .get ( " type" , "" ) ,
105+ "role" : result . role or "assistant" ,
106+ "content" : content_item .text ,
107+ "type" : content_item .type ,
171108 }
172109 ]
173110 set_event_completion (span , completion )
174111
175- else :
176- responses : List [ContentItem ] = []
177- set_event_completion (span , responses )
178-
179- if result ["system_fingerprint" ] is not None :
112+ if (
113+ hasattr (result , "system_fingerprint" )
114+ and result .system_fingerprint is not None
115+ ):
180116 span .set_attribute (
181117 SpanAttributes .LLM_SYSTEM_FINGERPRINT ,
182- result [ " system_fingerprint" ] ,
118+ result . system_fingerprint ,
183119 )
184120 # Get the usage
185- if result [ "usage" ] is not None :
186- usage : Usage = result [ " usage" ]
187- set_usage_attributes (span , dict (usage ))
121+ if hasattr ( result , "usage" ) and result . usage is not None :
122+ usage = result . usage
123+ set_usage_attributes (span , vars (usage ))
188124
189125 span .set_status (StatusCode .OK )
190126 span .end ()
0 commit comments