-
Notifications
You must be signed in to change notification settings - Fork 1.1k
fix(bedrock): label converse metrics with their own model #4512
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
mukktinaadh
wants to merge
1
commit into
traceloop:main
Choose a base branch
from
mukktinaadh:fix/bedrock-converse-metric-labels
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.
+131
−0
Open
Changes from all commits
Commits
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
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
116 changes: 116 additions & 0 deletions
116
packages/opentelemetry-instrumentation-bedrock/tests/metrics/test_converse_metric_labels.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,116 @@ | ||
| from opentelemetry import trace | ||
| from opentelemetry.instrumentation.bedrock import ( | ||
| MetricParams, | ||
| _get_vendor_model, | ||
| _handle_converse, | ||
| _handle_converse_stream, | ||
| ) | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.metrics.export import InMemoryMetricReader | ||
| from opentelemetry.semconv._incubating.attributes import ( | ||
| gen_ai_attributes as GenAIAttributes, | ||
| ) | ||
| from opentelemetry.semconv_ai import Meters | ||
|
|
||
| MODEL_ID = "amazon.titan-text-express-v1" | ||
| # The label the metric carries is whatever `_get_vendor_model` derives from the model id, | ||
| # so derive the expectation the same way instead of duplicating the parsing rule here. | ||
| _, _, EXPECTED_MODEL = _get_vendor_model(MODEL_ID) | ||
| STALE_VENDOR = "anthropic" | ||
| STALE_MODEL = "anthropic.claude-3-5-sonnet" | ||
|
|
||
| CONVERSE_RESPONSE = { | ||
| "output": {"message": {"role": "assistant", "content": [{"text": "hi"}]}}, | ||
| "stopReason": "end_turn", | ||
| "usage": {"inputTokens": 5, "outputTokens": 7, "totalTokens": 12}, | ||
| } | ||
|
|
||
| CONVERSE_KWARGS = { | ||
| "modelId": MODEL_ID, | ||
| "messages": [{"role": "user", "content": [{"text": "hi"}]}], | ||
| } | ||
|
|
||
|
|
||
| def _metric_params(): | ||
| """Real metric instruments backed by an in-memory reader.""" | ||
| reader = InMemoryMetricReader() | ||
| provider = MeterProvider(metric_readers=[reader]) | ||
| meter = provider.get_meter("test") | ||
|
|
||
| metric_params = MetricParams( | ||
| token_histogram=meter.create_histogram(Meters.LLM_TOKEN_USAGE), | ||
| choice_counter=meter.create_counter(Meters.LLM_GENERATION_CHOICES), | ||
| duration_histogram=meter.create_histogram(Meters.LLM_OPERATION_DURATION), | ||
| exception_counter=meter.create_counter("gen_ai.bedrock.completions.exceptions"), | ||
| guardrail_activation=meter.create_counter("guardrail.activation"), | ||
| guardrail_latency_histogram=meter.create_histogram("guardrail.latency"), | ||
| guardrail_coverage=meter.create_counter("guardrail.coverage"), | ||
| guardrail_sensitive_info=meter.create_counter("guardrail.sensitive_info"), | ||
| guardrail_topic=meter.create_counter("guardrail.topic"), | ||
| guardrail_content=meter.create_counter("guardrail.content"), | ||
| guardrail_words=meter.create_counter("guardrail.words"), | ||
| prompt_caching=meter.create_counter("prompt.caching"), | ||
| ) | ||
|
|
||
| # What a previous invoke_model call would have left on the shared params. | ||
| metric_params.vendor = STALE_VENDOR | ||
| metric_params.model = STALE_MODEL | ||
| metric_params.is_stream = False | ||
|
|
||
| return metric_params, reader | ||
|
|
||
|
|
||
| def _recorded_models(reader): | ||
| models = [] | ||
| for resource_metrics in reader.get_metrics_data().resource_metrics: | ||
| for scope_metrics in resource_metrics.scope_metrics: | ||
| for metric in scope_metrics.metrics: | ||
| for data_point in metric.data.data_points: | ||
| models.append(data_point.attributes.get(GenAIAttributes.GEN_AI_RESPONSE_MODEL)) | ||
| return models | ||
|
|
||
|
|
||
| def _span(): | ||
| return trace.get_tracer(__name__).start_span("test") | ||
|
|
||
|
|
||
| def test_converse_metrics_are_labelled_with_their_own_model(): | ||
| """Converse metric points must name the converse model, not a previous call's. | ||
|
|
||
| `metric_params` is shared by every call on the instrumentor and the metric labels are | ||
| read from it, so it has to be updated per call. Without that, a fresh instrumentor | ||
| labelled points with "" and an invoke_model call left its model behind on subsequent | ||
| converse points. | ||
| """ | ||
| metric_params, reader = _metric_params() | ||
|
|
||
| _handle_converse(_span(), CONVERSE_KWARGS, CONVERSE_RESPONSE, metric_params, None) | ||
|
|
||
| models = _recorded_models(reader) | ||
| assert models, "expected the converse call to record metric points" | ||
| assert set(models) == {EXPECTED_MODEL} | ||
| assert STALE_MODEL not in models | ||
|
|
||
|
|
||
| def test_converse_stream_metrics_are_labelled_with_their_own_model(): | ||
| metric_params, reader = _metric_params() | ||
|
|
||
| stream_response = {key: value for key, value in CONVERSE_RESPONSE.items() if key != "usage"} | ||
|
|
||
| def _parse_event(*args, **kwargs): | ||
| return { | ||
| "metadata": { | ||
| "usage": {"inputTokens": 5, "outputTokens": 7}, | ||
| } | ||
| } | ||
|
|
||
| stream_response["stream"] = type("Stream", (), {"_parse_event": _parse_event})() | ||
|
|
||
| _handle_converse_stream(_span(), CONVERSE_KWARGS, stream_response, metric_params, None) | ||
| for _ in stream_response["stream"]._parse_event(): | ||
| pass | ||
|
|
||
| models = _recorded_models(reader) | ||
| assert models, "expected the streamed converse call to record metric points" | ||
| assert set(models) == {EXPECTED_MODEL} | ||
| assert STALE_MODEL not in models |
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.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Bind metric labels to each Converse stream.
Both stream handlers set
modelon sharedmetric_paramsbefore the caller consumes the stream. If another Bedrock call starts before a stream'smetadataevent, that call replaces the model. The pending stream then records its token and duration metrics under the other call's model. Pass call-specific metric parameters to each metadata callback, and test two streams with interleaved consumption. (github.com)packages/opentelemetry-instrumentation-bedrock/opentelemetry/instrumentation/bedrock/__init__.py#L766-L766: bind the synchronous stream's model to its metric recording callback.packages/opentelemetry-instrumentation-bedrock/opentelemetry/instrumentation/bedrock/__init__.py#L846-L846: bind the asynchronous stream's model to its metric recording callback.📍 Affects 1 file
packages/opentelemetry-instrumentation-bedrock/opentelemetry/instrumentation/bedrock/__init__.py#L766-L766(this comment)packages/opentelemetry-instrumentation-bedrock/opentelemetry/instrumentation/bedrock/__init__.py#L846-L846🤖 Prompt for AI Agents