You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(anthropic): sum token usage across tool hops - #1731
When a Claude turn triggers tool calls, ClaudeLLM._stream_message sends follow-up requests (the tool hops and the finalization pass), but LLMResponseFinal only carried the usage of the last one. input_tokens / output_tokens / total_tokens, and so the llm_input_tokens / llm_output_tokens metrics, undercounted every multi-hop turn, both streaming and non-streaming.
Changes
Non-streaming: sum usage over every response of the turn.
Streaming: add input_tokens at each message_start; message_delta reports a running total per message, so only the increase since the previous delta of that message is added.
TestClaudeLLMUsage: non-streaming tool hop, streaming tool hop, and streaming without tools (unchanged). The first two fail on main and pass with the fix.
This change was prepared with the assistance of an AI coding agent (Claude) and reviewed before submission.
Follow-up
Anthropic token usage was undercounted when a turn made additional requests for tool calls and finalization. The total now includes usage from each response. Streaming output uses the increase between cumulative totals within each response.
The tests use the real Anthropic SDK against the existing local HTTP fixture. SDK construction runs outside the event loop in the affected fixtures, so Blockbuster remains active for the usage tests. Each streamed response in the tool turn reports two cumulative output totals. Non-streaming aggregation uses the SDK's typed message and usage fields.
ClaudeLLM reported only the last request's usage when tool calls
triggered follow-up requests, undercounting input and output tokens.
Accumulate usage across all requests in both streaming and
non-streaming paths.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
ClaudeLLM now aggregates token usage across initial responses, tool follow-ups, and finalization responses. In streaming turns, it sums input-token counts and adds output-token increments from each message’s running total. New tests cover non-streaming and streaming tool-call turns, and repeated streaming output-token totals without tools.
Merge Risk: Low · up to 23e71
The token usage fix itself looks sound. Before merging, add the missing Blockbuster skip marker to the new test class, and tidy the usage aggregation to follow repository style. The test mocking concern should also be resolved or explicitly accepted.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Tip
👋 New to CodeRabbit? Try chatting in this PR!
Ask questions about the changes or discuss a review suggestion by mentioning @coderabbitai in a PR comment or a reply to a CodeRabbit review comment.
Try: @coderabbitai explain the changes in this PR and what I should focus on when reviewing.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Note
Follow-up findings are listed below so you can review them separately from inline comments.
Follow-up (1)
Minor (1)
Minor · Use direct attribute access for usage in the aggregation loop. · anthropic_llm.py:244-246
plugins/anthropic/vision_agents/plugins/anthropic/anthropic_llm.py:244-246 Minor · Maintainability & Code Quality · Low value
Use direct attribute access for usage in the aggregation loop.
The loop adds three getattr calls on the non-streaming path. The responses are typed SDK messages, so direct access works and is the repository's preferred style.
154-154: Trivial · Maintainability & Code Quality · Low value
Annotate responses with ClaudeMessage instead of Any.
responses holds only ClaudeMessage results: the initial response, each tool-hop follow-up, and the finalization response. With List[Any], mypy does not check the values appended to it. A concrete annotation makes mypy check those appends.
This annotation does not type-check the usage, input_tokens, or output_tokens reads in the loop. Those reads use getattr and stay dynamically typed.
Confirm that mypy accepts the appended follow_up_response and final_response values. If the SDK return type for those calls is wider than Message, keep Any on this line.
Add a second message_delta to the follow-up and finalization streams.
The follow-up and finalization streams in test_streaming_usage_is_summed_across_tool_hops each contain one message_delta. With one delta, raw summation and incremental counting give the same value. A change that sums raw counts in either loop still passes. Each loop has its own increment logic, so each needs a fixture with two cumulative deltas. The expected totals stay at 18 output tokens. Raw summation with the new fixtures yields 25 and fails the assertion.
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
Remove the mocked Anthropic client from the new usage tests.
_run and _run_non_streaming replace llm.client with a SimpleNamespace whose messages.create is an AsyncMock. Drive these tests through a real AsyncAnthropic client, or record an explicit exception to the no-mock rule for this file.
Keep the SDK response contract in the aggregation.
Use List[ClaudeMessage] at Line 154 and normal attribute access here. Retain the explicit None checks for token counts. List[Any] and getattr remove static checks and silently accept responses without usage attributes.
As per coding guidelines: “Avoid using Any type” and “Avoid getattr, hasattr, delattr, setattr; prefer normal attribute access.”
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Quick win
Mark the usage test class with skip_blockbuster.
The streaming usage tests build an AsyncAnthropic client inside async test bodies. The root autouse Blockbuster fixture is active for them and does not exempt this construction. The construction can reach blocking calls such as os.stat through httpx SSL context setup, which raises BlockingError before the assertions run. The neighboring tests that construct the same client carry @pytest.mark.skip_blockbuster for this reason. Apply the same marker to the new class.
The Blockbuster and mocking findings are addressed. The usage tests now construct the real Anthropic SDK outside the event loop and exercise JSON and SSE through the existing local test server. The streaming tool-turn test checks two cumulative output reports in the initial response, the tool follow-up, and finalization. The non-streaming loop now uses typed SDK messages and direct usage-field access. All 14 Anthropic unit tests passed, and both tool-turn regressions failed with the implementation from main as expected.
This comment was drafted with Claude Code.
This branch has not been deployed
No deployments
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
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.
Why
When a Claude turn triggers tool calls,
ClaudeLLM._stream_messagesends follow-up requests (the tool hops and the finalization pass), butLLMResponseFinalonly carried the usage of the last one.input_tokens/output_tokens/total_tokens, and so thellm_input_tokens/llm_output_tokensmetrics, undercounted every multi-hop turn, both streaming and non-streaming.Changes
usageover every response of the turn.input_tokensat eachmessage_start;message_deltareports a running total per message, so only the increase since the previous delta of that message is added.TestClaudeLLMUsage: non-streaming tool hop, streaming tool hop, and streaming without tools (unchanged). The first two fail on main and pass with the fix.This change was prepared with the assistance of an AI coding agent (Claude) and reviewed before submission.
Follow-up
Anthropic token usage was undercounted when a turn made additional requests for tool calls and finalization. The total now includes usage from each response. Streaming output uses the increase between cumulative totals within each response.
The tests use the real Anthropic SDK against the existing local HTTP fixture. SDK construction runs outside the event loop in the affected fixtures, so Blockbuster remains active for the usage tests. Each streamed response in the tool turn reports two cumulative output totals. Non-streaming aggregation uses the SDK's typed message and usage fields.