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
feat(guardrails): report the usage units a guardrail's cost leaves out
ryan-crabbe-berri1548be823581
diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.jsonindex 5385b4d6f7e..c399e5594f6 100644--- a/litellm/proxy/_lazy_openapi_snapshot.json+++ b/litellm/proxy/_lazy_openapi_snapshot.json@@ -13142,6 +13142,13 @@"title": "Type","type": "string"},+ "untracked_usage_units": {+ "additionalProperties": {+ "type": "integer"+ },+ "title": "Untracked Usage Units",+ "type": "object"+ },"usage_units": {"additionalProperties": {"type": "integer"@@ -13197,7 +13204,8 @@"cost","cost_by_unit","cost_by_team",- "cost_by_key"+ "cost_by_key",+ "untracked_usage_units"],"title": "UsageDetailResponse","type": "object"@@ -13367,6 +13375,13 @@"title": "Totalrequests","type": "integer"},+ "totalUntrackedUsageUnits": {+ "additionalProperties": {+ "type": "integer"+ },+ "title": "Totaluntrackedusageunits",+ "type": "object"+ },"totalUsageUnits": {"additionalProperties": {"type": "integer"@@ -13382,7 +13397,8 @@"totalBlocked","passRate","totalUsageUnits",- "totalCost"+ "totalCost",+ "totalUntrackedUsageUnits"],"title": "UsageOverviewResponse","type": "object"@@ -13420,6 +13436,7 @@"type": "null"}],+ "description": "USD billed for usageUnits over the window, summed over days with tracked cost; null when none have it","title": "Cost"},"failRate": {@@ -13454,6 +13471,14 @@"title": "Type","type": "string"},+ "untrackedUsageUnits": {+ "additionalProperties": {+ "type": "integer"+ },+ "description": "The share of usageUnits that cost leaves out: units from days with no tracked cost, per counter",+ "title": "Untrackedusageunits",+ "type": "object"+ },"usageUnits": {"additionalProperties": {"type": "integer"@@ -13474,7 +13499,8 @@"status","trend","usageUnits",- "cost"+ "cost",+ "untrackedUsageUnits"],"title": "UsageOverviewRow","type": "object"@@ -28881,6 +28907,13 @@"title": "Totalrequests","type": "integer"},+ "totalUntrackedUsageUnits": {+ "additionalProperties": {+ "type": "integer"+ },+ "title": "Totaluntrackedusageunits",+ "type": "object"+ },"totalUsageUnits": {"additionalProperties": {"type": "integer"@@ -28896,7 +28929,8 @@"totalBlocked","passRate","totalUsageUnits",- "totalCost"+ "totalCost",+ "totalUntrackedUsageUnits"],"title": "UsageOverviewResponse","type": "object"@@ -28934,6 +28968,7 @@"type": "null"}],+ "description": "USD billed for usageUnits over the window, summed over days with tracked cost; null when none have it","title": "Cost"},"failRate": {@@ -28968,6 +29003,14 @@"title": "Type","type": "string"},+ "untrackedUsageUnits": {+ "additionalProperties": {+ "type": "integer"+ },+ "description": "The share of usageUnits that cost leaves out: units from days with no tracked cost, per counter",+ "title": "Untrackedusageunits",+ "type": "object"+ },"usageUnits": {"additionalProperties": {"type": "integer"@@ -28988,7 +29031,8 @@"status","trend","usageUnits",- "cost"+ "cost",+ "untrackedUsageUnits"],"title": "UsageOverviewRow","type": "object"diff --git a/litellm/proxy/guardrails/usage_endpoints.py b/litellm/proxy/guardrails/usage_endpoints.pyindex 69516487d7c..523efe0da75 100644--- a/litellm/proxy/guardrails/usage_endpoints.py+++ b/litellm/proxy/guardrails/usage_endpoints.py@@ -8,10 +8,10 @@ from collections.abc import Callable, Iterable, Mapping, Sequencefrom datetime import date, datetime, timedelta, timezonefrom itertools import groupbyfrom types import MappingProxyType-from typing import TYPE_CHECKING, Any, Final, Literal, overload+from typing import TYPE_CHECKING, Any, Final, Literal, TypeVar, overloadfrom fastapi import APIRouter, Depends, Query-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing_extensions import NotRequired, ReadOnly, TypedDictfrom litellm._logging import verbose_proxy_logger@@ -42,6 +42,8 @@ router: Final = APIRouter()_EMPTY_UNITS: Final[Mapping[str, int]] = MappingProxyType({})+_T = TypeVar("_T")+_USAGE_MAX_RANGE_DAYS: Final = 366@@ -183,6 +185,17 @@ def _cost_by(return MappingProxyType({key: _sum_tracked_cost(group) for key, group in groupby(ordered, key=key_of)})+def _untracked_rows(+ rows: "Sequence[prisma_models.LiteLLM_DailyGuardrailUsageUnits]",+) -> "tuple[prisma_models.LiteLLM_DailyGuardrailUsageUnits, ...]":+ """Rows whose cost is unknown, so their units are exactly what the tracked cost sums leave out."""+ return tuple(r for r in rows if r.cost is None)+++def _first_match(lookup_keys: Sequence[str], mapping: Mapping[str, _T], default: _T) -> _T:+ return next((mapping[k] for k in lookup_keys if k in mapping), default)++# --- Response models ---@@ -232,8 +245,12 @@ class UsageOverviewRow(BaseModel):status: str # healthy | warning | criticaltrend: str # up | down | stableusageUnits: Mapping[str, int]- cost: float | None- """USD billed for usageUnits over the window, summed over days with tracked cost; null when none have it."""+ cost: float | None = Field(+ description="USD billed for usageUnits over the window, summed over days with tracked cost; null when none have it"+ )+ untrackedUsageUnits: Mapping[str, int] = Field(+ description="The share of usageUnits that cost leaves out: units from days with no tracked cost, per counter"+ )class UsageOverviewResponse(BaseModel):@@ -244,10 +261,18 @@ class UsageOverviewResponse(BaseModel):passRate: floattotalUsageUnits: Mapping[str, int]totalCost: float | None+ totalUntrackedUsageUnits: Mapping[str, int]_EMPTY_OVERVIEW: Final = UsageOverviewResponse(- rows=[], chart=[], totalRequests=0, totalBlocked=0, passRate=100.0, totalUsageUnits=_EMPTY_UNITS, totalCost=None+ rows=[],+ chart=[],+ totalRequests=0,+ totalBlocked=0,+ passRate=100.0,+ totalUsageUnits=_EMPTY_UNITS,+ totalCost=None,+ totalUntrackedUsageUnits=_EMPTY_UNITS,)@@ -278,6 +303,7 @@ class UsageDetailResponse(BaseModel):cost_by_unit: Mapping[str, float | None]cost_by_team: Mapping[str, float | None]cost_by_key: Mapping[str, float | None]+ untracked_usage_units: Mapping[str, int]class UsageLogEntry(BaseModel):@@ -395,6 +421,7 @@ def _guardrail_overview_rows(prev_agg: Mapping[str, float],units_agg: Mapping[str, Mapping[str, int]],cost_agg: Mapping[str, float | None],+ untracked_agg: Mapping[str, Mapping[str, int]],) -> list[UsageOverviewRow]:rows: Final[list[UsageOverviewRow]] = []covered_keys: Final[set[str]] = set()@@ -420,8 +447,6 @@ def _guardrail_overview_rows(prev_fail = float(prev_agg.get(k, 0.0) or 0.0)breaktrend = _trend_from_comparison(fail_rate, prev_fail)- row_units: Mapping[str, int] = next((units_agg[k] for k in lookup_keys if k in units_agg), _EMPTY_UNITS)- row_cost: float | None = next((cost_agg[k] for k in lookup_keys if k in cost_agg), None)rows.append(UsageOverviewRow(id=gid,@@ -434,8 +459,9 @@ def _guardrail_overview_rows(avgLatency=None,status=_status_from_fail_rate(fail_rate),trend=trend,- usageUnits=row_units,- cost=row_cost,+ usageUnits=_first_match(lookup_keys, units_agg, _EMPTY_UNITS),+ cost=_first_match(lookup_keys, cost_agg, None),+ untrackedUsageUnits=_first_match(lookup_keys, untracked_agg, _EMPTY_UNITS),))# Add rows for guardrails with metrics but not in guardrails table (e.g. MCP, config)@@ -460,6 +486,7 @@ def _guardrail_overview_rows(trend=trend,usageUnits=units_agg.get(agg_key, _EMPTY_UNITS),cost=cost_agg.get(agg_key),+ untrackedUsageUnits=untracked_agg.get(agg_key, _EMPTY_UNITS),))return rows@@ -491,6 +518,7 @@ def _policy_overview_rows(trend=trend,usageUnits=_EMPTY_UNITS,cost=None,+ untrackedUsageUnits=_EMPTY_UNITS,))return rows@@ -545,13 +573,15 @@ async def guardrails_usage_overview(agg: Final = _aggregate_daily_metrics(metrics, "guardrail_id")prev_agg: Final = _prev_fail_rates(metrics_prev, "guardrail_id")+ untracked_rows: Final = _untracked_rows(units_rows)units_agg: Final = _units_by(units_rows, lambda r: r.guardrail_id)cost_agg: Final = _cost_by(units_rows, lambda r: r.guardrail_id)+ untracked_agg: Final = _units_by(untracked_rows, lambda r: r.guardrail_id)chart: Final = _chart_from_metrics(metrics)total_requests: Final = sum(a["requests"] for a in agg.values())total_blocked: Final = sum(a["blocked"] for a in agg.values())pass_rate: Final = (100.0 * (total_requests - total_blocked) / total_requests) if total_requests else 100.0- rows: Final = _guardrail_overview_rows(guardrails, agg, prev_agg, units_agg, cost_agg)+ rows: Final = _guardrail_overview_rows(guardrails, agg, prev_agg, units_agg, cost_agg, untracked_agg)return UsageOverviewResponse(rows=rows,chart=chart,@@ -560,6 +590,7 @@ async def guardrails_usage_overview(passRate=round(pass_rate, 1),totalUsageUnits=_sum_counter_units(units_rows),totalCost=_sum_tracked_cost(units_rows),+ totalUntrackedUsageUnits=_sum_counter_units(untracked_rows),)except Exception as e:from litellm.proxy.utils import handle_exception_on_proxy@@ -677,6 +708,7 @@ async def guardrails_usage_detail(cost_by_unit=_cost_by(units_rows, _counter_name),cost_by_team=_cost_by(units_rows, lambda r: r.team_id),cost_by_key=_cost_by(units_rows, lambda r: r.api_key),+ untracked_usage_units=_sum_counter_units(_untracked_rows(units_rows)),)diff --git a/tests/test_litellm/proxy/guardrails/test_usage_endpoints.py b/tests/test_litellm/proxy/guardrails/test_usage_endpoints.pyindex b8455b01e35..4a11c589810 100644--- a/tests/test_litellm/proxy/guardrails/test_usage_endpoints.py+++ b/tests/test_litellm/proxy/guardrails/test_usage_endpoints.py@@ -314,6 +314,7 @@ async def test_overview_degrades_units_to_empty_when_units_table_is_missing():assert (row.requestsEvaluated, row.usageUnits) == (4, {})assert (resp.totalRequests, resp.totalBlocked, resp.totalUsageUnits) == (4, 1, {})assert (row.cost, resp.totalCost) == (None, None)+ assert (row.untrackedUsageUnits, resp.totalUntrackedUsageUnits) == ({}, {})@pytest.mark.asyncio@@ -344,6 +345,40 @@ async def test_overview_reports_cost_per_row_and_total_summing_only_tracked_daysassert resp.totalCost == pytest.approx(0.45)+async def test_overview_reports_the_units_its_cost_leaves_out_per_row_and_total():+ """A row's cost silently under-reports whenever some of its days carry NULL, so+ the response must say exactly which units (per counter) that cost excludes.+ A guardrail whose rows are all priced reports none; one with only NULL rows+ reports all of its units; a mix reports just the NULL rows' units."""+ prisma = _prisma(+ find_many=[],+ metrics=[_metric("yaml-pii", requests=4, passed=3, blocked=1)],+ units=[+ _units_row("yaml-pii", usage_unit="contentPolicyUnits", units=1000, cost=0.15),+ _units_row("yaml-pii", date="2026-04-24", usage_unit="contentPolicyUnits", units=5000, cost=None),+ _units_row("yaml-pii", date="2026-04-24", usage_unit="topicPolicyUnits", units=40, cost=None),+ _units_row("yaml-pii", usage_unit="wordPolicyUnits", units=9, cost=0.0),+ _units_row("legacy-guard", usage_unit="topicPolicyUnits", units=7, cost=None),+ _units_row("priced-guard", usage_unit="contentPolicyUnits", units=3, cost=0.0003),+ ],+ )+ handler = _config_handler(+ _yaml_guardrail(guardrail_id="yaml-uuid", name="yaml-pii"),+ _yaml_guardrail(guardrail_id="legacy-uuid", name="legacy-guard"),+ _yaml_guardrail(guardrail_id="priced-uuid", name="priced-guard"),+ )+ p1, p2 = _patches(prisma, handler)+ with p1, p2:+ resp = await guardrails_usage_overview(start_date=START, end_date=END, user_api_key_dict=ADMIN)+ by_id = {r.id: r for r in resp.rows}+ assert by_id["yaml-uuid"].usageUnits == {"contentPolicyUnits": 6000, "topicPolicyUnits": 40, "wordPolicyUnits": 9}+ assert by_id["yaml-uuid"].untrackedUsageUnits == {"contentPolicyUnits": 5000, "topicPolicyUnits": 40}+ assert by_id["legacy-uuid"].untrackedUsageUnits == {"topicPolicyUnits": 7}+ assert by_id["priced-uuid"].untrackedUsageUnits == {}+ assert resp.totalUntrackedUsageUnits == {"contentPolicyUnits": 5000, "topicPolicyUnits": 47}++@pytest.mark.asyncioasync def test_detail_breaks_cost_down_by_unit_day_team_and_key():"""Every cost breakdown keeps the same keys as its units twin so the UI can@@ -380,6 +415,7 @@ async def test_detail_breaks_cost_down_by_unit_day_team_and_key():assert resp.cost_by_key == {"hash-1": pytest.approx(0.15), "hash-2": pytest.approx(0.03)}assert resp.cost_by_team.keys() == resp.usage_units_by_team.keys()assert resp.cost_by_key.keys() == resp.usage_units_by_key.keys()+ assert resp.untracked_usage_units == {"topicPolicyUnits": 10}@pytest.mark.asyncio@@ -400,6 +436,7 @@ async def test_detail_degrades_units_to_empty_when_units_table_is_missing():{},)assert (resp.cost, resp.cost_by_unit, resp.cost_by_team, resp.cost_by_key) == (None, {}, {}, {})+ assert resp.untracked_usage_units == {}# ---- logs -------------------------------------------------------------------diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex a3d8b22a672..b21bb523aa5 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -37825,6 +37825,10 @@ export interface components {trend: string;/** Type */type: string;+ /** Untracked Usage Units */+ untracked_usage_units: {+ [key: string]: number;+ };/** Usage Units */usage_units: {[key: string]: number;@@ -37890,6 +37894,10 @@ export interface components {totalCost: number | null;/** Totalrequests */totalRequests: number;+ /** Totaluntrackedusageunits */+ totalUntrackedUsageUnits: {+ [key: string]: number;+ };/** Totalusageunits */totalUsageUnits: {[key: string]: number;@@ -37901,7 +37909,10 @@ export interface components {avgLatency: number | null;/** Avgscore */avgScore: number | null;- /** Cost */+ /**+ * Cost+ * @description USD billed for usageUnits over the window, summed over days with tracked cost; null when none have it+ */cost: number | null;/** Failrate */failRate: number;@@ -37919,6 +37930,13 @@ export interface components {trend: string;/** Type */type: string;+ /**+ * Untrackedusageunits+ * @description The share of usageUnits that cost leaves out: units from days with no tracked cost, per counter+ */+ untrackedUsageUnits: {+ [key: string]: number;+ };/** Usageunits */usageUnits: {[key: string]: number;