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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(cost_tracking): map OpenAI cache_write_tokens for prompt cache creation billing
Krrish Dholakiae6ec1532439a
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex 33bf546c239..85ed0665ebf 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -457,7 +457,8 @@ def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult:cache_creation_tokens = (cast(Optional[int],- getattr(usage.prompt_tokens_details, "cache_creation_tokens", 0),+ getattr(usage.prompt_tokens_details, "cache_write_tokens", 0)+ or getattr(usage.prompt_tokens_details, "cache_creation_tokens", 0),)or 0)@@ -906,10 +907,6 @@ def get_token_type_cost_breakdown(cache_read_tokens = prompt_tokens_details["cache_hit_tokens"]cache_creation_tokens = prompt_tokens_details["cache_creation_tokens"]cache_creation_token_details = prompt_tokens_details["cache_creation_token_details"]- # Some OpenAI-compatible providers (e.g. kimi-k2) report cache-write tokens- # under `cache_write_tokens`; mirror the total-cost normalization path.- if not cache_creation_tokens:- cache_creation_tokens = _coerce_token_count(getattr(usage.prompt_tokens_details, "cache_write_tokens", 0))# Fall back to the private top-level counters the Usage constructor mirrors cache# tokens onto, so providers/callers that bypass prompt_tokens_details are covered.if not cache_read_tokens:diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.pyindex 50f6f791bc2..497e9dc8cad 100644--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py@@ -380,6 +380,14 @@ def get_logging_payload(kwargs, response_obj, start_time, end_time) -> SpendLogscached_tokens = prompt_tokens_details.get("cached_tokens")if isinstance(cached_tokens, int) and cached_tokens > 0:additional_usage_values["cache_read_input_tokens"] = cached_tokens+ if "cache_creation_input_tokens" not in additional_usage_values:+ prompt_tokens_details = additional_usage_values.get("prompt_tokens_details")+ if isinstance(prompt_tokens_details, dict):+ cache_write_tokens = prompt_tokens_details.get("cache_write_tokens") or prompt_tokens_details.get(+ "cache_creation_tokens"+ )+ if isinstance(cache_write_tokens, int) and cache_write_tokens > 0:+ additional_usage_values["cache_creation_input_tokens"] = cache_write_tokensclean_metadata["additional_usage_values"] = additional_usage_valuesif litellm.cache is not None:diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 714ad372a5f..2a340a548e8 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -1534,14 +1534,22 @@ class PromptTokensDetailsWrapper(audio_length_seconds: Optional[float] = None"""Length of audio sent to the model. Used for multimodal embeddings priced per audio-second."""+ cache_write_tokens: Optional[int] = None+ """Number of cache write (creation) tokens sent to the model. OpenAI naming (prompt_tokens_details.cache_write_tokens); this is the canonical field."""+cache_creation_tokens: Optional[int] = None- """Number of cache creation tokens sent to the model. Used for Anthropic prompt caching."""+ """Number of cache creation tokens sent to the model. Anthropic/Bedrock naming; kept in sync with cache_write_tokens for backwards compatibility."""cache_creation_token_details: Optional[CacheCreationTokenDetails] = None"""Details of cache creation tokens sent to the model. Used for tracking 5m/1h cache creation tokens for Anthropic prompt caching."""def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)+ cache_write_tokens = (+ self.cache_write_tokens if self.cache_write_tokens is not None else self.cache_creation_tokens+ )+ self.cache_write_tokens = cache_write_tokens+ self.cache_creation_tokens = cache_write_tokensif self.character_count is None:del self.character_countif self.image_count is None:@@ -1554,6 +1562,8 @@ class PromptTokensDetailsWrapper(del self.web_search_requestsif self.tool_use_tokens is None:del self.tool_use_tokens+ if self.cache_write_tokens is None:+ del self.cache_write_tokensif self.cache_creation_tokens is None:del self.cache_creation_tokensif self.cache_creation_token_details is None:@@ -1662,9 +1672,10 @@ class Usage(SafeAttributeModel, CompletionUsage):if "cache_creation_input_tokens" in params and isinstance(params["cache_creation_input_tokens"], int):if _prompt_tokens_details is None:_prompt_tokens_details = PromptTokensDetailsWrapper(- cache_creation_tokens=params["cache_creation_input_tokens"]+ cache_write_tokens=params["cache_creation_input_tokens"])else:+ _prompt_tokens_details.cache_write_tokens = params["cache_creation_input_tokens"]_prompt_tokens_details.cache_creation_tokens = params["cache_creation_input_tokens"]super().__init__(diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.pyindex 9ff67a82f40..15caad0be2f 100644--- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py+++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_llm_cost_calc_utils.py@@ -2111,6 +2111,37 @@ def test_token_type_cost_breakdown_reads_cache_write_tokens():)+def test_generic_cost_per_token_openai_cache_write_tokens_gpt_5_6():+ """+ Regression: OpenAI gpt-5.6 reports cache-write tokens under+ prompt_tokens_details.cache_write_tokens (not the Anthropic cache_creation_tokens+ name). Those tokens must be billed at the cache-write rate rather than the plain+ input rate. Customer report: cache creation tokens were never counted for the+ GPT-5.6 series, so cost was undercounted on cache-write requests.+ """+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")++ model = "gpt-5.6"+ usage = Usage(+ prompt_tokens=1000,+ completion_tokens=10,+ total_tokens=1010,+ prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=0, cache_write_tokens=800),+ )++ assert usage.prompt_tokens_details.cache_write_tokens == 800+ assert usage.prompt_tokens_details.cache_creation_tokens == 800++ prompt_cost, _ = generic_cost_per_token(model=model, usage=usage, custom_llm_provider="openai")++ info = litellm.get_model_info(model=model, custom_llm_provider="openai")+ expected_prompt = (1000 - 800) * info["input_cost_per_token"] + 800 * info["cache_creation_input_token_cost"]+ assert prompt_cost == pytest.approx(expected_prompt)+ assert info["cache_creation_input_token_cost"] > info["input_cost_per_token"]+ assert prompt_cost > 1000 * info["input_cost_per_token"]++def test_token_type_cost_breakdown_reconciles_with_generic_total():"""Both-ways check: the reasoning subset must sum with the remaining (text) outputdiff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.pyindex 5d10bb33751..228d0b0673c 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py@@ -109,6 +109,50 @@ def test_get_logging_payload_does_not_map_missing_or_zero_cached_tokens(prompt_tassert "cache_read_input_tokens" not in additional_usage_values+def test_get_logging_payload_maps_openai_cache_write_tokens_to_cache_creation_input_tokens():+ additional_usage_values = _get_additional_usage_values_for_usage(+ litellm.Usage(+ prompt_tokens=1000,+ completion_tokens=2,+ total_tokens=1002,+ prompt_tokens_details={"cached_tokens": 0, "cache_write_tokens": 800},+ )+ )++ assert additional_usage_values["cache_creation_input_tokens"] == 800+ assert additional_usage_values["prompt_tokens_details"]["cache_write_tokens"] == 800+++def test_get_logging_payload_preserves_anthropic_cache_creation_input_tokens():+ additional_usage_values = _get_additional_usage_values_for_usage(+ litellm.Usage(+ prompt_tokens=1000,+ completion_tokens=2,+ total_tokens=1002,+ cache_creation_input_tokens=300,+ )+ )++ assert additional_usage_values["cache_creation_input_tokens"] == 300+++ "prompt_tokens_details",+ [None, {"cached_tokens": 100}, {"cached_tokens": 100, "cache_write_tokens": 0}],+)+def test_get_logging_payload_does_not_map_missing_or_zero_cache_write_tokens(prompt_tokens_details):+ additional_usage_values = _get_additional_usage_values_for_usage(+ litellm.Usage(+ prompt_tokens=10,+ completion_tokens=2,+ total_tokens=12,+ prompt_tokens_details=prompt_tokens_details,+ )+ )++ assert "cache_creation_input_tokens" not in additional_usage_values++def test_sanitize_request_body_for_spend_logs_payload_basic():request_body = {"messages": [{"role": "user", "content": "Hello, how are you?"}],diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex a1a9448cc58..b19246cd7ec 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -17,7 +17,9 @@ from litellm.types.utils import (Delta,LlmProviders,ModelResponseStream,+ PromptTokensDetailsWrapper,StreamingChoices,+ Usage,)from litellm.utils import (ProviderConfigManager,@@ -34,6 +36,44 @@ from litellm.utils import (# Adds the parent directory to the system path+def test_usage_openai_cache_write_tokens_populates_both_names():+ """OpenAI reports cache-write tokens as prompt_tokens_details.cache_write_tokens.+ The Usage constructor must expose it under both cache_write_tokens (canonical,+ OpenAI naming) and cache_creation_tokens (legacy, Anthropic naming)."""+ usage = Usage(+ prompt_tokens=1000,+ completion_tokens=10,+ total_tokens=1010,+ prompt_tokens_details={"cached_tokens": 0, "cache_write_tokens": 800},+ )+ assert usage.prompt_tokens_details.cache_write_tokens == 800+ assert usage.prompt_tokens_details.cache_creation_tokens == 800+++def test_usage_anthropic_cache_creation_maps_to_cache_write_tokens():+ """Anthropic/Bedrock report the top-level cache_creation_input_tokens field.+ It must be normalized onto the OpenAI cache_write_tokens name as well as the+ legacy cache_creation_tokens name."""+ usage = Usage(+ prompt_tokens=500,+ completion_tokens=50,+ total_tokens=550,+ cache_creation_input_tokens=300,+ cache_read_input_tokens=120,+ )+ assert usage.prompt_tokens_details.cache_write_tokens == 300+ assert usage.prompt_tokens_details.cache_creation_tokens == 300+ assert usage.prompt_tokens_details.cached_tokens == 120+++def test_prompt_tokens_details_no_cache_write_tokens_when_absent():+ """A read-only cache hit (no cache write) must not surface cache-write fields."""+ details = PromptTokensDetailsWrapper(cached_tokens=800)+ assert details.cached_tokens == 800+ assert not hasattr(details, "cache_write_tokens")+ assert not hasattr(details, "cache_creation_tokens")++@pytest.fixturedef local_model_cost_map(monkeypatch):original_model_cost = litellm.model_cost