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
Org level tpm/rpm limits + Team tpm/rpm validation when assigned to org (#15549)
Krish Dholakia6bb1d77f45a3
diff --git a/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py b/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.pyindex 19ce8090db7..794568b210b 100644--- a/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py+++ b/enterprise/litellm_enterprise/proxy/management_endpoints/key_management_endpoints.py@@ -22,9 +22,21 @@ def add_team_member_key_duration(return data+def add_team_organization_id(+ team_table: Optional[LiteLLM_TeamTable],+ data: GenerateKeyRequest,+) -> GenerateKeyRequest:+ if team_table is None:+ return data+ setattr(data, "organization_id", team_table.organization_id)+ return data++def apply_enterprise_key_management_params(data: GenerateKeyRequest,team_table: Optional[LiteLLM_TeamTable],) -> GenerateKeyRequest:+data = add_team_member_key_duration(team_table, data)+ data = add_team_organization_id(team_table, data)return datadiff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex a02e15e0103..b1082c4cc49 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -817,6 +817,7 @@ class GenerateKeyRequest(KeyRequestBase):default=None,description="How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True",)+ organization_id: Optional[str] = Noneclass GenerateKeyResponse(KeyRequestBase):@@ -825,6 +826,7 @@ class GenerateKeyResponse(KeyRequestBase):expires: Optional[datetime] = Noneuser_id: Optional[str] = Nonetoken_id: Optional[str] = None+ organization_id: Optional[str] = Nonelitellm_budget_table: Optional[Any] = Nonetoken: Optional[str] = Nonecreated_by: Optional[str] = None@@ -1291,6 +1293,13 @@ class NewTeamRequest(TeamBase):object_permission: Optional[LiteLLM_ObjectPermissionBase] = Noneallowed_passthrough_routes: Optional[list] = Nonemodel_rpm_limit: Optional[Dict[str, int]] = None+ rpm_limit_type: Optional[+ Literal["guaranteed_throughput", "best_effort_throughput"]+ ] = None # raise an error if 'guaranteed_throughput' is set and we're overallocating rpm+ tpm_limit_type: Optional[+ Literal["guaranteed_throughput", "best_effort_throughput"]+ ] = None # raise an error if 'guaranteed_throughput' is set and we're overallocating tpm+model_tpm_limit: Optional[Dict[str, int]] = Noneteam_member_budget: Optional[float] = (None # allow user to set a budget for all team members@@ -1561,6 +1570,8 @@ class NewOrganizationRequest(LiteLLM_BudgetTable):models: List = []budget_id: Optional[str] = Nonemetadata: Optional[dict] = None+ model_rpm_limit: Optional[Dict[str, int]] = None+ model_tpm_limit: Optional[Dict[str, int]] = None########################################################## Object Permission - MCP, Vector Stores etc.@@ -1899,6 +1910,12 @@ class LiteLLM_VerificationTokenView(LiteLLM_VerificationToken):end_user_rpm_limit: Optional[int] = Noneend_user_max_budget: Optional[float] = None+ # Organization Params+ organization_max_budget: Optional[float] = None+ organization_tpm_limit: Optional[int] = None+ organization_rpm_limit: Optional[int] = None+ organization_metadata: Optional[dict] = None+# Time stampslast_refreshed_at: Optional[float] = None # last time joint view was pulled from db@@ -1913,6 +1930,9 @@ class LiteLLM_VerificationTokenView(LiteLLM_VerificationToken):kwargs[attr_name] = valueif key == "end_user_id" and value is not None and isinstance(value, int):kwargs[key] = str(value)++ if kwargs.get("organization_id") is not None:+ kwargs["org_id"] = kwargs.pop("organization_id")# Initialize the superclasssuper().__init__(**kwargs)@@ -2059,6 +2079,20 @@ class LiteLLM_OrganizationTableUpdate(LiteLLM_BudgetTable):models: Optional[List[str]] = Noneupdated_by: Optional[str] = Noneobject_permission: Optional[LiteLLM_ObjectPermissionBase] = None+ model_tpm_limit: Optional[Dict[str, int]] = None+ model_rpm_limit: Optional[Dict[str, int]] = None++ @model_validator(mode="before")+ @classmethod+ def set_model_info(cls, values):+ for field in LiteLLM_ManagementEndpoint_MetadataFields:+ if values.get(field) is not None:+ # add to metadata+ if values.get("metadata") is None:+ values.update({"metadata": {}})+ values["metadata"][field] = values.get(field)+ values.pop(field)+ return valuesclass LiteLLM_UserTable(LiteLLMPydanticObjectBase):diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex d95b7bd03d6..9f2684ff90d 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -524,14 +524,14 @@ async def get_tag_objects_batch(Optimizes for latency by:1. Fetching all cached tags in parallel2. Batch fetching uncached tags in one DB query-+Args:tag_names: List of tag names to fetchprisma_client: Prisma database clientuser_api_key_cache: Cache for storing tag objectsparent_otel_span: Optional OpenTelemetry span for tracingproxy_logging_obj: Optional proxy logging object-+Returns:Dictionary mapping tag_name to LiteLLM_TagTable object"""@@ -574,9 +574,7 @@ async def get_tag_objects_batch()tag_objects[tag_name] = LiteLLM_TagTable(**db_tag.dict())except Exception as e:- verbose_proxy_logger.debug(- f"Error batch fetching tags from database: {e}"- )+ verbose_proxy_logger.debug(f"Error batch fetching tags from database: {e}")return tag_objects@@ -593,14 +591,14 @@ async def get_tag_object(Returns tag object from cache or db.Uses default cache TTL (same as end_user objects) to avoid drift.-+Args:tag_name: Name of the tag to fetchprisma_client: Prisma database clientuser_api_key_cache: Cache for storing tag objectsparent_otel_span: Optional OpenTelemetry span for tracingproxy_logging_obj: Optional proxy logging object-+Returns:LiteLLM_TagTable object if found, None otherwise"""@@ -1355,6 +1353,8 @@ async def get_org_object(raise Exception("No DB Connected. See - https://docs.litellm.ai/docs/proxy/virtual_keys")+ if not isinstance(org_id, str):+ return None# check if in cachecached_org_obj = user_api_key_cache.async_get_cache(key="org_id:{}".format(org_id))@@ -1776,9 +1776,7 @@ async def _tag_max_budget_check(BudgetExceededError if any tag is over its max budget.Triggers a budget alert if any tag is over its max budget."""- from litellm.proxy.common_utils.http_parsing_utils import (- get_tags_from_request_body,- )+ from litellm.proxy.common_utils.http_parsing_utils import get_tags_from_request_bodyif prisma_client is None:returndiff --git a/litellm/proxy/auth/auth_utils.py b/litellm/proxy/auth/auth_utils.pyindex 49c8af55de4..e6de65da2bd 100644--- a/litellm/proxy/auth/auth_utils.py+++ b/litellm/proxy/auth/auth_utils.py@@ -453,6 +453,15 @@ def get_key_model_tpm_limit(return None+def get_model_rate_limit_from_metadata(+ user_api_key_dict: UserAPIKeyAuth,+ metadata_accessor_key: Literal["team_metadata", "organization_metadata"],+ rate_limit_key: Literal["model_rpm_limit", "model_tpm_limit"],+) -> Optional[Dict[str, int]]:+ if getattr(user_api_key_dict, metadata_accessor_key):+ return getattr(user_api_key_dict, metadata_accessor_key).get(rate_limit_key)+ return None+def get_team_model_rpm_limit(user_api_key_dict: UserAPIKeyAuth,) -> Optional[Dict[str, int]]:diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex bf0aa245b97..15090187381 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -27,6 +27,7 @@ from litellm._logging import verbose_proxy_loggerfrom litellm.constants import DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTEfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.auth.auth_utils import get_model_rate_limit_from_metadatafrom litellm.types.llms.openai import BaseLiteLLMOpenAIResponseObjectif TYPE_CHECKING:@@ -549,6 +550,83 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):)return rate_limit_response+ def create_organization_rate_limit_descriptor(+ self, user_api_key_dict: UserAPIKeyAuth, requested_model: Optional[str] = None+ ) -> List[RateLimitDescriptor]:+ descriptors: List[RateLimitDescriptor] = []++ # Global org rate limits+ if user_api_key_dict.org_id is not None and (+ user_api_key_dict.organization_rpm_limit is not None+ or user_api_key_dict.organization_tpm_limit is not None+ ):+ descriptors.append(+ RateLimitDescriptor(+ key="organization",+ value=user_api_key_dict.org_id,+ rate_limit={+ "requests_per_unit": user_api_key_dict.organization_rpm_limit,+ "tokens_per_unit": user_api_key_dict.organization_tpm_limit,+ "window_size": self.window_size,+ },+ )+ )++ # Model specific org rate limits+ if (+ get_model_rate_limit_from_metadata(+ user_api_key_dict, "organization_metadata", "model_rpm_limit"+ )+ is not None+ or get_model_rate_limit_from_metadata(+ user_api_key_dict, "organization_metadata", "model_tpm_limit"+ )+ is not None+ ):+ _tpm_limit_for_team_model = (+ get_model_rate_limit_from_metadata(+ user_api_key_dict, "organization_metadata", "model_tpm_limit"+ )+ or {}+ )+ _rpm_limit_for_team_model = (+ get_model_rate_limit_from_metadata(+ user_api_key_dict, "organization_metadata", "model_rpm_limit"+ )+ or {}+ )++ should_check_rate_limit = False+ if requested_model in _tpm_limit_for_team_model:+ should_check_rate_limit = True+ elif requested_model in _rpm_limit_for_team_model:+ should_check_rate_limit = True++ if should_check_rate_limit:+ model_specific_tpm_limit = None+ model_specific_rpm_limit = None+ if requested_model in _tpm_limit_for_team_model:+ model_specific_tpm_limit = _tpm_limit_for_team_model[+ requested_model+ ]+ if requested_model in _rpm_limit_for_team_model:+ model_specific_rpm_limit = _rpm_limit_for_team_model[+ requested_model+ ]+ descriptors.append(+ RateLimitDescriptor(+ key="model_per_organization",+ value=f"{user_api_key_dict.org_id}:{requested_model}",+ rate_limit={+ "requests_per_unit": model_specific_rpm_limit,+ "tokens_per_unit": model_specific_tpm_limit,+ "window_size": self.window_size,+ },+ )+ )++ return descriptors+def _add_model_per_key_rate_limit_descriptor(self,user_api_key_dict: UserAPIKeyAuth,@@ -616,11 +694,11 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):) -> bool:"""Determine if rate limit should be enforced based on limit type and model health.-+Args:limit_type: Type of rate limit ("dynamic", "guaranteed_throughput", "best_effort_throughput", or None)model_has_failures: Whether the model has recent failures-+Returns:True if rate limit should be enforced, False otherwise"""@@ -638,24 +716,24 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):) -> Optional[int]:"""Get the rate limit value to enforce based on limit type and model health.-+Args:limit_value: The configured limit valuelimit_type: Type of rate limit ("dynamic", "guaranteed_throughput", "best_effort_throughput", or None)model_has_failures: Whether the model has recent failures-+Returns:The limit value if it should be enforced, None otherwise"""if limit_value is None:return None-+if self._should_enforce_rate_limit(limit_type=limit_type,model_has_failures=model_has_failures,):return limit_value-+return Nonedef _is_dynamic_rate_limiting_enabled(@@ -665,11 +743,11 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):) -> bool:"""Check if dynamic rate limiting is enabled for either RPM or TPM.-+Args:rpm_limit_type: RPM rate limit typetpm_limit_type: TPM rate limit type-+Returns:True if dynamic mode is enabled for either limit type"""@@ -685,14 +763,14 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):) -> List[RateLimitDescriptor]:"""Create all rate limit descriptors for the request.-+Returns list of descriptors for API key, user, team, team member, end user, and model-specific limits."""from litellm.proxy.auth.auth_utils import (get_team_model_rpm_limit,get_team_model_tpm_limit,)-+descriptors = []# API Key rate limits@@ -839,7 +917,7 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):},))-+return descriptorsasync def _check_model_has_recent_failures(@@ -850,47 +928,47 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):"""Check if any deployment for this model has recent failures by usingthe router's existing failure tracking.-+Returns True if any deployment has failures in the current minute."""from litellm.proxy.proxy_server import llm_routerfrom litellm.router_utils.router_callbacks.track_deployment_metrics import (get_deployment_failures_for_current_minute,)-+if llm_router is None:return False-+try:# Get all deployments for this modelmodel_list = llm_router.get_model_list(model_name=model)if not model_list:return False-+# Check each deployment's failure countfor deployment in model_list:deployment_id = deployment.get("model_info", {}).get("id")if not deployment_id:continue-+# Use router's existing failure trackingfailure_count = get_deployment_failures_for_current_minute(litellm_router_instance=llm_router,deployment_id=deployment_id,)-+if failure_count > DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE:verbose_proxy_logger.debug(f"[Dynamic Rate Limit] Deployment {deployment_id} has {failure_count} failures "f"in current minute - enforcing rate limits for model {model}")return True-+verbose_proxy_logger.debug(f"[Dynamic Rate Limit] No failures detected for model {model} - allowing dynamic exceeding")return False-+except Exception as e:verbose_proxy_logger.debug(f"Error checking model failure status: {str(e)}, defaulting to enforce limits"@@ -915,15 +993,18 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):metadata = user_api_key_dict.metadata or {}rpm_limit_type = metadata.get("rpm_limit_type")tpm_limit_type = metadata.get("tpm_limit_type")-+# For dynamic mode, check if the model has recent failuresmodel_has_failures = Falserequested_model = data.get("model", None)-- if self._is_dynamic_rate_limiting_enabled(- rpm_limit_type=rpm_limit_type,- tpm_limit_type=tpm_limit_type,- ) and requested_model:++ if (+ self._is_dynamic_rate_limiting_enabled(+ rpm_limit_type=rpm_limit_type,+ tpm_limit_type=tpm_limit_type,+ )+ and requested_model+ ):model_has_failures = await self._check_model_has_recent_failures(model=requested_model,parent_otel_span=user_api_key_dict.parent_otel_span,@@ -938,6 +1019,63 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):model_has_failures=model_has_failures,)+ if (+ get_model_rate_limit_from_metadata(+ user_api_key_dict, "team_metadata", "model_rpm_limit"+ )+ is not None+ or get_model_rate_limit_from_metadata(+ user_api_key_dict, "team_metadata", "model_tpm_limit"+ )+ is not None+ ):+ _tpm_limit_for_team_model = (+ get_model_rate_limit_from_metadata(+ user_api_key_dict, "team_metadata", "model_tpm_limit"+ )+ or {}+ )+ _rpm_limit_for_team_model = (+ get_model_rate_limit_from_metadata(+ user_api_key_dict, "team_metadata", "model_rpm_limit"+ )+ or {}+ )+ should_check_rate_limit = False+ if requested_model in _tpm_limit_for_team_model:+ should_check_rate_limit = True+ elif requested_model in _rpm_limit_for_team_model:+ should_check_rate_limit = True++ if should_check_rate_limit:+ model_specific_tpm_limit = None+ model_specific_rpm_limit = None+ if requested_model in _tpm_limit_for_team_model:+ model_specific_tpm_limit = _tpm_limit_for_team_model[+ requested_model+ ]+ if requested_model in _rpm_limit_for_team_model:+ model_specific_rpm_limit = _rpm_limit_for_team_model[+ requested_model+ ]+ descriptors.append(+ RateLimitDescriptor(+ key="model_per_team",+ value=f"{user_api_key_dict.team_id}:{requested_model}",+ rate_limit={+ "requests_per_unit": model_specific_rpm_limit,+ "tokens_per_unit": model_specific_tpm_limit,+ "window_size": self.window_size,+ },+ )+ )++ # Org Level Rate Limits+ descriptors.extend(+ self.create_organization_rate_limit_descriptor(+ user_api_key_dict, requested_model+ )+ )# Only check rate limits if we have descriptors with actual limitsif descriptors:response = await self.should_rate_limit(@@ -1140,6 +1278,9 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):user_api_key = litellm_metadata.get("user_api_key")user_api_key_user_id = litellm_metadata.get("user_api_key_user_id")user_api_key_team_id = litellm_metadata.get("user_api_key_team_id")+ user_api_key_organization_id = litellm_metadata.get(+ "user_api_key_organization_id"+ )user_api_key_end_user_id = kwargs.get("user") or litellm_metadata.get("user_api_key_end_user_id")@@ -1251,6 +1392,16 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):))+ if model_group and user_api_key_organization_id:+ pipeline_operations.extend(+ self._create_pipeline_operations(+ key="model_per_organization",+ value=f"{user_api_key_organization_id}:{model_group}",+ rate_limit_type="tokens",+ total_tokens=total_tokens,+ )+ )+# Execute all increments in a single pipelineif pipeline_operations:await self.async_increment_tokens_with_ttl_preservation(diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.pyindex 17b91db69ef..06f92261d89 100644--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@ -132,9 +132,7 @@ class _ProxyDBLogger(CustomLogger):else kwargs.get("response_cost", None))tags: Optional[List[str]] = (- sl_object.get("request_tags", None)- if sl_object is not None- else None+ sl_object.get("request_tags", None) if sl_object is not None else None)if response_cost is not None:diff --git a/litellm/proxy/management_endpoints/common_utils.py b/litellm/proxy/management_endpoints/common_utils.pyindex 149ca6e2f6e..a2f93e35579 100644--- a/litellm/proxy/management_endpoints/common_utils.py+++ b/litellm/proxy/management_endpoints/common_utils.py@@ -3,6 +3,7 @@ from typing import Any, Dict, Optional, Unionfrom litellm.proxy._types import (KeyRequestBase,LiteLLM_ManagementEndpoint_MetadataFields_Premium,+ LiteLLM_OrganizationTable,LiteLLM_TeamTable,LitellmUserRoles,UserAPIKeyAuth,@@ -30,7 +31,11 @@ def _is_user_team_admin(def _set_object_metadata_field(- object_data: Union[LiteLLM_TeamTable, KeyRequestBase],+ object_data: Union[+ LiteLLM_TeamTable,+ KeyRequestBase,+ LiteLLM_OrganizationTable,+ ],field_name: str,value: Any,) -> None:@@ -44,6 +49,7 @@ def _set_object_metadata_field("""if field_name in LiteLLM_ManagementEndpoint_MetadataFields_Premium:_premium_user_check(field_name)+object_data.metadata = object_data.metadata or {}object_data.metadata[field_name] = value@@ -121,3 +127,23 @@ async def _upsert_budget_and_membership(},},)+++def _update_metadata_field(updated_kv: dict, field_name: str) -> None:+ """+ Helper function to update metadata fields that require premium user checks in the update endpoint++ Args:+ updated_kv: The key-value dict being used for the update+ field_name: Name of the metadata field being updated+ """+ if field_name in LiteLLM_ManagementEndpoint_MetadataFields_Premium:+ _premium_user_check()++ if field_name in updated_kv and updated_kv[field_name] is not None:+ # remove field from updated_kv+ _value = updated_kv.pop(field_name)+ if "metadata" in updated_kv and updated_kv["metadata"] is not None:+ updated_kv["metadata"][field_name] = _value+ else:+ updated_kv["metadata"] = {field_name: _value}diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex 371a325ee0e..eeae54055f8 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -33,6 +33,7 @@ from litellm.proxy.auth.auth_checks import (_delete_cache_key_object,can_team_access_model,get_key_object,+ get_org_object,get_team_object,)from litellm.proxy.auth.auth_utils import abbreviate_api_key@@ -613,6 +614,27 @@ async def _common_key_generation_helper( # noqa: PLR0915},)+ # check org key limits - done here to handle inheriting org id from team+ if data.organization_id is not None:+ from litellm.proxy.proxy_server import prisma_client, user_api_key_cache++ if prisma_client:+ org_table = await get_org_object(+ org_id=data.organization_id,+ user_api_key_cache=user_api_key_cache,+ prisma_client=prisma_client,+ )+ if org_table is None:+ raise HTTPException(+ status_code=400,+ detail=f"Organization not found for organization_id={data.organization_id}",+ )+ await _check_org_key_limits(+ org_table=org_table,+ data=data,+ prisma_client=prisma_client,+ )+response = await generate_key_helper_fn(request_type="key", **data_json, table_name="key")@@ -639,16 +661,28 @@ async def _common_key_generation_helper( # noqa: PLR0915return response-def check_team_key_model_specific_limits(+def _check_key_model_specific_limits(keys: List[LiteLLM_VerificationToken],- team_table: LiteLLM_TeamTableCachedObj,data: Union[GenerateKeyRequest, UpdateKeyRequest],+ entity_rpm_limit: Optional[int],+ entity_tpm_limit: Optional[int],+ entity_model_rpm_limit_dict: Dict[str, int],+ entity_model_tpm_limit_dict: Dict[str, int],+ entity_type: str, # "team" or "organization") -> None:"""- Check if the team key is allocating model specific limits. If so, raise an error if we're overallocating.+ Generic function to check if a key is allocating model specific limits.+ Raises an error if we're overallocating."""- if data.model_rpm_limit is None and data.model_tpm_limit is None:+ model_rpm_limit = getattr(data, "model_rpm_limit", None) or (+ data.metadata.get("model_rpm_limit", None) if data.metadata else None+ )+ model_tpm_limit = getattr(data, "model_tpm_limit", None) or (+ data.metadata.get("model_tpm_limit", None) if data.metadata else None+ )+ if model_rpm_limit is None and model_tpm_limit is None:return+# get total model specific tpm/rpm limitmodel_specific_rpm_limit: Dict[str, int] = {}model_specific_tpm_limit: Dict[str, int] = {}@@ -664,68 +698,64 @@ def check_team_key_model_specific_limits(model_specific_tpm_limit[model] = (model_specific_tpm_limit.get(model, 0) + tpm_limit)- if data.model_rpm_limit is not None:- for model, rpm_limit in data.model_rpm_limit.items():++ if model_rpm_limit is not None:+ for model, rpm_limit in model_rpm_limit.items():if (- team_table.rpm_limit is not None+ entity_rpm_limit is not Noneand model_specific_rpm_limit.get(model, 0) + rpm_limit- > team_table.rpm_limit+ > entity_rpm_limit):raise HTTPException(status_code=400,- detail=f"Allocated RPM limit={model_specific_rpm_limit.get(model, 0)} + Key RPM limit={rpm_limit} is greater than team RPM limit={team_table.rpm_limit}",- )- elif team_table.metadata and team_table.metadata.get("model_rpm_limit"):- team_model_specific_rpm_limit_dict = team_table.metadata.get(- "model_rpm_limit", {}- )- team_model_specific_rpm_limit = team_model_specific_rpm_limit_dict.get(- model+ detail=f"Allocated RPM limit={model_specific_rpm_limit.get(model, 0)} + Key RPM limit={rpm_limit} is greater than {entity_type} RPM limit={entity_rpm_limit}",)+ elif entity_model_rpm_limit_dict:+ entity_model_specific_rpm_limit = entity_model_rpm_limit_dict.get(model)if (- model_specific_rpm_limit.get(model, 0) + rpm_limit- > team_model_specific_rpm_limit+ entity_model_specific_rpm_limit+ and model_specific_rpm_limit.get(model, 0) + rpm_limit+ > entity_model_specific_rpm_limit):raise HTTPException(status_code=400,- detail=f"Allocated RPM limit={model_specific_rpm_limit.get(model, 0)} + Key RPM limit={rpm_limit} is greater than team RPM limit={team_model_specific_rpm_limit}",+ detail=f"Allocated RPM limit={model_specific_rpm_limit.get(model, 0)} + Key RPM limit={rpm_limit} is greater than {entity_type} RPM limit={entity_model_specific_rpm_limit}",)- if data.model_tpm_limit is not None:- for model, tpm_limit in data.model_tpm_limit.items():++ if model_tpm_limit is not None:+ for model, tpm_limit in model_tpm_limit.items():if (- team_table.tpm_limit is not None+ entity_tpm_limit is not Noneand model_specific_tpm_limit.get(model, 0) + tpm_limit- > team_table.tpm_limit+ > entity_tpm_limit):raise HTTPException(status_code=400,- detail=f"Allocated TPM limit={model_specific_tpm_limit.get(model, 0)} + Key TPM limit={tpm_limit} is greater than team TPM limit={team_table.tpm_limit}",- )- elif team_table.metadata and team_table.metadata.get("model_tpm_limit"):- team_model_specific_tpm_limit_dict = team_table.metadata.get(- "model_tpm_limit", {}- )- team_model_specific_tpm_limit = team_model_specific_tpm_limit_dict.get(- model+ detail=f"Allocated TPM limit={model_specific_tpm_limit.get(model, 0)} + Key TPM limit={tpm_limit} is greater than {entity_type} TPM limit={entity_tpm_limit}",)+ elif entity_model_tpm_limit_dict:+ entity_model_specific_tpm_limit = entity_model_tpm_limit_dict.get(model)if (- team_model_specific_tpm_limit+ entity_model_specific_tpm_limitand model_specific_tpm_limit.get(model, 0) + tpm_limit- > team_model_specific_tpm_limit+ > entity_model_specific_tpm_limit):raise HTTPException(status_code=400,- detail=f"Allocated TPM limit={model_specific_tpm_limit.get(model, 0)} + Key TPM limit={tpm_limit} is greater than team TPM limit={team_model_specific_tpm_limit}",+ detail=f"Allocated TPM limit={model_specific_tpm_limit.get(model, 0)} + Key TPM limit={tpm_limit} is greater than {entity_type} TPM limit={entity_model_specific_tpm_limit}",)-def check_team_key_rpm_tpm_limits(+def _check_key_rpm_tpm_limits(keys: List[LiteLLM_VerificationToken],- team_table: LiteLLM_TeamTableCachedObj,data: Union[GenerateKeyRequest, UpdateKeyRequest],+ entity_rpm_limit: Optional[int],+ entity_tpm_limit: Optional[int],+ entity_type: str, # "team" or "organization") -> None:"""- Check if the team key is allocating rpm/tpm limits. If so, raise an error if we're overallocating.+ Generic function to check if a key is allocating rpm/tpm limits.+ Raises an error if we're overallocating."""if keys is not None and len(keys) > 0:allocated_tpm = sum(key.tpm_limit for key in keys if key.tpm_limit is not None)@@ -733,26 +763,69 @@ def check_team_key_rpm_tpm_limits(else:allocated_tpm = 0allocated_rpm = 0+if (data.tpm_limit is not None- and team_table.tpm_limit is not None- and data.tpm_limit + allocated_tpm > team_table.tpm_limit+ and entity_tpm_limit is not None+ and data.tpm_limit + allocated_tpm > entity_tpm_limit):raise HTTPException(status_code=400,- detail=f"Allocated TPM limit={allocated_tpm} + Key TPM limit={data.tpm_limit} is greater than team TPM limit={team_table.tpm_limit}",+ detail=f"Allocated TPM limit={allocated_tpm} + Key TPM limit={data.tpm_limit} is greater than {entity_type} TPM limit={entity_tpm_limit}",)if (data.rpm_limit is not None- and team_table.rpm_limit is not None- and data.rpm_limit + allocated_rpm > team_table.rpm_limit+ and entity_rpm_limit is not None+ and data.rpm_limit + allocated_rpm > entity_rpm_limit):raise HTTPException(status_code=400,- detail=f"Allocated RPM limit={allocated_rpm} + Key RPM limit={data.rpm_limit} is greater than team RPM limit={team_table.rpm_limit}",+ detail=f"Allocated RPM limit={allocated_rpm} + Key RPM limit={data.rpm_limit} is greater than {entity_type} RPM limit={entity_rpm_limit}",)+def check_team_key_model_specific_limits(+ keys: List[LiteLLM_VerificationToken],+ team_table: LiteLLM_TeamTableCachedObj,+ data: Union[GenerateKeyRequest, UpdateKeyRequest],+) -> None:+ """+ Check if the team key is allocating model specific limits. If so, raise an error if we're overallocating.+ """+ entity_model_rpm_limit_dict = {}+ entity_model_tpm_limit_dict = {}+ if team_table.metadata:+ entity_model_rpm_limit_dict = team_table.metadata.get("model_rpm_limit", {})+ entity_model_tpm_limit_dict = team_table.metadata.get("model_tpm_limit", {})++ _check_key_model_specific_limits(+ keys=keys,+ data=data,+ entity_rpm_limit=team_table.rpm_limit,+ entity_tpm_limit=team_table.tpm_limit,+ entity_model_rpm_limit_dict=entity_model_rpm_limit_dict,+ entity_model_tpm_limit_dict=entity_model_tpm_limit_dict,+ entity_type="team",+ )+++def check_team_key_rpm_tpm_limits(+ keys: List[LiteLLM_VerificationToken],+ team_table: LiteLLM_TeamTableCachedObj,+ data: Union[GenerateKeyRequest, UpdateKeyRequest],+) -> None:+ """+ Check if the team key is allocating rpm/tpm limits. If so, raise an error if we're overallocating.+ """+ _check_key_rpm_tpm_limits(+ keys=keys,+ data=data,+ entity_rpm_limit=team_table.rpm_limit,+ entity_tpm_limit=team_table.tpm_limit,+ entity_type="team",+ )++async def _check_team_key_limits(team_table: LiteLLM_TeamTableCachedObj,data: Union[GenerateKeyRequest, UpdateKeyRequest],@@ -787,6 +860,105 @@ async def _check_team_key_limits()+def check_org_key_model_specific_limits(+ keys: List[LiteLLM_VerificationToken],+ org_table: LiteLLM_OrganizationTable,+ data: Union[GenerateKeyRequest, UpdateKeyRequest],+) -> None:+ """+ Check if the organization key is allocating model specific limits. If so, raise an error if we're overallocating.+ """+ # Get org limits from budget table if available+ entity_rpm_limit = None+ entity_tpm_limit = None+ entity_model_rpm_limit_dict = {}+ entity_model_tpm_limit_dict = {}++ if org_table.litellm_budget_table is not None:+ entity_rpm_limit = org_table.litellm_budget_table.rpm_limit+ entity_tpm_limit = org_table.litellm_budget_table.tpm_limit++ if org_table.metadata:+ entity_model_rpm_limit_dict = org_table.metadata.get("model_rpm_limit", {})+ entity_model_tpm_limit_dict = org_table.metadata.get("model_tpm_limit", {})++ _check_key_model_specific_limits(+ keys=keys,+ data=data,+ entity_rpm_limit=entity_rpm_limit,+ entity_tpm_limit=entity_tpm_limit,+ entity_model_rpm_limit_dict=entity_model_rpm_limit_dict,+ entity_model_tpm_limit_dict=entity_model_tpm_limit_dict,+ entity_type="organization",+ )+++def check_org_key_rpm_tpm_limits(+ keys: List[LiteLLM_VerificationToken],+ org_table: LiteLLM_OrganizationTable,+ data: Union[GenerateKeyRequest, UpdateKeyRequest],+) -> None:+ """+ Check if the organization key is allocating rpm/tpm limits. If so, raise an error if we're overallocating.+ """+ # Get org limits from budget table if available+ entity_rpm_limit = None+ entity_tpm_limit = None++ if org_table.litellm_budget_table is not None:+ entity_rpm_limit = org_table.litellm_budget_table.rpm_limit+ entity_tpm_limit = org_table.litellm_budget_table.tpm_limit++ _check_key_rpm_tpm_limits(+ keys=keys,+ data=data,+ entity_rpm_limit=entity_rpm_limit,+ entity_tpm_limit=entity_tpm_limit,+ entity_type="organization",+ )+++async def _check_org_key_limits(+ org_table: LiteLLM_OrganizationTable,+ data: Union[GenerateKeyRequest, UpdateKeyRequest],+ prisma_client: PrismaClient,+) -> None:+ """+ Check if the organization key is allocating guaranteed throughput limits. If so, raise an error if we're overallocating.++ Only runs check if tpm_limit_type or rpm_limit_type is "guaranteed_throughput"+ """++ rpm_limit_type = getattr(data, "rpm_limit_type", None) or (+ data.metadata.get("rpm_limit_type", None) if data.metadata else None+ )+ tpm_limit_type = getattr(data, "tpm_limit_type", None) or (+ data.metadata.get("tpm_limit_type", None) if data.metadata else None+ )++ if (+ tpm_limit_type != "guaranteed_throughput"+ and rpm_limit_type != "guaranteed_throughput"+ ):+ return+ # get all organization keys+ # calculate allocated tpm/rpm limit+ # check if specified tpm/rpm limit is greater than allocated tpm/rpm limit+ keys = await prisma_client.db.litellm_verificationtoken.find_many(+ where={"organization_id": org_table.organization_id},+ )+ check_org_key_model_specific_limits(+ keys=keys,+ org_table=org_table,+ data=data,+ )+ check_org_key_rpm_tpm_limits(+ keys=keys,+ org_table=org_table,+ data=data,+ )++@router.post("/key/generate",tags=["key management"],@@ -813,6 +985,7 @@ async def generate_key_fn(- key: Optional[str] - User defined key value. If not set, a 16-digit unique sk-key is created for you.- team_id: Optional[str] - The team id of the key- user_id: Optional[str] - The user id of the key+ - organization_id: Optional[str] - The organization id of the key. If not set, and team_id is set, the organization id will be the same as the team id. If conflict, an error will be raised.- budget_id: Optional[str] - The budget id associated with the key. Created by calling `/budget/new`.- models: Optional[list] - Model_name's a user is allowed to call. (if empty, key is allowed to call all models)- aliases: Optional[dict] - Any alias mappings, on top of anything in the config.yaml model list. - https://docs.litellm.ai/docs/proxy/virtual_keys#managing-auth---upgradedowngrade-models@@ -847,6 +1020,7 @@ async def generate_key_fn(- auto_rotate: Optional[bool] - Whether this key should be automatically rotated (regenerated)- rotation_interval: Optional[str] - How often to auto-rotate this key (e.g., '30s', '30m', '30h', '30d'). Required if auto_rotate=True.+Examples:1. Allow users to turn on/off pii masking@@ -1966,6 +2140,7 @@ async def generate_key_helper_fn( # noqa: PLR0915"allowed_cache_controls": allowed_cache_controls,"permissions": permissions_json,"model_max_budget": model_max_budget_json,+ "organization_id": organization_id,"budget_id": budget_id,"blocked": blocked,"created_by": created_by,@@ -2072,6 +2247,7 @@ async def generate_key_helper_fn( # noqa: PLR0915if request_type == "user":# if this is a /user/new request update the key_date with user_data fieldskey_data.update(user_data)+return key_datadiff --git a/litellm/proxy/management_endpoints/organization_endpoints.py b/litellm/proxy/management_endpoints/organization_endpoints.pyindex c477c57a1fc..b1c416562e3 100644--- a/litellm/proxy/management_endpoints/organization_endpoints.py+++ b/litellm/proxy/management_endpoints/organization_endpoints.py@@ -24,6 +24,7 @@ from litellm.proxy.management_endpoints.budget_management_endpoints import (new_budget,update_budget,)+from litellm.proxy.management_endpoints.common_utils import _set_object_metadata_fieldfrom litellm.proxy.management_helpers.object_permission_utils import (handle_update_object_permission_common,)@@ -32,29 +33,32 @@ from litellm.proxy.management_helpers.utils import (management_endpoint_wrapper,)from litellm.proxy.utils import PrismaClient+from litellm.utils import _update_dictionaryrouter = APIRouter()-def handle_nested_budget_structure_in_organization_update_request(raw_data: dict) -> dict:+def handle_nested_budget_structure_in_organization_update_request(+ raw_data: dict,+) -> dict:"""Transform organization update request to handle UI payload format.-+The UI sends nested budget data in 'litellm_budget_table', but ourmodel expects flat budget fields at the top level."""transformed_data = raw_data.copy()-+# Handle nested budget structure from UI- if 'litellm_budget_table' in transformed_data:- budget_data = transformed_data.pop('litellm_budget_table', {})+ if "litellm_budget_table" in transformed_data:+ budget_data = transformed_data.pop("litellm_budget_table", {})if budget_data:# Extract valid budget fields and merge into top levelbudget_fields = LiteLLM_BudgetTable.model_fields.keys()for key, value in budget_data.items():if key in budget_fields and value is not None:transformed_data[key] = value-+return transformed_data@@ -224,6 +228,15 @@ async def new_organization(created_by=user_api_key_dict.user_id or litellm_proxy_admin_name,updated_by=user_api_key_dict.user_id or litellm_proxy_admin_name,)++ for field in LiteLLM_ManagementEndpoint_MetadataFields:+ if getattr(data, field, None) is not None:+ _set_object_metadata_field(+ object_data=organization_row,+ field_name=field,+ value=getattr(data, field),+ )+new_organization_row = prisma_client.jsonify_object(organization_row.json(exclude_none=True))@@ -233,7 +246,8 @@ async def new_organization(response = await prisma_client.db.litellm_organizationtable.create(data={**new_organization_row, # type: ignore- }+ },+ include={"litellm_budget_table": True},)return response@@ -294,17 +308,16 @@ async def update_organization(# Transform UI payload to expected formatraw_data = await request.json()- raw_data_with_flat_budget_fields = handle_nested_budget_structure_in_organization_update_request(raw_data)-+ raw_data_with_flat_budget_fields = (+ handle_nested_budget_structure_in_organization_update_request(raw_data)+ )+# Create validated data modeldata = LiteLLM_OrganizationTableUpdate(**raw_data_with_flat_budget_fields)-+if data.updated_by is None:data.updated_by = user_api_key_dict.user_id- updated_organization_row = prisma_client.jsonify_object(- data.model_dump(exclude_none=True)- )existing_organization_row = (await prisma_client.db.litellm_organizationtable.find_unique(where={"organization_id": data.organization_id},@@ -316,6 +329,19 @@ async def update_organization(f"Organization not found for organization_id={data.organization_id}")+ updated_organization_row_json = data.model_dump(exclude_none=True)+ # Merge metadata from existing organization with updated metadata+ if updated_organization_row_json.get("metadata") is not None:+ existing_metadata = existing_organization_row.metadata or {}+ updated_metadata = updated_organization_row_json.get("metadata", {})+ merged_metadata = _update_dictionary(+ existing_dict=existing_metadata.copy(), new_dict=updated_metadata+ )+ updated_organization_row_json["metadata"] = merged_metadata++ updated_organization_row = prisma_client.jsonify_object(+ updated_organization_row_json+ )if data.object_permission is not None:updated_organization_row = await handle_update_object_permission(data_json=updated_organization_row,@@ -323,18 +349,20 @@ async def update_organization()# Handle budget updates if budget fields are provided- budget_fields = {k: v for k, v in data.model_dump().items()- if k in LiteLLM_BudgetTable.model_fields.keys() and v is not None}-+ budget_fields = {+ k: v+ for k, v in data.model_dump().items()+ if k in LiteLLM_BudgetTable.model_fields.keys() and v is not None+ }+if budget_fields and existing_organization_row.budget_id:await update_budget(budget_obj=BudgetNewRequest(- budget_id=existing_organization_row.budget_id,- **budget_fields+ budget_id=existing_organization_row.budget_id, **budget_fields),user_api_key_dict=user_api_key_dict,)-+# Remove budget fields from organization update datafor field in LiteLLM_BudgetTable.model_fields.keys():updated_organization_row.pop(field, None)@@ -502,16 +530,16 @@ async def info_organization(organization_id: str):if prisma_client is None:raise HTTPException(status_code=500, detail={"error": "No db connected"})- response: Optional[- LiteLLM_OrganizationTableWithMembers- ] = await prisma_client.db.litellm_organizationtable.find_unique(- where={"organization_id": organization_id},- include={- "litellm_budget_table": True,- "members": True,- "teams": True,- "object_permission": True,- },+ response: Optional[LiteLLM_OrganizationTableWithMembers] = (+ await prisma_client.db.litellm_organizationtable.find_unique(+ where={"organization_id": organization_id},+ include={+ "litellm_budget_table": True,+ "members": True,+ "teams": True,+ "object_permission": True,+ },+ ))if response is None:@@ -807,16 +835,16 @@ async def organization_member_update(},data={"budget_id": budget_id},)- final_organization_membership: Optional[- BaseModel- ] = await prisma_client.db.litellm_organizationmembership.find_unique(- where={- "user_id_organization_id": {- "user_id": data.user_id,- "organization_id": data.organization_id,- }- },- include={"litellm_budget_table": True},+ final_organization_membership: Optional[BaseModel] = (+ await prisma_client.db.litellm_organizationmembership.find_unique(+ where={+ "user_id_organization_id": {+ "user_id": data.user_id,+ "organization_id": data.organization_id,+ }+ },+ include={"litellm_budget_table": True},+ ))if final_organization_membership is None:@@ -967,4 +995,4 @@ async def add_member_to_organization(except Exception as e:raise ValueError(f"Error adding member={member} to organization={organization_id}: {e}"- )\ No newline at end of file+ )diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex 5be3c667bcd..c9e3cd67154 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -60,6 +60,7 @@ from litellm.proxy._types import (from litellm.proxy.auth.auth_checks import (allowed_route_check_inside_route,can_org_access_model,+ get_org_object,get_team_object,get_user_object,)@@ -67,6 +68,7 @@ from litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.management_endpoints.common_utils import (_is_user_team_admin,_set_object_metadata_field,+ _update_metadata_field,_upsert_budget_and_membership,_user_has_admin_view,)@@ -84,11 +86,7 @@ from litellm.proxy.management_helpers.utils import (add_new_member,management_endpoint_wrapper,)-from litellm.proxy.utils import (- PrismaClient,- _premium_user_check,- handle_exception_on_proxy,-)+from litellm.proxy.utils import PrismaClient, handle_exception_on_proxyfrom litellm.router import Routerfrom litellm.types.proxy.management_endpoints.common_daily_activity import (SpendAnalyticsPaginatedResponse,@@ -271,6 +269,240 @@ async def get_all_team_memberships(return returned_tm+def _check_team_model_specific_limits(+ teams: List[LiteLLM_TeamTable],+ data: Union[NewTeamRequest, UpdateTeamRequest],+ entity_rpm_limit: Optional[int],+ entity_tpm_limit: Optional[int],+ entity_model_rpm_limit_dict: Dict[str, int],+ entity_model_tpm_limit_dict: Dict[str, int],+ entity_type: str, # "organization"+) -> None:+ """+ Generic function to check if a team is allocating model specific limits.+ Raises an error if we're overallocating.+ """+ model_rpm_limit = getattr(data, "model_rpm_limit", None) or (+ data.metadata.get("model_rpm_limit", None) if data.metadata else None+ )+ model_tpm_limit = getattr(data, "model_tpm_limit", None) or (+ data.metadata.get("model_tpm_limit", None) if data.metadata else None+ )+ if model_rpm_limit is None and model_tpm_limit is None:+ return++ # get total model specific tpm/rpm limit+ model_specific_rpm_limit: Dict[str, int] = {}+ model_specific_tpm_limit: Dict[str, int] = {}++ for team in teams:+ if team.metadata and team.metadata.get("model_rpm_limit", None) is not None:+ for model, rpm_limit in team.metadata.get("model_rpm_limit", {}).items():+ model_specific_rpm_limit[model] = (+ model_specific_rpm_limit.get(model, 0) + rpm_limit+ )+ if team.metadata and team.metadata.get("model_tpm_limit", None) is not None:+ for model, tpm_limit in team.metadata.get("model_tpm_limit", {}).items():+ model_specific_tpm_limit[model] = (+ model_specific_tpm_limit.get(model, 0) + tpm_limit+ )++ if model_rpm_limit is not None:+ for model, rpm_limit in model_rpm_limit.items():+ if (+ entity_rpm_limit is not None+ and model_specific_rpm_limit.get(model, 0) + rpm_limit+ > entity_rpm_limit+ ):+ raise HTTPException(+ status_code=400,+ detail=f"Allocated RPM limit={model_specific_rpm_limit.get(model, 0)} + Team RPM limit={rpm_limit} is greater than {entity_type} RPM limit={entity_rpm_limit}",+ )+ elif entity_model_rpm_limit_dict:+ entity_model_specific_rpm_limit = entity_model_rpm_limit_dict.get(model)+ if (+ entity_model_specific_rpm_limit+ and model_specific_rpm_limit.get(model, 0) + rpm_limit+ > entity_model_specific_rpm_limit+ ):+ raise HTTPException(+ status_code=400,+ detail=f"Allocated RPM limit={model_specific_rpm_limit.get(model, 0)} + Team RPM limit={rpm_limit} is greater than {entity_type} RPM limit={entity_model_specific_rpm_limit}",+ )++ if model_tpm_limit is not None:+ for model, tpm_limit in model_tpm_limit.items():+ if (+ entity_tpm_limit is not None+ and model_specific_tpm_limit.get(model, 0) + tpm_limit+ > entity_tpm_limit+ ):+ raise HTTPException(+ status_code=400,+ detail=f"Allocated TPM limit={model_specific_tpm_limit.get(model, 0)} + Team TPM limit={tpm_limit} is greater than {entity_type} TPM limit={entity_tpm_limit}",+ )+ elif entity_model_tpm_limit_dict:+ entity_model_specific_tpm_limit = entity_model_tpm_limit_dict.get(model)+ if (+ entity_model_specific_tpm_limit+ and model_specific_tpm_limit.get(model, 0) + tpm_limit+ > entity_model_specific_tpm_limit+ ):+ raise HTTPException(+ status_code=400,+ detail=f"Allocated TPM limit={model_specific_tpm_limit.get(model, 0)} + Team TPM limit={tpm_limit} is greater than {entity_type} TPM limit={entity_model_specific_tpm_limit}",+ )+++def _check_team_rpm_tpm_limits(+ teams: List[LiteLLM_TeamTable],+ data: Union[NewTeamRequest, UpdateTeamRequest],+ entity_rpm_limit: Optional[int],+ entity_tpm_limit: Optional[int],+ entity_type: str, # "organization"+) -> None:+ """+ Generic function to check if a team is allocating rpm/tpm limits.+ Raises an error if we're overallocating.+ """+ if teams is not None and len(teams) > 0:+ allocated_tpm = sum(+ team.tpm_limit for team in teams if team.tpm_limit is not None+ )+ allocated_rpm = sum(+ team.rpm_limit for team in teams if team.rpm_limit is not None+ )+ else:+ allocated_tpm = 0+ allocated_rpm = 0++ if (+ data.tpm_limit is not None+ and entity_tpm_limit is not None+ and data.tpm_limit + allocated_tpm > entity_tpm_limit+ ):+ raise HTTPException(+ status_code=400,+ detail=f"Allocated TPM limit={allocated_tpm} + Team TPM limit={data.tpm_limit} is greater than {entity_type} TPM limit={entity_tpm_limit}",+ )+ if (+ data.rpm_limit is not None+ and entity_rpm_limit is not None+ and data.rpm_limit + allocated_rpm > entity_rpm_limit+ ):+ raise HTTPException(+ status_code=400,+ detail=f"Allocated RPM limit={allocated_rpm} + Team RPM limit={data.rpm_limit} is greater than {entity_type} RPM limit={entity_rpm_limit}",+ )+++def check_org_team_model_specific_limits(+ teams: List[LiteLLM_TeamTable],+ org_table: LiteLLM_OrganizationTable,+ data: Union[NewTeamRequest, UpdateTeamRequest],+) -> None:+ """+ Check if the organization team is allocating model specific limits. If so, raise an error if we're overallocating.+ """++ # Get org limits from budget table if available+ entity_rpm_limit = None+ entity_tpm_limit = None+ entity_model_rpm_limit_dict = {}+ entity_model_tpm_limit_dict = {}++ if org_table.litellm_budget_table is not None:+ entity_rpm_limit = org_table.litellm_budget_table.rpm_limit+ entity_tpm_limit = org_table.litellm_budget_table.tpm_limit++ if org_table.metadata:+ entity_model_rpm_limit_dict = org_table.metadata.get("model_rpm_limit", {})+ entity_model_tpm_limit_dict = org_table.metadata.get("model_tpm_limit", {})++ _check_team_model_specific_limits(+ teams=teams,+ data=data,+ entity_rpm_limit=entity_rpm_limit,+ entity_tpm_limit=entity_tpm_limit,+ entity_model_rpm_limit_dict=entity_model_rpm_limit_dict,+ entity_model_tpm_limit_dict=entity_model_tpm_limit_dict,+ entity_type="organization",+ )+++def check_org_team_rpm_tpm_limits(+ teams: List[LiteLLM_TeamTable],+ org_table: LiteLLM_OrganizationTable,+ data: Union[NewTeamRequest, UpdateTeamRequest],+) -> None:+ """+ Check if the organization team is allocating rpm/tpm limits. If so, raise an error if we're overallocating.+ """+ # Get org limits from budget table if available+ entity_rpm_limit = None+ entity_tpm_limit = None++ if org_table.litellm_budget_table is not None:+ entity_rpm_limit = org_table.litellm_budget_table.rpm_limit+ entity_tpm_limit = org_table.litellm_budget_table.tpm_limit++ _check_team_rpm_tpm_limits(+ teams=teams,+ data=data,+ entity_rpm_limit=entity_rpm_limit,+ entity_tpm_limit=entity_tpm_limit,+ entity_type="organization",+ )+++async def _check_org_team_limits(+ org_table: LiteLLM_OrganizationTable,+ data: Union[NewTeamRequest, UpdateTeamRequest],+ prisma_client: PrismaClient,+) -> None:+ """+ Check if the organization team is allocating guaranteed throughput limits. If so, raise an error if we're overallocating.++ Only runs check if tpm_limit_type or rpm_limit_type is "guaranteed_throughput"+ """++ rpm_limit_type = getattr(data, "rpm_limit_type", None) or (+ data.metadata.get("rpm_limit_type", None) if data.metadata else None+ )+ tpm_limit_type = getattr(data, "tpm_limit_type", None) or (+ data.metadata.get("tpm_limit_type", None) if data.metadata else None+ )++ if (+ tpm_limit_type != "guaranteed_throughput"+ and rpm_limit_type != "guaranteed_throughput"+ ):+ return+ # get all organization teams+ # calculate allocated tpm/rpm limit+ # check if specified tpm/rpm limit is greater than allocated tpm/rpm limit++ teams = await prisma_client.db.litellm_teamtable.find_many(+ where={"organization_id": org_table.organization_id},+ )++ # Convert teams to LiteLLM_TeamTable objects+ team_objs: List[LiteLLM_TeamTable] = []+ for team in teams:+ team_objs.append(LiteLLM_TeamTable(**team.model_dump()))++ check_org_team_model_specific_limits(+ teams=team_objs,+ org_table=org_table,+ data=data,+ )+ check_org_team_rpm_tpm_limits(+ teams=team_objs,+ org_table=org_table,+ data=data,+ )++#### TEAM MANAGEMENT ####@router.post("/team/new",@@ -361,6 +593,7 @@ async def new_team( # noqa: PLR0915create_audit_log_for_update,litellm_proxy_admin_name,prisma_client,+ user_api_key_cache,)if prisma_client is None:@@ -391,6 +624,25 @@ async def new_team( # noqa: PLR0915},)+ # check org key limits - done here to handle inheriting org id from team+ if data.organization_id is not None and prisma_client is not None:+ org_table = await get_org_object(+ org_id=data.organization_id,+ user_api_key_cache=user_api_key_cache,+ prisma_client=prisma_client,+ )+ if org_table is None:+ raise HTTPException(+ status_code=400,+ detail=f"Organization not found for organization_id={data.organization_id}",+ )++ await _check_org_team_limits(+ org_table=org_table,+ data=data,+ prisma_client=prisma_client,+ )+# If max_budget is not explicitly provided in the request,# check for a default value in the proxy configuration.if data.max_budget is None:@@ -594,6 +846,50 @@ async def new_team( # noqa: PLR0915raise handle_exception_on_proxy(e)+async def _create_team_update_audit_log(+ existing_team_row: LiteLLM_TeamTable,+ updated_kv: dict,+ team_id: str,+ litellm_changed_by: Optional[str],+ user_api_key_dict: UserAPIKeyAuth,+ litellm_proxy_admin_name: str,+) -> None:+ """+ Create an audit log entry for team update operations.++ Args:+ existing_team_row: The team row before the update+ updated_kv: Dictionary of updated key-value pairs+ team_id: The ID of the team being updated+ litellm_changed_by: Optional header indicating who made the change+ user_api_key_dict: User API key authentication details+ litellm_proxy_admin_name: Name of the proxy admin+ """+ from litellm.proxy.management_helpers.audit_logs import create_audit_log_for_update++ _before_value = existing_team_row.json(exclude_none=True)+ _before_value = json.dumps(_before_value, default=str)+ _after_value: str = json.dumps(updated_kv, default=str)++ asyncio.create_task(+ create_audit_log_for_update(+ request_data=LiteLLM_AuditLogs(+ id=str(uuid.uuid4()),+ updated_at=datetime.now(timezone.utc),+ changed_by=litellm_changed_by+ or user_api_key_dict.user_id+ or litellm_proxy_admin_name,+ changed_by_api_key=user_api_key_dict.api_key,+ table_name=LitellmTableNames.TEAM_TABLE_NAME,+ object_id=team_id,+ action="updated",+ updated_values=_after_value,+ before_value=_before_value,+ )+ )+ )++async def _update_model_table(data: UpdateTeamRequest,model_id: Optional[str],@@ -840,7 +1136,6 @@ async def update_team("""from litellm.proxy.auth.auth_checks import _cache_team_objectfrom litellm.proxy.proxy_server import (- create_audit_log_for_update,litellm_proxy_admin_name,llm_router,prisma_client,@@ -881,6 +1176,29 @@ async def update_team(# unsetting the organization_iddata.organization_id = None+ # check org team limits - if updating team that belongs to an org+ org_id_to_check = (+ data.organization_id+ if data.organization_id is not None+ else existing_team_row.organization_id+ )+ if (+ org_id_to_check is not None+ and isinstance(org_id_to_check, str)+ and prisma_client is not None+ ):+ org_table = await get_org_object(+ org_id=org_id_to_check,+ user_api_key_cache=user_api_key_cache,+ prisma_client=prisma_client,+ )+ if org_table is not None:+ await _check_org_team_limits(+ org_table=org_table,+ data=data,+ prisma_client=prisma_client,+ )+updated_kv = data.json(exclude_unset=True)# Check budget_duration and budget_reset_at@@ -919,14 +1237,14 @@ async def update_team(_team_metadata_fields = LiteLLM_ManagementEndpoint_MetadataFields_Premiumfor field in _team_metadata_fields:if field in updated_kv and updated_kv[field] is not None:- _update_team_metadata_field(+ _update_metadata_field(updated_kv=updated_kv,field_name=field,)for field in LiteLLM_ManagementEndpoint_MetadataFields:if field in updated_kv and updated_kv[field] is not None:- _update_team_metadata_field(+ _update_metadata_field(updated_kv=updated_kv,field_name=field,)@@ -968,26 +1286,13 @@ async def update_team(# Enterprise Feature - Audit Logging. Enable with litellm.store_audit_logs = Trueif litellm.store_audit_logs is True:- _before_value = existing_team_row.json(exclude_none=True)- _before_value = json.dumps(_before_value, default=str)- _after_value: str = json.dumps(updated_kv, default=str)-- asyncio.create_task(- create_audit_log_for_update(- request_data=LiteLLM_AuditLogs(- id=str(uuid.uuid4()),- updated_at=datetime.now(timezone.utc),- changed_by=litellm_changed_by- or user_api_key_dict.user_id- or litellm_proxy_admin_name,- changed_by_api_key=user_api_key_dict.api_key,- table_name=LitellmTableNames.TEAM_TABLE_NAME,- object_id=data.team_id,- action="updated",- updated_values=_after_value,- before_value=_before_value,- )- )+ await _create_team_update_audit_log(+ existing_team_row=existing_team_row,+ updated_kv=updated_kv,+ team_id=data.team_id,+ litellm_changed_by=litellm_changed_by,+ user_api_key_dict=user_api_key_dict,+ litellm_proxy_admin_name=litellm_proxy_admin_name,)return {"team_id": team_row.team_id, "data": team_row}@@ -2656,26 +2961,6 @@ async def get_paginated_teams(return [], 0-def _update_team_metadata_field(updated_kv: dict, field_name: str) -> None:- """- Helper function to update metadata fields that require premium user checks in the update endpoint-- Args:- updated_kv: The key-value dict being used for the update- field_name: Name of the metadata field being updated- """- if field_name in LiteLLM_ManagementEndpoint_MetadataFields_Premium:- _premium_user_check()-- if field_name in updated_kv and updated_kv[field_name] is not None:- # remove field from updated_kv- _value = updated_kv.pop(field_name)- if "metadata" in updated_kv and updated_kv["metadata"] is not None:- updated_kv["metadata"][field_name] = _value- else:- updated_kv["metadata"] = {field_name: _value}--@router.get("/team/filter/ui",tags=["team management"],diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 168bc45c0c7..eaf2c6c4ffe 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -2228,12 +2228,18 @@ class PrismaClient:b.tpm_limit AS litellm_budget_table_tpm_limit,b.rpm_limit AS litellm_budget_table_rpm_limit,b.model_max_budget as litellm_budget_table_model_max_budget,- b.soft_budget as litellm_budget_table_soft_budget+ b.soft_budget as litellm_budget_table_soft_budget,+ o.metadata as organization_metadata,+ b2.max_budget as organization_max_budget,+ b2.tpm_limit as organization_tpm_limit,+ b2.rpm_limit as organization_rpm_limitFROM "LiteLLM_VerificationToken" AS vLEFT JOIN "LiteLLM_TeamTable" AS t ON v.team_id = t.team_idLEFT JOIN "LiteLLM_TeamMembership" AS tm ON v.team_id = tm.team_id AND tm.user_id = v.user_idLEFT JOIN "LiteLLM_ModelTable" m ON t.model_id = m.idLEFT JOIN "LiteLLM_BudgetTable" AS b ON v.budget_id = b.budget_id+ LEFT JOIN "LiteLLM_OrganizationTable" AS o ON v.organization_id = o.organization_id+ LEFT JOIN "LiteLLM_BudgetTable" AS b2 ON o.budget_id = b2.budget_idWHERE v.token = '{token}'"""diff --git a/test_pydantic_fields.py b/test_pydantic_fields.pynew file mode 100644index 00000000000..6df535cfb94--- /dev/null+++ b/test_pydantic_fields.py@@ -0,0 +1,42 @@+from litellm.proxy._types import GenerateKeyRequest++# Test 1: Check if fields exist in model+print("=== Test 1: Check model_fields ===")+print(+ f"rpm_limit_type in model_fields: {'rpm_limit_type' in GenerateKeyRequest.model_fields}"+)+print(+ f"tpm_limit_type in model_fields: {'tpm_limit_type' in GenerateKeyRequest.model_fields}"+)++# Test 2: Create instance with empty dict (simulating FastAPI parsing minimal request)+print("\n=== Test 2: Create instance with minimal data ===")+instance = GenerateKeyRequest()+print(f"Instance created: {instance}")+print(f"Instance dict: {instance.model_dump()}")++# Test 3: Try to access the fields+print("\n=== Test 3: Try direct attribute access ===")+try:+ print(f"instance.rpm_limit_type = {instance.rpm_limit_type}")+ print(f"instance.tpm_limit_type = {instance.tpm_limit_type}")+except AttributeError as e:+ print(f"AttributeError: {e}")++# Test 4: Try getattr+print("\n=== Test 4: Try getattr ===")+print(+ f"getattr(instance, 'rpm_limit_type', None) = {getattr(instance, 'rpm_limit_type', None)}"+)+print(+ f"getattr(instance, 'tpm_limit_type', None) = {getattr(instance, 'tpm_limit_type', None)}"+)++# Test 5: Check what fields are actually set+print("\n=== Test 5: Check model_fields_set ===")+print(f"model_fields_set: {instance.model_fields_set}")++# Test 6: Check instance __dict__+print("\n=== Test 6: Check instance __dict__ ===")+print(f"'rpm_limit_type' in __dict__: {'rpm_limit_type' in instance.__dict__}")+print(f"'tpm_limit_type' in __dict__: {'tpm_limit_type' in instance.__dict__}")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.pyindex 5acc530517d..a8184a34d45 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@@ -15,6 +15,8 @@ from fastapi import HTTPExceptionfrom litellm.proxy._types import (GenerateKeyRequest,+ LiteLLM_BudgetTable,+ LiteLLM_OrganizationTable,LiteLLM_TeamTableCachedObj,LiteLLM_VerificationToken,LitellmUserRoles,@@ -23,9 +25,11 @@ from litellm.proxy._types import ()from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuthfrom litellm.proxy.management_endpoints.key_management_endpoints import (+ _check_org_key_limits,_check_team_key_limits,_common_key_generation_helper,_list_key_helper,+ check_org_key_model_specific_limits,check_team_key_model_specific_limits,generate_key_helper_fn,prepare_key_update_data,@@ -2059,3 +2063,553 @@ async def test_generate_key_with_object_permission():# Verify object_permission dict is NOT in the key dataassert "object_permission" not in key_data+++# ============================================+# Organization Key Limit Tests+# ============================================+++async def test_check_org_key_limits_no_existing_keys():+ """+ Test _check_org_key_limits when organization has no existing keys.+ Should allow any TPM/RPM limits within organization bounds.+ """+ # Mock prisma client+ mock_prisma_client = AsyncMock()+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[]+ )++ # Create organization table with limits in budget table+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-123",+ organization_alias="test-org",+ budget_id="budget-123",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-123",+ tpm_limit=20000,+ rpm_limit=2000,+ ),+ )++ # Create request with limits within organization bounds+ data = GenerateKeyRequest(+ tpm_limit=10000,+ rpm_limit=1000,+ tpm_limit_type="guaranteed_throughput",+ rpm_limit_type="guaranteed_throughput",+ )++ # Should not raise any exception+ await _check_org_key_limits(+ org_table=org_table,+ data=data,+ prisma_client=mock_prisma_client,+ )++ # Verify database was queried+ mock_prisma_client.db.litellm_verificationtoken.find_many.assert_called_once_with(+ where={"organization_id": "test-org-123"}+ )+++async def test_check_org_key_limits_with_existing_keys_within_bounds():+ """+ Test _check_org_key_limits when organization has existing keys but total allocation+ is still within organization limits.+ """+ # Create mock existing keys+ existing_key1 = MagicMock()+ existing_key1.tpm_limit = 5000+ existing_key1.rpm_limit = 400+ existing_key1.metadata = {}++ existing_key2 = MagicMock()+ existing_key2.tpm_limit = 3000+ existing_key2.rpm_limit = 500+ existing_key2.metadata = {}++ existing_key3 = MagicMock()+ existing_key3.tpm_limit = None # Should be ignored in calculation+ existing_key3.rpm_limit = None # Should be ignored in calculation+ existing_key3.metadata = {}++ mock_prisma_client = AsyncMock()+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[existing_key1, existing_key2, existing_key3]+ )++ # Create organization table with limits+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-456",+ organization_alias="test-org",+ budget_id="budget-456",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-456",+ tpm_limit=20000, # Total: 5000 + 3000 + 8000 (new) = 16000 < 20000 ✓+ rpm_limit=2000, # Total: 400 + 500 + 800 (new) = 1700 < 2000 ✓+ ),+ )++ # Create request that would still be within bounds+ data = GenerateKeyRequest(+ tpm_limit=8000,+ rpm_limit=800,+ tpm_limit_type="guaranteed_throughput",+ rpm_limit_type="guaranteed_throughput",+ )++ # Should not raise any exception+ await _check_org_key_limits(+ org_table=org_table,+ data=data,+ prisma_client=mock_prisma_client,+ )+++async def test_check_org_key_limits_tpm_overallocation():+ """+ Test _check_org_key_limits when new key would cause TPM overallocation.+ Should raise HTTPException with appropriate error message.+ """+ # Create mock existing keys with high TPM usage+ existing_key1 = MagicMock()+ existing_key1.tpm_limit = 12000+ existing_key1.rpm_limit = 500+ existing_key1.metadata = {}++ existing_key2 = MagicMock()+ existing_key2.tpm_limit = 6000+ existing_key2.rpm_limit = 400+ existing_key2.metadata = {}++ mock_prisma_client = AsyncMock()+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[existing_key1, existing_key2]+ )++ # Create organization table with limits+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-789",+ organization_alias="test-org",+ budget_id="budget-789",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-789",+ tpm_limit=20000, # Allocated: 12000 + 6000 = 18000, New: 3000, Total: 21000 > 20000 ✗+ rpm_limit=2000,+ ),+ )++ # Create request that would exceed TPM limits+ data = GenerateKeyRequest(+ tpm_limit=3000,+ rpm_limit=500,+ tpm_limit_type="guaranteed_throughput",+ )++ # Should raise HTTPException for TPM overallocation+ with pytest.raises(HTTPException) as exc_info:+ await _check_org_key_limits(+ org_table=org_table,+ data=data,+ prisma_client=mock_prisma_client,+ )++ assert exc_info.value.status_code == 400+ assert (+ "Allocated TPM limit=18000 + Key TPM limit=3000 is greater than organization TPM limit=20000"+ in str(exc_info.value.detail)+ )+++async def test_check_org_key_limits_rpm_overallocation():+ """+ Test _check_org_key_limits when new key would cause RPM overallocation.+ Should raise HTTPException with appropriate error message.+ """+ # Create mock existing keys with high RPM usage+ existing_key1 = MagicMock()+ existing_key1.tpm_limit = 5000+ existing_key1.rpm_limit = 1200+ existing_key1.metadata = {}++ existing_key2 = MagicMock()+ existing_key2.tpm_limit = 3000+ existing_key2.rpm_limit = 600+ existing_key2.metadata = {}++ mock_prisma_client = AsyncMock()+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[existing_key1, existing_key2]+ )++ # Create organization table with limits+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-101",+ organization_alias="test-org",+ budget_id="budget-101",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-101",+ tpm_limit=20000,+ rpm_limit=2000, # Allocated: 1200 + 600 = 1800, New: 300, Total: 2100 > 2000 ✗+ ),+ )++ # Create request that would exceed RPM limits+ data = GenerateKeyRequest(+ tpm_limit=5000,+ rpm_limit=300,+ rpm_limit_type="guaranteed_throughput",+ )++ # Should raise HTTPException for RPM overallocation+ with pytest.raises(HTTPException) as exc_info:+ await _check_org_key_limits(+ org_table=org_table,+ data=data,+ prisma_client=mock_prisma_client,+ )++ assert exc_info.value.status_code == 400+ assert (+ "Allocated RPM limit=1800 + Key RPM limit=300 is greater than organization RPM limit=2000"+ in str(exc_info.value.detail)+ )+++async def test_check_org_key_limits_no_org_limits():+ """+ Test _check_org_key_limits when organization has no TPM/RPM limits set.+ Should allow any key limits since there are no organization constraints.+ """+ # Create mock existing keys+ existing_key = MagicMock()+ existing_key.tpm_limit = 10000+ existing_key.rpm_limit = 1000+ existing_key.metadata = {}++ mock_prisma_client = AsyncMock()+ mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(+ return_value=[existing_key]+ )++ # Create organization table with no limits+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-202",+ organization_alias="test-org",+ budget_id="budget-202",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-202",+ tpm_limit=None, # No organization limit+ rpm_limit=None, # No organization limit+ ),+ )++ # Create request with any limits+ data = GenerateKeyRequest(+ tpm_limit=50000, # High limit should be allowed+ rpm_limit=5000, # High limit should be allowed+ tpm_limit_type="guaranteed_throughput",+ )++ # Should not raise any exception+ await _check_org_key_limits(+ org_table=org_table,+ data=data,+ prisma_client=mock_prisma_client,+ )+++def test_check_org_key_model_specific_limits_no_limits():+ """+ Test check_org_key_model_specific_limits when no model-specific limits are set.+ Should return without raising any exceptions.+ """+ # Create existing key with no model-specific limits+ existing_key = LiteLLM_VerificationToken(+ token="test-token-1",+ user_id="test-user",+ organization_id="test-org-123",+ metadata={},+ )++ keys = [existing_key]++ # Create organization table+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-123",+ organization_alias="test-org",+ budget_id="budget-123",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ metadata={},+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-123",+ tpm_limit=20000,+ rpm_limit=2000,+ ),+ )++ # Create request with no model-specific limits+ data = GenerateKeyRequest(+ model_rpm_limit=None,+ model_tpm_limit=None,+ )++ # Should not raise any exception+ check_org_key_model_specific_limits(+ keys=keys,+ org_table=org_table,+ data=data,+ )+++def test_check_org_key_model_specific_limits_rpm_overallocation():+ """+ Test check_org_key_model_specific_limits when model-specific RPM would cause overallocation.+ Should raise HTTPException with appropriate error message.+ """+ # Create existing keys with model-specific RPM limits+ existing_key1 = LiteLLM_VerificationToken(+ token="test-token-1",+ user_id="test-user-1",+ organization_id="test-org-456",+ metadata={+ "model_rpm_limit": {+ "gpt-4": 800,+ "gpt-3.5-turbo": 500,+ }+ },+ )++ existing_key2 = LiteLLM_VerificationToken(+ token="test-token-2",+ user_id="test-user-2",+ organization_id="test-org-456",+ metadata={+ "model_rpm_limit": {+ "gpt-4": 600,+ }+ },+ )++ keys = [existing_key1, existing_key2]++ # Create organization table with RPM limit+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-456",+ organization_alias="test-org",+ budget_id="budget-456",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ metadata={},+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-456",+ tpm_limit=20000,+ rpm_limit=2000, # Total organization RPM limit+ ),+ )++ # Create request that would exceed model-specific RPM limits+ # Existing gpt-4: 800 + 600 = 1400, New: 700, Total: 2100 > 2000 (org limit)+ data = GenerateKeyRequest(+ model_rpm_limit={+ "gpt-4": 700, # This would cause overallocation+ },+ model_tpm_limit=None,+ )++ # Should raise HTTPException for model-specific RPM overallocation+ with pytest.raises(HTTPException) as exc_info:+ check_org_key_model_specific_limits(+ keys=keys,+ org_table=org_table,+ data=data,+ )++ assert exc_info.value.status_code == 400+ assert (+ "Allocated RPM limit=1400 + Key RPM limit=700 is greater than organization RPM limit=2000"+ in str(exc_info.value.detail)+ )+++def test_check_org_key_model_specific_limits_org_model_rpm_overallocation():+ """+ Test check_org_key_model_specific_limits when organization has model-specific RPM limits+ in metadata and key allocation would exceed those limits.++ This tests the scenario where org_table.metadata["model_rpm_limit"] is set+ with per-model limits, not just a global organization RPM limit.+ """+ # Create existing keys with model-specific RPM limits+ existing_key1 = LiteLLM_VerificationToken(+ token="test-token-1",+ user_id="test-user-1",+ organization_id="test-org-789",+ metadata={+ "model_rpm_limit": {+ "gpt-4": 600,+ "gpt-3.5-turbo": 400,+ }+ },+ )++ existing_key2 = LiteLLM_VerificationToken(+ token="test-token-2",+ user_id="test-user-2",+ organization_id="test-org-789",+ metadata={+ "model_rpm_limit": {+ "gpt-4": 500,+ }+ },+ )++ keys = [existing_key1, existing_key2]++ # Create organization table with model-specific RPM limits in metadata+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-789",+ organization_alias="test-org",+ budget_id="budget-789",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ metadata={+ "model_rpm_limit": {+ "gpt-4": 1400, # Organization-level model-specific limit for gpt-4+ "gpt-3.5-turbo": 1000,+ }+ },+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-789",+ tpm_limit=None,+ rpm_limit=None,+ ),+ )++ # Create request that would exceed organization's model-specific RPM limits+ # Existing gpt-4: 600 + 500 = 1100, New: 400, Total: 1500 > 1400 (org model-specific limit)+ data = GenerateKeyRequest(+ model_rpm_limit={+ "gpt-4": 400, # This would cause overallocation against org model-specific limit+ },+ model_tpm_limit=None,+ )++ # Should raise HTTPException for organization model-specific RPM overallocation+ with pytest.raises(HTTPException) as exc_info:+ check_org_key_model_specific_limits(+ keys=keys,+ org_table=org_table,+ data=data,+ )++ assert exc_info.value.status_code == 400+ assert (+ "Allocated RPM limit=1100 + Key RPM limit=400 is greater than organization RPM limit=1400"+ in str(exc_info.value.detail)+ )+++def test_check_org_key_model_specific_limits_org_model_tpm_overallocation():+ """+ Test check_org_key_model_specific_limits when organization has model-specific TPM limits+ in metadata and key allocation would exceed those limits.++ This tests the scenario where org_table.metadata["model_tpm_limit"] is set+ with per-model limits, not just a global organization TPM limit.+ """+ # Create existing keys with model-specific TPM limits+ existing_key1 = LiteLLM_VerificationToken(+ token="test-token-1",+ user_id="test-user-1",+ organization_id="test-org-101",+ metadata={+ "model_tpm_limit": {+ "gpt-4": 10000,+ "claude-3": 6000,+ }+ },+ )++ existing_key2 = LiteLLM_VerificationToken(+ token="test-token-2",+ user_id="test-user-2",+ organization_id="test-org-101",+ metadata={+ "model_tpm_limit": {+ "gpt-4": 7000,+ }+ },+ )++ keys = [existing_key1, existing_key2]++ # Create organization table with model-specific TPM limits in metadata+ org_table = LiteLLM_OrganizationTable(+ organization_id="test-org-101",+ organization_alias="test-org",+ budget_id="budget-101",+ models=["gpt-4"],+ created_by="admin",+ updated_by="admin",+ metadata={+ "model_tpm_limit": {+ "gpt-4": 20000, # Organization-level model-specific limit for gpt-4+ "claude-3": 15000,+ }+ },+ litellm_budget_table=LiteLLM_BudgetTable(+ budget_id="budget-101",+ tpm_limit=None,+ rpm_limit=None,+ ),+ )++ # Create request that would exceed organization's model-specific TPM limits+ # Existing gpt-4: 10000 + 7000 = 17000, New: 4000, Total: 21000 > 20000 (org model-specific limit)+ data = GenerateKeyRequest(+ model_rpm_limit=None,+ model_tpm_limit={+ "gpt-4": 4000, # This would cause overallocation against org model-specific limit+ },+ )++ # Should raise HTTPException for organization model-specific TPM overallocation+ with pytest.raises(HTTPException) as exc_info:+ check_org_key_model_specific_limits(+ keys=keys,+ org_table=org_table,+ data=data,+ )++ assert exc_info.value.status_code == 400+ assert (+ "Allocated TPM limit=17000 + Key TPM limit=4000 is greater than organization TPM limit=20000"+ in str(exc_info.value.detail)+ )