From bcfc0e527402be08cba3b2a04f8dc47cbfa2744d Mon Sep 17 00:00:00 2001 From: srothh Date: Wed, 18 Nov 2026 13:58:36 +0100 Subject: [PATCH 1/5] feat(anthropic): Set gen_ai.usage.output_to kens.reasoning for non-streaming responses #5802 --- sentry_sdk/integrations/anthropic.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/sentry_sdk/integrations/anthropic.py b/sentry_sdk/integrations/anthropic.py index a7b6f9e512..d9654911e5 100644 --- a/sentry_sdk/integrations/anthropic.py +++ b/sentry_sdk/integrations/anthropic.py @@ -167,6 +167,7 @@ class _RecordedUsage: input_tokens: int = 0 cache_write_input_tokens: "Optional[int]" = 0 cache_read_input_tokens: "Optional[int]" = 0 + output_tokens_reasoning: "Optional[int]" = 0 class _StreamSpanContext: @@ -330,15 +331,16 @@ def _capture_exception(exc: "Any") -> None: sentry_sdk.capture_event(event, hint=hint) -def _get_token_usage(result: "Messages") -> "tuple[int, int, int, int]": +def _get_token_usage(result: "Messages") -> "tuple[int, int, int, int, int]": """ Get token usage from the Anthropic response. - Returns: (input_tokens, output_tokens, cache_read_input_tokens, cache_write_input_tokens) + Returns: (input_tokens, output_tokens, cache_read_input_tokens, cache_write_input_tokens, output_tokens_reasoning) """ input_tokens = 0 output_tokens = 0 cache_read_input_tokens = 0 cache_write_input_tokens = 0 + output_tokens_reasoning = 0 if hasattr(result, "usage"): usage = result.usage if hasattr(usage, "input_tokens") and isinstance(usage.input_tokens, int): @@ -353,6 +355,11 @@ def _get_token_usage(result: "Messages") -> "tuple[int, int, int, int]": usage.cache_creation_input_tokens, int ): cache_write_input_tokens = usage.cache_creation_input_tokens + if hasattr(usage, "output_tokens_details"): + reasoning = getattr(usage.output_tokens_details, "thinking_tokens", None) + if isinstance(reasoning, int): + output_tokens_reasoning = reasoning + # Anthropic's input_tokens excludes cached/cache_write tokens. # Normalize to total input tokens so downstream cost calculations @@ -364,6 +371,7 @@ def _get_token_usage(result: "Messages") -> "tuple[int, int, int, int]": output_tokens, cache_read_input_tokens, cache_write_input_tokens, + output_tokens_reasoning, ) @@ -726,6 +734,7 @@ def _set_output_data( content_blocks: "list[dict[str, Any]]", response_id: "str | None" = None, finish_reason: "str | None" = None, + output_tokens_reasoning: "int | None" = None, ) -> None: """ Set output data for the span based on the AI response.""" @@ -789,6 +798,9 @@ def _set_output_data( if output_tokens is not None: set_on_span(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens) + if output_tokens_reasoning is not None: + set_on_span(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING, output_tokens_reasoning) + if input_tokens is not None and output_tokens is not None: set_on_span(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, input_tokens + output_tokens) @@ -867,6 +879,7 @@ def _sentry_patched_create_sync(f: "Any", *args: "Any", **kwargs: "Any") -> "Any output_tokens, cache_read_input_tokens, cache_write_input_tokens, + output_tokens_reasoning, ) = _get_token_usage(result) content_blocks = [] @@ -886,6 +899,7 @@ def _sentry_patched_create_sync(f: "Any", *args: "Any", **kwargs: "Any") -> "Any output_tokens=output_tokens, cache_read_input_tokens=cache_read_input_tokens, cache_write_input_tokens=cache_write_input_tokens, + output_tokens_reasoning=output_tokens_reasoning, content_blocks=content_blocks, response_id=getattr(result, "id", None), finish_reason=getattr(result, "stop_reason", None), @@ -974,6 +988,7 @@ async def _sentry_patched_create_async( output_tokens, cache_read_input_tokens, cache_write_input_tokens, + output_tokens_reasoning, ) = _get_token_usage(result) content_blocks = [] @@ -993,6 +1008,7 @@ async def _sentry_patched_create_async( output_tokens=output_tokens, cache_read_input_tokens=cache_read_input_tokens, cache_write_input_tokens=cache_write_input_tokens, + output_tokens_reasoning=output_tokens_reasoning, content_blocks=content_blocks, response_id=getattr(result, "id", None), finish_reason=getattr(result, "stop_reason", None), From 71cf7a7eb3cfa7cc75b0de2f7532a86850787154 Mon Sep 17 00:00:00 2001 From: srothh Date: Wed, 18 Nov 2026 14:33:44 +0100 Subject: [PATCH 2/5] test(anthropic): Add tests for output_reasoning_tokens #5802 --- .../integrations/anthropic/test_anthropic.py | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index 2e6fe7c0dc..a01028066f 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -9041,6 +9041,161 @@ def test_cache_tokens_nonstreaming( assert span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE] == 20 +@pytest.mark.skipif( + ANTHROPIC_VERSION < (0, 105), + reason="usage.output_tokens_details added in https://github.com/anthropics/anthropic-sdk-python/commit/f18b01414b21b49943a6ba2cdaa30ff7dd6a3025.", +) +@pytest.mark.parametrize( + "output_tokens_details, expected_reasoning_tokens", + [ + ({"thinking_tokens": 15}, 15), + ({"thinking_tokens": 0}, 0), + (None, 0), + ], +) +@pytest.mark.parametrize("span_streaming", [True, False]) +@pytest.mark.parametrize("stream_gen_ai_spans", [True, False]) +def test_reasoning_tokens_nonstreaming( + sentry_init, + capture_events, + capture_items, + stream_gen_ai_spans, + span_streaming, + output_tokens_details, + expected_reasoning_tokens, +): + """Test reasoning (thinking) tokens are tracked for non-streaming responses.""" + sentry_init( + integrations=[AnthropicIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + stream_gen_ai_spans=stream_gen_ai_spans, + trace_lifecycle="stream" if span_streaming else "static", + ) + + client = Anthropic(api_key="z") + + client.messages._post = mock.Mock( + return_value=Message( + id="id", + model="claude-opus-4-8", + role="assistant", + content=[TextBlock(type="text", text="Response")], + type="message", + usage=Usage( + input_tokens=100, + output_tokens=50, + output_tokens_details=output_tokens_details, + ), + ) + ) + + if span_streaming or stream_gen_ai_spans: + items = capture_items("span") + + with start_transaction(name="anthropic"): + client.messages.create( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + ) + + sentry_sdk.flush() + (span,) = (item.payload for item in items) + span_data = span["attributes"] + else: + events = capture_events() + + with start_transaction(name="anthropic"): + client.messages.create( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + ) + + (span,) = events[0]["spans"] + span_data = span["data"] + + # Reasoning tokens are part of output_tokens, so totals are unchanged. + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 + assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 150 + assert ( + span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] + == expected_reasoning_tokens + ) + + +@pytest.mark.skipif( + ANTHROPIC_VERSION < (0, 105), + reason="usage.output_tokens_details added in https://github.com/anthropics/anthropic-sdk-python/commit/f18b01414b21b49943a6ba2cdaa30ff7dd6a3025.", +) +@pytest.mark.parametrize("span_streaming", [True, False]) +@pytest.mark.parametrize("stream_gen_ai_spans", [True, False]) +@pytest.mark.asyncio +async def test_reasoning_tokens_nonstreaming_async( + sentry_init, + capture_events, + capture_items, + stream_gen_ai_spans, + span_streaming, +): + """Test reasoning (thinking) tokens are tracked for async non-streaming responses.""" + sentry_init( + integrations=[AnthropicIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + stream_gen_ai_spans=stream_gen_ai_spans, + trace_lifecycle="stream" if span_streaming else "static", + ) + + client = AsyncAnthropic(api_key="z") + + client.messages._post = AsyncMock( + return_value=Message( + id="id", + model="claude-opus-4-8", + role="assistant", + content=[TextBlock(type="text", text="Response")], + type="message", + usage=Usage( + input_tokens=100, + output_tokens=50, + output_tokens_details={"thinking_tokens": 15}, + ), + ) + ) + + if span_streaming or stream_gen_ai_spans: + items = capture_items("span") + + with start_transaction(name="anthropic"): + await client.messages.create( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + ) + + sentry_sdk.flush() + (span,) = (item.payload for item in items) + span_data = span["attributes"] + else: + events = capture_events() + + with start_transaction(name="anthropic"): + await client.messages.create( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + ) + + (span,) = events[0]["spans"] + span_data = span["data"] + + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 + assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 150 + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 15 + + @pytest.mark.parametrize("span_streaming", [True, False]) @pytest.mark.parametrize("stream_gen_ai_spans", [True, False]) def test_input_tokens_include_cache_write_nonstreaming( From ac8ebf4a5d285347c9c6872627fa17137e48a586 Mon Sep 17 00:00:00 2001 From: srothh Date: Wed, 18 Nov 2026 14:37:23 +0100 Subject: [PATCH 3/5] ref(anthropic): Remove _RecordedUsage change from non-streaming branch --- sentry_sdk/integrations/anthropic.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sentry_sdk/integrations/anthropic.py b/sentry_sdk/integrations/anthropic.py index d9654911e5..e6275b26a8 100644 --- a/sentry_sdk/integrations/anthropic.py +++ b/sentry_sdk/integrations/anthropic.py @@ -167,7 +167,6 @@ class _RecordedUsage: input_tokens: int = 0 cache_write_input_tokens: "Optional[int]" = 0 cache_read_input_tokens: "Optional[int]" = 0 - output_tokens_reasoning: "Optional[int]" = 0 class _StreamSpanContext: @@ -360,7 +359,6 @@ def _get_token_usage(result: "Messages") -> "tuple[int, int, int, int, int]": if isinstance(reasoning, int): output_tokens_reasoning = reasoning - # Anthropic's input_tokens excludes cached/cache_write tokens. # Normalize to total input tokens so downstream cost calculations # (input_tokens - cached) don't produce negative values. @@ -799,7 +797,9 @@ def _set_output_data( set_on_span(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens) if output_tokens_reasoning is not None: - set_on_span(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING, output_tokens_reasoning) + set_on_span( + SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING, output_tokens_reasoning + ) if input_tokens is not None and output_tokens is not None: set_on_span(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, input_tokens + output_tokens) From fea2b6197cb3d2e0d4aeb653228a725526e0823f Mon Sep 17 00:00:00 2001 From: srothh Date: Wed, 18 Nov 2026 16:18:50 +0100 Subject: [PATCH 4/5] test(anthropic): Remove unnessecary parametrization from reasoning token test #5802 --- tests/integrations/anthropic/test_anthropic.py | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index a01028066f..f7e3f39488 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -9045,14 +9045,6 @@ def test_cache_tokens_nonstreaming( ANTHROPIC_VERSION < (0, 105), reason="usage.output_tokens_details added in https://github.com/anthropics/anthropic-sdk-python/commit/f18b01414b21b49943a6ba2cdaa30ff7dd6a3025.", ) -@pytest.mark.parametrize( - "output_tokens_details, expected_reasoning_tokens", - [ - ({"thinking_tokens": 15}, 15), - ({"thinking_tokens": 0}, 0), - (None, 0), - ], -) @pytest.mark.parametrize("span_streaming", [True, False]) @pytest.mark.parametrize("stream_gen_ai_spans", [True, False]) def test_reasoning_tokens_nonstreaming( @@ -9061,8 +9053,6 @@ def test_reasoning_tokens_nonstreaming( capture_items, stream_gen_ai_spans, span_streaming, - output_tokens_details, - expected_reasoning_tokens, ): """Test reasoning (thinking) tokens are tracked for non-streaming responses.""" sentry_init( @@ -9085,7 +9075,7 @@ def test_reasoning_tokens_nonstreaming( usage=Usage( input_tokens=100, output_tokens=50, - output_tokens_details=output_tokens_details, + output_tokens_details={"thinking_tokens": 15}, ), ) ) @@ -9119,10 +9109,7 @@ def test_reasoning_tokens_nonstreaming( # Reasoning tokens are part of output_tokens, so totals are unchanged. assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 150 - assert ( - span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] - == expected_reasoning_tokens - ) + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 15 @pytest.mark.skipif( From 9d4ffb88a7199e374611363a6158362e0233faf6 Mon Sep 17 00:00:00 2001 From: Simon Roth <39389607+srothh@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:24:10 +0100 Subject: [PATCH 5/5] feat(anthropic): Set gen_ai.usage.output_tokens.reasoning attributes for streaming responses (#8330) ### Description feat(anthropic): Set gen_ai.usage.output_tokens.reasoning attributes for streaming responses --- sentry_sdk/integrations/anthropic.py | 20 ++ .../integrations/anthropic/test_anthropic.py | 189 ++++++++++++++++++ 2 files changed, 209 insertions(+) diff --git a/sentry_sdk/integrations/anthropic.py b/sentry_sdk/integrations/anthropic.py index e6275b26a8..a38854c0f7 100644 --- a/sentry_sdk/integrations/anthropic.py +++ b/sentry_sdk/integrations/anthropic.py @@ -167,6 +167,7 @@ class _RecordedUsage: input_tokens: int = 0 cache_write_input_tokens: "Optional[int]" = 0 cache_read_input_tokens: "Optional[int]" = 0 + output_tokens_reasoning: int = 0 class _StreamSpanContext: @@ -423,6 +424,15 @@ def _collect_ai_data( incoming_usage, "cache_read_input_tokens", None ) + output_tokens_details = getattr( + incoming_usage, "output_tokens_details", None + ) + thinking_tokens = getattr( + output_tokens_details, "thinking_tokens", None + ) + if thinking_tokens is not None: + usage.output_tokens_reasoning = thinking_tokens + return ( model, usage, @@ -451,6 +461,15 @@ def _collect_ai_data( ) if cache_read_input_tokens is not None: usage.cache_read_input_tokens = cache_read_input_tokens + + output_tokens_details = getattr( + event.usage, "output_tokens_details", None + ) + thinking_tokens = getattr( + output_tokens_details, "thinking_tokens", None + ) + if thinking_tokens is not None: + usage.output_tokens_reasoning = thinking_tokens # TODO: Record event.usage.server_tool_use if event.delta.stop_reason is not None: @@ -1097,6 +1116,7 @@ def _set_streaming_output_data( output_tokens=usage.output_tokens, cache_read_input_tokens=usage.cache_read_input_tokens, cache_write_input_tokens=usage.cache_write_input_tokens, + output_tokens_reasoning=usage.output_tokens_reasoning, content_blocks=content_blocks, response_id=response_id, finish_reason=finish_reason, diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index f7e3f39488..7fa10b4e9b 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -9826,3 +9826,192 @@ def test_stream_messages_cache_tokens( assert span["data"][SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 210 assert span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHED] == 80 assert span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE] == 20 + + +@pytest.mark.skipif( + ANTHROPIC_VERSION < (0, 105), + reason="usage.output_tokens_details added in https://github.com/anthropics/anthropic-sdk-python/commit/f18b01414b21b49943a6ba2cdaa30ff7dd6a3025.", +) +@pytest.mark.parametrize("span_streaming", [True, False]) +@pytest.mark.parametrize("stream_gen_ai_spans", [True, False]) +def test_reasoning_tokens_streaming( + sentry_init, + capture_events, + capture_items, + get_model_response, + server_side_event_chunks, + stream_gen_ai_spans, + span_streaming, +): + """Test reasoning (thinking) tokens are tracked for streaming responses.""" + client = Anthropic(api_key="z") + + response = get_model_response( + server_side_event_chunks( + [ + MessageStartEvent( + type="message_start", + message=Message( + id="id", + model="claude-opus-4-8", + role="assistant", + content=[], + type="message", + usage=Usage(input_tokens=100, output_tokens=0), + ), + ), + MessageDeltaEvent( + type="message_delta", + delta=Delta(stop_reason="end_turn"), + usage=MessageDeltaUsage( + output_tokens=50, + output_tokens_details={"thinking_tokens": 15}, + ), + ), + ] + ) + ) + + sentry_init( + integrations=[AnthropicIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + stream_gen_ai_spans=stream_gen_ai_spans, + trace_lifecycle="stream" if span_streaming else "static", + ) + + if span_streaming or stream_gen_ai_spans: + items = capture_items("span") + + with mock.patch.object( + client._client, + "send", + return_value=response, + ) as _, start_transaction(name="anthropic"): + for _ in client.messages.create( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + stream=True, + ): + pass + + sentry_sdk.flush() + (span,) = (item.payload for item in items) + span_data = span["attributes"] + else: + events = capture_events() + + with mock.patch.object( + client._client, + "send", + return_value=response, + ) as _, start_transaction(name="anthropic"): + for _ in client.messages.create( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + stream=True, + ): + pass + + (span,) = events[0]["spans"] + span_data = span["data"] + + # Reasoning tokens are part of output_tokens, so totals are unchanged. + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 + assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 150 + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 15 + + +@pytest.mark.skipif( + ANTHROPIC_VERSION < (0, 105), + reason="usage.output_tokens_details added in https://github.com/anthropics/anthropic-sdk-python/commit/f18b01414b21b49943a6ba2cdaa30ff7dd6a3025.", +) +@pytest.mark.parametrize("span_streaming", [True, False]) +@pytest.mark.parametrize("stream_gen_ai_spans", [True, False]) +def test_stream_messages_reasoning_tokens( + sentry_init, + capture_events, + capture_items, + get_model_response, + server_side_event_chunks, + stream_gen_ai_spans, + span_streaming, +): + """Test reasoning (thinking) tokens are tracked for messages.stream().""" + client = Anthropic(api_key="z") + + response = get_model_response( + server_side_event_chunks( + [ + MessageStartEvent( + type="message_start", + message=Message( + id="id", + model="claude-opus-4-8", + role="assistant", + content=[], + type="message", + usage=Usage(input_tokens=100, output_tokens=0), + ), + ), + MessageDeltaEvent( + type="message_delta", + delta=Delta(stop_reason="end_turn"), + usage=MessageDeltaUsage( + output_tokens=50, + output_tokens_details={"thinking_tokens": 15}, + ), + ), + ] + ) + ) + + sentry_init( + integrations=[AnthropicIntegration()], + disabled_integrations=[StdlibIntegration], + traces_sample_rate=1.0, + stream_gen_ai_spans=stream_gen_ai_spans, + trace_lifecycle="stream" if span_streaming else "static", + ) + + if span_streaming or stream_gen_ai_spans: + items = capture_items("span") + + with mock.patch.object( + client._client, + "send", + return_value=response, + ) as _, start_transaction(name="anthropic"), client.messages.stream( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + ) as stream: + for event in stream: + pass + + sentry_sdk.flush() + (span,) = (item.payload for item in items) + span_data = span["attributes"] + else: + events = capture_events() + + with mock.patch.object( + client._client, + "send", + return_value=response, + ) as _, start_transaction(name="anthropic"), client.messages.stream( + max_tokens=1024, + messages=[{"role": "user", "content": "Hello"}], + model="claude-opus-4-8", + ) as stream: + for event in stream: + pass + + (span,) = events[0]["spans"] + span_data = span["data"] + + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 50 + assert span_data[SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 150 + assert span_data[SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 15