-
Notifications
You must be signed in to change notification settings - Fork 783
GenAI Utils | Inference Type and Span Creation #3768
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
keith-decker
wants to merge
29
commits into
open-telemetry:main
Choose a base branch
from
zhirafovod:util-genai-inference-clean
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
73a764c
cherry pick changes from previous PR
keith-decker 0d749a9
move span utils to new file
keith-decker 77d9c3c
remove span state, use otel context for parent/child
keith-decker 054ebe9
flatten LLMInvocation to use attributes instead of dict keys
keith-decker 9d3926f
helper function and docstrings
keith-decker 635b7f8
Merge branch 'main' into util-genai-inference-clean
keith-decker 9837cf4
refactor: store span and context token in LLMInvocation instead of Sp…
keith-decker 1a172d1
refactor: rename prompts/chat_generations to input_messages/output_me…
keith-decker 465ca78
refactor: simplify TelemetryHandler API by moving invocation data man…
keith-decker cd5aaa6
refactor: update relative imports to absolute imports
keith-decker 8347d17
Update handler to use a context manager instead of start_llm and stop…
keith-decker 742a36f
resolve tox -e doc failure
keith-decker 00e08a8
safeguard against empty request-model
keith-decker 109625c
Merge branch 'main' into util-genai-inference-clean
keith-decker 80c94bf
fix tox typecheck errors for utils
keith-decker f07c61f
refactor: move tracer to generator, clean up dead code
keith-decker d6f722f
remove unused linting hint
keith-decker fdc7f50
back off stricter request-model requirements
keith-decker da20448
reintroduce manual start/stop for langchain callback flow
keith-decker c1ff846
Merge branch 'main' into util-genai-inference-clean
aabmass 4a08d7f
clean up context handler, clarify unit tests
keith-decker 243bf8d
remove generator concept
keith-decker 3d6c8da
Merge branch 'main' into util-genai-inference-clean
keith-decker 5f8cd1c
update token types
keith-decker e987d66
Merge branch 'main' into util-genai-inference-clean
keith-decker 51d28c0
code cleanup
keith-decker 88d0149
Merge branch 'main' into util-genai-inference-clean
keith-decker 188e84b
Merge branch 'main' into util-genai-inference-clean
keith-decker c264c46
Merge branch 'main' into util-genai-inference-clean
keith-decker File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,7 +8,7 @@ dynamic = ["version"] | |
description = "OpenTelemetry GenAI Utils" | ||
readme = "README.rst" | ||
license = "Apache-2.0" | ||
requires-python = ">=3.8" | ||
requires-python = ">=3.9" | ||
authors = [ | ||
{ name = "OpenTelemetry Authors", email = "[email protected]" }, | ||
] | ||
|
@@ -25,8 +25,8 @@ classifiers = [ | |
"Programming Language :: Python :: 3.13", | ||
] | ||
dependencies = [ | ||
"opentelemetry-instrumentation ~= 0.51b0", | ||
"opentelemetry-semantic-conventions ~= 0.51b0", | ||
"opentelemetry-instrumentation ~= 0.57b0", | ||
"opentelemetry-semantic-conventions ~= 0.57b0", | ||
"opentelemetry-api>=1.31.0", | ||
] | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. |
119 changes: 119 additions & 0 deletions
119
util/opentelemetry-util-genai/src/opentelemetry/util/genai/generators.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
""" | ||
Span generation utilities for GenAI telemetry. | ||
|
||
This module maps GenAI (Generative AI) invocations to OpenTelemetry spans and | ||
applies GenAI semantic convention attributes. | ||
|
||
Classes: | ||
- BaseTelemetryGenerator: Abstract base for GenAI telemetry emitters. | ||
- SpanGenerator: Concrete implementation that creates and finalizes spans | ||
for LLM operations (e.g., chat) and records input/output messages when | ||
experimental mode and content capture settings allow. | ||
|
||
Usage: | ||
See `opentelemetry/util/genai/handler.py` for `TelemetryHandler`, which | ||
constructs `LLMInvocation` objects and delegates to `SpanGenerator.start`, | ||
`SpanGenerator.finish`, and `SpanGenerator.error` to produce spans that | ||
follow the GenAI semantic conventions. | ||
""" | ||
|
||
from contextvars import Token | ||
from typing import Dict, Optional | ||
from uuid import UUID | ||
|
||
from typing_extensions import TypeAlias | ||
|
||
from opentelemetry import context as otel_context | ||
from opentelemetry import trace | ||
from opentelemetry.semconv._incubating.attributes import ( | ||
gen_ai_attributes as GenAI, | ||
) | ||
from opentelemetry.trace import ( | ||
Span, | ||
SpanKind, | ||
Tracer, | ||
set_span_in_context, | ||
) | ||
|
||
from .span_utils import ( | ||
_apply_error_attributes, | ||
_apply_finish_attributes, | ||
) | ||
from .types import Error, LLMInvocation | ||
|
||
# Type alias matching the token type expected by opentelemetry.context.detach | ||
ContextToken: TypeAlias = Token[otel_context.Context] | ||
|
||
|
||
class BaseTelemetryGenerator: | ||
""" | ||
Abstract base for emitters mapping GenAI types -> OpenTelemetry. | ||
""" | ||
|
||
def start(self, invocation: LLMInvocation) -> None: | ||
raise NotImplementedError | ||
|
||
def finish(self, invocation: LLMInvocation) -> None: | ||
raise NotImplementedError | ||
|
||
def error(self, error: Error, invocation: LLMInvocation) -> None: | ||
raise NotImplementedError | ||
|
||
|
||
class SpanGenerator(BaseTelemetryGenerator): | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
Generates only spans. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
tracer: Optional[Tracer] = None, | ||
): | ||
self._tracer: Tracer = tracer or trace.get_tracer(__name__) | ||
|
||
# Store the active span and its context attachment token | ||
self._active: Dict[UUID, tuple[Span, ContextToken]] = {} | ||
pmcollins marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def start(self, invocation: LLMInvocation): | ||
# Create a span and attach it as current; keep the token to detach later | ||
span = self._tracer.start_span( | ||
name=f"{GenAI.GenAiOperationNameValues.CHAT.value} {invocation.request_model}", | ||
DylanRussell marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
kind=SpanKind.CLIENT, | ||
) | ||
invocation.span = span | ||
invocation.context_token = otel_context.attach( | ||
set_span_in_context(span) | ||
) | ||
|
||
def finish(self, invocation: LLMInvocation): | ||
if invocation.context_token is None or invocation.span is None: | ||
return | ||
|
||
_apply_finish_attributes(invocation.span, invocation) | ||
# Detach context and end span | ||
otel_context.detach(invocation.context_token) | ||
invocation.span.end() | ||
|
||
def error(self, error: Error, invocation: LLMInvocation): | ||
if invocation.context_token is None or invocation.span is None: | ||
return | ||
|
||
_apply_error_attributes(invocation.span, error) | ||
# Detach context and end span | ||
otel_context.detach(invocation.context_token) | ||
invocation.span.end() | ||
return |
144 changes: 144 additions & 0 deletions
144
util/opentelemetry-util-genai/src/opentelemetry/util/genai/handler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
""" | ||
Telemetry handler for GenAI invocations. | ||
|
||
This module exposes the `TelemetryHandler` class, which manages the lifecycle of | ||
GenAI (Generative AI) invocations and emits telemetry data (spans and related attributes). | ||
It supports starting, stopping, and failing LLM invocations. | ||
|
||
Classes: | ||
- TelemetryHandler: Manages GenAI invocation lifecycles and emits telemetry. | ||
|
||
Functions: | ||
- get_telemetry_handler: Returns a singleton `TelemetryHandler` instance. | ||
|
||
Usage: | ||
handler = get_telemetry_handler() | ||
handler.start_llm(input_messages, request_model, **attrs) | ||
handler.stop_llm(invocation, output_messages, **attrs) | ||
handler.fail_llm(invocation, error, **attrs) | ||
""" | ||
|
||
import time | ||
from typing import Any, List, Optional | ||
|
||
from opentelemetry.semconv.schemas import Schemas | ||
from opentelemetry.trace import get_tracer | ||
|
||
from .generators import SpanGenerator | ||
from .types import Error, InputMessage, LLMInvocation, OutputMessage | ||
from .version import __version__ | ||
|
||
|
||
def _apply_known_attrs_to_invocation( | ||
invocation: LLMInvocation, attributes: dict[str, Any] | ||
) -> None: | ||
"""Pop known fields from attributes and set them on the invocation. | ||
|
||
Mutates the provided attributes dict by popping known keys, leaving | ||
only unknown/custom attributes behind for the caller to persist into | ||
invocation.attributes. | ||
""" | ||
if "provider" in attributes: | ||
invocation.provider = attributes.pop("provider") | ||
if "response_model_name" in attributes: | ||
invocation.response_model_name = attributes.pop("response_model_name") | ||
if "response_id" in attributes: | ||
invocation.response_id = attributes.pop("response_id") | ||
if "input_tokens" in attributes: | ||
invocation.input_tokens = attributes.pop("input_tokens") | ||
DylanRussell marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if "output_tokens" in attributes: | ||
invocation.output_tokens = attributes.pop("output_tokens") | ||
|
||
|
||
class TelemetryHandler: | ||
DylanRussell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
High-level handler managing GenAI invocation lifecycles and emitting | ||
them as spans, metrics, and events. | ||
""" | ||
|
||
def __init__(self, **kwargs: Any): | ||
tracer_provider = kwargs.get("tracer_provider") | ||
self._tracer = get_tracer( | ||
__name__, | ||
__version__, | ||
tracer_provider, | ||
schema_url=Schemas.V1_36_0.value, | ||
) | ||
|
||
self._generator = SpanGenerator(tracer=self._tracer) | ||
pmcollins marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def start_llm( | ||
DylanRussell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self, | ||
request_model: str, | ||
input_messages: List[InputMessage], | ||
**attributes: Any, | ||
) -> LLMInvocation: | ||
"""Start an LLM invocation and create a pending span entry. | ||
|
||
Known attributes provided via ``**attributes`` (``provider``, | ||
``response_model_name``, ``response_id``, ``input_tokens``, | ||
``output_tokens``) are extracted and set as explicit fields on the | ||
``LLMInvocation``. Any remaining keys are preserved in | ||
``invocation.attributes`` for custom metadata. | ||
|
||
Returns the ``LLMInvocation`` to use with `stop_llm` and `fail_llm`. | ||
""" | ||
invocation = LLMInvocation( | ||
request_model=request_model, | ||
input_messages=input_messages, | ||
attributes=attributes, | ||
) | ||
_apply_known_attrs_to_invocation(invocation, invocation.attributes) | ||
self._generator.start(invocation) | ||
return invocation | ||
|
||
def stop_llm( | ||
self, | ||
invocation: LLMInvocation, | ||
output_messages: List[OutputMessage], | ||
**attributes: Any, | ||
) -> LLMInvocation: | ||
"""Finalize an LLM invocation successfully and end its span.""" | ||
invocation.end_time = time.time() | ||
invocation.output_messages = output_messages | ||
_apply_known_attrs_to_invocation(invocation, attributes) | ||
invocation.attributes.update(attributes) | ||
self._generator.finish(invocation) | ||
return invocation | ||
|
||
def fail_llm( | ||
self, invocation: LLMInvocation, error: Error, **attributes: Any | ||
) -> LLMInvocation: | ||
"""Fail an LLM invocation and end its span with error status.""" | ||
invocation.end_time = time.time() | ||
_apply_known_attrs_to_invocation(invocation, attributes) | ||
invocation.attributes.update(**attributes) | ||
self._generator.error(error, invocation) | ||
return invocation | ||
|
||
|
||
def get_telemetry_handler(**kwargs: Any) -> TelemetryHandler: | ||
""" | ||
Returns a singleton TelemetryHandler instance. | ||
""" | ||
handler: Optional[TelemetryHandler] = getattr( | ||
get_telemetry_handler, "_default_handler", None | ||
) | ||
if handler is None: | ||
handler = TelemetryHandler(**kwargs) | ||
setattr(get_telemetry_handler, "_default_handler", handler) | ||
return handler |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.