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
feat(anthropic/chat/transformation.py): account for 1h vs. 5m cache creation token cost difference
Krrish Dholakia2f45c7ffd396
diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex c5b47763f07..60a31198415 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -1,11 +1,12 @@# What is this?## Helper utilities for cost_per_token()-from typing import Any, Literal, Optional, Tuple, cast+from typing import Any, Literal, Optional, Tuple, TypedDict, castimport litellmfrom litellm._logging import verbose_loggerfrom litellm.types.utils import (+ CacheCreationTokenDetails,CallTypes,ImageResponse,ModelInfo,@@ -115,7 +116,7 @@ def _generic_cost_per_character(def _get_token_base_cost(model_info: ModelInfo, usage: Usage-) -> Tuple[float, float, float, float]:+) -> Tuple[float, float, float, float, float]:"""Return prompt cost, completion cost, and cache costs for a given model and usage.@@ -134,6 +135,10 @@ def _get_token_base_cost(cache_creation_cost = cast(float, _get_cost_per_unit(model_info, "cache_creation_input_token_cost"))+ cache_creation_cost_above_1hr = cast(+ float,+ _get_cost_per_unit(model_info, "cache_creation_input_token_cost_above_1hr"),+ )cache_read_cost = cast(float, _get_cost_per_unit(model_info, "cache_read_input_token_cost"))@@ -194,7 +199,13 @@ def _get_token_base_cost(except Exception:continue- return prompt_base_cost, completion_base_cost, cache_creation_cost, cache_read_cost+ return (+ prompt_base_cost,+ completion_base_cost,+ cache_creation_cost,+ cache_creation_cost_above_1hr,+ cache_read_cost,+ )def calculate_cost_component(@@ -241,120 +252,258 @@ def _get_cost_per_unit(return default_value-def generic_cost_per_token(- model: str, usage: Usage, custom_llm_provider: str-) -> Tuple[float, float]:+def calculate_cache_writing_cost(+ cache_creation_tokens: int,+ cache_creation_token_details: Optional[CacheCreationTokenDetails],+ cache_creation_cost_above_1hr: float,+ cache_creation_cost: float,+) -> float:"""- Calculates the cost per token for a given model, prompt tokens, and completion tokens.-- Handles context caching as well.-- Input:- - model: str, the model name without provider prefix- - usage: LiteLLM Usage block, containing anthropic caching information-- Returns:- Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd+ Adjust cost of cache creation tokens based on the cache creation token details."""-- ## GET MODEL INFO- model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider)-- ## CALCULATE INPUT COST- ### Cost of processing (non-cache hit + cache hit) + Cost of cache-writing (cache writing)- prompt_cost = 0.0- ### PROCESSING COST- text_tokens = usage.prompt_tokens- cache_hit_tokens = 0- cache_creation_tokens = 0- audio_tokens = 0- character_count = 0- image_count = 0- video_length_seconds = 0- if usage.prompt_tokens_details:- cache_hit_tokens = (- cast(- Optional[int], getattr(usage.prompt_tokens_details, "cached_tokens", 0)- )- or 0+ total_cost: float = 0.0+ if cache_creation_token_details is not None:+ # get the number of 5m and 1h cache creation tokens+ cache_creation_tokens_5m = (+ cache_creation_token_details.ephemeral_5m_input_tokens)- cache_creation_tokens = (- cast(- Optional[int],- getattr(usage.prompt_tokens_details, "cache_creation_tokens", 0),- )- or 0+ cache_creation_tokens_1h = (+ cache_creation_token_details.ephemeral_1h_input_tokens)- text_tokens = (- cast(- Optional[int], getattr(usage.prompt_tokens_details, "text_tokens", None)- )- or 0 # default to prompt tokens, if this field is not set+ # add the number of 5m and 1h cache creation tokens to the cache creation tokens+ total_cost += (+ cache_creation_tokens_5m * cache_creation_cost+ if cache_creation_tokens_5m is not None+ else 0.0)- audio_tokens = (- cast(Optional[int], getattr(usage.prompt_tokens_details, "audio_tokens", 0))- or 0+ total_cost += (+ cache_creation_tokens_1h * cache_creation_cost_above_1hr+ if cache_creation_tokens_1h is not None+ else 0.0)- character_count = (- cast(- Optional[int],- getattr(usage.prompt_tokens_details, "character_count", 0),- )- or 0+ else:+ total_cost += cache_creation_tokens * cache_creation_cost+ return total_cost+++class PromptTokensDetailsResult(TypedDict):+ cache_hit_tokens: int+ cache_creation_tokens: int+ cache_creation_token_details: Optional[CacheCreationTokenDetails]+ text_tokens: int+ audio_tokens: int+ character_count: int+ image_count: int+ video_length_seconds: int+++def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult:+ cache_hit_tokens = (+ cast(Optional[int], getattr(usage.prompt_tokens_details, "cached_tokens", 0))+ or 0+ )+ cache_creation_tokens = (+ cast(+ Optional[int],+ getattr(usage.prompt_tokens_details, "cache_creation_tokens", 0),)- image_count = (- cast(Optional[int], getattr(usage.prompt_tokens_details, "image_count", 0))- or 0+ or 0+ )+ cache_creation_token_details = (+ cast(+ Optional[CacheCreationTokenDetails],+ getattr(usage.prompt_tokens_details, "cache_creation_token_details", None),)- video_length_seconds = (- cast(- Optional[int],- getattr(usage.prompt_tokens_details, "video_length_seconds", 0),- )- or 0+ or None+ )+ text_tokens = (+ cast(Optional[int], getattr(usage.prompt_tokens_details, "text_tokens", None))+ or 0 # default to prompt tokens, if this field is not set+ )+ audio_tokens = (+ cast(Optional[int], getattr(usage.prompt_tokens_details, "audio_tokens", 0))+ or 0+ )+ character_count = (+ cast(+ Optional[int],+ getattr(usage.prompt_tokens_details, "character_count", 0),+ )+ or 0+ )+ image_count = (+ cast(Optional[int], getattr(usage.prompt_tokens_details, "image_count", 0)) or 0+ )+ video_length_seconds = (+ cast(+ Optional[int],+ getattr(usage.prompt_tokens_details, "video_length_seconds", 0),)+ or 0+ )- ## EDGE CASE - text tokens not set inside PromptTokensDetails+ return PromptTokensDetailsResult(+ cache_hit_tokens=cache_hit_tokens,+ cache_creation_tokens=cache_creation_tokens,+ cache_creation_token_details=cache_creation_token_details,+ text_tokens=text_tokens,+ audio_tokens=audio_tokens,+ character_count=character_count,+ image_count=image_count,+ video_length_seconds=video_length_seconds,+ )- if text_tokens == 0:- text_tokens = (- usage.prompt_tokens- - cache_hit_tokens- - audio_tokens- - cache_creation_tokens++class CompletionTokensDetailsResult(TypedDict):+ audio_tokens: int+ text_tokens: int+ reasoning_tokens: int+++def _parse_completion_tokens_details(usage: Usage) -> CompletionTokensDetailsResult:+ audio_tokens = (+ cast(+ Optional[int],+ getattr(usage.completion_tokens_details, "audio_tokens", 0),)+ or 0+ )+ text_tokens = (+ cast(+ Optional[int],+ getattr(usage.completion_tokens_details, "text_tokens", None),+ )+ or 0 # default to completion tokens, if this field is not set+ )+ reasoning_tokens = (+ cast(+ Optional[int],+ getattr(usage.completion_tokens_details, "reasoning_tokens", 0),+ )+ or 0+ )- prompt_base_cost, completion_base_cost, cache_creation_cost, cache_read_cost = (- _get_token_base_cost(model_info=model_info, usage=usage)+ return CompletionTokensDetailsResult(+ audio_tokens=audio_tokens,+ text_tokens=text_tokens,+ reasoning_tokens=reasoning_tokens,)- prompt_cost = float(text_tokens) * prompt_base_cost++def _calculate_input_cost(+ prompt_tokens_details: PromptTokensDetailsResult,+ model_info: ModelInfo,+ prompt_base_cost: float,+ cache_read_cost: float,+ cache_creation_cost: float,+ cache_creation_cost_above_1hr: float,+) -> float:+ """+ Calculates the input cost for a given model, prompt tokens, and completion tokens.+ """+ prompt_cost = float(prompt_tokens_details["text_tokens"]) * prompt_base_cost### CACHE READ COST - Now uses tiered pricing- prompt_cost += float(cache_hit_tokens) * cache_read_cost+ prompt_cost += float(prompt_tokens_details["cache_hit_tokens"]) * cache_read_cost### AUDIO COSTprompt_cost += calculate_cost_component(- model_info, "input_cost_per_audio_token", audio_tokens+ model_info, "input_cost_per_audio_token", prompt_tokens_details["audio_tokens"])### CACHE WRITING COST - Now uses tiered pricing- prompt_cost += float(cache_creation_tokens) * cache_creation_cost+ prompt_cost += calculate_cache_writing_cost(+ cache_creation_tokens=prompt_tokens_details["cache_creation_tokens"],+ cache_creation_token_details=prompt_tokens_details[+ "cache_creation_token_details"+ ],+ cache_creation_cost_above_1hr=cache_creation_cost_above_1hr,+ cache_creation_cost=cache_creation_cost,+ )### CHARACTER COSTprompt_cost += calculate_cost_component(- model_info, "input_cost_per_character", character_count+ model_info, "input_cost_per_character", prompt_tokens_details["character_count"])### IMAGE COUNT COSTprompt_cost += calculate_cost_component(- model_info, "input_cost_per_image", image_count+ model_info, "input_cost_per_image", prompt_tokens_details["image_count"])### VIDEO LENGTH COSTprompt_cost += calculate_cost_component(- model_info, "input_cost_per_video_per_second", video_length_seconds+ model_info,+ "input_cost_per_video_per_second",+ prompt_tokens_details["video_length_seconds"],+ )++ return prompt_cost+++def generic_cost_per_token(+ model: str, usage: Usage, custom_llm_provider: str+) -> Tuple[float, float]:+ """+ Calculates the cost per token for a given model, prompt tokens, and completion tokens.++ Handles context caching as well.++ Input:+ - model: str, the model name without provider prefix+ - usage: LiteLLM Usage block, containing anthropic caching information++ Returns:+ Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd+ """++ ## GET MODEL INFO+ model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider)++ ## CALCULATE INPUT COST+ ### Cost of processing (non-cache hit + cache hit) + Cost of cache-writing (cache writing)+ prompt_cost = 0.0+ ### PROCESSING COST+ prompt_tokens_details = PromptTokensDetailsResult(+ cache_hit_tokens=0,+ cache_creation_tokens=0,+ cache_creation_token_details=None,+ text_tokens=usage.prompt_tokens,+ audio_tokens=0,+ character_count=0,+ image_count=0,+ video_length_seconds=0,+ )+ if usage.prompt_tokens_details:+ prompt_tokens_details = _parse_prompt_tokens_details(usage)++ ## EDGE CASE - text tokens not set inside PromptTokensDetails++ if prompt_tokens_details["text_tokens"] == 0:+ text_tokens = (+ usage.prompt_tokens+ - prompt_tokens_details["cache_hit_tokens"]+ - prompt_tokens_details["audio_tokens"]+ - prompt_tokens_details["cache_creation_tokens"]+ )+ prompt_tokens_details["text_tokens"] = text_tokens++ (+ prompt_base_cost,+ completion_base_cost,+ cache_creation_cost,+ cache_creation_cost_above_1hr,+ cache_read_cost,+ ) = _get_token_base_cost(model_info=model_info, usage=usage)++ prompt_cost = _calculate_input_cost(+ prompt_tokens_details=prompt_tokens_details,+ model_info=model_info,+ prompt_base_cost=prompt_base_cost,+ cache_read_cost=cache_read_cost,+ cache_creation_cost=cache_creation_cost,+ cache_creation_cost_above_1hr=cache_creation_cost_above_1hr,)## CALCULATE OUTPUT COST@@ -363,27 +512,10 @@ def generic_cost_per_token(reasoning_tokens = 0is_text_tokens_total = Falseif usage.completion_tokens_details is not None:- audio_tokens = (- cast(- Optional[int],- getattr(usage.completion_tokens_details, "audio_tokens", 0),- )- or 0- )- text_tokens = (- cast(- Optional[int],- getattr(usage.completion_tokens_details, "text_tokens", None),- )- or 0 # default to completion tokens, if this field is not set- )- reasoning_tokens = (- cast(- Optional[int],- getattr(usage.completion_tokens_details, "reasoning_tokens", 0),- )- or 0- )+ completion_tokens_details = _parse_completion_tokens_details(usage)+ audio_tokens = completion_tokens_details["audio_tokens"]+ text_tokens = completion_tokens_details["text_tokens"]+ reasoning_tokens = completion_tokens_details["reasoning_tokens"]if text_tokens == 0:text_tokens = usage.completion_tokensdiff --git a/litellm/utils.py b/litellm/utils.pyindex e3dba0c7e47..dc7911f7d11 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -4891,6 +4891,9 @@ def _get_model_info_helper( # noqa: PLR0915cache_read_input_token_cost=_model_info.get("cache_read_input_token_cost", None),+ cache_creation_input_token_cost_above_1hr=_model_info.get(+ "cache_creation_input_token_cost_above_1hr", None+ ),input_cost_per_character=_model_info.get("input_cost_per_character", None),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 2cd00fd016b..8e49fe7b58d 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@@ -22,8 +22,11 @@ sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system path-from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token-from litellm.types.utils import Usage+from litellm.litellm_core_utils.llm_cost_calc.utils import (+ calculate_cache_writing_cost,+ generic_cost_per_token,+)+from litellm.types.utils import CacheCreationTokenDetails, Usagedef test_reasoning_tokens_no_price_set():@@ -385,3 +388,79 @@ def test_string_cost_values_with_threshold():assert round(prompt_cost, 12) == round(expected_prompt_cost, 12)assert round(completion_cost, 12) == round(expected_completion_cost, 12)+++def test_calculate_cache_writing_cost():+ """Test the calculate_cache_writing_cost function with detailed cache creation token breakdown."""++ # Test case 1: With cache creation token details (matching the provided input)+ cache_creation_tokens = 14055+ cache_creation_token_details = CacheCreationTokenDetails(+ ephemeral_5m_input_tokens=56, ephemeral_1h_input_tokens=13999+ )+ cache_creation_cost_above_1hr = 6e-06+ cache_creation_cost = 3.75e-06++ result = calculate_cache_writing_cost(+ cache_creation_tokens=cache_creation_tokens,+ cache_creation_token_details=cache_creation_token_details,+ cache_creation_cost_above_1hr=cache_creation_cost_above_1hr,+ cache_creation_cost=cache_creation_cost,+ )++ # Expected calculation:+ # 5m tokens: 56 * 3.75e-06 = 0.00021+ # 1h tokens: 13999 * 6e-06 = 0.083994+ # Total: 0.00021 + 0.083994 = 0.084204+ expected_cost = (56 * 3.75e-06) + (13999 * 6e-06)++ assert round(result, 6) == round(expected_cost, 6)+ assert round(result, 6) == 0.084204++ # Test case 2: Without cache creation token details (fallback behavior)+ cache_creation_tokens_no_details = 1000+ cache_creation_token_details_none = None+ cache_creation_cost_fallback = 5e-06++ result_no_details = calculate_cache_writing_cost(+ cache_creation_tokens=cache_creation_tokens_no_details,+ cache_creation_token_details=cache_creation_token_details_none,+ cache_creation_cost_above_1hr=cache_creation_cost_above_1hr,+ cache_creation_cost=cache_creation_cost_fallback,+ )++ # Expected calculation when no details: 1000 * 5e-06 = 0.005+ expected_cost_no_details = 1000 * 5e-06++ assert round(result_no_details, 6) == round(expected_cost_no_details, 6)+ assert result_no_details == 0.005++ # Test case 3: With cache creation token details but None values+ cache_creation_token_details_partial = CacheCreationTokenDetails(+ ephemeral_5m_input_tokens=None, ephemeral_1h_input_tokens=100+ )++ result_partial = calculate_cache_writing_cost(+ cache_creation_tokens=500,+ cache_creation_token_details=cache_creation_token_details_partial,+ cache_creation_cost_above_1hr=6e-06,+ cache_creation_cost=3e-06,+ )++ # Expected calculation: 0 (for None 5m tokens) + (100 * 6e-06) = 0.0006+ expected_cost_partial = (0.0) + (100 * 6e-06)++ assert round(result_partial, 6) == round(expected_cost_partial, 6)+ assert round(result_partial, 6) == 0.0006++ # Test case 4: Zero costs+ result_zero = calculate_cache_writing_cost(+ cache_creation_tokens=1000,+ cache_creation_token_details=CacheCreationTokenDetails(+ ephemeral_5m_input_tokens=50, ephemeral_1h_input_tokens=950+ ),+ cache_creation_cost_above_1hr=0.0,+ cache_creation_cost=0.0,+ )++ assert result_zero == 0.0