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: add proxy-wide default tpm/rpm limits per deployment
Ephrim Stanleycac685014ff2
diff --git a/litellm/litellm_core_utils/sensitive_data_masker.py b/litellm/litellm_core_utils/sensitive_data_masker.pyindex 663c3fac801..f22cfa11a3d 100644--- a/litellm/litellm_core_utils/sensitive_data_masker.py+++ b/litellm/litellm_core_utils/sensitive_data_masker.py@@ -30,7 +30,9 @@ class SensitiveDataMasker:# If any key segment matches one of these, the key is not considered sensitive# even if it also matches a sensitive pattern. For example, "input_cost_per_token"# contains "token" but "cost" overrides that — it's a pricing field, not a secret.- self.non_sensitive_overrides = non_sensitive_overrides or {"cost"}+ # Similarly, "*_limit" fields (tpm_limit, rpm_limit, etc.) are rate/budget caps,+ # not credentials, even though their names may contain "key" (e.g. default_api_key_tpm_limit).+ self.non_sensitive_overrides = non_sensitive_overrides or {"cost", "limit"}self.visible_prefix = visible_prefixself.visible_suffix = visible_suffixdiff --git a/litellm/proxy/auth/auth_utils.py b/litellm/proxy/auth/auth_utils.pyindex a03e1fb94c1..235b217610a 100644--- a/litellm/proxy/auth/auth_utils.py+++ b/litellm/proxy/auth/auth_utils.py@@ -539,8 +539,49 @@ def bytes_to_mb(bytes_value: int):# helpers used by parallel request limiter to handle model rpm/tpm limits for a given api key+def _get_deployment_default_rpm_limit(model_name: str) -> Optional[int]:+ """+ Return the default_api_key_rpm_limit configured on the deployment for model_name,+ or None if not set.+ """+ from litellm.proxy.proxy_server import llm_router++ if llm_router is None:+ return None+ deployments = llm_router.get_model_list(model_name=model_name)+ if not deployments:+ return None+ for deployment in deployments:+ litellm_params = deployment.get("litellm_params", {})+ limit = litellm_params.get("default_api_key_rpm_limit")+ if limit is not None:+ return int(limit)+ return None+++def _get_deployment_default_tpm_limit(model_name: str) -> Optional[int]:+ """+ Return the default_api_key_tpm_limit configured on the deployment for model_name,+ or None if not set.+ """+ from litellm.proxy.proxy_server import llm_router++ if llm_router is None:+ return None+ deployments = llm_router.get_model_list(model_name=model_name)+ if not deployments:+ return None+ for deployment in deployments:+ litellm_params = deployment.get("litellm_params", {})+ limit = litellm_params.get("default_api_key_tpm_limit")+ if limit is not None:+ return int(limit)+ return None++def get_key_model_rpm_limit(user_api_key_dict: UserAPIKeyAuth,+ model_name: Optional[str] = None,) -> Optional[Dict[str, int]]:"""Get the model rpm limit for a given api key.@@ -549,6 +590,7 @@ def get_key_model_rpm_limit(1. Key metadata (model_rpm_limit)2. Key model_max_budget (rpm_limit per model)3. Team metadata (model_rpm_limit)+ 4. Deployment default_api_key_rpm_limit (when model_name is provided)"""# 1. Check key metadata first (takes priority)if user_api_key_dict.metadata:@@ -567,13 +609,22 @@ def get_key_model_rpm_limit(# 3. Fallback to team metadataif user_api_key_dict.team_metadata:- return user_api_key_dict.team_metadata.get("model_rpm_limit")+ team_limit = user_api_key_dict.team_metadata.get("model_rpm_limit")+ if team_limit:+ return team_limit++ # 4. Fallback to deployment default_api_key_rpm_limit+ if model_name is not None:+ default_limit = _get_deployment_default_rpm_limit(model_name)+ if default_limit is not None:+ return {model_name: default_limit}return Nonedef get_key_model_tpm_limit(user_api_key_dict: UserAPIKeyAuth,+ model_name: Optional[str] = None,) -> Optional[Dict[str, int]]:"""Get the model tpm limit for a given api key.@@ -582,6 +633,7 @@ def get_key_model_tpm_limit(1. Key metadata (model_tpm_limit)2. Key model_max_budget (tpm_limit per model)3. Team metadata (model_tpm_limit)+ 4. Deployment default_api_key_tpm_limit (when model_name is provided)"""# 1. Check key metadata first (takes priority)if user_api_key_dict.metadata:@@ -600,7 +652,15 @@ def get_key_model_tpm_limit(# 3. Fallback to team metadataif user_api_key_dict.team_metadata:- return user_api_key_dict.team_metadata.get("model_tpm_limit")+ team_limit = user_api_key_dict.team_metadata.get("model_tpm_limit")+ if team_limit:+ return team_limit++ # 4. Fallback to deployment default_api_key_tpm_limit+ if model_name is not None:+ default_limit = _get_deployment_default_tpm_limit(model_name)+ if default_limit is not None:+ return {model_name: default_limit}return Nonediff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex 19c8c484b4d..5aaac088dc2 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -687,8 +687,12 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):if not requested_model:return- _tpm_limit_for_key_model = get_key_model_tpm_limit(user_api_key_dict)- _rpm_limit_for_key_model = get_key_model_rpm_limit(user_api_key_dict)+ _tpm_limit_for_key_model = get_key_model_tpm_limit(+ user_api_key_dict, model_name=requested_model+ )+ _rpm_limit_for_key_model = get_key_model_rpm_limit(+ user_api_key_dict, model_name=requested_model+ )if _tpm_limit_for_key_model is None and _rpm_limit_for_key_model is None:returndiff --git a/litellm/types/router.py b/litellm/types/router.pyindex e8ff2115ff5..5d28349b5e4 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -188,6 +188,11 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):max_file_size_mb: Optional[float] = None+ # Proxy-wide default rate limits applied to any API key using this deployment+ # when the key does not have a model-specific tpm/rpm limit configured.+ default_api_key_tpm_limit: Optional[int] = None+ default_api_key_rpm_limit: Optional[int] = None+# Deployment budgetsmax_budget: Optional[float] = Nonebudget_duration: Optional[str] = Nonediff --git a/tests/test_litellm/proxy/auth/test_auth_utils.py b/tests/test_litellm/proxy/auth/test_auth_utils.pyindex 5e42b110aa0..be4db666a04 100644--- a/tests/test_litellm/proxy/auth/test_auth_utils.py+++ b/tests/test_litellm/proxy/auth/test_auth_utils.py@@ -2,7 +2,7 @@Unit tests for auth_utils functions related to rate limiting and customer ID extraction."""-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.auth.auth_utils import (@@ -315,3 +315,132 @@ def test_get_end_user_id_falls_back_to_deprecated_user_header_name():result = get_end_user_id_from_request_body(request_body={}, request_headers=headers)assert result == "user-legacy"+++def _make_deployment_dict(model_name: str, tpm: int = None, rpm: int = None) -> dict:+ """Helper to build a minimal deployment dict as returned by router.get_model_list."""+ litellm_params: dict = {"model": model_name}+ if tpm is not None:+ litellm_params["default_api_key_tpm_limit"] = tpm+ if rpm is not None:+ litellm_params["default_api_key_rpm_limit"] = rpm+ return {"model_name": model_name, "litellm_params": litellm_params}+++_ROUTER_PATCH = "litellm.proxy.proxy_server.llm_router"+++class TestDeploymentDefaultRpmLimit:+ """Tests for deployment default_api_key_rpm_limit fallback in get_key_model_rpm_limit."""++ def test_returns_deployment_default_when_key_has_no_limits(self):+ """Case 2 from spec: key has no model-specific limits, falls back to deployment default."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1", rpm=200)+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_rpm_limit(user_api_key_dict, model_name="model1")+ assert result == {"model1": 200}++ def test_key_model_limit_takes_priority_over_deployment_default(self):+ """Case 1 from spec: key model-specific limit wins over deployment default."""+ user_api_key_dict = UserAPIKeyAuth(+ api_key="sk-123",+ metadata={"model_rpm_limit": {"model1": 10}},+ )+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1", rpm=200)+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_rpm_limit(user_api_key_dict, model_name="model1")+ assert result == {"model1": 10}++ def test_returns_none_when_no_deployment_default_and_no_key_limits(self):+ """Returns None when neither the key nor the deployment has any rpm limit."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1") # no rpm default+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_rpm_limit(user_api_key_dict, model_name="model1")+ assert result is None++ def test_returns_none_without_model_name_even_when_deployment_has_default(self):+ """No model_name means deployment fallback is skipped."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1", rpm=200)+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_rpm_limit(user_api_key_dict)+ assert result is None++ def test_returns_none_when_llm_router_is_none(self):+ """No router means deployment fallback returns None gracefully."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ with patch(_ROUTER_PATCH, None):+ result = get_key_model_rpm_limit(user_api_key_dict, model_name="model1")+ assert result is None+++class TestDeploymentDefaultTpmLimit:+ """Tests for deployment default_api_key_tpm_limit fallback in get_key_model_tpm_limit."""++ def test_returns_deployment_default_when_key_has_no_limits(self):+ """Case 2 from spec: key has no model-specific limits, falls back to deployment default."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1", tpm=100)+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_tpm_limit(user_api_key_dict, model_name="model1")+ assert result == {"model1": 100}++ def test_key_model_limit_takes_priority_over_deployment_default(self):+ """Case 1 from spec: key model-specific limit wins over deployment default."""+ user_api_key_dict = UserAPIKeyAuth(+ api_key="sk-123",+ metadata={"model_tpm_limit": {"model1": 20}},+ )+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1", tpm=100)+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_tpm_limit(user_api_key_dict, model_name="model1")+ assert result == {"model1": 20}++ def test_returns_none_when_no_deployment_default_and_no_key_limits(self):+ """Returns None when neither the key nor the deployment has any tpm limit."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1") # no tpm default+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_tpm_limit(user_api_key_dict, model_name="model1")+ assert result is None++ def test_returns_none_without_model_name_even_when_deployment_has_default(self):+ """No model_name means deployment fallback is skipped."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ mock_router = MagicMock()+ mock_router.get_model_list.return_value = [+ _make_deployment_dict("model1", tpm=100)+ ]+ with patch(_ROUTER_PATCH, mock_router):+ result = get_key_model_tpm_limit(user_api_key_dict)+ assert result is None++ def test_returns_none_when_llm_router_is_none(self):+ """No router means deployment fallback returns None gracefully."""+ user_api_key_dict = UserAPIKeyAuth(api_key="sk-123")+ with patch(_ROUTER_PATCH, None):+ result = get_key_model_tpm_limit(user_api_key_dict, model_name="model1")+ assert result is Nonediff --git a/tests/test_litellm/proxy/test_model_info_default_limits.py b/tests/test_litellm/proxy/test_model_info_default_limits.pynew file mode 100644index 00000000000..e749c84dfb2--- /dev/null+++ b/tests/test_litellm/proxy/test_model_info_default_limits.py@@ -0,0 +1,163 @@+"""+Tests verifying that default_api_key_tpm_limit and default_api_key_rpm_limit set in+litellm_params are returned by the /model/info endpoint.+"""++from unittest.mock import MagicMock, patch++import pytest++from litellm.proxy.proxy_server import _get_proxy_model_info+from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo+++def _make_deployment(+ model_name: str,+ default_tpm: int = None,+ default_rpm: int = None,+) -> Deployment:+ params: dict = {"model": f"openai/{model_name}"}+ if default_tpm is not None:+ params["default_api_key_tpm_limit"] = default_tpm+ if default_rpm is not None:+ params["default_api_key_rpm_limit"] = default_rpm+ return Deployment(+ model_name=model_name,+ litellm_params=LiteLLM_Params(**params),+ model_info=ModelInfo(),+ )+++class TestModelInfoDefaultLimitsInResponse:+ """+ Verify _get_proxy_model_info (the helper used by the /model/info endpoint) returns+ default_api_key_tpm_limit and default_api_key_rpm_limit from litellm_params.+ """++ def test_default_tpm_and_rpm_present_in_model_info_response(self):+ """Both defaults should appear in the litellm_params section of the response."""+ deployment = _make_deployment("model1", default_tpm=100, default_rpm=200)+ model_dict = deployment.model_dump(exclude_none=True)++ result = _get_proxy_model_info(model=model_dict)++ litellm_params = result["litellm_params"]+ assert litellm_params.get("default_api_key_tpm_limit") == 100+ assert litellm_params.get("default_api_key_rpm_limit") == 200++ def test_default_tpm_only_present_when_only_tpm_configured(self):+ """Only the configured default appears; the other stays absent."""+ deployment = _make_deployment("model1", default_tpm=500)+ model_dict = deployment.model_dump(exclude_none=True)++ result = _get_proxy_model_info(model=model_dict)++ litellm_params = result["litellm_params"]+ assert litellm_params.get("default_api_key_tpm_limit") == 500+ assert "default_api_key_rpm_limit" not in litellm_params++ def test_default_rpm_only_present_when_only_rpm_configured(self):+ """Only the configured default appears; the other stays absent."""+ deployment = _make_deployment("model1", default_rpm=300)+ model_dict = deployment.model_dump(exclude_none=True)++ result = _get_proxy_model_info(model=model_dict)++ litellm_params = result["litellm_params"]+ assert litellm_params.get("default_api_key_rpm_limit") == 300+ assert "default_api_key_tpm_limit" not in litellm_params++ def test_defaults_absent_when_not_configured(self):+ """Neither field appears when not set on the deployment."""+ deployment = _make_deployment("model1")+ model_dict = deployment.model_dump(exclude_none=True)++ result = _get_proxy_model_info(model=model_dict)++ litellm_params = result["litellm_params"]+ assert "default_api_key_tpm_limit" not in litellm_params+ assert "default_api_key_rpm_limit" not in litellm_params++ def test_defaults_not_masked_or_stripped_by_sensitive_data_filter(self):+ """+ default_api_key_tpm_limit / default_api_key_rpm_limit must not be+ treated as sensitive and must survive remove_sensitive_info_from_deployment.+ """+ deployment = _make_deployment("model1", default_tpm=100, default_rpm=200)+ model_dict = deployment.model_dump(exclude_none=True)++ result = _get_proxy_model_info(model=model_dict)++ # Values should be unchanged integers, not masked strings+ assert result["litellm_params"]["default_api_key_tpm_limit"] == 100+ assert result["litellm_params"]["default_api_key_rpm_limit"] == 200+++class TestModelInfoEndpointWithRouter:+ """+ Integration-style tests simulating the /model/info endpoint reading from the router.+ """++ @pytest.mark.asyncio+ async def test_model_info_endpoint_returns_defaults_for_specific_model_id(self):+ """+ When litellm_model_id is provided, the endpoint should return the deployment's+ default limits in litellm_params.+ """+ from litellm.proxy.proxy_server import model_info_v1+ from litellm.proxy._types import UserAPIKeyAuth++ deployment = _make_deployment("model1", default_tpm=100, default_rpm=200)++ mock_router = MagicMock()+ mock_router.get_deployment.return_value = deployment++ user_api_key_dict = UserAPIKeyAuth(api_key="sk-test")++ with patch("litellm.proxy.proxy_server.llm_router", mock_router), \+ patch("litellm.proxy.proxy_server.llm_model_list", [{}]), \+ patch("litellm.proxy.proxy_server.user_model", None):+ response = await model_info_v1(+ user_api_key_dict=user_api_key_dict,+ litellm_model_id="some-model-id",+ )++ assert len(response["data"]) == 1+ litellm_params = response["data"][0]["litellm_params"]+ assert litellm_params.get("default_api_key_tpm_limit") == 100+ assert litellm_params.get("default_api_key_rpm_limit") == 200++ @pytest.mark.asyncio+ async def test_model_info_endpoint_returns_defaults_in_full_model_list(self):+ """+ Without litellm_model_id, the endpoint iterates all models. Each deployment's+ default limits should appear in its litellm_params entry.+ """+ from litellm.proxy.proxy_server import model_info_v1+ from litellm.proxy._types import UserAPIKeyAuth++ deployment = _make_deployment("model1", default_tpm=100, default_rpm=200)+ deployment_dict = deployment.model_dump(exclude_none=True)++ mock_router = MagicMock()+ mock_router.get_model_names.return_value = ["model1"]+ mock_router.get_model_access_groups.return_value = {}+ mock_router.get_model_list.return_value = [deployment_dict]++ user_api_key_dict = UserAPIKeyAuth(api_key="sk-test")++ with patch("litellm.proxy.proxy_server.llm_router", mock_router), \+ patch("litellm.proxy.proxy_server.llm_model_list", [deployment_dict]), \+ patch("litellm.proxy.proxy_server.user_model", None), \+ patch("litellm.proxy.proxy_server.get_key_models", return_value=["model1"]), \+ patch("litellm.proxy.proxy_server.get_team_models", return_value=["model1"]), \+ patch("litellm.proxy.proxy_server.get_complete_model_list", return_value=["model1"]):+ response = await model_info_v1(+ user_api_key_dict=user_api_key_dict,+ litellm_model_id=None,+ )++ assert len(response["data"]) >= 1+ litellm_params = response["data"][0]["litellm_params"]+ assert litellm_params.get("default_api_key_tpm_limit") == 100+ assert litellm_params.get("default_api_key_rpm_limit") == 200