|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +Telemetry handler for GenAI invocations. |
| 17 | +
|
| 18 | +This module exposes the `TelemetryHandler` class, which manages the lifecycle of |
| 19 | +GenAI (Generative AI) invocations and emits telemetry data (spans and related attributes). |
| 20 | +It supports starting, stopping, and failing LLM invocations. |
| 21 | +
|
| 22 | +Classes: |
| 23 | + - TelemetryHandler: Manages GenAI invocation lifecycles and emits telemetry. |
| 24 | +
|
| 25 | +Functions: |
| 26 | + - get_telemetry_handler: Returns a singleton `TelemetryHandler` instance. |
| 27 | +
|
| 28 | +Usage: |
| 29 | + handler = get_telemetry_handler() |
| 30 | +
|
| 31 | + # Create an invocation object with your request data |
| 32 | + # The span and context_token attributes are set by the TelemetryHandler, and |
| 33 | + # managed by the TelemetryHandler during the lifecycle of the span. |
| 34 | +
|
| 35 | + # Use the context manager to manage the lifecycle of an LLM invocation. |
| 36 | + with handler.llm(invocation) as invocation: |
| 37 | + # Populate outputs and any additional attributes |
| 38 | + invocation.output_messages = [...] |
| 39 | + invocation.attributes.update({"more": "attrs"}) |
| 40 | +
|
| 41 | + # Or, if you prefer to manage the lifecycle manually |
| 42 | + invocation = LLMInvocation( |
| 43 | + request_model="my-model", |
| 44 | + input_messages=[...], |
| 45 | + provider="my-provider", |
| 46 | + attributes={"custom": "attr"}, |
| 47 | + ) |
| 48 | +
|
| 49 | + # Start the invocation (opens a span) |
| 50 | + handler.start_llm(invocation) |
| 51 | +
|
| 52 | + # Populate outputs and any additional attributes, then stop (closes the span) |
| 53 | + invocation.output_messages = [...] |
| 54 | + invocation.attributes.update({"more": "attrs"}) |
| 55 | + handler.stop_llm(invocation) |
| 56 | +
|
| 57 | + # Or, in case of error |
| 58 | + handler.fail_llm(invocation, Error(type="...", message="...")) |
| 59 | +""" |
| 60 | + |
| 61 | +from __future__ import annotations |
| 62 | + |
| 63 | +from contextlib import contextmanager |
| 64 | +from typing import Iterator, Optional |
| 65 | + |
| 66 | +from opentelemetry import context as otel_context |
| 67 | +from opentelemetry.semconv._incubating.attributes import ( |
| 68 | + gen_ai_attributes as GenAI, |
| 69 | +) |
| 70 | +from opentelemetry.semconv.schemas import Schemas |
| 71 | +from opentelemetry.trace import ( |
| 72 | + SpanKind, |
| 73 | + TracerProvider, |
| 74 | + get_tracer, |
| 75 | + set_span_in_context, |
| 76 | +) |
| 77 | +from opentelemetry.util.genai.span_utils import ( |
| 78 | + _apply_error_attributes, |
| 79 | + _apply_finish_attributes, |
| 80 | +) |
| 81 | +from opentelemetry.util.genai.types import Error, LLMInvocation |
| 82 | +from opentelemetry.util.genai.version import __version__ |
| 83 | + |
| 84 | + |
| 85 | +class TelemetryHandler: |
| 86 | + """ |
| 87 | + High-level handler managing GenAI invocation lifecycles and emitting |
| 88 | + them as spans, metrics, and events. |
| 89 | + """ |
| 90 | + |
| 91 | + def __init__(self, tracer_provider: TracerProvider | None = None): |
| 92 | + self._tracer = get_tracer( |
| 93 | + __name__, |
| 94 | + __version__, |
| 95 | + tracer_provider, |
| 96 | + schema_url=Schemas.V1_36_0.value, |
| 97 | + ) |
| 98 | + |
| 99 | + def start_llm( |
| 100 | + self, |
| 101 | + invocation: LLMInvocation, |
| 102 | + ) -> LLMInvocation: |
| 103 | + """Start an LLM invocation and create a pending span entry.""" |
| 104 | + # Create a span and attach it as current; keep the token to detach later |
| 105 | + span = self._tracer.start_span( |
| 106 | + name=f"{GenAI.GenAiOperationNameValues.CHAT.value} {invocation.request_model}", |
| 107 | + kind=SpanKind.CLIENT, |
| 108 | + ) |
| 109 | + invocation.span = span |
| 110 | + invocation.context_token = otel_context.attach( |
| 111 | + set_span_in_context(span) |
| 112 | + ) |
| 113 | + return invocation |
| 114 | + |
| 115 | + def stop_llm(self, invocation: LLMInvocation) -> LLMInvocation: # pylint: disable=no-self-use |
| 116 | + """Finalize an LLM invocation successfully and end its span.""" |
| 117 | + if invocation.context_token is None or invocation.span is None: |
| 118 | + # TODO: Provide feedback that this invocation was not started |
| 119 | + return invocation |
| 120 | + |
| 121 | + _apply_finish_attributes(invocation.span, invocation) |
| 122 | + # Detach context and end span |
| 123 | + otel_context.detach(invocation.context_token) |
| 124 | + invocation.span.end() |
| 125 | + return invocation |
| 126 | + |
| 127 | + def fail_llm( # pylint: disable=no-self-use |
| 128 | + self, invocation: LLMInvocation, error: Error |
| 129 | + ) -> LLMInvocation: |
| 130 | + """Fail an LLM invocation and end its span with error status.""" |
| 131 | + if invocation.context_token is None or invocation.span is None: |
| 132 | + # TODO: Provide feedback that this invocation was not started |
| 133 | + return invocation |
| 134 | + |
| 135 | + _apply_error_attributes(invocation.span, error) |
| 136 | + # Detach context and end span |
| 137 | + otel_context.detach(invocation.context_token) |
| 138 | + invocation.span.end() |
| 139 | + return invocation |
| 140 | + |
| 141 | + @contextmanager |
| 142 | + def llm( |
| 143 | + self, invocation: Optional[LLMInvocation] = None |
| 144 | + ) -> Iterator[LLMInvocation]: |
| 145 | + """Context manager for LLM invocations. |
| 146 | +
|
| 147 | + Only set data attributes on the invocation object, do not modify the span or context. |
| 148 | +
|
| 149 | + Starts the span on entry. On normal exit, finalizes the invocation and ends the span. |
| 150 | + If an exception occurs inside the context, marks the span as error, ends it, and |
| 151 | + re-raises the original exception. |
| 152 | + """ |
| 153 | + if invocation is None: |
| 154 | + invocation = LLMInvocation( |
| 155 | + request_model="", |
| 156 | + ) |
| 157 | + self.start_llm(invocation) |
| 158 | + try: |
| 159 | + yield invocation |
| 160 | + except Exception as exc: |
| 161 | + self.fail_llm(invocation, Error(message=str(exc), type=type(exc))) |
| 162 | + raise |
| 163 | + self.stop_llm(invocation) |
| 164 | + |
| 165 | + |
| 166 | +def get_telemetry_handler( |
| 167 | + tracer_provider: TracerProvider | None = None, |
| 168 | +) -> TelemetryHandler: |
| 169 | + """ |
| 170 | + Returns a singleton TelemetryHandler instance. |
| 171 | + """ |
| 172 | + handler: Optional[TelemetryHandler] = getattr( |
| 173 | + get_telemetry_handler, "_default_handler", None |
| 174 | + ) |
| 175 | + if handler is None: |
| 176 | + handler = TelemetryHandler(tracer_provider=tracer_provider) |
| 177 | + setattr(get_telemetry_handler, "_default_handler", handler) |
| 178 | + return handler |
0 commit comments