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(cost): coerce string tiered-pricing costs and share tier helper

Shivam Rawat8548816ae463
diff --git a/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.py b/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.py
new file mode 100644
index 00000000000..7091563ae8f
--- /dev/null
+++ b/litellm/litellm_core_utils/llm_cost_calc/tiered_pricing.py
@@ -0,0 +1,99 @@
+"""
+Provider-neutral graduated tiered pricing calculation.
+
+Shared by provider cost calculators (e.g. Dashscope) and the proxy budget
+reservation logic so neither has to depend on the other.
+"""
+
+from typing import List, Optional, Union
+
+
+def _coerce_cost_per_token(value: Union[float, int, str, None]) -> float:
+ """
+ Coerce a per-token cost into a float.
+
+ Model cost values loaded from YAML config may arrive as strings (e.g.
+ scientific notation like "4e-07"), which would break arithmetic.
+ """
+ if value is None:
+ return 0.0
+ if isinstance(value, str):
+ try:
+ return float(value)
+ except ValueError:
+ return 0.0
+ return float(value)
+
+
+def calculate_tiered_cost(
+ tokens: int,
+ tiered_pricing: List[dict],
+ cost_key: str,
+ fallback_cost_key: Optional[str] = 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 = 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 = sorted_tiers[-1]
+ remaining_tokens = 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
diff --git a/litellm/llms/dashscope/cost_calculator.py b/litellm/llms/dashscope/cost_calculator.py
index 2f710d78126..2732b97cd35 100644
--- a/litellm/llms/dashscope/cost_calculator.py
+++ b/litellm/llms/dashscope/cost_calculator.py
@@ -7,6 +7,7 @@ Handles tiered pricing and prompt caching scenarios.
from dataclasses import dataclass
from typing import List, Optional, Tuple
+from litellm.litellm_core_utils.llm_cost_calc.tiered_pricing import calculate_tiered_cost
from litellm.types.utils import ModelInfo, Usage
from litellm.utils import get_model_info
@@ -42,80 +43,6 @@ def _extract_token_breakdown(usage: Usage) -> TokenBreakdown:
return TokenBreakdown(text_tokens, cached_tokens, completion_tokens, reasoning_tokens)
-def _calculate_tiered_cost(
- tokens: int,
- tiered_pricing: List[dict],
- cost_key: str,
- fallback_cost_key: Optional[str] = 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 = 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 * 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 = sorted_tiers[-1]
- remaining_tokens = tokens - tokens_processed
- cost_per_token = last_tier.get(cost_key) or last_tier.get(fallback_cost_key, 0)
- total_cost += remaining_tokens * cost_per_token
-
- return total_cost
-
-
def _calculate_prompt_cost(
breakdown: TokenBreakdown,
model_info: ModelInfo,
@@ -123,12 +50,12 @@ def _calculate_prompt_cost(
) -> float:
"""Calculate total prompt cost including cached tokens."""
if tiered_pricing:
- text_cost = _calculate_tiered_cost(
+ text_cost = calculate_tiered_cost(
tokens=breakdown.text_tokens,
tiered_pricing=tiered_pricing,
cost_key="input_cost_per_token",
)
- cache_cost = _calculate_tiered_cost(
+ cache_cost = calculate_tiered_cost(
tokens=breakdown.cached_tokens,
tiered_pricing=tiered_pricing,
cost_key="cache_read_input_token_cost",
@@ -155,12 +82,12 @@ def _calculate_completion_cost(
) -> float:
"""Calculate total completion cost including reasoning tokens."""
if tiered_pricing:
- completion_cost = _calculate_tiered_cost(
+ completion_cost = calculate_tiered_cost(
tokens=breakdown.completion_tokens,
tiered_pricing=tiered_pricing,
cost_key="output_cost_per_token",
)
- reasoning_cost = _calculate_tiered_cost(
+ reasoning_cost = calculate_tiered_cost(
tokens=breakdown.reasoning_tokens,
tiered_pricing=tiered_pricing,
cost_key="output_cost_per_reasoning_token",
diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.py
index c72049e9c74..55e9deaf125 100644
--- a/litellm/proxy/spend_tracking/budget_reservation.py
+++ b/litellm/proxy/spend_tracking/budget_reservation.py
@@ -10,7 +10,7 @@ import litellm
from litellm._logging import verbose_proxy_logger
from litellm.caching import DualCache
from litellm.litellm_core_utils.duration_parser import duration_in_seconds
-from litellm.llms.dashscope.cost_calculator import _calculate_tiered_cost
+from litellm.litellm_core_utils.llm_cost_calc.tiered_pricing import calculate_tiered_cost
from litellm.proxy._types import (
LiteLLM_TeamMembership,
LiteLLM_TeamTable,
@@ -938,7 +938,7 @@ def _estimate_request_input_cost_for_model(
return None
tiered_pricing = model_info.get("tiered_pricing")
if isinstance(tiered_pricing, list) and tiered_pricing:
- return _calculate_tiered_cost(
+ return calculate_tiered_cost(
tokens=input_tokens,
tiered_pricing=tiered_pricing,
cost_key="input_cost_per_token",
@@ -985,11 +985,11 @@ def _estimate_request_max_cost_for_model(
output_multiplier = _get_output_multiplier(request_body=request_body)
tiered_pricing = model_info.get("tiered_pricing")
if isinstance(tiered_pricing, list) and tiered_pricing:
- return _calculate_tiered_cost(
+ return calculate_tiered_cost(
tokens=input_tokens,
tiered_pricing=tiered_pricing,
cost_key="input_cost_per_token",
- ) + _calculate_tiered_cost(
+ ) + calculate_tiered_cost(
tokens=output_tokens * output_multiplier,
tiered_pricing=tiered_pricing,
cost_key="output_cost_per_token",
@@ -1056,6 +1056,13 @@ def _get_model_cost_info(
model_group_info = llm_router.get_model_group_info(model_group=model)
if model_group_info is not None:
model_group_cost_info = model_group_info.model_dump()
+ # Reservation runs before routing, so the concrete deployment is
+ # unknown here. We assume deployments in a group share pricing and
+ # use the first tiered table we find as the estimate. This is a
+ # best-effort admission gate; post-request billing is exact against
+ # the deployment that actually served the request. Mixing tiered and
+ # flat deployments in one group can therefore over- or under-estimate
+ # at reservation time only.
deployments = llm_router.get_model_list(model_name=model) or []
for deployment in deployments:
model_id = deployment.get("model_info", {}).get("id")
diff --git a/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py b/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py
index 05279202e8e..6041a8c8377 100644
--- a/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py
+++ b/tests/test_litellm/llms/dashscope/test_dashscope_cost_calculator.py
@@ -131,6 +131,71 @@ class TestDashscopeCostCalculator:
assert math.isclose(prompt_cost, expected_total_prompt_cost, rel_tol=1e-10)
+ def _register_string_valued_tiered_model(self, model_key: str) -> None:
+ """Register a model whose tier costs are strings, mimicking YAML config parsing."""
+ litellm.model_cost[model_key] = {
+ "litellm_provider": "dashscope",
+ "mode": "chat",
+ "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",
+ },
+ ],
+ }
+
+ 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.
+ """
+ self._register_string_valued_tiered_model("dashscope/qwen-str-tier-test")
+
+ usage = Usage(prompt_tokens=500, completion_tokens=200)
+ prompt_cost, completion_cost = dashscope_cost_per_token(
+ 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)
+
+ 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.
+ """
+ self._register_string_valued_tiered_model("dashscope/qwen-str-tier-test")
+
+ usage = Usage(prompt_tokens=2500, completion_tokens=3000)
+ prompt_cost, completion_cost = dashscope_cost_per_token(
+ 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"))
+ )
+ # 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"))
+ )
+
+ 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)
+
def test_dashscope_tiered_pricing_exceeding_highest_tier(self):
"""
Tests tiered pricing when token count exceeds the highest defined tier range.