Skip to content

Commit 3e61f1c

Browse files
committed
openai: pass the context when contructing the event from stream choices
Pass the full context instead of the deprecated trace_id, span_id and trace_flags.
1 parent 70d798a commit 3e61f1c

File tree

1 file changed

+6
-12
lines changed
  • instrumentation/elastic-opentelemetry-instrumentation-openai/src/opentelemetry/instrumentation/openai

1 file changed

+6
-12
lines changed

instrumentation/elastic-opentelemetry-instrumentation-openai/src/opentelemetry/instrumentation/openai/helpers.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@
1818
from timeit import default_timer
1919
from typing import TYPE_CHECKING, Optional
2020

21+
from opentelemetry import context
2122
from opentelemetry._logs import Logger, LogRecord
23+
from opentelemetry.metrics import Histogram
2224
from opentelemetry.semconv._incubating.attributes.gen_ai_attributes import (
2325
GEN_AI_OPENAI_REQUEST_SERVICE_TIER,
2426
GEN_AI_OPENAI_RESPONSE_SERVICE_TIER,
2527
GEN_AI_OPERATION_NAME,
2628
GEN_AI_OUTPUT_TYPE,
2729
GEN_AI_REQUEST_CHOICE_COUNT,
30+
GEN_AI_REQUEST_ENCODING_FORMATS,
2831
GEN_AI_REQUEST_FREQUENCY_PENALTY,
2932
GEN_AI_REQUEST_MAX_TOKENS,
3033
GEN_AI_REQUEST_MODEL,
@@ -43,15 +46,8 @@
4346
)
4447
from opentelemetry.semconv.attributes.error_attributes import ERROR_TYPE
4548
from opentelemetry.semconv.attributes.server_attributes import SERVER_ADDRESS, SERVER_PORT
46-
47-
try:
48-
from opentelemetry.semconv._incubating.attributes.gen_ai_attributes import GEN_AI_REQUEST_ENCODING_FORMATS
49-
except ImportError:
50-
# available since 1.29.0
51-
GEN_AI_REQUEST_ENCODING_FORMATS = "gen_ai.request.encoding_formats"
52-
53-
from opentelemetry.metrics import Histogram
5449
from opentelemetry.trace import Span
50+
from opentelemetry.trace.propagation import set_span_in_context
5551
from opentelemetry.util.types import Attributes
5652

5753
EVENT_GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"
@@ -380,15 +376,13 @@ def _send_logs_from_stream_choices(
380376
"message": message,
381377
}
382378
# StreamWrapper is consumed after start_as_current_span exits, so capture the current span
383-
ctx = span.get_span_context()
379+
ctx = set_span_in_context(span, context.get_current())
384380
# keep compat on the exported attributes with Event
385381
log = LogRecord(
386382
event_name=EVENT_GEN_AI_CHOICE,
387383
body=body,
388384
attributes={**attributes, "event.name": EVENT_GEN_AI_CHOICE},
389-
trace_id=ctx.trace_id,
390-
span_id=ctx.span_id,
391-
trace_flags=ctx.trace_flags,
385+
context=ctx,
392386
)
393387
logger.emit(log)
394388

0 commit comments

Comments
 (0)