Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions litellm/proxy/spend_tracking/savings.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,13 +410,18 @@ def compute_savings_spend(
if usage is None or not model:
return SavingsSpend(compression=compression, prompt_caching=prompt_caching)

# 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: Final = litellm.autorouter_savings_baseline_model
# The counterfactual is one model an operator would have run instead of the router.
# `litellm_settings.autorouter_savings_baseline_model` wins when set; otherwise the
# baseline the deciding router derived from its hardest tier and recorded on its
# decision, so the driver is on by default for auto-routed traffic. Neither present
# 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.
decision: Final = routing_decision if isinstance(routing_decision, Mapping) else {}
recorded: Final = decision.get("savings_baseline_model")
baseline_model: Final = litellm.autorouter_savings_baseline_model or (
recorded if isinstance(recorded, str) else None
)
autorouter: Final = (
compute_autorouter_savings(
baseline_model=baseline_model,
Expand Down
36 changes: 36 additions & 0 deletions litellm/router_strategy/complexity_router/complexity_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,37 @@ def __init__(

verbose_router_logger.debug("ComplexityRouter initialized for %s with tiers: %s", model_name, self.config.tiers)

def _hardest_tier_models(self) -> tuple[str, ...]:
"""The model pool of the most severe tier this router configures.

The hardest *configured* tier, not REASONING unconditionally: a deployment
that only defines SIMPLE and MEDIUM is still measured against the best it
could actually have picked.
"""
for tier in reversed(TIER_SEVERITY_ORDER):
models = self.config.tiers.get(tier.value)
if models:
return tuple(models) if isinstance(models, list) else (models,)
return ()

@property
def savings_baseline_model(self) -> str | None:
"""The derived model this router's savings are measured against, or ``None``.

``None`` whenever `litellm_settings.autorouter_savings_baseline_model` is set:
the spend writer reads that setting directly and it overrides anything a router
would derive, so deriving underneath it would price candidates per decision
only to be ignored. The property re-checks the setting per call because it is a
module attribute an operator can flip on a running proxy.
"""
import litellm
from litellm.router_strategy.savings_baseline import resolve_baseline

if litellm.autorouter_savings_baseline_model is not None:
return None
baseline: Final = resolve_baseline(self.litellm_router_instance, self._hardest_tier_models())
return baseline.model if baseline is not None else None
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

def _estimate_tokens(self, text: str) -> int:
"""
Estimate token count from text.
Expand Down Expand Up @@ -716,6 +747,11 @@ def _build_routing_decision(
cause=cause,
conversation_continuing=conversation_continuing,
)
# Recorded here rather than resolved at spend-write time: one model name can
# carry several tag-scoped routers with different tier ladders, and only the
# deciding instance knows which of them routed the request.
if (baseline := self.savings_baseline_model) is not None:
decision["savings_baseline_model"] = baseline
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
if tier is not None:
decision["tier"] = tier.value
if score is not None:
Expand Down
159 changes: 159 additions & 0 deletions litellm/router_strategy/savings_baseline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""The default counterfactual a complexity router's savings are measured against.

`litellm_settings.autorouter_savings_baseline_model` names the model the traffic would
have run on without a router. When the operator sets it, that answer wins and nothing
here runs. When they do not, the router's own tier ladder already names it: without a
router a deployment has to pick one model that can carry the hardest request it will
see, so the default baseline is the priciest model in the hardest configured tier. A
cheap tier is a choice the router made, not a ceiling it was bounded by.

Candidates are ranked once against a fixed reference request, not against each request
that runs. Ranking per request means reading the request, and every input shape it can
take; a default must not carry that surface. An operator whose pool ordering genuinely
depends on request shape names the baseline in config, which skips this file entirely.

Baselines are always provider-qualified, because they travel to the spend writer as a
bare string with no provider beside them; an operator who writes ``deepseek-r1`` meaning
Azure would otherwise be priced against whoever else owns that name.
"""

from collections.abc import Iterable
from typing import TYPE_CHECKING, Final, NamedTuple

from litellm._logging import verbose_router_logger
from litellm.types.utils import PromptTokensDetailsWrapper, Usage

if TYPE_CHECKING:
from litellm.router import Router


# One long cached prompt with a short completion: the shape auto-routed traffic takes,
# and the shape whose ordering a flat-rate comparison gets wrong.
_REFERENCE_REQUEST: Final = Usage(
prompt_tokens=20_000,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
completion_tokens=1_000,
total_tokens=21_000,
prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=19_000, cache_creation_tokens=1_000, text_tokens=0),
)


class Baseline(NamedTuple):
"""The counterfactual deployment: what it is called, and which deployment it was.

``model`` is what the operator would recognise, and the string the spend writer
prices the counterfactual under. ``deployment_id`` only ranks: a deployment can be
charged something other than its model's public rate, and
`Router.get_deployment_model_info` is what merges the two.
"""

model: str
deployment_id: str | None = None


def canonical_model(model: str, custom_llm_provider: str | None = None) -> str | None:
"""``provider/model``, or ``None`` when the pair names no known provider.

A deployment may name its vendor in the model prefix or in a separate
``custom_llm_provider``, and the bare name alone is not enough to price: it can
resolve to a different vendor's rates, or to nothing at all.
"""
import litellm

try:
resolved, provider, _, _ = litellm.get_llm_provider(model=model, custom_llm_provider=custom_llm_provider)
except Exception as e: # noqa: BLE001 # an unroutable candidate cannot be the baseline
verbose_router_logger.debug("savings baseline: cannot resolve candidate %s (%s)", model, e)
return None
return f"{provider}/{resolved}"


def _models_in(router: "Router", group_name: str) -> tuple[Baseline, ...]:
"""The candidates a tier entry actually calls, each with its own pricing key.

`litellm_params.model` is not always a model: on Azure it is the deployment name,
absent from the cost map, and `model_info.base_model` names the real one. Wildcard
and aliased deployments behave the same, and router.py resolves pricing through
that same base_model chain. A name matching no deployment is a tier pointing
straight at a provider model rather than at a configured group, and prices under
its own name because there is no deployment to override it.
"""
indices: Final = router.model_name_to_deployment_indices.get(group_name)
if not indices:
return (Baseline(qualified),) if (qualified := canonical_model(group_name)) else ()

def candidate(index: int) -> Baseline | None:
deployment: Final = router.model_list[index]
params: Final = deployment.get("litellm_params")
if not isinstance(params, dict):
return None
info: Final = deployment.get("model_info")
base: Final = info.get("base_model") if isinstance(info, dict) else None
model: Final = base or params.get("base_model") or params.get("model")
qualified: Final = canonical_model(model, params.get("custom_llm_provider")) if model else None
if qualified is None:
return None
deployment_id: Final = info.get("id") if isinstance(info, dict) else None
return Baseline(qualified, str(deployment_id) if deployment_id else None)

return tuple(c for index in indices if (c := candidate(index)) is not None)


def _priced(router: "Router", candidate: Baseline) -> tuple[float, Baseline] | None:
"""``(cost_of_the_reference_request, candidate)``, or ``None`` when unpriceable.

"Most expensive" is a property of a request, not of a rate: a deployment dearer per
output token can be cheaper per cached token, so comparing a chosen pair of rates
orders cache-heavy traffic backwards. Costing one reference request through the same
engine the savings use leaves cache rates, tiered tables and every other billing
dimension to that engine. A candidate that prices to nothing there cannot stand in
for what the traffic would have cost.
"""
from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token

provider, _, model_name = candidate.model.partition("/")
try:
info: Final = router.get_deployment_model_info(candidate.deployment_id or "", candidate.model)
if info is None:
return None
prompt_cost, completion_cost = generic_cost_per_token(
model=model_name or candidate.model,
usage=_REFERENCE_REQUEST,
custom_llm_provider=provider,
model_info=info,
)
except Exception as e: # noqa: BLE001 # an unpriceable candidate simply cannot be the baseline
verbose_router_logger.debug("savings baseline: no pricing for candidate %s (%s)", candidate.model, e)
return None
cost: Final = prompt_cost + completion_cost
if cost <= 0.0:
verbose_router_logger.debug("savings baseline: candidate %s prices to nothing", candidate.model)
return None
return (cost, candidate)


def _most_expensive(router: "Router", candidates: Iterable[Baseline]) -> Baseline | None:
"""The candidate that would have cost the most on the reference request."""
priced: Final = tuple(r for candidate in candidates if (r := _priced(router, candidate)) is not None)
if not priced:
verbose_router_logger.debug("savings baseline: no priceable candidates; savings driver disabled")
return None
return max(priced)[1]


def resolve_baseline(router: "Router", group_names: Iterable[str]) -> Baseline | None:
"""The derived baseline for a router whose hardest tier offers ``group_names``.

Derived per call rather than cached: the parent router adds and removes deployments
while it runs, so a baseline pinned on first use would keep naming a model the
router no longer has, and a pricier one added later could never become the baseline.
Resolving costs tens of microseconds against a network call.

Never raises. This is read on the routing path to decorate a request that is about
to be served, and a dashboard's counterfactual is not worth failing a live request
over; an unresolvable baseline zeroes the savings driver instead.
"""
try:
return _most_expensive(router, (c for name in group_names for c in _models_in(router, name)))
except Exception as e: # noqa: BLE001 # see docstring: routing must not fail for a metric
verbose_router_logger.warning("savings baseline: could not resolve, savings will read zero (%s)", e)
return None
2 changes: 2 additions & 0 deletions litellm/types/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2807,6 +2807,7 @@ class StandardLoggingRoutingDecision(TypedDict, total=False):
escalated: bool
tier_boundaries: StandardLoggingRoutingDecisionTierBoundaries
conversation_continuing: bool
savings_baseline_model: str


# Fields whose values quote the caller's prompt. Dropped when an operator turns message
Expand All @@ -2827,6 +2828,7 @@ class StandardLoggingRoutingDecision(TypedDict, total=False):
"escalated",
"tier_boundaries",
"conversation_continuing",
"savings_baseline_model",
}
)

Expand Down
64 changes: 58 additions & 6 deletions tests/test_litellm/proxy/spend_tracking/test_savings.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ def test_a_switch_onto_a_partly_cached_model_still_pays_for_the_write():
)
assert reported < if_treated_as_same_model / 10, "a mostly-cold switch must not be priced as a continuation"


def test_a_baseline_that_prices_caching_implicitly_still_pays_for_its_prompt():
"""OpenAI, Azure and Gemini entries carry no `cache_creation_input_token_cost`,
because those providers cache implicitly and charge nothing to write. Leaving this
Expand All @@ -505,9 +506,7 @@ def test_a_baseline_that_prices_caching_implicitly_still_pays_for_its_prompt():
assert gpt5.get("cache_creation_input_token_cost") is None, "pick a baseline with no cache-write rate"
haiku = litellm.get_model_info("claude-haiku-4-5", "anthropic")
baseline_pays_input = 20_000 * gpt5["input_cost_per_token"] + 1_000 * gpt5["output_cost_per_token"]
actually_paid = (
20_000 * haiku["cache_creation_input_token_cost"] + 1_000 * haiku["output_cost_per_token"]
)
actually_paid = 20_000 * haiku["cache_creation_input_token_cost"] + 1_000 * haiku["output_cost_per_token"]
assert reported == pytest.approx(baseline_pays_input - actually_paid)
assert reported > 0, "routing a cold first turn onto a cheaper model is a saving, not a loss"

Expand All @@ -530,9 +529,7 @@ def test_a_baseline_with_no_cache_read_rate_is_charged_its_input_rate():
assert grok.get("cache_read_input_token_cost") is None, "pick a baseline with no cache-read rate"
haiku = litellm.get_model_info("claude-haiku-4-5", "anthropic")
baseline_pays_input = 20_000 * grok["input_cost_per_token"] + 1_000 * grok["output_cost_per_token"]
actually_paid = (
20_000 * haiku["cache_creation_input_token_cost"] + 1_000 * haiku["output_cost_per_token"]
)
actually_paid = 20_000 * haiku["cache_creation_input_token_cost"] + 1_000 * haiku["output_cost_per_token"]
assert reported == pytest.approx(baseline_pays_input - actually_paid)


Expand Down Expand Up @@ -617,3 +614,58 @@ def test_the_baseline_is_priced_on_the_basis_the_request_was_billed_at(basis, ex

baseline = 20_000 * gpt["input_cost_per_token"] + 1_000 * gpt["output_cost_per_token"]
assert reported == pytest.approx(expected_multiplier * baseline - served)


def test_a_baseline_recorded_on_the_decision_turns_the_driver_on():
"""The router derives a default from its hardest tier and records it on the
decision, so an operator who configures nothing still sees the driver work."""
result = compute_savings_spend(
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True, "savings_baseline_model": "anthropic/claude-opus-5"},
usage_object=_cached_usage_object(),
)
assert result.autorouter != 0.0


def test_the_configured_baseline_overrides_the_recorded_one(monkeypatch):
"""Config names what the operator would really have run; the derived value is only
a default underneath it."""
monkeypatch.setattr(litellm, "autorouter_savings_baseline_model", "claude-sonnet-5")
with_override = compute_savings_spend(
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True, "savings_baseline_model": "anthropic/claude-opus-5"},
usage_object=_cached_usage_object(),
)
against_sonnet = compute_autorouter_savings(
baseline_model="claude-sonnet-5",
selected_model="claude-haiku-4-5",
selected_provider="anthropic",
usage=Usage(**_cached_usage_object()),
)
against_opus = compute_autorouter_savings(
baseline_model="anthropic/claude-opus-5",
selected_model="claude-haiku-4-5",
selected_provider="anthropic",
usage=Usage(**_cached_usage_object()),
)
assert against_sonnet != against_opus, "the test needs baselines that price apart"
assert with_override.autorouter == against_sonnet


def test_a_non_string_recorded_baseline_is_ignored():
"""The decision crosses a JSON boundary, so the writer must not trust its shape."""
result = compute_savings_spend(
model="claude-haiku-4-5",
custom_llm_provider="anthropic",
compression_saved_tokens=0,
cache_read_input_tokens=0,
routing_decision={"conversation_continuing": True, "savings_baseline_model": ["anthropic/claude-opus-5"]},
usage_object=_cached_usage_object(),
)
assert result.autorouter == 0.0
Loading
Loading