Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
10 changes: 5 additions & 5 deletions litellm/models/autorouter_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ class LiteLLM_AutoRouterSession(LiteLLMPydanticObjectBase):

@property
def baseline_model(self) -> str | None:
"""The baseline most covered turns were priced against, or None when none were estimated.
"""The baseline recorded by most session turns, including historical turns.

A router reconfigured mid-session leaves turns priced against two baselines; the row keeps both
counts, and the label is the one that priced the most money-carrying turns rather than whatever the
counts, and the label is the one recorded by the most turns rather than whatever the
router is configured with now.
"""
if not self.savings_estimated_baseline_models:
if not self.baseline_models:
return None
return max(
self.savings_estimated_baseline_models,
key=lambda model: (self.savings_estimated_baseline_models[model], model),
self.baseline_models,
key=lambda model: (self.baseline_models[model], model),
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
)
137 changes: 137 additions & 0 deletions litellm/proxy/db/autorouter_savings_comparison.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
from collections.abc import Mapping
from contextlib import AbstractAsyncContextManager
from datetime import timedelta
from math import isclose
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, Protocol, cast

from pydantic import BaseModel, ConfigDict, TypeAdapter

from litellm._logging import verbose_proxy_logger
from litellm.constants import MAX_SPENDLOG_ROWS_TO_QUERY
from litellm.proxy.db.autorouter_session_rollup import AUTOROUTER_SESSION_WINDOW_SQL
from litellm.proxy.db.create_views import SupportsRawQueries

if TYPE_CHECKING:
from litellm.proxy.utils import PrismaClient


class SessionSavingsComparison(BaseModel):
model_config = ConfigDict(frozen=True, allow_inf_nan=False)

router_name: str
router_type: str
turns: int
estimated_turns: int
actual_spend: float
saved_spend: float
complete: bool

def coverage_fields(self, recorded_savings: float, recorded_turns: int) -> Mapping[str, float | int]:
if self.turns != recorded_turns or not self.complete:
return MappingProxyType({})
if not isclose(self.saved_spend, recorded_savings, rel_tol=1e-9, abs_tol=1e-9):
return MappingProxyType({})
return MappingProxyType(
{
"savings_estimated_turns": self.estimated_turns,
"savings_estimated_actual_spend": self.actual_spend,
"savings_estimated_saved_spend": self.saved_spend,
}
)


class _ReadTransactions(Protocol):
def tx(self, *, timeout: timedelta, max_wait: timedelta) -> AbstractAsyncContextManager[SupportsRawQueries]: ...


_COMPARISONS: Final = TypeAdapter(tuple[SessionSavingsComparison, ...])


async def historical_session_comparisons(
prisma_client: "PrismaClient",
start_date: str,
end_date: str,
api_key: str | None,
user_id: str | None,
session_id: str | None = None,
) -> Mapping[tuple[str, str], SessionSavingsComparison]:
try:
reader: Final = cast(_ReadTransactions, prisma_client.read_db) # cast-ok: untyped Prisma transaction delegate
async with reader.tx(timeout=timedelta(seconds=3), max_wait=timedelta(seconds=1)) as transaction:
await transaction.execute_raw("SET TRANSACTION READ ONLY")
await transaction.execute_raw("SET LOCAL statement_timeout = 2000")
rows: Final = await transaction.query_raw(
HISTORICAL_SESSION_COMPARISONS_SQL,
start_date,
end_date,
api_key,
user_id,
session_id,
)
comparisons: Final = _COMPARISONS.validate_python(rows or ())
return MappingProxyType({(row.router_name, row.router_type): row for row in comparisons})
except Exception: # noqa: BLE001 # missing retained logs must not discard recorded dollar savings
verbose_proxy_logger.warning("Historical auto-router cost comparison unavailable; preserving recorded savings")
return MappingProxyType({})


HISTORICAL_SESSION_COMPARISONS_SQL: Final = f"""
WITH {AUTOROUTER_SESSION_WINDOW_SQL}, scoped AS MATERIALIZED (
SELECT * FROM windowed WHERE $5::text IS NULL OR session_id = $5::text
), limited_logs AS MATERIALIZED (
SELECT session.api_key, session.session_id, session.router_name, session.router_type, session.comparison_user_id,
logs.spend, logs.prompt_tokens + logs.completion_tokens AS tokens,
logs.metadata::jsonb -> 'routing_decision' AS decision,
logs.metadata::jsonb -> 'autorouter_savings' AS savings,
logs.metadata::jsonb -> 'autorouter_savings_estimate' AS estimate
FROM scoped AS session JOIN "LiteLLM_SpendLogs" AS logs
ON logs.api_key = session.api_key
AND CASE WHEN char_length(logs.session_id) > 256
THEN 'sha256:' || encode(sha256(convert_to(logs.session_id, 'UTF8')), 'hex')
ELSE logs.session_id END = session.session_id
AND (session.comparison_user_id IS NULL OR logs."user" = session.comparison_user_id)
AND logs."startTime" BETWEEN session.first_turn_at AND session.last_turn_at
AND COALESCE(logs.metadata::jsonb #>> '{{routing_decision,router_model_name}}', logs.model_group)
= session.router_name
WHERE session.savings_estimated_turns < session.turns
AND logs.status = 'success' AND COALESCE(logs.metadata::jsonb ->> 'internal_call_origin', '') = ''
LIMIT {MAX_SPENDLOG_ROWS_TO_QUERY + 1}
), facts AS (
SELECT *,
CASE WHEN jsonb_typeof(decision -> 'classifier_cost') = 'number'
THEN (decision ->> 'classifier_cost')::float8 ELSE 0 END AS classifier,
CASE WHEN jsonb_typeof(savings) = 'number' AND (
estimate IS NULL OR estimate = 'null'::jsonb OR (
jsonb_typeof(estimate -> 'version') = 'number' AND estimate ->> 'version' IN ('1', '2', '3')
AND estimate ->> 'status' = 'estimated'
)
) THEN savings::text::float8 END AS saved
FROM limited_logs
), compared AS (
SELECT api_key, session_id, router_name, router_type, comparison_user_id,
COUNT(*) AS turns, SUM(spend + classifier) AS spend, SUM(tokens) AS total_tokens,
COUNT(saved) AS estimated_turns,
COALESCE(SUM(spend + classifier) FILTER (WHERE saved IS NOT NULL), 0)::float8 AS actual_spend,
COALESCE(SUM(saved), 0)::float8 AS saved_spend
FROM facts GROUP BY 1, 2, 3, 4, 5
), reconciled AS (
SELECT session.*, logs.estimated_turns, logs.actual_spend,
COALESCE((SELECT COUNT(*) FROM limited_logs) <= {MAX_SPENDLOG_ROWS_TO_QUERY}
AND logs.turns = session.turns AND logs.total_tokens = session.total_tokens
AND ABS(logs.spend - session.spend) <= GREATEST(1e-9, ABS(session.spend) * 1e-9)
AND ABS(logs.saved_spend - session.saved_spend) <= GREATEST(1e-9, ABS(session.saved_spend) * 1e-9), FALSE
) AS recovered
FROM scoped AS session LEFT JOIN compared AS logs
ON logs.api_key = session.api_key AND logs.session_id = session.session_id
AND logs.router_name = session.router_name AND logs.router_type = session.router_type
AND logs.comparison_user_id IS NOT DISTINCT FROM session.comparison_user_id
)
SELECT router_name, router_type,
SUM(turns)::bigint AS turns,
SUM(CASE WHEN recovered THEN estimated_turns ELSE savings_estimated_turns END)::bigint AS estimated_turns,
SUM(CASE WHEN recovered THEN actual_spend ELSE savings_estimated_actual_spend END)::float8 AS actual_spend,
SUM(saved_spend)::float8 AS saved_spend,
BOOL_AND(recovered OR savings_estimated_turns = turns) AS complete
FROM reconciled GROUP BY router_name, router_type
"""
18 changes: 11 additions & 7 deletions litellm/proxy/db/autorouter_session_rollup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
key and user session rollups with one atomic statement per turn: each upsert classifies
the turn (same model, first visit, return to a model the session already used, out of
order) against the row's own columns, so nothing is read before the write and concurrent
pods compose. The benchmarks endpoint aggregates these rows and never touches
LiteLLM_SpendLogs.
pods compose. The benchmarks endpoint aggregates these rows and can recover matching historical
costs from retained spend logs when estimate coverage predates these columns.
"""

from __future__ import annotations
Expand Down Expand Up @@ -45,20 +45,24 @@
savings_estimated_baseline_models
"""

AUTOROUTER_BENCHMARKS_SQL: Final = f"""
WITH windowed AS (
SELECT {_SESSION_COLUMNS} FROM "LiteLLM_AutoRouterSession"
AUTOROUTER_SESSION_WINDOW_SQL: Final = f"""
windowed AS (
SELECT {_SESSION_COLUMNS}, NULL::text AS comparison_user_id FROM "LiteLLM_AutoRouterSession"
WHERE $4::text IS NULL
AND last_turn_at >= $1::timestamp
AND first_turn_at < $2::timestamp
AND ($3::text IS NULL OR api_key = $3::text)
UNION ALL
SELECT {_SESSION_COLUMNS} FROM "LiteLLM_AutoRouterUserSession"
SELECT {_SESSION_COLUMNS}, user_id AS comparison_user_id FROM "LiteLLM_AutoRouterUserSession"
WHERE (($4::text IS NOT NULL AND user_id = $4::text) OR ($4::text IS NULL AND api_key = ''))
AND last_turn_at >= $1::timestamp
AND first_turn_at < $2::timestamp
AND ($3::text IS NULL OR api_key = $3::text)
),
)
"""

AUTOROUTER_BENCHMARKS_SQL: Final = f"""
WITH {AUTOROUTER_SESSION_WINDOW_SQL},
tier_maps AS (
SELECT router_name, router_type, jsonb_object_agg(tier, tier_turns) AS tier_turns
FROM (
Expand Down
107 changes: 90 additions & 17 deletions litellm/proxy/management_endpoints/auto_router_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from collections.abc import Mapping, Sequence
from datetime import datetime, timedelta, timezone
from itertools import chain, groupby
from math import isclose
from types import MappingProxyType
from typing import TYPE_CHECKING, Annotated, Final, Protocol
from uuid import uuid4
Expand All @@ -31,6 +32,7 @@
can_key_call_resolved_model,
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.db.autorouter_savings_comparison import historical_session_comparisons
from litellm.proxy.db.autorouter_session_rollup import (
AUTOROUTER_BENCHMARKS_SQL,
bounded_session_id,
Expand Down Expand Up @@ -652,6 +654,7 @@ class _SessionAggRow(BaseModel):
savings_estimated_turns: int = 0
savings_estimated_actual_spend: float = 0.0
savings_estimated_saved_spend: float = 0.0
savings_comparison_complete: bool = True
classifier_cost: float
classifier_cost_recorded_turns: int
session_seconds: float
Expand Down Expand Up @@ -679,18 +682,25 @@ def _cache_bucket(turns: int, hits: int) -> AutoRouterCacheBucket:


def _savings_cohort(
turns: int, estimated_turns: int, actual_spend: float, saved_spend: float
turns: int, estimated_turns: int, actual_spend: float, saved_spend: float, recorded_savings: float
) -> tuple[float | None, float | None]:
if turns > 0 and estimated_turns == 0:
if turns > 0 and estimated_turns == 0 and recorded_savings == 0:
return None, None
return saved_spend, actual_spend + saved_spend
if not isclose(saved_spend, recorded_savings, rel_tol=1e-9, abs_tol=1e-9):
return recorded_savings, None
return recorded_savings, actual_spend + recorded_savings


def _benchmark_totals(row: _SessionAggRow) -> AutoRouterBenchmarkTotals:
return_misses: Final = row.return_turns - row.return_hits
saved_spend, baseline_spend = _savings_cohort(
row.turns, row.savings_estimated_turns, row.savings_estimated_actual_spend, row.savings_estimated_saved_spend
)
saved_spend, compared_baseline = _savings_cohort(
row.turns,
row.savings_estimated_turns,
row.savings_estimated_actual_spend,
row.savings_estimated_saved_spend,
row.saved_spend,
)
baseline_spend: Final = compared_baseline if row.savings_comparison_complete else None
sessions: Final = row.sessions
return AutoRouterBenchmarkTotals(
sessions=sessions,
Expand All @@ -705,9 +715,7 @@ def _benchmark_totals(row: _SessionAggRow) -> AutoRouterBenchmarkTotals:
classifier_cost=row.classifier_cost if row.classifier_cost_recorded_turns == row.turns else None,
baseline_spend=baseline_spend,
saved_pct=_pct(saved_spend, baseline_spend) if saved_spend is not None and baseline_spend is not None else None,
saved_per_session=(row.savings_estimated_saved_spend / sessions if sessions else 0.0)
if row.savings_estimated_turns == row.turns
else None,
saved_per_session=(saved_spend / sessions if sessions else 0.0) if saved_spend is not None else None,
cache=AutoRouterCacheStats(
coverage_pct=_pct(row.covered_turns, row.turns),
hit_rate_pct=_pct(row.cache_hits, row.covered_turns),
Expand Down Expand Up @@ -773,6 +781,7 @@ def _summed_agg_row(rows: Sequence[_SessionAggRow]) -> _SessionAggRow:
savings_estimated_turns=sum(row.savings_estimated_turns for row in rows),
savings_estimated_actual_spend=sum(row.savings_estimated_actual_spend for row in rows),
savings_estimated_saved_spend=sum(row.savings_estimated_saved_spend for row in rows),
savings_comparison_complete=all(row.savings_comparison_complete for row in rows),
classifier_cost=sum(row.classifier_cost for row in rows),
classifier_cost_recorded_turns=sum(row.classifier_cost_recorded_turns for row in rows),
session_seconds=sum(row.session_seconds for row in rows),
Expand Down Expand Up @@ -847,8 +856,8 @@ async def get_auto_router_benchmarks(
Benchmarks for the auto-router dashboard: session shape, savings against the configured
baseline, and prompt-caching behaviour bucketed by what the router did.

Reads session rollups folded once per request at spend-write time, so this endpoint
never scans LiteLLM_SpendLogs. A user filter selects only turns attributed to that
Reads session rollups folded once per request at spend-write time, with bounded
retained-log recovery for historical comparisons. A user filter selects only turns attributed to that
internal user when written; older key-only history remains outside user views. A session
is in the window when it overlaps it: its last turn is on or after start_date and its first turn is on or before
end_date. Overall hit rate is over telemetry-bearing turns; each bucket's hit rate is
Expand Down Expand Up @@ -882,7 +891,43 @@ async def get_auto_router_benchmarks(
api_key,
user_id,
)
rows: Final = _SESSION_AGG_ROWS.validate_python(raw_rows or ())
recorded_rows: Final = _SESSION_AGG_ROWS.validate_python(raw_rows or ())
comparisons: Final = (
await historical_session_comparisons(
prisma_client,
start_day.isoformat(),
(end_day + timedelta(days=1)).isoformat(),
api_key,
user_id,
)
if any(row.savings_estimated_turns < row.turns for row in recorded_rows)
else MappingProxyType({})
)
covered_rows: Final = tuple(
row.model_copy(
update={
**comparison.coverage_fields(row.saved_spend, row.turns),
"savings_comparison_complete": comparison.complete and comparison.turns == row.turns,
}
)
if (comparison := comparisons.get((row.router_name, row.router_type)))
else row.model_copy(update={"savings_comparison_complete": row.savings_estimated_turns == row.turns})
for row in recorded_rows
)
rows: Final = tuple(
row.model_copy(
update={
"savings_comparison_complete": row.savings_comparison_complete
and isclose(
row.saved_spend,
row.savings_estimated_saved_spend,
rel_tol=1e-9,
abs_tol=1e-9,
),
}
)
for row in covered_rows
)
groups: Final = (
*(_benchmark_group(row) for row in rows),
*_idle_router_groups(llm_router, frozenset((row.router_name, row.router_type) for row in rows)),
Expand Down Expand Up @@ -920,15 +965,43 @@ async def get_auto_router_session(

if prisma_client is None:
raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)
row: Final = await AutoRouterSessionRepository(prisma_client).find_latest_for_key(
recorded: Final = await AutoRouterSessionRepository(prisma_client).find_latest_for_key(
user_api_key_dict.api_key, bounded_session_id(session_id)
)
if row is None:
if recorded is None:
raise HTTPException(
status_code=404, detail=f"No auto-routed turns recorded for session {session_id!r} under this key"
)
saved_spend, baseline_spend = _savings_cohort(
row.turns, row.savings_estimated_turns, row.savings_estimated_actual_spend, row.savings_estimated_saved_spend
comparisons: Final = (
await historical_session_comparisons(
prisma_client,
recorded.first_turn_at.isoformat(),
(recorded.last_turn_at + timedelta(microseconds=1)).isoformat(),
user_api_key_dict.api_key,
None,
bounded_session_id(session_id),
)
if recorded.savings_estimated_turns < recorded.turns
else MappingProxyType({})
)
comparison: Final = comparisons.get((recorded.router_name, recorded.router_type))
row: Final = (
recorded.model_copy(update=comparison.coverage_fields(recorded.saved_spend, recorded.turns))
if comparison
else recorded
)
saved_spend, compared_baseline = _savings_cohort(
row.turns,
row.savings_estimated_turns,
row.savings_estimated_actual_spend,
row.savings_estimated_saved_spend,
row.saved_spend,
)
baseline_spend: Final = (
compared_baseline
if row.savings_estimated_turns == row.turns
or (comparison and comparison.complete and comparison.turns == row.turns)
else None
)
return AutoRouterSessionResponse(
session_id=session_id,
Expand All @@ -943,7 +1016,7 @@ async def get_auto_router_session(
baseline_spend=baseline_spend if row.savings_estimated_turns == row.turns else None,
savings_estimated_baseline_spend=baseline_spend,
baseline_model=row.baseline_model,
baseline_models=row.savings_estimated_baseline_models,
baseline_models=row.baseline_models,
)


Expand Down
Loading
Loading