Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changelog/4615.added
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`opentelemetry-instrumentation-botocore`: capture Bedrock prompt cache token usage
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
GEN_AI_RESPONSE_FINISH_REASONS,
GEN_AI_SYSTEM,
GEN_AI_TOKEN_TYPE,
GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
GEN_AI_USAGE_INPUT_TOKENS,
GEN_AI_USAGE_OUTPUT_TOKENS,
GenAiOperationNameValues,
Expand Down Expand Up @@ -462,7 +464,7 @@ def before_service_call(
# this is used to calculate the operation duration metric, duration may be skewed by request_hook
self._operation_start = default_timer()

# pylint: disable=no-self-use,too-many-locals
# pylint: disable=no-self-use,too-many-locals,too-many-branches
def _converse_on_success(
self,
span: Span,
Expand All @@ -482,6 +484,16 @@ def _converse_on_success(
GEN_AI_USAGE_OUTPUT_TOKENS,
output_tokens,
)
if cache_read := usage.get("cacheReadInputTokens"):
span.set_attribute(
GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
cache_read,
)
if cache_write := usage.get("cacheWriteInputTokens"):
span.set_attribute(
GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
cache_write,
)

if stop_reason := result.get("stopReason"):
span.set_attribute(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,16 @@ def _process_event(self, event):

if output_tokens := usage.get("outputTokens"):
self._response["usage"]["outputTokens"] = output_tokens

if cache_read := usage.get("cacheReadInputTokens"):
self._response["usage"]["cacheReadInputTokens"] = (
cache_read
)

if cache_write := usage.get("cacheWriteInputTokens"):
self._response["usage"]["cacheWriteInputTokens"] = (
cache_write
)
self._complete_stream(self._response)

return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from botocore.response import StreamingBody

from opentelemetry.instrumentation.botocore.extensions.bedrock_utils import (
ConverseStreamWrapper,
InvokeModelWithResponseStreamWrapper,
_Choice,
)
Expand Down Expand Up @@ -3077,6 +3078,35 @@ def test_converse_stream_with_missing_output_in_response():
assert choice.index == 0


def test_converse_stream_accumulates_cache_tokens():
Copy link
Copy Markdown
Contributor

@xrmx xrmx May 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to also assert the attributes on a test with a recording instead, if this isn't something added recently you may already have it in the recordings.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review @xrmx! I looked into this — the cache token fields (cacheReadInputTokens / cacheWriteInputTokens) are only part of the bedrock-runtime service model on more recent boto3 (≥ 1.39.5). The current test factors all pin older versions (1.29.4 in -2, 1.35.16 in -3, 1.35.56 in -1), which strip these fields from the response before the instrumentor sees them — so a VCR cassette alone wouldn't help. That's why I went with the unit test on ConverseStreamWrapper to validate the streaming-metadata accumulation.

If you'd prefer a VCR-based test, I can bump boto3 in one of the factors (e.g. -3) to ≥ 1.39.5 and record a cassette with prompt caching enabled. Happy to do either — let me know how you'd like to proceed.

# The ConverseStream metadata event carries prompt cache token usage;
# the wrapper should accumulate it alongside input/output tokens.
wrapper = ConverseStreamWrapper(
stream=mock.MagicMock(),
stream_done_callback=lambda *args, **kwargs: None,
stream_error_callback=lambda *args, **kwargs: None,
)

wrapper._process_event(
{
"metadata": {
"usage": {
"inputTokens": 8,
"outputTokens": 10,
"cacheReadInputTokens": 1500,
"cacheWriteInputTokens": 25,
}
}
}
)

usage = wrapper._response["usage"]
assert usage["inputTokens"] == 8
assert usage["outputTokens"] == 10
assert usage["cacheReadInputTokens"] == 1500
assert usage["cacheWriteInputTokens"] == 25


def amazon_nova_messages():
return [
{"role": "user", "content": [{"text": "Say this is a test"}]},
Expand Down