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(spend): read what a request cost from the record instead of pricing it again (#35736)

tin-berri22f68c0c6ba3
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py
index f04a9d61d4a..25d448e48e9 100644
--- a/litellm/cost_calculator.py
+++ b/litellm/cost_calculator.py
@@ -1051,6 +1051,8 @@ def _store_cost_breakdown_in_logging_obj(
cache_read_cost: float | None = None,
cache_creation_cost: float | None = None,
reasoning_cost: float | None = None,
+ service_tier: str | None = None,
+ data_residency: str | None = None,
) -> None:
"""
Helper function to store cost breakdown in the logging object.
@@ -1068,6 +1070,8 @@ def _store_cost_breakdown_in_logging_obj(
margin_percent: Margin percentage applied (0.10 = 10%)
margin_fixed_amount: Fixed margin amount in USD
margin_total_amount: Total margin added in USD
+ service_tier: Tier the costs above were priced on, already resolved
+ data_residency: Region uplift the costs above were priced on, already resolved
"""
if litellm_logging_obj is None:
return
@@ -1089,6 +1093,8 @@ def _store_cost_breakdown_in_logging_obj(
cache_read_cost=cache_read_cost,
cache_creation_cost=cache_creation_cost,
reasoning_cost=reasoning_cost,
+ service_tier=service_tier,
+ data_residency=data_residency,
)
except Exception as breakdown_error:
@@ -1469,6 +1475,8 @@ def completion_cost(
margin_percent=margin_percent,
margin_fixed_amount=margin_fixed_amount,
margin_total_amount=margin_total_amount,
+ service_tier=service_tier,
+ data_residency=data_residency,
)
return _final_cost
@@ -1657,6 +1665,8 @@ def completion_cost(
cache_read_cost=_cache_read_cost,
cache_creation_cost=_cache_creation_cost,
reasoning_cost=_reasoning_cost,
+ service_tier=service_tier,
+ data_residency=data_residency,
)
return _final_cost
@@ -2351,6 +2361,7 @@ def handle_realtime_stream_cost_calculation(
cost_for_built_in_tools_cost_usd_dollar=0.0,
total_cost_usd_dollar=total_cost,
additional_costs={"transcription_cost": transcription_cost} if transcription_cost > 0 else None,
+ data_residency=data_residency,
)
return total_cost
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 66d82bd18f1..f38b2859259 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1286,6 +1286,8 @@ class Logging(LiteLLMLoggingBaseClass):
cache_read_cost: float | None = None,
cache_creation_cost: float | None = None,
reasoning_cost: float | None = None,
+ service_tier: str | None = None,
+ data_residency: str | None = None,
) -> None:
"""
Helper method to store cost breakdown in the logging object.
@@ -1302,6 +1304,8 @@ class Logging(LiteLLMLoggingBaseClass):
margin_percent: Margin percentage applied (0.10 = 10%)
margin_fixed_amount: Fixed margin amount in USD
margin_total_amount: Total margin added in USD
+ service_tier: Tier the costs above were priced on, already resolved
+ data_residency: Region uplift the costs above were priced on, already resolved
"""
self.cost_breakdown = CostBreakdown(
@@ -1309,6 +1313,8 @@ class Logging(LiteLLMLoggingBaseClass):
output_cost=output_cost,
total_cost=total_cost,
tool_usage_cost=cost_for_built_in_tools_cost_usd_dollar,
+ service_tier=service_tier,
+ data_residency=data_residency,
)
if cache_read_cost is not None and cache_read_cost > 0:
self.cost_breakdown["cache_read_cost"] = cache_read_cost
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.py
index 7c9ee96e809..b24ed4b8282 100644
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@ -1885,8 +1885,9 @@ class DBSpendUpdateWriter:
cache_read_input_tokens=cache_read_input_tokens,
routing_decision=_metadata.get("routing_decision"),
model_id=payload.get("model_id"),
- llm_router=_get_llm_router(),
+ llm_router=_get_llm_router,
usage_object=usage_obj,
+ cost_breakdown=_metadata.get("cost_breakdown"),
)
daily_transaction = BaseDailySpendTransaction(
diff --git a/litellm/proxy/spend_tracking/savings.py b/litellm/proxy/spend_tracking/savings.py
index 1a1c813d784..a318b11e4c0 100644
--- a/litellm/proxy/spend_tracking/savings.py
+++ b/litellm/proxy/spend_tracking/savings.py
@@ -8,7 +8,7 @@ are known) and summed into the daily tables; tokens cannot be priced after they
have been aggregated across models.
"""
-from collections.abc import Mapping
+from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, NamedTuple
import litellm
@@ -105,11 +105,81 @@ def _model_info(model: _ModelIdentity) -> ModelInfo | None:
return None
-def _cost_of_usage(model: _ModelIdentity, usage: Usage, model_info: ModelInfo | None = None) -> float | None:
+class PricingBasis(NamedTuple):
+ """The tier and region a request was priced on, as the cost calculator resolved them.
+
+ Read back off the request's recorded ``cost_breakdown`` rather than re-derived. The
+ tier the biller used comes from ``optional_params``, which no log record carries, and
+ the served tier that does survive on the usage object is a different fact with the
+ opposite precedence, so a spend-time re-derivation would disagree with the invoice on
+ exactly the requests where the tier changed the price.
+ """
+
+ service_tier: str | None = None
+ data_residency: str | None = None
+
+
+_STANDARD_RATES = PricingBasis()
+
+
+def _pricing_basis(cost_breakdown: Mapping[str, object] | None) -> PricingBasis:
+ """The basis recorded on a request, defaulting to standard rates when absent.
+
+ Rows written before this field shipped carry neither key, and there is no backfill:
+ they price at standard rates, which is what they already did.
+
+ Both values survive a JSON round trip on the way here, so neither is guaranteed to be
+ a string. `generic_cost_per_token` calls `.lower()` on both without a type check, and
+ the resulting `AttributeError` would be swallowed into a silent zero by the caller's
+ `except`, so anything that is not a string is dropped here instead.
+ """
+ if not cost_breakdown:
+ return _STANDARD_RATES
+ service_tier = cost_breakdown.get("service_tier")
+ data_residency = cost_breakdown.get("data_residency")
+ return PricingBasis(
+ service_tier=service_tier if isinstance(service_tier, str) else None,
+ data_residency=data_residency if isinstance(data_residency, str) else None,
+ )
+
+
+def _recorded_token_cost(cost_breakdown: Mapping[str, object] | None) -> float | None:
+ """What the biller charged for this request's tokens, or ``None`` when unrecorded.
+
+ ``input_cost`` already carries the cache buckets, so it and ``output_cost`` sum to
+ exactly what `generic_cost_per_token` returns for the same request; the separate
+ ``cache_read_cost`` and ``cache_creation_cost`` entries decompose that sum rather than
+ adding to it, and including them would charge those tokens twice.
+
+ Built-in tool cost, discount and margin are deliberately left out. They are properties
+ of the request and the operator's contract rather than of the model the router picked,
+ so they land on both sides of the comparison or neither, and only the total the
+ counterfactual can also be priced on belongs here.
+ """
+ if not cost_breakdown:
+ return None
+ input_cost = cost_breakdown.get("input_cost")
+ output_cost = cost_breakdown.get("output_cost")
+ if not isinstance(input_cost, (int, float)) or not isinstance(output_cost, (int, float)):
+ return None
+ return float(input_cost) + float(output_cost)
+
+
+def _cost_of_usage(
+ model: _ModelIdentity,
+ usage: Usage,
+ model_info: ModelInfo | None = None,
+ basis: PricingBasis = _STANDARD_RATES,
+) -> float | None:
"""What ``usage`` costs on ``model``, or ``None`` when the model has no pricing."""
try:
prompt_cost, completion_cost = generic_cost_per_token(
- model=model.model, usage=usage, custom_llm_provider=model.provider, model_info=model_info
+ model=model.model,
+ usage=usage,
+ custom_llm_provider=model.provider,
+ service_tier=basis.service_tier,
+ data_residency=basis.data_residency,
+ model_info=model_info,
)
except Exception as e: # noqa: BLE001 # get_model_info raises bare Exception for unmapped models; degrade to zero savings
verbose_proxy_logger.debug(
@@ -228,6 +298,7 @@ def compute_autorouter_savings(
usage: Usage,
conversation_continuing: bool = True,
selected_info: ModelInfo | None = None,
+ cost_breakdown: Mapping[str, object] | None = None,
) -> float:
"""Net dollars the router saved, or cost, by serving this request on ``selected_model``.
@@ -237,6 +308,20 @@ def compute_autorouter_savings(
dashboard has to be able to say so. Zero when both sides resolve to the same
deployment, or when either cannot be resolved or priced.
+ Only one side of this subtraction is a counterfactual. What the request cost on the
+ model that served it is a number the operator was actually billed, and the cost
+ calculator already wrote it down, so ``cost_breakdown`` is read rather than
+ re-derived. Recomputing it means restating every pricing dimension the biller
+ applied, and each one omitted is a silent disagreement with the ``spend`` column
+ beside it; a request billed at a priority tier recomputed at standard rates reads as
+ half its real cost.
+
+ The baseline has no such record, since it never ran, so it is priced through the same
+ cost engine on the basis the biller used for this request. An operator running that
+ one model instead of the router would have sent this request to the same tier and the
+ same region, because both are properties of the request and the deployment's
+ contract, not of which model the router happened to pick.
+
``conversation_continuing`` says whether the baseline would already have had this
prompt cached. It defaults to True because that is the conservative reading: a
request whose shape the router could not determine is charged the write and
@@ -255,11 +340,16 @@ def compute_autorouter_savings(
# name alone reports as zero.
if baseline == selected:
return 0.0
+ basis = _pricing_basis(cost_breakdown)
baseline_info = _model_info(baseline)
baseline_cost = _cost_of_usage(
- baseline, _baseline_usage(usage, conversation_continuing, baseline_info), baseline_info
+ baseline, _baseline_usage(usage, conversation_continuing, baseline_info), baseline_info, basis
)
- selected_cost = _cost_of_usage(selected, usage, selected_info)
+ # Falls back to pricing the request only when the biller recorded nothing, which is
+ # every row written before the breakdown carried its basis.
+ selected_cost = _recorded_token_cost(cost_breakdown)
+ if selected_cost is None:
+ selected_cost = _cost_of_usage(selected, usage, selected_info, basis)
if baseline_cost is None or selected_cost is None:
return 0.0
return baseline_cost - selected_cost
@@ -287,7 +377,8 @@ def compute_savings_spend(
routing_decision: Mapping[str, object] | None = None,
usage_object: Mapping[str, object] | None = None,
model_id: str | None = None,
- llm_router: "Router | None" = None,
+ llm_router: "Callable[[], Router | None] | None" = None,
+ cost_breakdown: Mapping[str, object] | None = None,
) -> SavingsSpend:
"""
Dollar savings for one request, split by optimization driver.
@@ -299,6 +390,17 @@ def compute_savings_spend(
baseline the router recorded on its ``routing_decision``, and are zero unless the
two differ. That record also says whether the conversation was already underway,
which is what tells a mid-conversation switch from a first turn.
+
+ ``llm_router`` is passed as a provider rather than a router because every spend write
+ calls this and only auto-routed ones need one, so looking it up eagerly at the call
+ site would fetch and discard it on the rest.
+
+ ``cost_breakdown`` is what the cost calculator recorded for this request, and it
+ carries both what the request really cost and the tier and region it was priced on.
+ Only the auto-router driver reads it. Compression and prompt caching price a
+ hypothetical token delta off flat rate keys, so they are blind to tiered pricing in
+ the same way; that is pre-existing behaviour on two shipped drivers rather than
+ something introduced here, and moving those numbers is its own change.
"""
input_cost, cache_read_cost = _input_and_cache_read_cost(model, custom_llm_provider)
compression = max(compression_saved_tokens, 0) * input_cost
@@ -311,19 +413,23 @@ def compute_savings_spend(
# The counterfactual is one model an operator would have run instead of the router,
# configured once for the proxy rather than derived per request. Unset means the
# driver is off; a routing decision is what says this request was auto-routed at all.
+ # Both are checked before anything is resolved, because every spend write reaches
+ # here and only auto-routed ones can produce a number.
+ baseline_model = litellm.autorouter_savings_baseline_model
decision = routing_decision if isinstance(routing_decision, Mapping) else {}
autorouter = (
compute_autorouter_savings(
- baseline_model=litellm.autorouter_savings_baseline_model,
+ baseline_model=baseline_model,
selected_model=model,
selected_provider=custom_llm_provider,
usage=usage,
# Absent means the router never recorded a shape, which is the conservative
# reading: charge the cache write rather than claim a first turn's saving.
conversation_continuing=decision.get("conversation_continuing") is not False,
- selected_info=_effective_model_info(llm_router, model_id, model or ""),
+ selected_info=_effective_model_info(llm_router() if llm_router else None, model_id, model or ""),
+ cost_breakdown=cost_breakdown,
)
- if decision
+ if decision and baseline_model
else 0.0
)
return SavingsSpend(compression=compression, prompt_caching=prompt_caching, autorouter=autorouter)
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.py
index ca2e7fcc038..11a1b686c2e 100644
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@ -1428,7 +1428,11 @@ class ComplexityRouter(CustomLogger):
if isinstance(metadata, dict):
metadata[RETURN_RAW_MODEL_NAME_METADATA_KEY] = True
- conversation_continuing = _conversation_is_continuing(self._resolve_messages(messages, request_kwargs))
+ # Resolved once for the whole hook. Resolution converts Responses API input into
+ # chat-completions messages, so it is real work on every non-chat surface, and
+ # both the conversation shape and the classifier read the same list.
+ resolved_messages = self._resolve_messages(messages, request_kwargs)
+ conversation_continuing = _conversation_is_continuing(resolved_messages)
use_session_affinity = self.config.session_affinity and not self.config.plugins
session_id = self._get_session_id_from_request_kwargs(request_kwargs) if use_session_affinity else None
@@ -1440,7 +1444,6 @@ class ComplexityRouter(CustomLogger):
routed_model: str | None = pinned_model
pin_escalation_keyword: str | None = None
if self.escalation_keywords:
- resolved_messages = self._resolve_messages(messages, request_kwargs)
user_message = _newest_turn_ask(resolved_messages) if resolved_messages else None
if user_message is not None:
pin_escalation_keyword = self._matched_escalation_keyword(user_message)
@@ -1487,6 +1490,7 @@ class ComplexityRouter(CustomLogger):
input=input,
specific_deployment=specific_deployment,
conversation_continuing=conversation_continuing,
+ resolved_messages=resolved_messages,
)
if cache_key is not None and response is not None:
await self.litellm_router_instance.cache.async_set_cache(
@@ -1504,6 +1508,7 @@ class ComplexityRouter(CustomLogger):
input: str | list | None = None,
specific_deployment: bool | None = False,
conversation_continuing: bool = True,
+ resolved_messages: Sequence[Mapping[str, object]] | None = None,
) -> PreRoutingHookResponse | None:
"""
Classifies the request by complexity and returns the appropriate model.
@@ -1516,13 +1521,17 @@ class ComplexityRouter(CustomLogger):
messages: The messages in the request.
input: Optional input for Responses API or embeddings.
specific_deployment: Whether a specific deployment was requested.
+ resolved_messages: Messages the caller already resolved, to avoid converting
+ the request format a second time. Resolved here when absent, so a direct
+ caller does not have to.
Returns:
PreRoutingHookResponse with the routed model, or None if no routing needed.
"""
from litellm.types.router import PreRoutingHookResponse
- resolved_messages = self._resolve_messages(messages, request_kwargs)
+ if resolved_messages is None:
+ resolved_messages = self._resolve_messages(messages, request_kwargs)
if not resolved_messages:
verbose_router_logger.debug("ComplexityRouter: No messages could be resolved, skipping routing")
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 21d69d9925a..c63f4d53572 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2991,9 +2991,18 @@ class CachingDetails(TypedDict):
class CostBreakdown(TypedDict, total=False):
"""
- Detailed cost breakdown for a request
+ Detailed cost breakdown for a request.
+
+ ``service_tier`` and ``data_residency`` record the pricing basis the cost was
+ computed on, not what the caller asked for. A consumer that has to price a
+ counterfactual against this request (what another model would have charged for
+ it) needs the same basis to compare like with like, and re-deriving it from the
+ request is not possible after the fact: the tier the biller used comes from
+ ``optional_params``, which no log record carries.
"""
+ service_tier: Optional[str]
+ data_residency: Optional[str]
input_cost: float # Cost of raw (non-cached) input tokens only
cache_read_cost: float # Cost of cache-read tokens (discounted rate)
cache_creation_cost: float # Cost of cache-write tokens (premium rate)
diff --git a/tests/test_litellm/proxy/spend_tracking/test_savings.py b/tests/test_litellm/proxy/spend_tracking/test_savings.py
index 6d0195b632b..1d6b0da561d 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_savings.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_savings.py
@@ -534,3 +534,86 @@ def test_a_baseline_with_no_cache_read_rate_is_charged_its_input_rate():
20_000 * haiku["cache_creation_input_token_cost"] + 1_000 * haiku["output_cost_per_token"]
)
assert reported == pytest.approx(baseline_pays_input - actually_paid)
+
+
+def _breakdown(input_cost: float, output_cost: float = 0.0, **extra: object) -> dict:
+ """A `cost_breakdown` as the cost calculator records it on the spend log."""
+ return {"input_cost": input_cost, "output_cost": output_cost, **extra}
+
+
+def test_the_served_arm_is_read_from_the_record_not_repriced():
+ """What the request cost on the model that served it is not a counterfactual; the
+ cost calculator already billed it and wrote the number down. Recomputing it restates
+ every pricing dimension the biller applied and drops the ones it forgets, so the
+ driver disagrees with the `spend` column beside it.
+
+ Pinned with a negotiated rate no public map lookup can produce, so re-pricing from
+ the model name cannot land on this number. Tool spend and margin are recorded too and
+ must stay out: the baseline cannot be priced with them, so charging them to the
+ served arm alone would read as the router losing money on every tool call.
+ """
+ usage = _usage(fresh=20_000, cached=0, written=0, out=1_000)
+ negotiated_input, negotiated_output = 0.0123, 0.0456
+
+ reported = compute_autorouter_savings(
+ baseline_model="anthropic/claude-opus-5",
+ selected_model="gpt-5.5",
+ selected_provider="openai",
+ usage=usage,
+ conversation_continuing=False,
+ cost_breakdown=_breakdown(
+ negotiated_input,
+ negotiated_output,
+ tool_usage_cost=5.0,
+ margin_total_amount=2.0,
+ total_cost=negotiated_input + negotiated_output + 7.0,
+ ),
+ )
+
+ opus = litellm.get_model_info("claude-opus-5", "anthropic")
+ public = 20_000 * opus["input_cost_per_token"] + 1_000 * opus["output_cost_per_token"]
+ assert reported == pytest.approx(public - (negotiated_input + negotiated_output))
+
+
+ "basis, expected_multiplier",
+ [
+ pytest.param({"service_tier": "priority"}, 2.0, id="priority tier doubles the baseline"),
+ pytest.param({"data_residency": "eu"}, 1.1, id="eu residency uplifts the baseline"),
+ pytest.param({}, 1.0, id="no basis recorded prices at standard"),
+ pytest.param(None, 1.0, id="row predating the field prices at standard"),
+ pytest.param({"service_tier": True, "data_residency": 17}, 1.0, id="a non-string basis is dropped"),
+ ],
+)
+def test_the_baseline_is_priced_on_the_basis_the_request_was_billed_at(basis, expected_multiplier):
+ """A request billed at a priority tier, or through a regional host, would have been
+ billed the same way on the single model an operator ran instead of the router, so the
+ counterfactual carries that basis too. Dropping it prices the two arms from different
+ books; neither multiplier cancels out of the difference, because both are per-model.
+
+ The served model has no tiered rates and no uplift of its own, so only the baseline
+ can move: a fix that forwards the basis to the served arm alone leaves these numbers
+ unchanged. The non-string case guards the JSON round trip, where `.lower()` inside
+ the pricer would raise and be swallowed into a silent $0.00 for the whole row.
+ """
+ gpt = litellm.get_model_info("gpt-5.5", "openai")
+ haiku = litellm.get_model_info("claude-haiku-4-5", "anthropic")
+ assert gpt.get("input_cost_per_token_priority") == 2 * gpt["input_cost_per_token"]
+ assert gpt.get("regional_processing_uplift_multiplier_eu") == 1.1
+ assert haiku.get("input_cost_per_token_priority") is None, "served model must not move with the basis"
+ assert haiku.get("regional_processing_uplift_multiplier_eu") is None
+
+ usage = _usage(fresh=20_000, cached=0, written=0, out=1_000)
+ served = 20_000 * haiku["input_cost_per_token"] + 1_000 * haiku["output_cost_per_token"]
+
+ reported = compute_autorouter_savings(
+ baseline_model="openai/gpt-5.5",
+ selected_model="claude-haiku-4-5",
+ selected_provider="anthropic",
+ usage=usage,
+ conversation_continuing=False,
+ cost_breakdown=None if basis is None else _breakdown(served, **basis),
+ )
+
+ baseline = 20_000 * gpt["input_cost_per_token"] + 1_000 * gpt["output_cost_per_token"]
+ assert reported == pytest.approx(expected_multiplier * baseline - served)