fix(python): stop double-counting cached tokens in Usage.tally() - #125
Draft
rootkiller6788 wants to merge 1 commit into
Draft
fix(python): stop double-counting cached tokens in Usage.tally()#125rootkiller6788 wants to merge 1 commit into
rootkiller6788 wants to merge 1 commit into
Conversation
Usage.tally() added subusage.total_tokens and then added subusage.cached_token_count again on top. cached_token_count is already included in total_tokens (cached tokens are part of the prompt), so the aggregate total was inflated by the cached token count on every tally. Remove the redundant addition and add unit tests covering single and multiple usage accumulation.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Usage.tally()double-counts cached tokens when aggregating usage across messages/turns.The method currently does:
total_tokensis documented as "Total number of tokens used in the request (prompt + generation)". Cached tokens are a subset of the prompt tokens, so they are already included intotal_tokens. Addingsubusage.cached_token_counta second time inflates the aggregated total.Repro
Fix
Remove the redundant
self.total_tokens += subusage.cached_token_countline sototal_tokensis only accumulated once, and addtests/test_usage.pycovering single and multiple usage accumulation (including a cached-token case that would fail before this fix).Verification
Usage.cost()pricing logic.