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(responses): count billed background responses toward the creator's project and per-model budgets (#47504)

Mateo Wangd776277647c4
diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py
index 00779bfe8ec..1fa461d7ab7 100644
--- a/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py
+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_responses_cost.py
@@ -59,6 +59,19 @@ if TYPE_CHECKING:
from litellm.router import Router
_STORED_RESPONSE_ADAPTER: Final[TypeAdapter[dict[str, object]]] = TypeAdapter(dict[str, object])
+
+
+class _RoutedModelInfo(BaseModel):
+ model_config = ConfigDict(frozen=True)
+ id: str | None = None
+
+
+class _RoutedDeployment(BaseModel):
+ model_config = ConfigDict(frozen=True)
+ model_info: _RoutedModelInfo = _RoutedModelInfo()
+
+
+_ROUTED_DEPLOYMENTS: Final = TypeAdapter(tuple[_RoutedDeployment, ...])
_RETRIEVE_RESPONSE_CALL_TYPE: Final = "aget_responses"
@@ -314,10 +327,23 @@ class CheckResponsesCost:
INTERNAL_CALL_ORIGIN_METADATA_KEY: BACKGROUND_RESPONSE_COST_POLL_CALL_ORIGIN,
**target.model_metadata,
**(_deployment_metadata(deployment) if deployment is not None else {}),
+ **self._requested_model_group(target, job.team_id),
}
),
)
+ def _requested_model_group(self, target: _PollTarget, team_id: str | None) -> Mapping[str, object]:
+ requested: Final = target.model_metadata.get("model_group")
+ if target.deployment is None or not isinstance(requested, str):
+ return MappingProxyType({})
+ routed: Final = _ROUTED_DEPLOYMENTS.validate_python(
+ self.llm_router.get_model_list(model_name=requested, team_id=team_id) or ()
+ )
+ serving_id: Final = target.deployment.model_info.id
+ return MappingProxyType(
+ {"model_group": requested} if any(row.model_info.id == serving_id for row in routed) else {}
+ )
+
async def _bill_once(
self,
job: ManagedObjectRow,
diff --git a/enterprise/litellm_enterprise/proxy/common_utils/managed_object_attribution.py b/enterprise/litellm_enterprise/proxy/common_utils/managed_object_attribution.py
index 3c7735b53c0..16b1b0e973c 100644
--- a/enterprise/litellm_enterprise/proxy/common_utils/managed_object_attribution.py
+++ b/enterprise/litellm_enterprise/proxy/common_utils/managed_object_attribution.py
@@ -107,8 +107,10 @@ class ManagedObjectCreatorAttribution:
user's alias, because a resolvable name is more useful on the spend row than a null.
user_api_key_org_id is resolved too: the spend update writer reads it off this metadata
to increment organization spend, so leaving it out drops the cost from org accounting.
- A background response also carries its end user and the key, team, and user budgets, the
- way the read that billed it before did, and never names a key-scoped creator as its user.
+ A background response also carries its end user, the creating key's project and its alias,
+ and the key, team, and user budgets and per-model budgets, the way the read that billed it
+ before did, and never names a key-scoped creator as its user. A key that sets no budget of
+ its own takes its budget tier's, the same rule auth applies.
"""
def __init__(self, prisma_client: PrismaClient, poller_name: str) -> None:
@@ -126,9 +128,23 @@ class ManagedObjectCreatorAttribution:
"user_api_key_user_id": _creator_user_id(job.created_by),
**_shared_metadata(job, rows),
**({"user_api_key_end_user_id": end_user_id} if end_user_id else {}),
- **_budget_fields(rows.key, "user_api_key_spend", "user_api_key_max_budget"),
- **_budget_fields(rows.team, "user_api_key_team_spend", "user_api_key_team_max_budget"),
- **_budget_fields(rows.user, "user_api_key_user_spend", "user_api_key_user_max_budget"),
+ "user_api_key_project_id": getattr(rows.key, "project_id", None),
+ "user_api_key_project_alias": getattr(
+ getattr(rows.key, "litellm_project_table", None), "project_alias", None
+ ),
+ **_key_budget_fields(rows.key),
+ **_budget_fields(
+ rows.team,
+ "user_api_key_team_spend",
+ "user_api_key_team_max_budget",
+ "user_api_key_team_model_max_budget",
+ ),
+ **_budget_fields(
+ rows.user,
+ "user_api_key_user_spend",
+ "user_api_key_user_max_budget",
+ "user_api_key_user_model_max_budget",
+ ),
}
async def _rows(self, job: ManagedObjectRow, object_id: str) -> _CreatorRows:
@@ -155,7 +171,9 @@ class ManagedObjectCreatorAttribution:
if not api_key or _is_cli_session_key(api_key, created_by):
return None
try:
- return await _token_table(self._prisma_client).find_unique(where={"token": api_key})
+ return await _token_table(self._prisma_client).find_unique(
+ where={"token": api_key}, include={"litellm_budget_table": True, "litellm_project_table": True}
+ )
except Exception as e:
verbose_proxy_logger.error(f"{self._poller_name}: could not look up the creating key for {object_id}: {e}")
return None
@@ -212,7 +230,28 @@ def _organization_id(row: object) -> str | None:
return cast("str | None", getattr(row, "organization_id", None)) if row is not None else None
-def _budget_fields(row: object, spend_key: str, max_budget_key: str) -> Mapping[str, object]:
+def _budget_fields(row: object, spend_key: str, max_budget_key: str, model_max_budget_key: str) -> Mapping[str, object]:
if row is None:
return {}
- return {spend_key: getattr(row, "spend", None), max_budget_key: getattr(row, "max_budget", None)}
+ return {
+ spend_key: getattr(row, "spend", None),
+ max_budget_key: getattr(row, "max_budget", None),
+ model_max_budget_key: getattr(row, "model_max_budget", None),
+ }
+
+
+def _key_budget_fields(key: object) -> Mapping[str, object]:
+ if key is None:
+ return {}
+ tier: Final = getattr(key, "litellm_budget_table", None)
+ return {
+ "user_api_key_spend": getattr(key, "spend", None),
+ "user_api_key_max_budget": _own_or_tier_budget(key, tier, "max_budget"),
+ "user_api_key_model_max_budget": _own_or_tier_budget(key, tier, "model_max_budget"),
+ }
+
+
+def _own_or_tier_budget(key: object, tier: object, field: str) -> object:
+ own: Final = getattr(key, field, None)
+ tier_value: Final = getattr(tier, field, None)
+ return own if tier_value is None or own not in (None, {}) else tier_value
diff --git a/tests/integration/spend/test_background_response_billed_once.py b/tests/integration/spend/test_background_response_billed_once.py
index 8a9818a7532..6d481a98fd0 100644
--- a/tests/integration/spend/test_background_response_billed_once.py
+++ b/tests/integration/spend/test_background_response_billed_once.py
@@ -5,6 +5,7 @@ from collections.abc import Callable, Mapping
from concurrent.futures import ThreadPoolExecutor
from typing import Final
+import httpx
import openai
import pytest
from integration._support.client import Gateway, Scenario, eventually, held, list_value, object_value, string_value
@@ -611,6 +612,59 @@ def test_a_background_response_bills_the_end_user_who_created_it_once(gateway: G
assert _charged_end_users(upstream.model_id) == [end_user]
+def _project_spend(project_id: str) -> float:
+ rows: Final = read_rows('SELECT spend FROM "LiteLLM_ProjectTable" WHERE project_id = %s', (project_id,))
+ return number(rows[0]["spend"])
+
+
+def _next_create(scenario: Scenario, key: str, model: str) -> httpx.Response:
+ response: Final = scenario.gateway.request(
+ "POST", "/v1/responses", {"model": model, "input": PROMPT, "background": True, "store": False}, key=key
+ )
+ if response.status_code == 200:
+ scenario.cleanups.callback(forget_row, string_value(object_value(response.json())["id"]))
+ return response
+
+
+def _key_budget(scenario: Scenario, budget_owner: str, model_budget: JsonValue) -> Mapping[str, JsonValue]:
+ if budget_owner == "key":
+ return {"model_max_budget": model_budget}
+ if budget_owner == "user":
+ return {"user_id": scenario.user(model_max_budget=model_budget)}
+ if budget_owner == "budget_tier":
+ return {"budget_id": scenario.budget(model_max_budget=model_budget)}
+ return {}
+
+
[email protected]("budget_owner", ["key", "team", "user", "budget_tier"])
+def test_a_billed_background_response_counts_toward_its_creators_project_and_model_budget(
+ gateway: Gateway, budget_owner: str
+) -> None:
+ with gateway.scenario() as scenario:
+ upstream: Final = scripted_upstream(scenario, background_routes("completed"))
+ model_budget: Final[JsonValue] = {upstream.model: {"max_budget": PRICE / 2, "budget_duration": "1d"}}
+ team_id: Final = scenario.team(**({"model_max_budget": model_budget} if budget_owner == "team" else {}))
+ project_id: Final = scenario.project(team_id)
+ key: Final = scenario.key(
+ team_id=team_id, project_id=project_id, **_key_budget(scenario, budget_owner, model_budget)
+ )
+ response_id: Final = create_background_response(scenario, key, upstream.model)
+ read: Final = read_response(gateway, key, response_id)
+ assert (read,) in (settling_reads("completed", 1), free_reads("completed", 1))
+ eventually(
+ lambda: (key_spend(key), _project_spend(project_id)),
+ lambda spends: spends[0] > 0 and costs(spends[0])(spends[1]),
+ seconds=SPEND_LANDING_SECONDS,
+ )
+ refused: Final = eventually(
+ lambda: _next_create(scenario, key, upstream.model),
+ lambda response: response.status_code != 200,
+ seconds=SPEND_LANDING_SECONDS,
+ )
+ assert f"exceeded budget for model={upstream.model}" in refused.text, refused.text
+
+
@pytest.mark.timeout(240)
def test_the_read_that_settles_a_background_response_splits_its_charge_into_input_and_output(
gateway: Gateway,
diff --git a/tests/unit/proxy/common_utils/test_check_responses_cost.py b/tests/unit/proxy/common_utils/test_check_responses_cost.py
index f606658fa09..d78c3ef6185 100644
--- a/tests/unit/proxy/common_utils/test_check_responses_cost.py
+++ b/tests/unit/proxy/common_utils/test_check_responses_cost.py
@@ -7,7 +7,7 @@ import dataclasses
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
-from types import MappingProxyType
+from types import MappingProxyType, SimpleNamespace
from typing import Final
from unittest.mock import AsyncMock, MagicMock, Mock, patch
@@ -1217,8 +1217,6 @@ class TestCheckResponsesCost:
"""The poll's billing event is the one billed event of a background job, so its spend row must name
the key, team, org, user, and tags of the create it settles, read off the managed object row,
never the poller itself."""
- from types import SimpleNamespace
-
mock_job = MagicMock()
mock_job.unified_object_id = "resp_test_attributed"
mock_job.id = "job-attributed"
@@ -1494,6 +1492,122 @@ async def test_the_billing_event_carries_the_creators_end_user():
assert billed.metadata["user_api_key_end_user_id"] == "customer-42"
+async def test_the_billing_event_carries_the_creating_keys_project_and_every_creator_model_budget():
+ key_budget: Final = {"gpt-5": {"max_budget": 1.0, "budget_duration": "1d"}}
+ team_budget: Final = {"gpt-5": {"max_budget": 2.0, "budget_duration": "7d"}}
+ user_budget: Final = {"gpt-5": {"max_budget": 3.0, "budget_duration": "30d"}}
+ table: Final = _InMemoryManagedObjectTable(
+ rows=(
+ _StoredResponse(
+ id="job-budgets",
+ unified_object_id="resp_budgets",
+ status="queued",
+ created_by="alice",
+ api_key="hash-alice",
+ team_id="team-alpha",
+ ),
+ )
+ )
+ billed_logger: Final = _RecordingBilledLogger()
+ poller: Final = _poller_over(table, billed_logger)
+ poller.prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=SimpleNamespace(
+ key_alias=None,
+ organization_id=None,
+ spend=0.0,
+ max_budget=None,
+ project_id="project-1",
+ litellm_project_table=SimpleNamespace(project_alias="project-one"),
+ model_max_budget=key_budget,
+ )
+ )
+ poller.prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
+ return_value=SimpleNamespace(
+ team_alias=None, organization_id=None, spend=0.0, max_budget=None, model_max_budget=team_budget
+ )
+ )
+ poller.prisma_client.db.litellm_usertable.find_unique = AsyncMock(
+ return_value=SimpleNamespace(
+ user_email=None, user_alias=None, spend=0.0, max_budget=None, model_max_budget=user_budget
+ )
+ )
+
+ await poller.bill_if_finished(response_id="resp_budgets", response=_terminal_response())
+
+ (billed,) = billed_logger.billed
+ assert {
+ field: billed.metadata.get(field)
+ for field in (
+ "user_api_key_project_id",
+ "user_api_key_project_alias",
+ "user_api_key_model_max_budget",
+ "user_api_key_team_model_max_budget",
+ "user_api_key_user_model_max_budget",
+ )
+ } == {
+ "user_api_key_project_id": "project-1",
+ "user_api_key_project_alias": "project-one",
+ "user_api_key_model_max_budget": key_budget,
+ "user_api_key_team_model_max_budget": team_budget,
+ "user_api_key_user_model_max_budget": user_budget,
+ }
+
+
+_TIER_MODEL_BUDGET: Final = {"gpt-5": {"max_budget": 4.0, "budget_duration": "1d"}}
+_KEY_MODEL_BUDGET: Final = {"gpt-5": {"max_budget": 1.0, "budget_duration": "1d"}}
+
+
+ ("key_max_budget", "key_model_max_budget", "billed_max_budget", "billed_model_max_budget"),
+ [
+ (None, {}, 5.0, _TIER_MODEL_BUDGET),
+ (None, None, 5.0, _TIER_MODEL_BUDGET),
+ (2.0, _KEY_MODEL_BUDGET, 2.0, _KEY_MODEL_BUDGET),
+ ],
+ ids=["key_with_an_empty_budget_map", "key_with_no_budget_map", "key_with_its_own_budgets"],
+)
+async def test_the_billing_event_takes_the_keys_budget_tier_only_where_the_key_sets_no_budget_of_its_own(
+ key_max_budget: float | None,
+ key_model_max_budget: dict[str, object] | None,
+ billed_max_budget: float,
+ billed_model_max_budget: dict[str, object],
+):
+ table: Final = _InMemoryManagedObjectTable(
+ rows=(
+ _StoredResponse(
+ id="job-tier",
+ unified_object_id="resp_tier",
+ status="queued",
+ created_by="key:hash-tier",
+ api_key="hash-tier",
+ ),
+ )
+ )
+ billed_logger: Final = _RecordingBilledLogger()
+ poller: Final = _poller_over(table, billed_logger)
+ poller.prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=SimpleNamespace(
+ key_alias=None,
+ organization_id=None,
+ spend=0.0,
+ max_budget=key_max_budget,
+ project_id=None,
+ model_max_budget=key_model_max_budget,
+ litellm_budget_table=SimpleNamespace(max_budget=5.0, model_max_budget=_TIER_MODEL_BUDGET),
+ )
+ )
+
+ await poller.bill_if_finished(response_id="resp_tier", response=_terminal_response())
+
+ (billed,) = billed_logger.billed
+ assert (billed.metadata.get("user_api_key_max_budget"), billed.metadata.get("user_api_key_model_max_budget")) == (
+ billed_max_budget,
+ billed_model_max_budget,
+ )
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("created_by", "billed_user_id"),
@@ -1599,6 +1713,10 @@ async def _bill_through_a_priced_deployment(
read: ResponsesAPIResponse,
litellm_params: Mapping[str, object] = _PRICED_LITELLM_PARAMS,
model_info: Mapping[str, object] = MappingProxyType({}),
+ model_name: str = "priced-gpt",
+ requested_model: str = "priced-gpt",
+ model_group_alias: Mapping[str, str] = MappingProxyType({}),
+ team_id: str | None = None,
) -> _PricedBilling:
import litellm
from litellm_enterprise.proxy.common_utils.check_responses_cost import CheckResponsesCost
@@ -1610,7 +1728,16 @@ async def _bill_through_a_priced_deployment(
custom_llm_provider="openai", model_id="deployment-custom", response_id="resp_upstream"
)
table: Final = _InMemoryManagedObjectTable(
- rows=(_StoredResponse(id="job-priced", unified_object_id=response_id, status="queued", api_key="hash-alice"),)
+ rows=(
+ _StoredResponse(
+ id="job-priced",
+ unified_object_id=response_id,
+ status="queued",
+ api_key="hash-alice",
+ file_object={"model": requested_model},
+ team_id=team_id,
+ ),
+ )
)
prisma_client: Final = MagicMock()
prisma_client.db.litellm_managedobjecttable = table
@@ -1620,11 +1747,12 @@ async def _bill_through_a_priced_deployment(
router: Final = litellm.Router(
model_list=[
{
- "model_name": "priced-gpt",
+ "model_name": model_name,
"litellm_params": dict(litellm_params),
"model_info": {"id": "deployment-custom", **model_info},
}
- ]
+ ],
+ model_group_alias=dict(model_group_alias),
)
charge: Final = await CheckResponsesCost(
proxy_logging_obj=MagicMock(), prisma_client=prisma_client, llm_router=router
@@ -1657,6 +1785,75 @@ async def test_the_billing_event_prices_the_fetched_usage_at_the_deployment_rate
assert billing.table.statuses == {"job-priced": "completed"}
+ ("model_name", "deployment_model", "requested_model", "model_group_alias", "model_info", "model_group"),
+ [
+ ("openai/*", "openai/*", "openai/gpt-5.6", {}, {}, "openai/gpt-5.6"),
+ ("priced-gpt", "openai/gpt-5.6", "priced-alias", {"priced-alias": "priced-gpt"}, {}, "priced-alias"),
+ ("priced-gpt", "openai/gpt-5.6", "gpt-5.6-2026-01-01", {}, {}, "priced-gpt"),
+ (
+ "model_name_team-1_abc",
+ "openai/gpt-5.6",
+ "team-gpt",
+ {},
+ {"team_id": "team-1", "team_public_model_name": "team-gpt"},
+ "team-gpt",
+ ),
+ (
+ "model_name_team-1_wild",
+ "openai/*",
+ "openai/gpt-5.6",
+ {},
+ {"team_id": "team-1", "team_public_model_name": "openai/*"},
+ "openai/gpt-5.6",
+ ),
+ (
+ "model_name_team-2_abc",
+ "openai/gpt-5.6",
+ "team-gpt",
+ {},
+ {"team_id": "team-2", "team_public_model_name": "team-gpt"},
+ "model_name_team-2_abc",
+ ),
+ ],
+ ids=[
+ "wildcard_route",
+ "model_group_alias",
+ "fallback_kept_the_provider_model_name",
+ "team_model",
+ "team_wildcard",
+ "another_teams_model",
+ ],
+)
+async def test_the_billing_event_names_the_requested_model_as_its_model_group_only_while_it_routes_to_the_deployment(
+ monkeypatch: pytest.MonkeyPatch,
+ model_name: str,
+ deployment_model: str,
+ requested_model: str,
+ model_group_alias: Mapping[str, str],
+ model_info: Mapping[str, object],
+ model_group: str,
+):
+ import litellm
+
+ capture: Final = _spend_capture_logger()
+ monkeypatch.setattr(litellm, "_async_success_callback", [capture])
+
+ await _bill_through_a_priced_deployment(
+ _terminal_response(),
+ litellm_params={**_PRICED_LITELLM_PARAMS, "model": deployment_model},
+ model_info=model_info,
+ model_name=model_name,
+ requested_model=requested_model,
+ model_group_alias=model_group_alias,
+ team_id="team-1",
+ )
+
+ (payload,) = capture.payloads
+ assert payload["model_group"] == model_group
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("base_model_in", ["litellm_params", "model_info"])
async def test_the_billing_event_prices_the_usage_at_the_deployments_base_model(