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): support cache_creation_input_token_cost in tiered pricing and make tier selection all-or-nothing
mateo6517c1dc0671
diff --git a/ci_cd/generate_model_prices_schema.py b/ci_cd/generate_model_prices_schema.pyindex 0f449f01ec9..1b60f986ca4 100644--- a/ci_cd/generate_model_prices_schema.py+++ b/ci_cd/generate_model_prices_schema.py@@ -96,6 +96,7 @@ ARRAY_KEYS: dict[str, JsonSchema] = {"output_cost_per_token": NONNEG_NUMBER,"output_cost_per_reasoning_token": NONNEG_NUMBER,"cache_read_input_token_cost": NONNEG_NUMBER,+ "cache_creation_input_token_cost": NONNEG_NUMBER,"input_cost_per_query": NONNEG_NUMBER,},"additionalProperties": False,diff --git a/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.py b/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.pyindex fb0f130a6cf..d4ce6abfcc4 100644--- a/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.py+++ b/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.py@@ -1,5 +1,5 @@"""-Provider-neutral graduated tiered pricing calculation.+Provider-neutral tiered pricing calculation.Shared by provider cost calculators (e.g. Dashscope) and the proxy budgetreservation logic so neither has to depend on the other.@@ -25,80 +25,6 @@ def _coerce_cost_per_token(value: float | str | None) -> float:return float(value)-def calculate_tiered_cost(- tokens: int,- tiered_pricing: list[dict],- cost_key: str,- fallback_cost_key: str | None = None,-) -> float:- """- Calculate cost for a given number of tokens based on a true tiered pricing structure.-- This function iterates through sorted pricing tiers, calculates the cost for the- number of tokens that fall into each tier's range, and sums them up to get the total cost.-- Args:- tokens (int): The total number of tokens to calculate the cost for.- tiered_pricing (List[dict]): A list of dictionaries, where each dictionary- represents a pricing tier.- cost_key (str): The key in the tier dictionary that holds the per-token cost- (e.g., 'input_cost_per_token').- fallback_cost_key (Optional[str], optional): A fallback key to use if the- primary `cost_key` is not found in a tier. Defaults to None.-- Returns:- float: The total calculated cost for the given tokens.-- Example:- >>> tiered_pricing = [- ... {"range": [0, 100000], "input_cost_per_token": 0.0001},- ... {"range": [100000, 500000], "input_cost_per_token": 0.00005},- ... ]-- Calculating cost for 150,000 tokens:- (100,000 * 0.0001) + (50,000 * 0.00005) = $12.5- """- if not tiered_pricing or tokens <= 0:- return 0.0-- total_cost = 0.0- tokens_processed = 0-- sorted_tiers: Final = sorted(tiered_pricing, key=lambda x: x.get("range", [0, 0])[0])-- for tier in sorted_tiers:- if tokens_processed >= tokens:- break-- tier_range = tier.get("range", [])- if len(tier_range) != 2:- continue-- range_start, range_end = tier_range-- if tokens <= range_start:- continue-- tier_start = max(range_start, tokens_processed)- tier_end = min(range_end, tokens)-- if tier_end > tier_start:- tokens_in_tier = tier_end - tier_start- cost_per_token = tier.get(cost_key) or tier.get(fallback_cost_key, 0)- total_cost += tokens_in_tier * _coerce_cost_per_token(cost_per_token)- tokens_processed = tier_end-- # After loop, check if any tokens remain (i.e., tokens > highest tier's end range)- # and charge them at the last tier's rate.- if tokens_processed < tokens and sorted_tiers:- last_tier: Final = sorted_tiers[-1]- remaining_tokens: Final = tokens - tokens_processed- cost_per_token = last_tier.get(cost_key) or last_tier.get(fallback_cost_key, 0)- total_cost += remaining_tokens * _coerce_cost_per_token(cost_per_token)-- return total_cost--def select_tier_for_input(tiered_pricing: list[dict],input_tokens: int,diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex b94851794f0..f0ec734bbc6 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -8,6 +8,10 @@ from typing import Any, Final, Literal, TypedDict, castimport litellmfrom litellm._logging import verbose_logger+from litellm.litellm_core_utils.llm_cost_calc.tiered_pricing import (+ select_tier_for_input,+ tier_rate,+)from litellm.types.utils import (CacheCreationTokenDetails,CallTypes,@@ -207,6 +211,33 @@ def _parse_above_token_threshold(key: str) -> float:return float(threshold_str.replace("k", "")) * (1000 if "k" in threshold_str else 1)+def _get_tiered_base_costs(model_info: ModelInfo, usage: Usage) -> tuple[float, float, float, float, float] | None:+ """+ Resolve the base rates from a model's ``tiered_pricing`` table, if it has one.++ Tiered pricing is all-or-nothing: one tier is picked from the request's input tokens+ and every token of the request is billed at that tier's rate. Rates the tier does not+ declare fall back to the tier's input rate, so a request never mixes tiers.+ """+ tiered_pricing: Final = model_info.get("tiered_pricing")+ if not isinstance(tiered_pricing, list) or not tiered_pricing:+ return None++ tier: Final = select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=usage.prompt_tokens)+ if tier is None or "input_cost_per_token" not in tier:+ return None++ cache_creation_cost: Final = tier_rate(tier, "cache_creation_input_token_cost", "input_cost_per_token")+ return (+ tier_rate(tier, "input_cost_per_token"),+ tier_rate(tier, "output_cost_per_token"),+ cache_creation_cost,+ tier_rate(tier, "cache_creation_input_token_cost_above_1hr", "cache_creation_input_token_cost")+ or cache_creation_cost,+ tier_rate(tier, "cache_read_input_token_cost", "input_cost_per_token"),+ )++def _get_token_base_cost(model_info: ModelInfo,usage: Usage,@@ -226,6 +257,10 @@ def _get_token_base_cost(Returns:Tuple[float, float, float, float] - (prompt_cost, completion_cost, cache_creation_cost, cache_read_cost)"""+ tiered_base_costs: Final = _get_tiered_base_costs(model_info=model_info, usage=usage)+ if tiered_base_costs is not None:+ return tiered_base_costs+# Get service tier aware cost keysinput_cost_key: Final = _get_service_tier_cost_key("input_cost_per_token", service_tier)output_cost_key: Final = _get_service_tier_cost_key("output_cost_per_token", service_tier)diff --git a/litellm/llms/dashscope/cost_calculator.py b/litellm/llms/dashscope/cost_calculator.pyindex 22a0d38d598..ea6d50f5b00 100644--- a/litellm/llms/dashscope/cost_calculator.py+++ b/litellm/llms/dashscope/cost_calculator.py@@ -1,108 +1,100 @@"""Cost calculator for Dashscope Chat models.-Handles tiered pricing and prompt caching scenarios.+Alibaba Model Studio tiered pricing is all-or-nothing: the tier is picked from the+total input tokens of a single request, and every token of that request (input,+cached, cache-creation, output, reasoning) is billed at that one tier's rate.+See https://help.aliyun.com/zh/model-studio/billing-for-model-studio"""from dataclasses import dataclassfrom typing import Final-from litellm.litellm_core_utils.llm_cost_calc.tiered_pricing import calculate_tiered_cost+from litellm.litellm_core_utils.llm_cost_calc.tiered_pricing import select_tier_for_input, tier_rate+from litellm.litellm_core_utils.llm_cost_calc.utils import (+ _parse_completion_tokens_details,+ _parse_prompt_tokens_details,+)from litellm.types.utils import ModelInfo, Usagefrom litellm.utils import get_model_info-@dataclass+@dataclass(frozen=True, slots=True)class TokenBreakdown:- """Token breakdown for cost calculation."""-text_tokens: intcached_tokens: int+ cache_creation_tokens: intcompletion_tokens: intreasoning_tokens: int+ @property+ def total_input_tokens(self) -> int:+ return self.text_tokens + self.cached_tokens + self.cache_creation_tokens-def _extract_token_breakdown(usage: Usage) -> TokenBreakdown:- """Extract token counts from usage, handling cached and reasoning tokens."""- cached_tokens = 0- if usage.prompt_tokens_details and hasattr(usage.prompt_tokens_details, "cached_tokens"):- cached_tokens = usage.prompt_tokens_details.cached_tokens or 0-- text_tokens: Final = usage.prompt_tokens - cached_tokens- reasoning_tokens = 0- if (- hasattr(usage, "completion_tokens_details")- and usage.completion_tokens_details- and hasattr(usage.completion_tokens_details, "reasoning_tokens")- ):- reasoning_tokens = usage.completion_tokens_details.reasoning_tokens or 0+def _extract_token_breakdown(usage: Usage) -> TokenBreakdown:+ prompt_details: Final = _parse_prompt_tokens_details(usage)+ cached_tokens: Final = prompt_details["cache_hit_tokens"]+ cache_creation_tokens: Final = prompt_details["cache_creation_tokens"]+ text_tokens: Final = max(usage.prompt_tokens - cached_tokens - cache_creation_tokens, 0)++ reasoning_tokens: Final = _parse_completion_tokens_details(usage)["reasoning_tokens"]+ completion_tokens: Final = max((usage.completion_tokens or 0) - reasoning_tokens, 0)++ return TokenBreakdown(+ text_tokens=text_tokens,+ cached_tokens=cached_tokens,+ cache_creation_tokens=cache_creation_tokens,+ completion_tokens=completion_tokens,+ reasoning_tokens=reasoning_tokens,+ )- completion_tokens: Final = (usage.completion_tokens or 0) - reasoning_tokens- return TokenBreakdown(text_tokens, cached_tokens, completion_tokens, reasoning_tokens)+def _flat_rate(model_info: ModelInfo, cost_key: str, fallback_cost_key: str) -> float:+ value: Final = model_info.get(cost_key)+ if value is None:+ return float(model_info.get(fallback_cost_key) or 0.0)+ return float(value)def _calculate_prompt_cost(breakdown: TokenBreakdown,model_info: ModelInfo,- tiered_pricing: list[dict] | None,+ tier: dict | None,) -> float:- """Calculate total prompt cost including cached tokens."""- if tiered_pricing:- text_cost: Final = calculate_tiered_cost(- tokens=breakdown.text_tokens,- tiered_pricing=tiered_pricing,- cost_key="input_cost_per_token",- )- cache_cost = calculate_tiered_cost(- tokens=breakdown.cached_tokens,- tiered_pricing=tiered_pricing,- cost_key="cache_read_input_token_cost",- fallback_cost_key="input_cost_per_token",+ if tier is not None:+ return (+ (breakdown.text_tokens * tier_rate(tier, "input_cost_per_token"))+ + (breakdown.cached_tokens * tier_rate(tier, "cache_read_input_token_cost", "input_cost_per_token"))+ + (+ breakdown.cache_creation_tokens+ * tier_rate(tier, "cache_creation_input_token_cost", "input_cost_per_token")+ ))- return text_cost + cache_costinput_cost: Final = float(model_info.get("input_cost_per_token") or 0.0)+ cache_read_cost: Final = _flat_rate(model_info, "cache_read_input_token_cost", "input_cost_per_token")+ cache_creation_cost: Final = _flat_rate(model_info, "cache_creation_input_token_cost", "input_cost_per_token")- # For cache_cost, first try the specific key, then fall back to input_cost.- cache_cost_val: Final = model_info.get("cache_read_input_token_cost")- if cache_cost_val is None:- cache_cost = input_cost- else:- cache_cost = float(cache_cost_val)-- return (breakdown.text_tokens * input_cost) + (breakdown.cached_tokens * cache_cost)+ return (+ (breakdown.text_tokens * input_cost)+ + (breakdown.cached_tokens * cache_read_cost)+ + (breakdown.cache_creation_tokens * cache_creation_cost)+ )def _calculate_completion_cost(breakdown: TokenBreakdown,model_info: ModelInfo,- tiered_pricing: list[dict] | None,+ tier: dict | None,) -> float:- """Calculate total completion cost including reasoning tokens."""- if tiered_pricing:- completion_cost: Final = calculate_tiered_cost(- tokens=breakdown.completion_tokens,- tiered_pricing=tiered_pricing,- cost_key="output_cost_per_token",- )- reasoning_cost = calculate_tiered_cost(- tokens=breakdown.reasoning_tokens,- tiered_pricing=tiered_pricing,- cost_key="output_cost_per_reasoning_token",- fallback_cost_key="output_cost_per_token",+ if tier is not None:+ return (breakdown.completion_tokens * tier_rate(tier, "output_cost_per_token")) + (+ breakdown.reasoning_tokens * tier_rate(tier, "output_cost_per_reasoning_token", "output_cost_per_token"))- return completion_cost + reasoning_costoutput_cost: Final = float(model_info.get("output_cost_per_token") or 0.0)-- # For reasoning_cost, first try the specific key, then fall back to output_cost.- reasoning_cost_val: Final = model_info.get("output_cost_per_reasoning_token")- if reasoning_cost_val is None:- reasoning_cost = output_cost- else:- reasoning_cost = float(reasoning_cost_val)+ reasoning_cost: Final = _flat_rate(model_info, "output_cost_per_reasoning_token", "output_cost_per_token")return (breakdown.completion_tokens * output_cost) + (breakdown.reasoning_tokens * reasoning_cost)@@ -122,11 +114,15 @@ def cost_per_token(model: str, usage: Usage) -> tuple[float, float]:"""model_info: Final = get_model_info(model=model, custom_llm_provider="dashscope")breakdown: Final = _extract_token_breakdown(usage)- tiered_pricing = model_info.get("tiered_pricing") if isinstance(model_info.get("tiered_pricing"), list) else None-- prompt_cost = _calculate_prompt_cost(breakdown=breakdown, model_info=model_info, tiered_pricing=tiered_pricing)- completion_cost: Final = _calculate_completion_cost(- breakdown=breakdown, model_info=model_info, tiered_pricing=tiered_pricing+ raw_tiers: Final = model_info.get("tiered_pricing")+ tiered_pricing: Final = raw_tiers if isinstance(raw_tiers, list) else None+ tier: Final = (+ select_tier_for_input(tiered_pricing=tiered_pricing, input_tokens=breakdown.total_input_tokens)+ if tiered_pricing+ else None)+ prompt_cost: Final = _calculate_prompt_cost(breakdown=breakdown, model_info=model_info, tier=tier)+ completion_cost: Final = _calculate_completion_cost(breakdown=breakdown, model_info=model_info, tier=tier)+return prompt_cost, completion_costdiff --git a/model_prices_and_context_window.schema.json b/model_prices_and_context_window.schema.jsonindex 56400e0666b..4c54822736c 100644--- a/model_prices_and_context_window.schema.json+++ b/model_prices_and_context_window.schema.json@@ -731,6 +731,10 @@"type": "number","minimum": 0},+ "cache_creation_input_token_cost": {+ "type": "number",+ "minimum": 0+ },"input_cost_per_query": {"type": "number","minimum": 0diff --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 158cdb45f6b..8531291d42d 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@@ -523,6 +523,118 @@ def test_generic_cost_per_token_honors_non_standard_above_threshold():litellm.model_cost.pop(model, None)+def test_generic_cost_per_token_tiered_pricing_charges_cache_creation_at_tier_rate():+ """Regression for LIT-4375: a tier's cache_creation_input_token_cost must be billed+ on the generic (provider-agnostic) path, not silently dropped."""+ model = "litellm-test-tiered-cache-creation"+ custom_llm_provider = "openrouter"+ litellm.register_model(+ {+ model: {+ "litellm_provider": custom_llm_provider,+ "mode": "chat",+ "tiered_pricing": [+ {+ "range": [0, 256000],+ "input_cost_per_token": 3.25e-07,+ "output_cost_per_token": 1.95e-06,+ "cache_creation_input_token_cost": 4.063e-07,+ "cache_read_input_token_cost": 3.25e-08,+ },+ {+ "range": [256000, 1000000],+ "input_cost_per_token": 6.5e-07,+ "output_cost_per_token": 3.9e-06,+ "cache_creation_input_token_cost": 8.125e-07,+ "cache_read_input_token_cost": 6.5e-08,+ },+ ],+ }+ }+ )++ try:+ usage = Usage(+ prompt_tokens=300000, # 200k new + 60k cache creation + 40k cache read+ completion_tokens=1000,+ total_tokens=301000,+ prompt_tokens_details=PromptTokensDetailsWrapper(+ cached_tokens=40000, cache_creation_tokens=60000+ ),+ )+ prompt_cost, completion_cost = generic_cost_per_token(+ model=model,+ usage=usage,+ custom_llm_provider=custom_llm_provider,+ )++ expected_prompt = (+ (200000 * 6.5e-07) + (60000 * 8.125e-07) + (40000 * 6.5e-08)+ )+ assert round(prompt_cost, 10) == round(expected_prompt, 10)+ assert round(completion_cost, 10) == round(1000 * 3.9e-06, 10)+ finally:+ litellm.model_cost.pop(model, None)+++def test_generic_cost_per_token_tiered_pricing_is_all_or_nothing():+ """Tiered pricing bills the whole request at the tier picked from its input tokens,+ for any provider, and falls back to flat pricing when no tier matches."""+ model = "litellm-test-tiered-all-or-nothing"+ custom_llm_provider = "openrouter"+ litellm.register_model(+ {+ model: {+ "litellm_provider": custom_llm_provider,+ "mode": "chat",+ "input_cost_per_token": 1e-06,+ "output_cost_per_token": 2e-06,+ "tiered_pricing": [+ {+ "range": [0, 32000],+ "input_cost_per_token": 4.6e-07,+ "output_cost_per_token": 2.3e-06,+ },+ {+ "range": [32000, 128000],+ "input_cost_per_token": 7e-07,+ "output_cost_per_token": 3.5e-06,+ },+ ],+ }+ }+ )++ try:+ usage = Usage(prompt_tokens=40000, completion_tokens=1000, total_tokens=41000)+ prompt_cost, completion_cost = generic_cost_per_token(+ model=model,+ usage=usage,+ custom_llm_provider=custom_llm_provider,+ )+ assert round(prompt_cost, 10) == round(40000 * 7e-07, 10)+ assert round(completion_cost, 10) == round(1000 * 3.5e-06, 10)++ boundary_usage = Usage(prompt_tokens=32000, completion_tokens=10, total_tokens=32010)+ boundary_prompt_cost, _ = generic_cost_per_token(+ model=model,+ usage=boundary_usage,+ custom_llm_provider=custom_llm_provider,+ )+ assert round(boundary_prompt_cost, 10) == round(32000 * 4.6e-07, 10)++ empty_prompt_usage = Usage(prompt_tokens=0, completion_tokens=100, total_tokens=100)+ empty_prompt_cost, empty_completion_cost = generic_cost_per_token(+ model=model,+ usage=empty_prompt_usage,+ custom_llm_provider=custom_llm_provider,+ )+ assert empty_prompt_cost == 0.0+ assert round(empty_completion_cost, 10) == round(100 * 2e-06, 10)+ finally:+ litellm.model_cost.pop(model, None)++def test_generic_cost_per_token_gpt55():"""gpt-5.5: base pricing — $5/1M input, $30/1M output, $0.50/1M cached input."""model = "gpt-5.5"diff --git a/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py b/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.pyindex 6041a8c8377..20549fbd0fb 100644--- a/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py+++ b/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py@@ -2,13 +2,12 @@Test suite for Dashscope cost calculation functionality.Tests the cost calculation for Dashscope models including:-- Correctly calculates graduated tiered pricing.+- All-or-nothing tiered pricing, selected by the request's total input tokens.- Falls back to flat-rate pricing for non-tiered models.-- Handles interactions with cached tokens.-- Correctly calculates costs for token counts exceeding the highest defined tier.+- Handles cache read and cache creation tokens.+- Correctly prices requests exceeding the highest defined tier."""-import jsonimport mathimport osimport sys@@ -41,7 +40,6 @@ class TestDashscopeCostCalculator:"""usage = Usage(prompt_tokens=1000, completion_tokens=500)- # We call the specific calculator for dashscopeprompt_cost, completion_cost = dashscope_cost_per_token(model="qwen-max", usage=usage)@@ -55,7 +53,7 @@ class TestDashscopeCostCalculator:def test_dashscope_tiered_pricing_within_first_tier(self):"""- Tests the dashscope tiered pricing when token count is entirely within the first tier.+ Tests the dashscope tiered pricing when the request's input falls in the first tier.Uses 'dashscope/qwen-flash' as a real-world example."""# Tier 1 for qwen-flash is [0, 256,000] tokens@@ -73,10 +71,10 @@ class TestDashscopeCostCalculator:assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10)- def test_dashscope_tiered_pricing_spanning_multiple_tiers(self):+ def test_dashscope_tiered_pricing_bills_whole_request_at_selected_tier(self):"""- Tests the dashscope tiered pricing with the corrected graduated calculation logic.- This is the most important test for validating the fix.+ Regression: Model Studio tiered pricing is all-or-nothing, not graduated. An input+ above the first tier's range must bill every token at the higher tier's rate."""# Tiering for qwen-flash: Tier 1: [0, 256k], Tier 2: [256k, 1M]usage = Usage(prompt_tokens=300000, completion_tokens=300000)@@ -88,23 +86,54 @@ class TestDashscopeCostCalculator:tier_1 = model_info["tiered_pricing"][0]tier_2 = model_info["tiered_pricing"][1]- # Expected prompt cost: (256,000 tokens * tier_1_price) + (44,000 tokens * tier_2_price)- expected_prompt_cost = (256000 * tier_1["input_cost_per_token"]) + (+ expected_prompt_cost = 300000 * tier_2["input_cost_per_token"]+ expected_completion_cost = 300000 * tier_2["output_cost_per_token"]++ assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)+ assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10)++ graduated_prompt_cost = (256000 * tier_1["input_cost_per_token"]) + (44000 * tier_2["input_cost_per_token"])+ assert prompt_cost > graduated_prompt_cost- # Expected completion cost: (256,000 tokens * tier_1_price) + (44,000 tokens * tier_2_price)- expected_completion_cost = (256000 * tier_1["output_cost_per_token"]) + (- 44000 * tier_2["output_cost_per_token"]+ def test_dashscope_tiered_pricing_boundary_stays_in_lower_tier(self):+ """+ A request of exactly range_end tokens stays in the lower tier, matching the+ official `0 < Token <= 256K` phrasing.+ """+ usage = Usage(prompt_tokens=256000, completion_tokens=1000)+ prompt_cost, completion_cost = dashscope_cost_per_token(+ model="qwen-flash", usage=usage)- assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)- assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10)+ tier_1 = litellm.get_model_info("dashscope/qwen-flash")["tiered_pricing"][0]++ assert math.isclose(+ prompt_cost, 256000 * tier_1["input_cost_per_token"], rel_tol=1e-10+ )+ assert math.isclose(+ completion_cost, 1000 * tier_1["output_cost_per_token"], rel_tol=1e-10+ )++ def test_dashscope_tiered_pricing_output_uses_input_selected_tier(self):+ """+ The tier is chosen by input volume only: a small input with a huge output stays+ on the first tier's output rate.+ """+ usage = Usage(prompt_tokens=1000, completion_tokens=400000)+ _, completion_cost = dashscope_cost_per_token(model="qwen-flash", usage=usage)++ tier_1 = litellm.get_model_info("dashscope/qwen-flash")["tiered_pricing"][0]++ assert math.isclose(+ completion_cost, 400000 * tier_1["output_cost_per_token"], rel_tol=1e-10+ )def test_dashscope_tiered_pricing_with_caching(self):"""- Tests tiered pricing with cached tokens. This replaces the old, incorrect test.- Uses qwen3-coder-plus, which has cache-specific pricing defined.+ Tests tiered pricing with cached tokens: the tier is selected from the total+ input (text + cached), and cache reads bill at that tier's cache rate."""usage = Usage(prompt_tokens=50000, # 10k cached + 40k new@@ -115,28 +144,43 @@ class TestDashscopeCostCalculator:prompt_cost, _ = dashscope_cost_per_token(model="qwen3-coder-plus", usage=usage)- model_info = litellm.get_model_info("dashscope/qwen3-coder-plus")- tier_1 = model_info["tiered_pricing"][0]- tier_2 = model_info["tiered_pricing"][1]-- # 10k cached tokens are all in the first tier- expected_cache_cost = 10000 * tier_1["cache_read_input_token_cost"]+ # 50k total input falls in qwen3-coder-plus tier 2 ([32k, 128k])+ tier_2 = litellm.get_model_info("dashscope/qwen3-coder-plus")["tiered_pricing"][1]- # 40k new tokens: 32k in tier 1, and the remaining 8k in tier 2- expected_text_cost = (32000 * tier_1["input_cost_per_token"]) + (- 8000 * tier_2["input_cost_per_token"]+ expected_prompt_cost = (40000 * tier_2["input_cost_per_token"]) + (+ 10000 * tier_2["cache_read_input_token_cost"])- expected_total_prompt_cost = expected_cache_cost + expected_text_cost+ assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)++ def test_dashscope_tiered_pricing_exceeding_highest_tier(self):+ """+ Requests above the highest declared range bill entirely at the last tier's rate.+ """+ usage = Usage(+ prompt_tokens=1200000, completion_tokens=1000+ ) # Max defined range for qwen-flash is 1M++ prompt_cost, _ = dashscope_cost_per_token(model="qwen-flash", usage=usage)- assert math.isclose(prompt_cost, expected_total_prompt_cost, rel_tol=1e-10)+ tier_2 = litellm.get_model_info("dashscope/qwen-flash")["tiered_pricing"][1]- def _register_string_valued_tiered_model(self, model_key: str) -> None:- """Register a model whose tier costs are strings, mimicking YAML config parsing."""+ assert math.isclose(+ prompt_cost, 1200000 * tier_2["input_cost_per_token"], rel_tol=1e-10+ )++ def _register_tiered_model(self, model_key: str, tiered_pricing: list[dict]) -> None:litellm.model_cost[model_key] = {"litellm_provider": "dashscope","mode": "chat",- "tiered_pricing": [+ "tiered_pricing": tiered_pricing,+ }++ def _register_string_valued_tiered_model(self, model_key: str) -> None:+ """Register a model whose tier costs are strings, mimicking YAML config parsing."""+ self._register_tiered_model(+ model_key,+ [{"range": [0, 1000],"input_cost_per_token": "4e-07",@@ -148,12 +192,12 @@ class TestDashscopeCostCalculator:"output_cost_per_token": "3.2e-06",},],- }+ )def test_dashscope_tiered_pricing_string_costs_within_tier(self):"""- Regression: YAML-parsed tier costs can be strings (e.g. "4e-07"). Costs that- fall entirely within a single tier must still be computed as floats.+ Regression: YAML-parsed tier costs can be strings (e.g. "4e-07") and must still+ be computed as floats."""self._register_string_valued_tiered_model("dashscope/qwen-str-tier-test")@@ -162,18 +206,13 @@ class TestDashscopeCostCalculator:model="qwen-str-tier-test", usage=usage)- expected_prompt_cost = 500 * float("4e-07")- expected_completion_cost = 200 * float("1.6e-06")-- assert prompt_cost > 0- assert completion_cost > 0- assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)- assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10)+ assert math.isclose(prompt_cost, 500 * float("4e-07"), rel_tol=1e-10)+ assert math.isclose(completion_cost, 200 * float("1.6e-06"), rel_tol=1e-10)def test_dashscope_tiered_pricing_string_costs_exceeding_highest_tier(self):"""- Regression: string-valued tier costs must also be coerced in the- remaining-tokens path that charges tokens above the highest tier.+ Regression: string-valued tier costs must also be coerced on the last-tier+ fallback path used by requests above the highest range."""self._register_string_valued_tiered_model("dashscope/qwen-str-tier-test")@@ -182,43 +221,137 @@ class TestDashscopeCostCalculator:model="qwen-str-tier-test", usage=usage)- # prompt: 1000 @ tier1 + 1000 @ tier2 + 500 remaining @ tier2 rate- expected_prompt_cost = (- (1000 * float("4e-07")) + (1000 * float("8e-07")) + (500 * float("8e-07"))+ assert math.isclose(prompt_cost, 2500 * float("8e-07"), rel_tol=1e-10)+ assert math.isclose(completion_cost, 3000 * float("3.2e-06"), rel_tol=1e-10)++ def test_dashscope_tiered_cache_creation_tokens_use_tier_rate(self):+ """+ Regression (tiered cache creation): cache-creation tokens must bill at the+ selected tier's cache_creation_input_token_cost, not the input rate.+ """+ self._register_tiered_model(+ "dashscope/qwen-cache-write-test",+ [+ {+ "range": [0, 256000],+ "input_cost_per_token": 3.25e-07,+ "output_cost_per_token": 1.95e-06,+ "cache_creation_input_token_cost": 4.063e-07,+ "cache_read_input_token_cost": 3.25e-08,+ },+ {+ "range": [256000, 1000000],+ "input_cost_per_token": 6.5e-07,+ "output_cost_per_token": 3.9e-06,+ "cache_creation_input_token_cost": 8.125e-07,+ "cache_read_input_token_cost": 6.5e-08,+ },+ ],)- # completion: 1000 @ tier1 + 1000 @ tier2 + 1000 remaining @ tier2 rate- expected_completion_cost = (- (1000 * float("1.6e-06")) + (1000 * float("3.2e-06")) + (1000 * float("3.2e-06"))++ usage = Usage(+ prompt_tokens=300000, # 200k new + 60k cache creation + 40k cache read+ completion_tokens=1000,+ prompt_tokens_details=PromptTokensDetailsWrapper(+ cached_tokens=40000, cache_creation_tokens=60000+ ),+ )++ prompt_cost, _ = dashscope_cost_per_token(+ model="qwen-cache-write-test", usage=usage+ )++ expected_prompt_cost = (+ (200000 * 6.5e-07) + (60000 * 8.125e-07) + (40000 * 6.5e-08))- assert prompt_cost > 0- assert completion_cost > 0assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)- assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10)- def test_dashscope_tiered_pricing_exceeding_highest_tier(self):+ def test_dashscope_tiered_cache_creation_falls_back_to_tier_input_rate(self):"""- Tests tiered pricing when token count exceeds the highest defined tier range.- This replaces the old, incorrect test and validates the new fallback logic.+ Tiers without a cache_creation_input_token_cost bill cache-creation tokens at+ that tier's input rate."""+ self._register_tiered_model(+ "dashscope/qwen-no-cache-write-test",+ [+ {+ "range": [0, 256000],+ "input_cost_per_token": 3.25e-07,+ "output_cost_per_token": 1.95e-06,+ }+ ],+ )+usage = Usage(- prompt_tokens=1200000, completion_tokens=1000- ) # Max defined range for qwen-flash is 1M+ prompt_tokens=10000,+ completion_tokens=100,+ prompt_tokens_details=PromptTokensDetailsWrapper(cache_creation_tokens=4000),+ )- prompt_cost, _ = dashscope_cost_per_token(model="qwen-flash", usage=usage)+ prompt_cost, _ = dashscope_cost_per_token(+ model="qwen-no-cache-write-test", usage=usage+ )- model_info = litellm.get_model_info("dashscope/qwen-flash")- tier_1 = model_info["tiered_pricing"][0]- tier_2 = model_info["tiered_pricing"][1]+ assert math.isclose(prompt_cost, 10000 * 3.25e-07, rel_tol=1e-10)- # Expected cost: (tier_1_tokens * tier_1_price) + (tokens_up_to_max_range_in_tier_2 * tier_2_price) + (remaining_tokens * tier_2_price)- tokens_in_tier_2_range = 1000000 - 256000- remaining_tokens_over_max = 1200000 - 1000000+ def test_dashscope_flat_cache_creation_tokens_use_flat_rate(self):+ """Flat-priced models bill cache-creation tokens at their cache-creation rate."""+ litellm.model_cost["dashscope/qwen-flat-cache-write-test"] = {+ "litellm_provider": "dashscope",+ "mode": "chat",+ "input_cost_per_token": 3.25e-07,+ "output_cost_per_token": 1.95e-06,+ "cache_creation_input_token_cost": 4.063e-07,+ "cache_read_input_token_cost": 3.25e-08,+ }++ usage = Usage(+ prompt_tokens=10000,+ completion_tokens=100,+ prompt_tokens_details=PromptTokensDetailsWrapper(+ cached_tokens=2000, cache_creation_tokens=3000+ ),+ )++ prompt_cost, _ = dashscope_cost_per_token(+ model="qwen-flat-cache-write-test", usage=usage+ )expected_prompt_cost = (- (256000 * tier_1["input_cost_per_token"])- + (tokens_in_tier_2_range * tier_2["input_cost_per_token"])- + (remaining_tokens_over_max * tier_2["input_cost_per_token"])+ (5000 * 3.25e-07) + (3000 * 4.063e-07) + (2000 * 3.25e-08))assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)++ def test_dashscope_tiered_pricing_zero_input_falls_back_to_flat_rates(self):+ """+ No tier can be selected without input tokens, so an empty-prompt request must+ not be charged at the most expensive tier.+ """+ litellm.model_cost["dashscope/qwen-zero-input-test"] = {+ "litellm_provider": "dashscope",+ "mode": "chat",+ "input_cost_per_token": 4e-07,+ "output_cost_per_token": 1.6e-06,+ "tiered_pricing": [+ {+ "range": [0, 1000],+ "input_cost_per_token": 4e-07,+ "output_cost_per_token": 1.6e-06,+ },+ {+ "range": [1000, 2000],+ "input_cost_per_token": 8e-07,+ "output_cost_per_token": 3.2e-06,+ },+ ],+ }++ usage = Usage(prompt_tokens=0, completion_tokens=500)+ prompt_cost, completion_cost = dashscope_cost_per_token(+ model="qwen-zero-input-test", usage=usage+ )++ assert prompt_cost == 0.0+ assert math.isclose(completion_cost, 500 * 1.6e-06, rel_tol=1e-10)diff --git a/tests/test_litellm/test_model_prices_schema.py b/tests/test_litellm/test_model_prices_schema.pyindex ccb0541d318..cb7023e6c12 100644--- a/tests/test_litellm/test_model_prices_schema.py+++ b/tests/test_litellm/test_model_prices_schema.py@@ -100,6 +100,24 @@ def test_schema_accepts_minimal_and_unknown_optional_fields(committed_schema: diassert validator.is_valid({"some-model": {"litellm_provider": "openai", "brand_new_field": {"nested": True}}})+def test_schema_accepts_cache_creation_cost_inside_a_pricing_tier(committed_schema: dict):+ validator = build_validator(committed_schema)+ entry = {+ "litellm_provider": "dashscope",+ "mode": "chat",+ "tiered_pricing": [+ {+ "range": [0, 256000],+ "input_cost_per_token": 3.25e-07,+ "output_cost_per_token": 1.95e-06,+ "cache_creation_input_token_cost": 4.063e-07,+ "cache_read_input_token_cost": 3.25e-08,+ }+ ],+ }+ assert validator.is_valid({"some-model": entry})++DATED_VARIANT = re.compile(r"^(.*?)-(\d{4}-\d{2}-\d{2})$")SERVICE_TIER_SUFFIXES = ("_flex", "_priority")diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex 8e9e6167fb9..01e7e5c7ffd 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -1021,6 +1021,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid():"input_cost_per_token": {"type": "number"},"output_cost_per_token": {"type": "number"},"cache_read_input_token_cost": {"type": "number"},+ "cache_creation_input_token_cost": {"type": "number"},"output_cost_per_reasoning_token": {"type": "number"},"max_results_range": {"type": "array",