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]

feat: add show budget window usage

Thijmen Stavenuiter8c5fa0c0f9ec
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 7e190e8b19d..22edbf33f94 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -106,6 +106,7 @@ from litellm.proxy.management_helpers.team_member_permission_checks import (
TeamMemberPermissionChecks,
)
from litellm.proxy.management_helpers.utils import management_endpoint_wrapper
+from litellm.proxy.spend_tracking.budget_reservation import get_budget_window_start
from litellm.proxy.spend_tracking.spend_tracking_utils import _is_master_key
from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (
get_ui_settings_cached,
@@ -3516,6 +3517,61 @@ async def _build_model_max_budget_usage(
return result
+async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None:
+ """
+ Attach current-window spend to each entry in key_info["budget_limits"], in place.
+
+ Per-window spend is not persisted in the DB; it lives in the cross-pod spend
+ counters (spend:key:{hashed_token}:window:{budget_duration}) that
+ _virtual_key_multi_budget_check enforces against, so we read the same
+ counters via get_current_spend. Passing max_budget + window_start makes the
+ read re-check against the authoritative spend-log aggregate when the counter
+ is stale-low (e.g. after a Redis flush), same as the enforcement path.
+ """
+ from litellm.proxy.proxy_server import get_current_spend
+
+ budget_limits: Any = key_info.get("budget_limits")
+ if isinstance(budget_limits, str):
+ try:
+ budget_limits = json.loads(budget_limits)
+ except (TypeError, ValueError):
+ return
+ key_info["budget_limits"] = budget_limits
+ if not isinstance(budget_limits, list):
+ return
+
+ for idx, window in enumerate(budget_limits):
+ w: dict | None = None
+ if isinstance(window, dict):
+ w = window
+ elif hasattr(window, "model_dump"):
+ try:
+ w = window.model_dump()
+ except Exception: # noqa: BLE001
+ continue
+ budget_limits[idx] = w
+ if not w:
+ continue
+ duration: Any = w.get("budget_duration")
+ max_budget: Any = w.get("max_budget")
+ if not duration:
+ continue
+ try:
+ max_budget = float(max_budget) if max_budget is not None else None
+ except (TypeError, ValueError):
+ max_budget = None
+ counter_key: Final = f"spend:key:{api_key_hash}:window:{duration}"
+ spend: Final = await get_current_spend(
+ counter_key=counter_key,
+ fallback_spend=0.0,
+ max_budget=max_budget,
+ window_entity_type="Key",
+ window_entity_id=api_key_hash,
+ window_start=get_budget_window_start(w),
+ )
+ w["current_spend"] = round(spend, 4)
+
+
@router.post(
"/v2/key/info",
tags=["key management"],
@@ -3597,6 +3653,8 @@ async def info_key_fn_v2(
model_max_budget=model_max_budget,
user_api_key_cache=user_api_key_cache,
)
+ if k_token_hash:
+ await _attach_budget_limits_usage(key_info=k_dict, api_key_hash=k_token_hash)
filtered_key_info.append(k_dict)
return {"key": data.keys, "info": filtered_key_info}
@@ -3633,6 +3691,9 @@ async def info_key_fn(
- model_max_budget: dict - Per-model budgets, e.g. {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}}
- model_max_budget_usage: dict | None - Current-window spend per model, present only when
the key has per-model budgets
+ - budget_limits: list | None - Concurrent budget windows. Each entry includes
+ current_spend: spend accumulated in the window so far (read from the same cross-pod
+ spend counter the budget enforcement uses)
- models: list - Model_name's the key is allowed to call
- tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits
- metadata: dict - Metadata for the key, e.g. {"team": "core-infra"}
@@ -3709,6 +3770,7 @@ async def info_key_fn(
model_max_budget=model_max_budget,
user_api_key_cache=user_api_key_cache,
)
+ await _attach_budget_limits_usage(key_info=key_info, api_key_hash=key_token_hash)
# Attach object_permission if object_permission_id is set
key_info = await attach_object_permission_to_dict(key_info, prisma_client)
diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
index bdf09a95e4b..59f7a2f1e8e 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
@@ -13789,6 +13789,212 @@ async def test_info_key_fn_v2_budget_table_fallback(monkeypatch):
mock_prisma_client.db.query_raw.assert_not_awaited()
+async def test_info_key_fn_budget_limits_includes_current_spend(monkeypatch):
+ """
+ /key/info should attach current_spend to each budget_limits window, read from
+ the same spend counter (spend:key:{token}:window:{duration}) that budget
+ enforcement uses.
+ """
+ from unittest.mock import AsyncMock, MagicMock
+
+ from litellm.proxy._types import LiteLLM_VerificationToken
+ from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn
+
+ test_key_token = "hashed_token_window_test"
+ budget_limits = [
+ {
+ "reset_at": "2026-08-15T18:00:00+00:00",
+ "max_budget": 2.0,
+ "budget_duration": "1h",
+ }
+ ]
+
+ mock_prisma_client = AsyncMock()
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ mock_user_api_key_cache = AsyncMock()
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
+ )
+ mock_get_current_spend = AsyncMock(return_value=0.73)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
+ )
+
+ mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
+ mock_key_info.token = test_key_token
+ mock_key_info.object_permission_id = None
+ mock_key_info.user_id = "user-w"
+ mock_key_info.team_id = None
+ mock_key_info.litellm_budget_table = None
+ mock_key_info.model_dump.return_value = {
+ "token": test_key_token,
+ "budget_limits": [dict(w) for w in budget_limits],
+ "user_id": "user-w",
+ "team_id": None,
+ "object_permission_id": None,
+ "litellm_budget_table": None,
+ }
+ mock_key_info.dict.return_value = mock_key_info.model_dump.return_value
+
+ mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=mock_key_info
+ )
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-test-window-key",
+ )
+
+ result = await info_key_fn(
+ key="sk-test-window-key",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ windows = result["info"]["budget_limits"]
+ assert len(windows) == 1
+ assert windows[0]["current_spend"] == 0.73
+ assert windows[0]["max_budget"] == 2.0
+ assert windows[0]["budget_duration"] == "1h"
+
+ mock_get_current_spend.assert_awaited_once()
+ call_kwargs = mock_get_current_spend.await_args.kwargs
+ assert call_kwargs["counter_key"] == f"spend:key:{test_key_token}:window:1h"
+ assert call_kwargs["max_budget"] == 2.0
+ assert call_kwargs["window_entity_type"] == "Key"
+ assert call_kwargs["window_entity_id"] == test_key_token
+ assert call_kwargs["window_start"] is not None
+
+
+async def test_info_key_fn_no_budget_limits_skips_spend_lookup(monkeypatch):
+ """Keys without budget_limits should not trigger window spend lookups."""
+ from unittest.mock import AsyncMock, MagicMock
+
+ from litellm.proxy._types import LiteLLM_VerificationToken
+ from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn
+
+ test_key_token = "hashed_token_no_windows"
+
+ mock_prisma_client = AsyncMock()
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ mock_user_api_key_cache = AsyncMock()
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
+ )
+ mock_get_current_spend = AsyncMock(return_value=0.0)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
+ )
+
+ mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
+ mock_key_info.token = test_key_token
+ mock_key_info.object_permission_id = None
+ mock_key_info.user_id = "user-nw"
+ mock_key_info.team_id = None
+ mock_key_info.litellm_budget_table = None
+ mock_key_info.model_dump.return_value = {
+ "token": test_key_token,
+ "budget_limits": None,
+ "user_id": "user-nw",
+ "team_id": None,
+ "object_permission_id": None,
+ "litellm_budget_table": None,
+ }
+ mock_key_info.dict.return_value = mock_key_info.model_dump.return_value
+
+ mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
+ return_value=mock_key_info
+ )
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-test-no-window-key",
+ )
+
+ result = await info_key_fn(
+ key="sk-test-no-window-key",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ assert result["info"]["budget_limits"] is None
+ mock_get_current_spend.assert_not_awaited()
+
+
+async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch):
+ """/v2/key/info should attach current_spend to each budget_limits window."""
+ from unittest.mock import AsyncMock, MagicMock
+
+ from litellm.proxy._types import KeyRequest, LiteLLM_VerificationToken
+ from litellm.proxy.management_endpoints.key_management_endpoints import (
+ info_key_fn_v2,
+ )
+
+ test_key_token = "hashed_token_v2_window_test"
+
+ mock_prisma_client = AsyncMock()
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ mock_user_api_key_cache = AsyncMock()
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
+ )
+ mock_get_current_spend = AsyncMock(return_value=1.25)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
+ )
+
+ mock_key = MagicMock(spec=LiteLLM_VerificationToken)
+ mock_key.token = test_key_token
+ mock_key.user_id = "user-v2-w"
+ mock_key.team_id = None
+ mock_key.model_dump.return_value = {
+ "token": test_key_token,
+ "budget_limits": [
+ {
+ "reset_at": "2026-08-15T18:00:00+00:00",
+ "max_budget": 2.0,
+ "budget_duration": "1h",
+ },
+ {
+ "reset_at": "2026-08-16T00:00:00+00:00",
+ "max_budget": 20.0,
+ "budget_duration": "1d",
+ },
+ ],
+ "user_id": "user-v2-w",
+ "team_id": None,
+ "litellm_budget_table": None,
+ }
+ mock_key.dict.return_value = mock_key.model_dump.return_value
+
+ mock_prisma_client.get_data = AsyncMock(return_value=[mock_key])
+
+ user_api_key_dict = UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-admin-v2-w",
+ )
+
+ result = await info_key_fn_v2(
+ data=KeyRequest(keys=[test_key_token]),
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ assert len(result["info"]) == 1
+ windows = result["info"][0]["budget_limits"]
+ assert len(windows) == 2
+ assert windows[0]["current_spend"] == 1.25
+ assert windows[1]["current_spend"] == 1.25
+ assert mock_get_current_spend.await_count == 2
+ counter_keys = {
+ call.kwargs["counter_key"] for call in mock_get_current_spend.await_args_list
+ }
+ assert counter_keys == {
+ f"spend:key:{test_key_token}:window:1h",
+ f"spend:key:{test_key_token}:window:1d",
+ }
+
+
@pytest.mark.asyncio
async def test_info_key_fn_provider_prefix_spend_fallback(monkeypatch):
"""Cached spend for 'gpt-4o' matches budget key 'openai/gpt-4o' via suffix match."""