16
16
from opentelemetry .trace import SpanKind , Span
17
17
from opentelemetry .trace .status import Status , StatusCode
18
18
from .span_attributes import LLMSpanAttributes
19
+ from opentelemetry .semconv .attributes import (
20
+ error_attributes as ErrorAttributes ,
21
+ )
19
22
from opentelemetry .semconv ._incubating .attributes import (
20
23
gen_ai_attributes as GenAIAttributes ,
21
- error_attributes as ErrorAttributes ,
22
24
)
23
25
from .utils import (
24
26
silently_fail ,
28
30
set_span_attribute ,
29
31
set_event_completion ,
30
32
extract_tools_prompt ,
33
+ set_event_prompt ,
31
34
)
32
35
from opentelemetry .trace import Tracer
36
+ import json
33
37
34
38
35
39
def chat_completions_create (tracer : Tracer ):
@@ -43,16 +47,15 @@ def traced_method(wrapped, instance, args, kwargs):
43
47
tools_prompt = extract_tools_prompt (item )
44
48
llm_prompts .append (tools_prompt if tools_prompt else item )
45
49
46
- span_attributes = {
47
- ** get_llm_request_attributes (kwargs , prompts = llm_prompts ),
48
- }
50
+ span_attributes = {** get_llm_request_attributes (kwargs )}
49
51
50
52
attributes = LLMSpanAttributes (** span_attributes )
51
53
52
54
span_name = f"{ attributes .gen_ai_operation_name } { attributes .gen_ai_request_model } "
53
55
54
56
span = tracer .start_span (name = span_name , kind = SpanKind .CLIENT )
55
57
_set_input_attributes (span , attributes )
58
+ set_event_prompt (span , json .dumps (llm_prompts ))
56
59
57
60
try :
58
61
result = wrapped (* args , ** kwargs )
@@ -112,13 +115,15 @@ def _set_response_attributes(span, result):
112
115
}
113
116
for choice in choices
114
117
]
118
+ finish_reasons = []
115
119
for choice in choices :
116
- if choice .finish_reason :
117
- set_span_attribute (
118
- span ,
119
- GenAIAttributes .GEN_AI_RESPONSE_FINISH_REASONS ,
120
- choice .finish_reason ,
121
- )
120
+ finish_reasons .append (choice .finish_reason or "error" )
121
+
122
+ set_span_attribute (
123
+ span ,
124
+ GenAIAttributes .GEN_AI_RESPONSE_FINISH_REASONS ,
125
+ finish_reasons ,
126
+ )
122
127
set_event_completion (span , responses )
123
128
124
129
if getattr (result , "id" , None ):
@@ -270,14 +275,15 @@ def build_streaming_response(self, chunk):
270
275
):
271
276
content .append (tool_call .function .arguments )
272
277
278
+ finish_reasons = []
273
279
for choice in choices :
274
- finish_reason = choice .finish_reason
275
- if finish_reason :
276
- set_span_attribute (
277
- self .span ,
278
- GenAIAttributes .GEN_AI_RESPONSE_FINISH_REASONS ,
279
- finish_reason ,
280
- )
280
+ finish_reasons . append ( choice .finish_reason or "error" )
281
+
282
+ set_span_attribute (
283
+ self .span ,
284
+ GenAIAttributes .GEN_AI_RESPONSE_FINISH_REASONS ,
285
+ finish_reasons ,
286
+ )
281
287
if content :
282
288
self .result_content .append (content [0 ])
283
289
0 commit comments