-
Notifications
You must be signed in to change notification settings - Fork 821
GenAI Utils | Add metrics to LLMInvocations #3891
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
15
commits into
open-telemetry:main
Choose a base branch
from
zhirafovod:genai-utils-metrics
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 11 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
17ed036
add metrics to genai utils
keith-decker a866479
add Instruments class for GenAI metrics and refactor metric recording
keith-decker 4574c99
refactor: streamline metric payload handling in InvocationMetricsReco…
keith-decker ae36766
fix: grammar
keith-decker 6b4ef50
doc: added changelog
keith-decker 8253692
fix: update version for semconvs
keith-decker b3e3a9e
Merge branch 'main' into genai-utils-metrics
keith-decker e97ffc1
Merge branch 'main' into genai-utils-metrics
keith-decker 0b7b80a
Merge branch 'main' into genai-utils-metrics
keith-decker dde7b5e
Lint fixes
keith-decker a41bb69
Merge branch 'main' into genai-utils-metrics
keith-decker 232df6c
Fix Nits, remove overly defensive code
keith-decker c6e1324
Add monotonic timing support for LLM invocation duration calculations
keith-decker 6c71646
small cleanups to types to simplify code
aabmass e92b67a
cleanup test
aabmass 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
52 changes: 52 additions & 0 deletions
52
util/opentelemetry-util-genai/src/opentelemetry/util/genai/instruments.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,52 @@ | ||
| from opentelemetry.metrics import Histogram, Meter | ||
| from opentelemetry.semconv._incubating.metrics import gen_ai_metrics | ||
|
|
||
| _GEN_AI_CLIENT_OPERATION_DURATION_BUCKETS = [ | ||
| 0.01, | ||
| 0.02, | ||
| 0.04, | ||
| 0.08, | ||
| 0.16, | ||
| 0.32, | ||
| 0.64, | ||
| 1.28, | ||
| 2.56, | ||
| 5.12, | ||
| 10.24, | ||
| 20.48, | ||
| 40.96, | ||
| 81.92, | ||
| ] | ||
|
|
||
| _GEN_AI_CLIENT_TOKEN_USAGE_BUCKETS = [ | ||
| 1, | ||
| 4, | ||
| 16, | ||
| 64, | ||
| 256, | ||
| 1024, | ||
| 4096, | ||
| 16384, | ||
| 65536, | ||
| 262144, | ||
| 1048576, | ||
| 4194304, | ||
| 16777216, | ||
| 67108864, | ||
| ] | ||
|
|
||
|
|
||
| class Instruments: | ||
| def __init__(self, meter: Meter): | ||
| self.operation_duration_histogram: Histogram = meter.create_histogram( | ||
| name=gen_ai_metrics.GEN_AI_CLIENT_OPERATION_DURATION, | ||
| description="Duration of GenAI client operation", | ||
| unit="s", | ||
| explicit_bucket_boundaries_advisory=_GEN_AI_CLIENT_OPERATION_DURATION_BUCKETS, | ||
| ) | ||
| self.token_usage_histogram: Histogram = meter.create_histogram( | ||
| name=gen_ai_metrics.GEN_AI_CLIENT_TOKEN_USAGE, | ||
| description="Number of input and output tokens used by GenAI clients", | ||
| unit="{token}", | ||
| explicit_bucket_boundaries_advisory=_GEN_AI_CLIENT_TOKEN_USAGE_BUCKETS, | ||
| ) |
125 changes: 125 additions & 0 deletions
125
util/opentelemetry-util-genai/src/opentelemetry/util/genai/metrics.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,125 @@ | ||
| """Helpers for emitting GenAI metrics from LLM invocations.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import time | ||
| from numbers import Number | ||
| from typing import Dict, Optional | ||
|
|
||
| from opentelemetry.metrics import Histogram, Meter | ||
| from opentelemetry.semconv._incubating.attributes import ( | ||
| gen_ai_attributes as GenAI, | ||
| ) | ||
| from opentelemetry.trace import Span, set_span_in_context | ||
| from opentelemetry.util.genai.instruments import Instruments | ||
| from opentelemetry.util.genai.types import LLMInvocation | ||
| from opentelemetry.util.types import AttributeValue | ||
|
|
||
| _NS_PER_SECOND = 1_000_000_000 | ||
|
|
||
|
|
||
| def _now_ns() -> int: | ||
| return time.time_ns() | ||
|
|
||
|
|
||
| def _get_span_start_time_ns(span: Optional[Span]) -> Optional[int]: | ||
aabmass marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if span is None: | ||
| return None | ||
| for attr in ("start_time", "_start_time"): | ||
| value = getattr(span, attr, None) | ||
| if isinstance(value, int): | ||
| return value | ||
| return None | ||
|
|
||
|
|
||
| def _calculate_duration_seconds(span: Optional[Span]) -> Optional[float]: | ||
| """Calculate duration in seconds from span start time to now.""" | ||
| start_time_ns = _get_span_start_time_ns(span) | ||
| if start_time_ns is None: | ||
| return None | ||
| elapsed_ns = max(_now_ns() - start_time_ns, 0) | ||
| return elapsed_ns / _NS_PER_SECOND | ||
|
|
||
|
|
||
| class InvocationMetricsRecorder: | ||
| """Records duration and token usage histograms for GenAI invocations.""" | ||
|
|
||
| def __init__(self, meter: Meter): | ||
| instruments = Instruments(meter) | ||
| self._duration_histogram: Histogram = ( | ||
| instruments.operation_duration_histogram | ||
| ) | ||
| self._token_histogram: Histogram = instruments.token_usage_histogram | ||
|
Comment on lines
+59
to
+63
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. consider making this two functions instead of class self._duration_histogram = create_operation_histogram(meter)
self._token_histogram = create_token_histogram(meter) |
||
|
|
||
| def record( | ||
| self, | ||
| span: Optional[Span], | ||
| invocation: LLMInvocation, | ||
| *, | ||
| error_type: Optional[str] = None, | ||
| ) -> None: | ||
| """Record duration and token metrics for an invocation if possible.""" | ||
| if span is None: | ||
| return | ||
|
|
||
| tokens: list[tuple[int, str]] = [] | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if isinstance(invocation.input_tokens, int): | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| tokens.append( | ||
| ( | ||
| invocation.input_tokens, | ||
| GenAI.GenAiTokenTypeValues.INPUT.value, | ||
| ) | ||
| ) | ||
| if isinstance(invocation.output_tokens, int): | ||
| tokens.append( | ||
| ( | ||
| invocation.output_tokens, | ||
| GenAI.GenAiTokenTypeValues.COMPLETION.value, | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ) | ||
| ) | ||
|
|
||
| if not tokens: | ||
| return | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| attributes: Dict[str, AttributeValue] = { | ||
| GenAI.GEN_AI_OPERATION_NAME: GenAI.GenAiOperationNameValues.CHAT.value | ||
| } | ||
| if invocation.request_model: | ||
| attributes[GenAI.GEN_AI_REQUEST_MODEL] = invocation.request_model | ||
| if invocation.provider: | ||
| attributes[GenAI.GEN_AI_PROVIDER_NAME] = invocation.provider | ||
| if invocation.response_model_name: | ||
| attributes[GenAI.GEN_AI_RESPONSE_MODEL] = ( | ||
| invocation.response_model_name | ||
| ) | ||
|
|
||
| # Calculate duration from span timing | ||
| duration_seconds = _calculate_duration_seconds(span) | ||
|
|
||
| span_context = set_span_in_context(span) | ||
| if error_type: | ||
| attributes["error.type"] = error_type | ||
|
|
||
| if ( | ||
| duration_seconds is not None | ||
| and isinstance(duration_seconds, Number) | ||
keith-decker marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| and duration_seconds >= 0 | ||
| ): | ||
| duration_attributes: Dict[str, AttributeValue] = dict(attributes) | ||
| self._duration_histogram.record( | ||
| float(duration_seconds), | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| attributes=duration_attributes, | ||
| context=span_context, | ||
| ) | ||
|
|
||
| for token in tokens: | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| token_attributes: Dict[str, AttributeValue] = dict(attributes) | ||
| token_attributes[GenAI.GEN_AI_TOKEN_TYPE] = token[1] | ||
| self._token_histogram.record( | ||
| token[0], | ||
| attributes=token_attributes, | ||
| context=span_context, | ||
| ) | ||
keith-decker marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| __all__ = ["InvocationMetricsRecorder"] | ||
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.