Repository navigation
fix(cost_calculator): prevent double-counting Anthropic cache tokens in custom pricing (#40006) - #40016
Conversation
…nd Model Hub UI Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…mutation Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
|
77cdf3a to
a3205d8
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
lets-order-some-fries
left a comment
There was a problem hiding this comment.
I filed #40006, so I checked this against the cases I had already built for it rather than just reading the diff. The fix is correct and the gate is the right shape. Numbers below are from applying your production change to litellm_internal_staging at 2151dcbd and running each path.
| case | before | with your change |
|---|---|---|
| normal Anthropic response (the reported bug) | 10.990x | 1.000x |
legacy kwargs, no usage object (cache_read_input_tokens= passed directly) |
1.000x | 1.000x |
| OpenAI-shaped usage, control | 1.000x | 1.000x |
The middle row is the one I most expected a gate like this to break, and it doesn't. With no usage object _pt_details stays None, so the re-inflation still fires and the cached tokens are still billed — if that had regressed, cached tokens would have gone entirely unbilled on that path, which is worse than the bug being fixed. Worth keeping a test on it; I don't see one in the diff.
On whether _pt_details is None is a tight enough gate. I looked for a shape where the details object is present but the cache count lives only on the Anthropic-style attributes, since that would skip re-inflation while prompt_tokens still excluded the cache tokens. Constructed by hand it does under-bill (the fresh input tokens drop out). But I could not find a provider that produces it, and I checked before raising it:
bedrock/chat/converse_transformation.pydoesinput_tokens += cache_read_input_tokens(L1927) and setscached_tokens=in the details (L1933) — same contract as Anthropic, so your gate covers it.anthropic/experimental_pass_through/adapters/streaming_iterator.pysetscache_read_input_tokens=0with no details, so re-inflation adds zero.vertex_aiandusage_object_transformationboth set the details alongside.
So the tighter gate (comparing prompt_tokens against text_tokens + cached + creation) would only defend a shape nothing currently emits. I'd keep yours — it is simpler and reads as the invariant it enforces. Mentioning the edge only so the choice is on the record if a provider later reports cache tokens without folding them in.
One housekeeping thing: the diff currently carries four unrelated Dockerfile changes (--extra mongodb) from base drift. They will make the PR look wider than it is when a maintainer skims it; a rebase onto current litellm_internal_staging should drop them and leave just cost_calculator.py and the test file.
Thanks for picking this up so quickly — the reproduction in your description matches what I measured independently.
a3205d8 to
65926aa
Compare
|
Rebased cleanly onto latest litellm_internal_staging (commit 65926aa). All base-drift lines in Dockerfiles have been eliminated, isolating the diff exclusively to litellm/cost_calculator.py and ests/test_litellm/test_cost_calculator.py. All unit tests pass cleanly. |
…ow read fails Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…iption feat(model_hub): surface model_info.description in Model Hub
…ip_save_on_failed_read fix(health): skip background health check DB writes when the latest-row read fails
…in custom pricing (BerriAI#40006) Anthropic responses transformed via calculate_usage() already normalize prompt_tokens to include cache_read_input_tokens and cache_creation_input_tokens. When prompt_tokens_details is present, cost_per_token was re-adding these cached tokens a second time to _normalized_prompt_tokens, causing custom_cost_per_token to bill cached tokens twice: once at the regular input rate and again at the custom cache rate. Skip re-inflating prompt_tokens when prompt_tokens_details is already populated from the provider usage transformation.
65926aa to
45d883a
Compare
|
Thanks for the thoughtful review and for sharing your test findings @lets-order-some-fries! I've rebased the branch onto current \litellm_internal_staging\ to drop the unrelated base-drift diffs. The PR now touches strictly \litellm/cost_calculator.py\ and \ ests/test_litellm/test_cost_calculator.py, with all 195 cost calculator tests passing cleanly. |
|
| # prompt_tokens already includes cache tokens, so re-inflation is skipped. | ||
| _normalized_prompt_tokens = float(prompt_tokens) | ||
| if _is_anthropic_style: | ||
| if _is_anthropic_style and _pt_details is None: |
There was a problem hiding this comment.
Raw cache usage undercharges When a
ModelResponse contains a Usage built with raw Anthropic-style prompt_tokens and cache_read_input_tokens, the Usage constructor creates prompt_tokens_details without adding cached tokens to prompt_tokens. completion_cost retains that usage shape, but this guard treats the details as proof that the cache tokens were already added. Custom pricing then subtracts those tokens from an already uninflated prompt total, undercharging regular input tokens. The updated test covers only usage that has already been normalized; please retain coverage for this raw shape too.
|
@amasen02 I checked greptile's P1 on main at
Main's One thing for whoever decides: main's default pricing already reads
# calculate_usage / Bedrock converse fold cache tokens into prompt_tokens and record the rest as
# text_tokens; a Usage built from raw Anthropic kwargs has no text_tokens and still needs them added.
_text_tokens = getattr(_pt_details, "text_tokens", None) if _pt_details is not None else None
_prompt_includes_cache = (
_text_tokens is not None
and float(prompt_tokens) >= _text_tokens + _cache_read_tokens + _cache_creation_tokens
)
_normalized_prompt_tokens = float(prompt_tokens)
if _is_anthropic_style and not _prompt_includes_cache:
_normalized_prompt_tokens += _cache_read_tokens + _cache_creation_tokensOn a copy of main this gives Test sketch (import at the top of the file); on main the from litellm.llms.anthropic.chat.transformation import AnthropicConfig
_RATES = {"input_cost_per_token": 1e-6, "output_cost_per_token": 5e-6, "cache_read_input_token_cost": 1e-7}
_EXPECTED = 1000 * 1e-6 + 800 * 1e-7 + 50 * 5e-6 # 0.00133
@pytest.mark.parametrize(
"usage",
[
# built from Anthropic kwargs: prompt_tokens excludes the cache reads
Usage(prompt_tokens=1000, completion_tokens=50, total_tokens=1050, cache_read_input_tokens=800),
# an Anthropic response: calculate_usage folds them into prompt_tokens
AnthropicConfig().calculate_usage(
usage_object={
"input_tokens": 1000,
"output_tokens": 50,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 800,
},
reasoning_content=None,
),
],
ids=["raw_kwargs", "calculate_usage"],
)
def test_custom_pricing_anthropic_cache_reads_billed_once(usage):
response = ModelResponse(model="claude-sonnet-4-5", choices=[], usage=usage)
cost = litellm.completion_cost(
completion_response=response, custom_llm_provider="anthropic", custom_cost_per_token=_RATES
)
assert cost == pytest.approx(_EXPECTED)
def test_custom_pricing_anthropic_legacy_kwargs_without_usage_object():
prompt_cost, completion_cost = litellm.cost_per_token(
model="claude-sonnet-4-5",
custom_llm_provider="anthropic",
prompt_tokens=1000,
completion_tokens=50,
cache_read_input_tokens=800,
custom_cost_per_token=_RATES,
)
assert prompt_cost + completion_cost == pytest.approx(_EXPECTED)A correction to #40006: the proxy's per-deployment pricing doesn't pass The branch also needs a rebase onto main: it has conflicts, the retarget brought in 12 unrelated files, and the test file is now |
Fixes #40006
Motivation and Context
When a deployment configures
custom_cost_per_tokenwithcache_read_input_token_cost(and optionallycache_creation_input_token_cost), cache-read tokens on Anthropic responses are billed twice: once at the regular input rate and again at the custom cache-read rate.Root Cause
In
litellm/cost_calculator.py:AnthropicConfig.calculate_usage()normalizes Anthropic responses intoUsage, setting:prompt_tokens = input_tokens + cache_read_input_tokens + cache_creation_input_tokensprompt_tokens_detailswithcached_tokens,cache_creation_tokens, andtext_tokenscost_per_token()(lines 416-419), when_is_anthropic_stylewas set fromcache_read_input_tokens, it unconditionally re-added_cache_read_tokens + _cache_creation_tokensto_normalized_prompt_tokens:usage_object.prompt_tokensalready included cache tokens,_normalized_prompt_tokenswas inflated a second time. When_cost_per_token_custom_pricing_helper()calculated:regular_prompt_tokensstill contained the cache tokens, causing them to be charged atinput_cost_per_tokenas well as atcache_read_input_token_cost.Proposed Fix
Skip re-inflating
prompt_tokenswhenprompt_tokens_detailsis already populated from the provider usage transformation:This ensures:
AnthropicConfig, Bedrock converse, etc.) retain their normalizedprompt_tokenswithout double-counting.cost_per_token()passing rawprompt_tokenswith no usage object continue to be re-inflated properly.Verification & Reproduction
Minimal Reproduction
got 0.11001000(overcharge of$0.10000000, 11x higher than configured rate)got 0.01001000(exact 1.000x match with configured rate)Unit Tests
test_custom_pricing_anthropic_cache_tokens_not_double_countedintests/test_litellm/test_cost_calculator.py.test_custom_pricing_anthropic_cache_creation_not_double_countedintests/test_litellm/test_cost_calculator.py.test_custom_pricing_anthropic_style_cache_tokens_not_double_countedto drive throughAnthropicConfig.calculate_usage().tests/test_litellm/test_cost_calculator.pypass cleanly.