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
refactor(proxy): type the per-model budget plumbing added yesterday
Devin AI4f5e290f60f5
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.jsonindex 664e1669834..9dcc46ebcee 100644--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@ -1,6 +1,6 @@{"reportAny": {- "limit": 19955+ "limit": 19954},"reportArgumentType": {"limit": 2566@@ -57,7 +57,7 @@"limit": 5663},"reportMissingTypeArgument": {- "limit": 15555+ "limit": 15553},"reportMissingTypeStubs": {"limit": 40@@ -105,13 +105,13 @@"limit": 109},"reportUnknownMemberType": {- "limit": 39011+ "limit": 39007},"reportUnknownParameterType": {- "limit": 19885+ "limit": 19883},"reportUnknownVariableType": {- "limit": 30569+ "limit": 30568},"reportUnnecessaryCast": {"limit": 117diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.pyindex 3297aa95715..c1a2384e693 100644--- a/litellm/llms/anthropic/common_utils.py+++ b/litellm/llms/anthropic/common_utils.py@@ -4,7 +4,7 @@ This file contains common utils for anthropic calls.import copyimport re-from collections.abc import Mapping, Sequence+from collections.abc import Mapping, MutableMapping, Sequencefrom datetime import datetime, timezonefrom types import MappingProxyTypefrom typing import Any, Final, Literal@@ -443,7 +443,7 @@ class AnthropicModelInfo(BaseLLMModelInfo):@staticmethoddef maybe_drop_disabled_thinking(model: str,- optional_params: dict, # mutable-ok: in-place out-param, same contract as AnthropicConfig._maybe_drop_speed_param+ optional_params: MutableMapping[str, object], # mutable-ok: in-place out-param, as in _maybe_drop_speed_paramcustom_llm_provider: str,) -> None:"""Omit ``thinking={'type': 'disabled'}`` for always-on-thinking modelsdiff --git a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.pyindex 2a87afb5990..c8cbbba8784 100644--- a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py+++ b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py@@ -352,8 +352,8 @@ async def _check_summary_model_budget()return False- user_model_max_budget: Final = getattr(user_api_key_auth, "user_model_max_budget", None)- user_id: Final = getattr(user_api_key_auth, "user_id", None)+ user_model_max_budget: Final = user_api_key_auth.user_model_max_budget+ user_id: Final = user_api_key_auth.user_idif isinstance(user_model_max_budget, dict) and user_model_max_budget and user_id is not None:try:await model_max_budget_limiter.is_user_within_model_budget(diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 0840d37ffa1..d5338811a1f 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -2808,7 +2808,7 @@ class UserAPIKeyAuth(LiteLLM_VerificationTokenView): # the expected response ob# Values stay `object` rather than BudgetConfig: this is the raw JSON column,# and validating it here would make one malformed row fail auth outright.# resolve_model_budget validates the single entry a request actually needs.- user_model_max_budget: dict[str, object] | None = None+ user_model_max_budget: Mapping[str, object] | None = Nonerequest_route: str | None = Noneis_session_token: bool = False# Server-only marker set exclusively by the MCP gateway admission path@@ -2986,8 +2986,8 @@ class UserInfoV2Response(LiteLLMPydanticObjectBase):sso_user_id: str | None = Noneteams: list[str] = [] # Just team IDs, not full team objectsobject_permission: LiteLLM_ObjectPermissionTable | None = None- model_max_budget: dict | None = None- model_max_budget_usage: dict | None = None+ model_max_budget: Mapping[str, object] | None = None+ model_max_budget_usage: Mapping[str, Mapping[str, object]] | None = Nonefrom litellm.models.config import LiteLLM_Config as LiteLLM_Config # noqa: E402diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.pyindex fe4f1ee4ae5..d4fc091cc84 100644--- a/litellm/proxy/auth/user_api_key_auth.py+++ b/litellm/proxy/auth/user_api_key_auth.py@@ -197,9 +197,9 @@ async def _read_user_model_max_budget(user_id: str | None,prisma_client: PrismaClient | None,user_api_key_cache: UserApiKeyCache,- parent_otel_span: object,+ parent_otel_span: Span | None,proxy_logging_obj: ProxyLogging,-) -> dict | None:+) -> Mapping[str, object] | None:"""The user row's `model_max_budget`, or None when the row cannot be read.A user whose row is missing must not be refused: this is a budget lookup,@@ -213,13 +213,13 @@ async def _read_user_model_max_budget(prisma_client=prisma_client,user_api_key_cache=user_api_key_cache,user_id_upsert=False,- parent_otel_span=parent_otel_span, # pyright: ignore[reportArgumentType] # Span is a runtime union, not usable in an annotation here+ parent_otel_span=parent_otel_span,proxy_logging_obj=proxy_logging_obj,)except Exception as e: # noqa: BLE001 # mirrors the main path's toleranceverbose_logger.debug("Unable to read user for the per-model budget check: %s", e)return None- return getattr(user_obj, "model_max_budget", None)+ return user_obj.model_max_budget if user_obj is not None else Noneasync def _check_user_model_budget(@@ -3168,8 +3168,7 @@ async def _run_post_custom_auth_checks(# loaded the user row yet. The attach is unconditional because the post-call# spend hook reads this field off the token: gating it on the same condition# as enforcement would leave the user's counter uncharged whenever this- # request was not itself enforceable, which is the untracked-spend bug this- # PR exists to fix.+ # request was not itself enforceable, so its spend would go untracked.user_budget: Final = await _read_user_model_max_budget(user_id=valid_token.user_id,prisma_client=prisma_client,diff --git a/type-discipline-budget.json b/type-discipline-budget.jsonindex 627811a7f1d..81f7c6aa40b 100644--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@ -1,6 +1,6 @@{"LIT001": {- "limit": 22805+ "limit": 22801},"LIT002": {"limit": 26873diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex cf55dc69e86..156238b99e2 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -36200,7 +36200,9 @@ export interface components {} | null;/** Model Max Budget Usage */model_max_budget_usage?: {- [key: string]: unknown;+ [key: string]: {+ [key: string]: unknown;+ };} | null;/*** Models