Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix: fixing descriptor/response size difference when indexing descriptor

Luiz Rennó Costaf8711200d08a
diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.py
index b73765781ec..b04d14bcc8b 100644
--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py
+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py
@@ -17,7 +17,7 @@ from typing import (
Union,
cast,
)
-
+from math import floor
from fastapi import HTTPException
from litellm import DualCache
@@ -525,12 +525,13 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):
# Find which descriptor hit the limit
for i, status in enumerate(response["statuses"]):
if status["code"] == "OVER_LIMIT":
- descriptor = descriptors[i]
+ descriptor = descriptors[floor(i/2)]
raise HTTPException(
status_code=429,
detail=f"Rate limit exceeded for {descriptor['key']}: {descriptor['value']}. Remaining: {status['limit_remaining']}",
headers={
- "retry-after": str(self.window_size)
+ "retry-after": str(self.window_size),
+ "rate_limit_type": str(status["rate_limit_type"])
}, # Retry after 1 minute
)
diff --git a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
index 3f7fdc55f36..694a49159c0 100644
--- a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
+++ b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
@@ -724,6 +724,156 @@ async def test_model_specific_rate_limits_only_called_when_configured_v3():
), "should_rate_limit should be called when model-specific limits match requested model"
+async def test_tpm_api_key_rate_limits_v3():
+
+ _api_key = "sk-12345"
+ _api_key_hash = hash_token(_api_key)
+ model = "gpt-3.5-turbo"
+ rpm_limit = 2
+ tpm_limit = 2
+
+ rpms = {model: rpm_limit}
+ tpms = {model: tpm_limit}
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=_api_key_hash,
+ key_alias=_api_key,
+ rpm_limit_per_model=rpms,
+ tpm_limit_per_model=tpms,
+ models=[],
+ )
+
+ user_api_key_dict.metadata["model_tpm_limit"] = tpms
+ user_api_key_dict.metadata["model_rpm_limit"] = rpms
+
+ local_cache = DualCache()
+ parallel_request_handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+
+ # Mock should_rate_limit to capture the descriptors
+ captured_descriptors = None
+ original_should_rate_limit = parallel_request_handler.should_rate_limit
+
+ async def mock_should_rate_limit(descriptors, **kwargs):
+ nonlocal captured_descriptors
+ captured_descriptors = descriptors
+ # Return Error response to ensure HTTPException
+ return {
+ "overall_code": "OVER_LIMIT",
+ "statuses": [{'code': 'OK', 'current_limit': 2, 'limit_remaining': 1, 'rate_limit_type': 'requests', 'descriptor_key': 'model_per_key'},
+ {'code': 'OVER_LIMIT', 'current_limit': 2, 'limit_remaining': -18, 'rate_limit_type': 'tokens', 'descriptor_key': 'model_per_key'}]
+ }
+
+ parallel_request_handler.should_rate_limit = mock_should_rate_limit
+
+ # Test the pre-call hook
+ error = None
+ try:
+ await parallel_request_handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=local_cache,
+ data={"model": model},
+ call_type="",
+ )
+ except HTTPException as e:
+ error=e
+ assert e.status_code == 429
+ assert "rate_limit_type" in e.headers
+ assert e.headers.get("rate_limit_type") == "tokens"
+ assert "retry-after" in e.headers
+
+
+ assert error is not None, "An Exception must be thrown"
+ assert captured_descriptors is not None, "Rate limit descriptors should be captured"
+
+ model_per_key_descriptor = None
+ for descriptor in captured_descriptors:
+ if descriptor["key"] == "model_per_key":
+ model_per_key_descriptor = descriptor
+ break
+
+ assert model_per_key_descriptor is not None, "Api-Key descriptor should be present"
+ assert model_per_key_descriptor["value"] == f"{_api_key_hash}:{model}", "Api-Key value should combine api_key and model"
+ assert model_per_key_descriptor["rate_limit"]["requests_per_unit"] == rpm_limit, "Api-Key RPM limit should be set"
+ assert model_per_key_descriptor["rate_limit"]["tokens_per_unit"] == tpm_limit, "Api-Key TPM limit should be set"
+
+
+async def test_rpm_api_key_rate_limits_v3():
+
+ _api_key = "sk-12345"
+ _api_key_hash = hash_token(_api_key)
+ model = "gpt-3.5-turbo"
+ rpm_limit = 2
+ tpm_limit = 2
+
+ rpms = {model: rpm_limit}
+ tpms = {model: tpm_limit}
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=_api_key_hash,
+ key_alias=_api_key,
+ rpm_limit_per_model=rpms,
+ tpm_limit_per_model=tpms,
+ models=[],
+ )
+
+ user_api_key_dict.metadata["model_tpm_limit"] = tpms
+ user_api_key_dict.metadata["model_rpm_limit"] = rpms
+
+ local_cache = DualCache()
+ parallel_request_handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+
+ # Mock should_rate_limit to capture the descriptors
+ captured_descriptors = None
+ original_should_rate_limit = parallel_request_handler.should_rate_limit
+
+ async def mock_should_rate_limit(descriptors, **kwargs):
+ nonlocal captured_descriptors
+ captured_descriptors = descriptors
+ # Return Error response to ensure HTTPException
+ return {
+ "overall_code": "OVER_LIMIT",
+ "statuses": [{'code': 'OVER_LIMIT', 'current_limit': 2, 'limit_remaining': -2, 'rate_limit_type': 'requests', 'descriptor_key': 'model_per_key'},
+ {'code': 'OK', 'current_limit': 2, 'limit_remaining': 2, 'rate_limit_type': 'tokens', 'descriptor_key': 'model_per_key'}]
+ }
+
+ parallel_request_handler.should_rate_limit = mock_should_rate_limit
+
+ # Test the pre-call hook
+ error = None
+ try:
+ await parallel_request_handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=local_cache,
+ data={"model": model},
+ call_type="",
+ )
+ except HTTPException as e:
+ error=e
+ assert e.status_code == 429
+ assert "rate_limit_type" in e.headers
+ assert e.headers.get("rate_limit_type") == "requests"
+ assert "retry-after" in e.headers
+
+ assert error is not None, "An Exception must be thrown"
+ assert captured_descriptors is not None, "Rate limit descriptors should be captured"
+
+ model_per_key_descriptor = None
+ for descriptor in captured_descriptors:
+ if descriptor["key"] == "model_per_key":
+ model_per_key_descriptor = descriptor
+ break
+
+ assert model_per_key_descriptor is not None, "Api-Key descriptor should be present"
+ assert model_per_key_descriptor["value"] == f"{_api_key_hash}:{model}", "Api-Key value should combine api_key and model"
+ assert model_per_key_descriptor["rate_limit"]["requests_per_unit"] == rpm_limit, "Api-Key RPM limit should be set"
+ assert model_per_key_descriptor["rate_limit"]["tokens_per_unit"] == tpm_limit, "Api-Key TPM limit should be set"
+
@pytest.mark.asyncio
async def test_team_member_rate_limits_v3():
"""
@@ -763,6 +913,7 @@ async def test_team_member_rate_limits_v3():
parallel_request_handler.should_rate_limit = mock_should_rate_limit
# Test the pre-call hook
+
await parallel_request_handler.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=local_cache,