Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(anthropic): bill undetailed iteration cache writes at the 5m rate

mateo-berri0ab23f5ce9eb
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py
index 0dc877a700b..31713f8f085 100644
--- a/litellm/llms/anthropic/chat/transformation.py
+++ b/litellm/llms/anthropic/chat/transformation.py
@@ -1,7 +1,7 @@
import json
import re
import time
-from collections.abc import Iterable, Mapping
+from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Any, Final, NoReturn, cast
import httpx
@@ -2120,23 +2120,25 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):
@staticmethod
def _aggregate_cache_creation_token_details(
- cache_creation_objects: Iterable[Mapping[str, Any] | None],
+ iterations: Sequence[Mapping[str, Any]],
) -> CacheCreationTokenDetails | None:
- breakdowns: Final = tuple(c for c in cache_creation_objects if isinstance(c, Mapping))
+ breakdowns: Final = tuple(c for c in (it.get("cache_creation") for it in iterations) if isinstance(c, Mapping))
if not breakdowns:
return None
+ detailed_5m: Final = sum(int(c.get("ephemeral_5m_input_tokens") or 0) for c in breakdowns)
+ detailed_1h: Final = sum(int(c.get("ephemeral_1h_input_tokens") or 0) for c in breakdowns)
+ total: Final = sum(int(it.get("cache_creation_input_tokens") or 0) for it in iterations)
+ undetailed: Final = max(total - detailed_5m - detailed_1h, 0)
return CacheCreationTokenDetails(
- ephemeral_5m_input_tokens=sum(int(c.get("ephemeral_5m_input_tokens") or 0) for c in breakdowns),
- ephemeral_1h_input_tokens=sum(int(c.get("ephemeral_1h_input_tokens") or 0) for c in breakdowns),
+ ephemeral_5m_input_tokens=detailed_5m + undetailed,
+ ephemeral_1h_input_tokens=detailed_1h,
)
@staticmethod
def _resolve_cache_creation_token_details(usage: Mapping[str, Any]) -> CacheCreationTokenDetails | None:
iterations: Final = usage.get("iterations")
if iterations:
- aggregated: Final = AnthropicConfig._aggregate_cache_creation_token_details(
- it.get("cache_creation") for it in iterations
- )
+ aggregated: Final = AnthropicConfig._aggregate_cache_creation_token_details(iterations)
if aggregated is not None:
return aggregated
cache_creation: Final = usage.get("cache_creation")
diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
index 79255d4f923..867b148bfc3 100644
--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
@@ -157,6 +157,56 @@ def test_calculate_usage_aggregates_cache_creation_split_across_iterations():
assert prompt_cost != pytest.approx(20000 * rate_5m)
+def test_calculate_usage_bills_undetailed_iteration_cache_writes_at_5m_rate():
+ """
+ When only some iterations carry the cache_creation breakdown, the writes
+ without a breakdown must still be billed (at the default 5m rate) instead
+ of silently priced at zero once details exist.
+
+ Regression for the Cursor Bugbot finding on the LIT-4868 fix.
+ """
+ from litellm.llms.anthropic.cost_calculation import cost_per_token
+
+ config = AnthropicConfig()
+ usage_object = {
+ "input_tokens": 0,
+ "output_tokens": 5,
+ "iterations": [
+ {
+ "type": "message",
+ "input_tokens": 0,
+ "output_tokens": 3,
+ "cache_creation_input_tokens": 10000,
+ "cache_read_input_tokens": 0,
+ "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 10000},
+ },
+ {
+ "type": "message",
+ "input_tokens": 0,
+ "output_tokens": 2,
+ "cache_creation_input_tokens": 7000,
+ "cache_read_input_tokens": 0,
+ },
+ ],
+ }
+
+ usage = config.calculate_usage(usage_object=usage_object, reasoning_content=None)
+
+ details = usage.prompt_tokens_details.cache_creation_token_details
+ assert details is not None
+ assert details.ephemeral_5m_input_tokens == 7000
+ assert details.ephemeral_1h_input_tokens == 10000
+ assert usage.prompt_tokens_details.cache_creation_tokens == 17000
+
+ info = litellm.get_model_info(model="claude-opus-4-8", custom_llm_provider="anthropic")
+ rate_5m = info["cache_creation_input_token_cost"]
+ rate_1h = info["cache_creation_input_token_cost_above_1hr"]
+
+ prompt_cost, _ = cost_per_token(model="claude-opus-4-8", usage=usage)
+ assert prompt_cost == pytest.approx(7000 * rate_5m + 10000 * rate_1h)
+ assert prompt_cost != pytest.approx(10000 * rate_1h)
+
+
def test_calculate_usage_clamps_text_tokens_when_reasoning_estimate_exceeds_output():
config = AnthropicConfig()