Skip to content

fix(anthropic): include cache tokens in total_tokens - #6857

Open
LHMQ878 wants to merge 2 commits into
crewAIInc:mainfrom
LHMQ878:fix/6768-anthropic-cache-total-tokens
Open

fix(anthropic): include cache tokens in total_tokens#6857
LHMQ878 wants to merge 2 commits into
crewAIInc:mainfrom
LHMQ878:fix/6768-anthropic-cache-total-tokens

Conversation

@LHMQ878

@LHMQ878 LHMQ878 commented Aug 7, 2026

Copy link
Copy Markdown

Summary

Anthropic usage extraction only summed input_tokens and output_tokens for total_tokens, so prompt-cache reads and cache writes were left out of the total.

This change includes cache_read_input_tokens and cache_creation_input_tokens in total_tokens, and updates the existing unit test accordingly.

Fixes #6768

Test plan

  • Run test_anthropic_cache_creation_tokens_extraction and test_anthropic_token_usage_tracking
  • Confirm total_tokens equals input + output + cache_read + cache_creation when cache fields are present
  • Confirm missing cache fields still default to zero and do not inflate totals

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f9ab0fba-f84e-4154-9fd5-3c6e53639f98

📥 Commits

Reviewing files that changed from the base of the PR and between d389c13 and dfb84b3.

📒 Files selected for processing (1)
  • lib/crewai/tests/llms/anthropic/test_anthropic.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/crewai/tests/llms/anthropic/test_anthropic.py

📝 Walkthrough

Walkthrough

The Anthropic tests now cover omitted and explicit zero cache fields. They also verify cache-read and cache-creation tokens in synchronous and asynchronous streaming usage totals.

Changes

Anthropic token usage tests

Layer / File(s) Summary
Usage fixtures and zero-default fields
lib/crewai/tests/llms/anthropic/test_anthropic.py
Adds reusable final-message setup. Tests verify zero cache counters when fields are omitted or explicitly set to zero.
Synchronous and asynchronous cache accounting
lib/crewai/tests/llms/anthropic/test_anthropic.py
Adds streaming tests for cache-read and cache-creation token accounting in prompt and total usage summaries for both execution modes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The tests cover required totals and defaults, but the provided changes show no production extractor update to implement the linked issue. Update the Anthropic usage extractor so total_tokens adds input, output, cache-read, and cache-creation tokens, then retain the listed tests.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states that Anthropic cache tokens are included in total_tokens, matching the stated fix.
Description check ✅ Passed The description explains the Anthropic token-counting defect, intended fix, linked issue, and test coverage.
Out of Scope Changes check ✅ Passed The listed changes are confined to Anthropic usage tests and directly support the linked issue objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
lib/crewai/tests/llms/anthropic/test_anthropic.py (1)

1640-1660: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for missing cache fields.

This test covers only responses that include both cache fields. Add a behavior test with only input_tokens and output_tokens. Assert that total_tokens remains their sum and both cache-specific outputs are zero.

As per coding guidelines, **/tests/**/*.py: Write unit tests for new functionality that focus on behavior rather than implementation details.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/crewai/tests/llms/anthropic/test_anthropic.py` around lines 1640 - 1660,
Extend test_anthropic_cache_creation_tokens_extraction coverage with a response
usage object containing only input_tokens and output_tokens. Assert total_tokens
equals their sum and both cached_prompt_tokens and cache_creation_tokens default
to zero, focusing on observable extraction behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@lib/crewai/tests/llms/anthropic/test_anthropic.py`:
- Around line 1640-1660: Extend test_anthropic_cache_creation_tokens_extraction
coverage with a response usage object containing only input_tokens and
output_tokens. Assert total_tokens equals their sum and both
cached_prompt_tokens and cache_creation_tokens default to zero, focusing on
observable extraction behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f0f5c07e-26c8-4a39-be55-def8ab0f31a3

📥 Commits

Reviewing files that changed from the base of the PR and between 18c52c4 and fcf1ac1.

📒 Files selected for processing (2)
  • lib/crewai/src/crewai/llms/providers/anthropic/completion.py
  • lib/crewai/tests/llms/anthropic/test_anthropic.py

@LHMQ878

LHMQ878 commented Aug 7, 2026

Copy link
Copy Markdown
Author

Addressed: the missing-cache-fields test now also asserts total_tokens stays input+output when cache counters are absent/zero.

@anujbolewar anujbolewar left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Correct — total_tokens now includes cache read and cache creation tokens, which matches how Anthropic bills them, and the updated test pins it. Worth confirming the streaming path applies the identical accounting, since there is often a separate usage extractor there — if it still sums input plus output only, totals would diverge between streaming and non-streaming calls.

Confirm sync/async streaming use the shared extractor so cache read/creation stay in billed totals, and strengthen the missing-cache-fields assertions.
@LHMQ878
LHMQ878 force-pushed the fix/6768-anthropic-cache-total-tokens branch from 7fe4a50 to d389c13 Compare August 8, 2026 02:34
@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@LHMQ878

LHMQ878 commented Aug 8, 2026

Copy link
Copy Markdown
Author

@anujbolewar Confirmed — streaming does not use a separate usage extractor.

Both sync and async streaming paths call the same _extract_anthropic_token_usage on stream.get_final_message() (same helper as non-streaming messages.create). After #6844 landed on main, that helper already folds cache_read_input_tokens + cache_creation_input_tokens into billed input_tokens, so total_tokens = input_tokens + output_tokens includes cache counters on streaming and non-streaming alike.

To pin that, I rebased onto latest main and added unit tests that drive sync/async stream=True calls with mocked final-message usage and assert total_tokens == 200 (100+50+30+20), plus the missing-cache-fields total stays at input+output only.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/crewai/tests/llms/anthropic/test_anthropic.py`:
- Around line 1683-1687: Add separate test cases for the usage-token handling
around the existing Anthropic test: one fixture must omit both cache attributes
entirely, and another must define both attributes as numeric 0 values. Assert
the resulting usage fields for each case, preserving the existing expectations
for input, output, total, and cache token values.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b295f38a-2aad-42e5-93ed-e68db31fa45f

📥 Commits

Reviewing files that changed from the base of the PR and between 92012ae and d389c13.

📒 Files selected for processing (1)
  • lib/crewai/tests/llms/anthropic/test_anthropic.py

Comment thread lib/crewai/tests/llms/anthropic/test_anthropic.py
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Conversational Flow golden use case improvements - Anthropic total_tokens omits cache read/write tokens, undercounting cost

2 participants