Skip to content

fix(cost_calculator): prevent double-counting Anthropic cache tokens in custom pricing (#40006) - #40016

Open
amasen02 wants to merge 6 commits into
BerriAI:mainfrom
amasen02:fix/custom-pricing-anthropic-cache-read-double-count-40006
Open

amasen02 wants to merge 6 commits into
BerriAI:mainfrom
amasen02:fix/custom-pricing-anthropic-cache-read-double-count-40006

Conversation

@amasen02

@amasen02 amasen02 commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Fixes #40006

Motivation and Context

When a deployment configures custom_cost_per_token with cache_read_input_token_cost (and optionally cache_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:

  1. AnthropicConfig.calculate_usage() normalizes Anthropic responses into Usage, setting:
    • prompt_tokens = input_tokens + cache_read_input_tokens + cache_creation_input_tokens
    • prompt_tokens_details with cached_tokens, cache_creation_tokens, and text_tokens
  2. However, in cost_per_token() (lines 416-419), when _is_anthropic_style was set from cache_read_input_tokens, it unconditionally re-added _cache_read_tokens + _cache_creation_tokens to _normalized_prompt_tokens:
    _normalized_prompt_tokens = float(prompt_tokens)
    if _is_anthropic_style:
        _normalized_prompt_tokens += _cache_read_tokens + _cache_creation_tokens
  3. Because usage_object.prompt_tokens already included cache tokens, _normalized_prompt_tokens was inflated a second time. When _cost_per_token_custom_pricing_helper() calculated:
    regular_prompt_tokens = max(prompt_tokens - cached_tokens - cache_creation_tokens, 0)
    regular_prompt_tokens still contained the cache tokens, causing them to be charged at input_cost_per_token as well as at cache_read_input_token_cost.

Proposed Fix

Skip re-inflating prompt_tokens when prompt_tokens_details is already populated from the provider usage transformation:

_normalized_prompt_tokens = float(prompt_tokens)
if _is_anthropic_style and _pt_details is None:
    _normalized_prompt_tokens += _cache_read_tokens + _cache_creation_tokens

This ensures:

  • Responses that went through provider transformations (AnthropicConfig, Bedrock converse, etc.) retain their normalized prompt_tokens without double-counting.
  • Legacy direct callers of cost_per_token() passing raw prompt_tokens with no usage object continue to be re-inflated properly.

Verification & Reproduction

Minimal Reproduction

import os, litellm
from litellm.types.utils import ModelResponse, Choices, Message
from litellm.llms.anthropic.chat.transformation import AnthropicConfig

os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")

N = 100_000
usage = AnthropicConfig().calculate_usage(
    usage_object={"input_tokens": 10, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": N},
    reasoning_content=None,
)
resp = ModelResponse(model="claude-sonnet-4-5", choices=[], usage=usage)

custom = {
    "input_cost_per_token": 1e-06,
    "output_cost_per_token": 5e-06,
    "cache_read_input_token_cost": 1e-07,
}

cost = litellm.completion_cost(completion_response=resp, custom_llm_provider="anthropic", custom_cost_per_token=custom)
expected = 10 * 1e-06 + N * 1e-07
  • Before fix: got 0.11001000 (overcharge of $0.10000000, 11x higher than configured rate)
  • After fix: got 0.01001000 (exact 1.000x match with configured rate)

Unit Tests

  • Added test_custom_pricing_anthropic_cache_tokens_not_double_counted in tests/test_litellm/test_cost_calculator.py.
  • Added test_custom_pricing_anthropic_cache_creation_not_double_counted in tests/test_litellm/test_cost_calculator.py.
  • Updated test_custom_pricing_anthropic_style_cache_tokens_not_double_counted to drive through AnthropicConfig.calculate_usage().
  • All 140/140 unit tests in tests/test_litellm/test_cost_calculator.py pass cleanly.

milan-berri and others added 2 commits August 21, 2026 02:41
…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>
@CLAassistant

CLAassistant commented Sep 6, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 4 committers have signed the CLA.

✅ ryan-crabbe-berri
✅ milan-berri
❌ yassin-berriai
❌ amasen02
You have signed the CLA already but the status is still pending? Let us recheck it.

@amasen02
amasen02 changed the base branch from main to litellm_internal_staging September 6, 2026 05:49
@amasen02
amasen02 force-pushed the fix/custom-pricing-anthropic-cache-read-double-count-40006 branch from 77cdf3a to a3205d8 Compare September 6, 2026 05:50
@codspeed

codspeed Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing amasen02:fix/custom-pricing-anthropic-cache-read-double-count-40006 (45d883a) with litellm_internal_staging (af6dc1d)

Open in CodSpeed

@codecov

codecov Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@lets-order-some-fries lets-order-some-fries left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.py does input_tokens += cache_read_input_tokens (L1927) and sets cached_tokens= in the details (L1933) — same contract as Anthropic, so your gate covers it.
  • anthropic/experimental_pass_through/adapters/streaming_iterator.py sets cache_read_input_tokens=0 with no details, so re-inflation adds zero.
  • vertex_ai and usage_object_transformation both 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.

@amasen02
amasen02 force-pushed the fix/custom-pricing-anthropic-cache-read-double-count-40006 branch from a3205d8 to 65926aa Compare September 7, 2026 14:03
@amasen02

amasen02 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

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.

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:49
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
yassin-berriai and others added 4 commits September 13, 2026 09:44
…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.
@amasen02
amasen02 force-pushed the fix/custom-pricing-anthropic-cache-read-double-count-40006 branch from 65926aa to 45d883a Compare September 14, 2026 23:05
@amasen02

Copy link
Copy Markdown
Contributor Author

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.

@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 14:41
@amasen02
amasen02 marked this pull request as ready for review September 29, 2026 13:04
@amasen02
amasen02 requested a review from a team September 29, 2026 13:04
@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Medium risk] Fixes double-counting of Anthropic cache tokens in cost calculation.

The PR should not merge until custom pricing handles unnormalized Usage objects with cache-token details without undercharging them.

Findings

  1. P1 Raw cache usage undercharges ▶

Summary

The PR corrects custom cache-token pricing for normalized Anthropic usage, makes background health-check persistence stop when its deduplication read fails, and adds model-group descriptions to API and hub views.

  • The pricing guard also changes how already-constructed, unnormalized Usage objects are billed; that path needs to remain supported.

Reviews (1) · Last reviewed commit: "fix(cost_calculator): prevent double-cou..."

# 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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 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.

@lets-order-some-fries

Copy link
Copy Markdown
Contributor

@amasen02 I checked greptile's P1 on main at 684a1edd44, and it's real. On 09-06 I called the fix correct and set this shape aside as hand-built only; I missed that it is exactly what Usage builds from int Anthropic cache kwargs.

Usage(prompt_tokens=1000, completion_tokens=50, total_tokens=1050, cache_read_input_tokens=800) in a ModelResponse, through completion_cost at input 1e-6, output 5e-6, cache read 1e-7, should cost 0.00133. Main gives 0.00133, this branch 0.00053. Usage.__init__ copies the 800 into prompt_tokens_details without adding it to prompt_tokens (litellm/types/utils.py:1924-1940), so L436 skips re-inflation and the helper subtracts 800 from the 1000 fresh tokens. (Branch figure: main's helper, unchanged by the diff, given the prompt_tokens your gate leaves; I didn't run the branch.)

Main's test_custom_pricing_anthropic_style_cache_tokens_not_double_counted (tests/unit/test_cost_calculator.py:2849-2889) is this shape: 0.009075 on main, 0.003675 under the gate. The branch swapped its input for calculate_usage, so the case is no longer tested.

One thing for whoever decides: main's default pricing already reads Usage.prompt_tokens as including cache. Without custom_cost_per_token, that test's Usage bills 0.003675 at claude-sonnet-4-5's map rates, which are the test's rates, and a Router deployment with custom prices bills the 1000/800 case above at 0.00053. So the gate makes this branch agree with the other paths; what it changes is the custom branch's own contract and its test. If that is the intended contract, the other consistent fix is to keep the gate and restore the raw-shape test with the new expectation and a comment saying so. If the old contract should hold:

calculate_usage and Bedrock converse record the uncached part as text_tokens (litellm/llms/anthropic/chat/transformation.py:2432-2437), so gating on it gets both shapes right. In place of L435-437:

    # 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_tokens

On a copy of main this gives 0.00133 for the case above and 0.01001 for #40006's (main 0.11001), and tests/unit/test_cost_calculator.py passes unchanged. It still double-counts, as main does, usage with inflated prompt_tokens and a cache-read attribute but no text_tokens (Gemini without promptTokensDetails). That differs from the raw shape only in prompt_tokens, so no gate on these fields gets both.

Test sketch (import at the top of the file); on main the calculate_usage case fails with 0.00213:

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 custom_cost_per_token (a Router deployment bills the #40006 case at 0.01001 on main), so both #40006 and this P1 only reach direct completion_cost/cost_per_token callers, who can pass their own Usage.

The branch also needs a rebase onto main: it has conflicts, the retarget brought in 12 unrelated files, and the test file is now tests/unit/test_cost_calculator.py (#43186).

This branch has not been deployed

No deployments
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.

[Bug]: custom_cost_per_token bills Anthropic cache-read tokens twice

7 participants