-
Notifications
You must be signed in to change notification settings - Fork 36
Add streaming metrics and attribute #269
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
lmolkova
wants to merge
6
commits into
open-telemetry:main
Choose a base branch
from
lmolkova:streaming-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 all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
cb3b195
Add streaming metrics and attributes
lmolkova a9691c4
feedback
lmolkova d768086
make monotonic start time not none
lmolkova a31b1bc
Merge branch 'main' into streaming-metrics
lmolkova 1c6c70a
Fix streaming conformance scenarios: expected_spans as dict[str,int]
lmolkova f5d99da
Remove redundant None-check on non-optional _monotonic_start_s (fix t…
lmolkova 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
There are no files selected for viewing
1 change: 1 addition & 0 deletions
1
instrumentation/opentelemetry-instrumentation-genai-anthropic/.changelog/269.added
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 @@ | ||
| Emit streaming timing metrics (time-to-first-chunk and time-per-output-chunk) for streaming messages. |
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
87 changes: 87 additions & 0 deletions
87
...on/opentelemetry-instrumentation-genai-anthropic/tests/conformance/inference_streaming.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,87 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Conformance scenario: anthropic streaming chat (inference). | ||
|
|
||
| Exercises the streaming messages path so the streaming timing metrics | ||
| (time-to-first-chunk and time-per-output-chunk) are emitted and validated in | ||
| addition to the duration and token usage metrics. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from typing import Any | ||
| from unittest import mock | ||
|
|
||
| from anthropic import Anthropic | ||
|
|
||
| from opentelemetry.instrumentation.genai.anthropic import AnthropicInstrumentor | ||
| from opentelemetry.sdk._logs import LoggerProvider | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.test.weaver_live_check import LiveCheckReport | ||
| from opentelemetry.test_util_genai.conformance import Scenario | ||
| from opentelemetry.test_util_genai.instrumentor import instrument | ||
|
|
||
|
|
||
| class InferenceStreamingScenario(Scenario): | ||
| expected_spans = {"chat": 1} | ||
| expected_metrics = ( | ||
| "gen_ai.client.operation.duration", | ||
| "gen_ai.client.token.usage", | ||
| "gen_ai.client.operation.time_to_first_chunk", | ||
| "gen_ai.client.operation.time_per_output_chunk", | ||
| ) | ||
|
|
||
| def validate(self, report: LiveCheckReport) -> None: | ||
| super().validate(report) | ||
| stream_values = [ | ||
| attr["value"] | ||
| for entry in report["samples"] | ||
| if "span" in entry | ||
| for attr in entry["span"]["attributes"] | ||
| if attr["name"] == "gen_ai.request.stream" | ||
| ] | ||
| assert stream_values == [True], ( | ||
| "streaming messages should set gen_ai.request.stream=true on the " | ||
| f"chat span; saw {stream_values}" | ||
| ) | ||
|
|
||
| def run( | ||
| self, | ||
| *, | ||
| tracer_provider: TracerProvider, | ||
| meter_provider: MeterProvider, | ||
| logger_provider: LoggerProvider, | ||
| vcr: Any, | ||
| ) -> None: | ||
| key_override = ( | ||
| {} | ||
| if os.getenv("ANTHROPIC_API_KEY") | ||
| else {"ANTHROPIC_API_KEY": "test_anthropic_api_key"} | ||
| ) | ||
| with mock.patch.dict(os.environ, key_override): | ||
| with instrument( | ||
| AnthropicInstrumentor(), | ||
| tracer_provider=tracer_provider, | ||
| logger_provider=logger_provider, | ||
| meter_provider=meter_provider, | ||
| content_capture="SPAN_ONLY", | ||
| ): | ||
| with vcr.use_cassette( | ||
| "test_sync_messages_create_streaming.yaml" | ||
| ): | ||
| with Anthropic().messages.create( | ||
| model="claude-sonnet-4-20250514", | ||
| max_tokens=100, | ||
| messages=[ | ||
| { | ||
| "role": "user", | ||
| "content": "Say hello in one word.", | ||
| } | ||
| ], | ||
| stream=True, | ||
| ) as stream: | ||
| for _ in stream: | ||
| pass |
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
90 changes: 90 additions & 0 deletions
90
instrumentation/opentelemetry-instrumentation-genai-anthropic/tests/test_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,90 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Metric-recording tests for the Anthropic instrumentation.""" | ||
|
|
||
| import pytest | ||
|
|
||
| from opentelemetry.semconv._incubating.attributes import ( | ||
| gen_ai_attributes as GenAIAttributes, | ||
| ) | ||
| from opentelemetry.semconv._incubating.metrics import gen_ai_metrics | ||
|
|
||
| MODEL = "claude-sonnet-4-20250514" | ||
| MESSAGES = [{"role": "user", "content": "Say hello in one word."}] | ||
|
|
||
|
|
||
| def _metrics_by_name(metric_reader): | ||
| by_name = {} | ||
| for rm in metric_reader.get_metrics_data().resource_metrics: | ||
| for scope in rm.scope_metrics: | ||
| for metric in scope.metrics: | ||
| by_name[metric.name] = metric | ||
| return by_name | ||
|
|
||
|
|
||
| def _assert_streaming_timing_metrics(metric_reader): | ||
| """Assert the streaming timing metrics are emitted through the real | ||
| Anthropic stream wrapper path. | ||
|
|
||
| Regression coverage for the ``invocation=invocation`` wiring in | ||
| ``wrappers.py``: dropping it would keep every span/attribute test green but | ||
| silently stop emitting TTFC and per-output-chunk metrics for Anthropic | ||
| streaming. | ||
| """ | ||
| metrics = _metrics_by_name(metric_reader) | ||
|
|
||
| ttfc = metrics.get( | ||
| gen_ai_metrics.GEN_AI_CLIENT_OPERATION_TIME_TO_FIRST_CHUNK | ||
| ) | ||
| assert ttfc is not None | ||
| ttfc_point = ttfc.data.data_points[0] | ||
| assert ttfc_point.count == 1 | ||
| assert ttfc_point.sum >= 0 | ||
| assert ( | ||
| ttfc_point.attributes[GenAIAttributes.GEN_AI_OPERATION_NAME] | ||
| == GenAIAttributes.GenAiOperationNameValues.CHAT.value | ||
| ) | ||
| assert ttfc_point.attributes[GenAIAttributes.GEN_AI_REQUEST_MODEL] == MODEL | ||
|
|
||
| per_chunk = metrics.get( | ||
| gen_ai_metrics.GEN_AI_CLIENT_OPERATION_TIME_PER_OUTPUT_CHUNK | ||
| ) | ||
| assert per_chunk is not None | ||
| per_chunk_point = per_chunk.data.data_points[0] | ||
| # One record per inter-chunk gap; the streaming cassette has several events. | ||
| assert per_chunk_point.count >= 1 | ||
| assert per_chunk_point.sum >= 0 | ||
|
|
||
|
|
||
| def test_sync_messages_streaming_timing_metrics( | ||
| metric_reader, anthropic_client, instrument_with_content, vcr | ||
| ): | ||
| with vcr.use_cassette("test_sync_messages_create_streaming.yaml"): | ||
| with anthropic_client.messages.create( | ||
| model=MODEL, | ||
| max_tokens=100, | ||
| messages=MESSAGES, | ||
| stream=True, | ||
| ) as stream: | ||
| for _ in stream: | ||
| pass | ||
|
|
||
| _assert_streaming_timing_metrics(metric_reader) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio() | ||
| async def test_async_messages_streaming_timing_metrics( | ||
| metric_reader, async_anthropic_client, instrument_with_content, vcr | ||
| ): | ||
| with vcr.use_cassette("test_async_messages_create_streaming.yaml"): | ||
| async with await async_anthropic_client.messages.create( | ||
| model=MODEL, | ||
| max_tokens=100, | ||
| messages=MESSAGES, | ||
| stream=True, | ||
| ) as stream: | ||
| async for _ in stream: | ||
| pass | ||
|
|
||
| _assert_streaming_timing_metrics(metric_reader) |
1 change: 1 addition & 0 deletions
1
instrumentation/opentelemetry-instrumentation-genai-openai/.changelog/269.added
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 @@ | ||
| Emit streaming timing metrics (time-to-first-chunk and time-per-output-chunk) for streaming chat completions. |
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
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
todo: let's automate it in post-release workflow