fix: Fix Anthropic cumulative usage metrics inflation #5276
+247
−1
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.
Fix Anthropic cumulative usage metrics inflation
Summary
_is_cumulative_usageflag to Anthropic streaming responses to distinguish cumulative metrics from incremental metricsRoot Cause: During tool calling, Anthropic returns cumulative usage totals across multiple streaming events (e.g., Event 1: 63k tokens, Event 2: 64k tokens including Event 1, Event 3: 65k tokens including Events 1+2). Agno was accumulating these values (63k + 64k + 65k = 192k) instead of using the final cumulative total (65k).
Fix: Mark Anthropic usage metrics as cumulative with
_is_cumulative_usage = Trueflag, then check this flag in base model and use assignment (=) instead of accumulation (+=) for cumulative metrics.Type of change
Checklist
./scripts/format.shand./scripts/validate.sh)Files Modified
libs/agno/agno/models/anthropic/claude.py(lines 586-589)_is_cumulative_usage = Trueflag when parsing streaming usage metricslibs/agno/agno/models/base.py(lines 810-817)_populate_assistant_messageto check for cumulative usage flag=) for cumulative metrics, accumulation (+=) for incremental metricslibs/agno/tests/unit/models/test_anthropic_cumulative_usage.py(new file)test_anthropic_cumulative_usage_not_inflated: Verifies Anthropic cumulative usage is replaced correctlytest_non_cumulative_usage_still_accumulates: Ensures OpenAI/Gemini behavior remains unchangedTest Results
$ python -m pytest libs/agno/tests/unit/models/ -v ======================== 19 passed, 1 warning in 2.89s =========================All existing model tests pass, including:
Additional Notes
Before Fix (Bug)
After Fix (Correct)
Impact
getattr()with defaultFalsefor missing flagReferences