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(proxy): reserve measured input tokens for multimodal project ITPM

mateo-berric1c23bf39ad8
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.json
index 5eb72a5c243..7ac52925459 100644
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@ -57,7 +57,7 @@
"limit": 5681
},
"reportMissingTypeArgument": {
- "limit": 15607
+ "limit": 15606
},
"reportMissingTypeStubs": {
"limit": 40
@@ -108,7 +108,7 @@
"limit": 39154
},
"reportUnknownParameterType": {
- "limit": 19946
+ "limit": 19945
},
"reportUnknownVariableType": {
"limit": 30772
@@ -132,7 +132,7 @@
"limit": 27
},
"reportUnusedClass": {
- "limit": 23
+ "limit": 22
},
"reportUnusedFunction": {
"limit": 139
diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.py
index 80d58abee7d..751b301a93d 100644
--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py
+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py
@@ -3119,47 +3119,6 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):
responses_api_request=data,
)
- @classmethod
- def _contains_responses_file_reference(cls, value: object) -> bool:
- if isinstance(value, dict):
- return value.get("type") == "input_file" or any(
- cls._contains_responses_file_reference(child) for child in value.values()
- )
- if isinstance(value, list):
- return any(cls._contains_responses_file_reference(child) for child in value)
- return False
-
- @classmethod
- def _contains_unmeasurable_chat_media(cls, value: object) -> bool:
- if isinstance(value, dict):
- return value.get("type") in ("document", "file", "video_url") or any(
- cls._contains_unmeasurable_chat_media(child) for child in value.values()
- )
- if isinstance(value, list):
- return any(cls._contains_unmeasurable_chat_media(child) for child in value)
- return False
-
- @classmethod
- def _contains_image_content(cls, value: object) -> bool:
- if isinstance(value, dict):
- media_type: Final = value.get("media_type") or value.get("mime_type")
- return (
- value.get("type") in ("image", "image_url", "input_image")
- or (isinstance(media_type, str) and media_type.startswith("image/"))
- or any(cls._contains_image_content(child) for child in value.values())
- )
- if isinstance(value, list):
- return any(cls._contains_image_content(child) for child in value)
- return False
-
- @classmethod
- def _requires_conservative_responses_input_reservation(cls, data: object, call_type: str | None) -> bool:
- if not isinstance(data, dict):
- return False
- return call_type in RESPONSES_API_CALL_TYPES and (
- data.get("previous_response_id") is not None or cls._contains_responses_file_reference(data.get("input"))
- )
-
@staticmethod
def _count_pretokenized_embedding_input(value: object) -> int | None:
if not isinstance(value, list):
@@ -3312,33 +3271,13 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):
if v is not None
]
min_configured_otpm_limit: Final = min(configured_otpm_limits) if configured_otpm_limits else None
- configured_itpm_limits: Final = [ # mutable-ok: min calculation materializes validated limits
- int(v)
- for d in io_token_descriptors
- if d["key"] == PROJECT_ITPM_DESCRIPTOR_KEY
- for v in [ # mutable-ok: comprehension binds the optional descriptor value
- (d.get("rate_limit") or {}).get( # mutable-ok: optional descriptor fallback
- "tokens_per_unit"
- )
- ]
- if v is not None
- ]
- min_configured_itpm_limit: Final = min(configured_itpm_limits) if configured_itpm_limits else None
-
_, raw_estimated_output_tokens = self._estimate_input_and_output_tokens(
data=data,
min_configured_tpm_limit=min_configured_otpm_limit,
call_type=call_type,
)
- raw_estimated_input_tokens: Final = (
- min_configured_itpm_limit
- if min_configured_itpm_limit is not None
- and (
- self._requires_conservative_responses_input_reservation(data, call_type)
- or self._contains_unmeasurable_chat_media(data.get("messages"))
- or self._contains_image_content(data)
- )
- else self._estimate_precise_input_tokens(data=data, model=requested_model, call_type=call_type)
+ raw_estimated_input_tokens: Final = self._estimate_precise_input_tokens(
+ data=data, model=requested_model, call_type=call_type
)
estimated_input_tokens: Final = max(raw_estimated_input_tokens, 1)
estimated_output_tokens: Final = (
diff --git a/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py b/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py
index e04ea66db5e..fd7e0626af9 100644
--- a/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py
+++ b/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py
@@ -2386,13 +2386,34 @@ async def test_itpm_rejects_large_audio_payload_that_would_pass_flat_estimate(
{
"role": "user",
"content": [
+ {"type": "text", "text": "describe this"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/high-resolution.png",
"detail": "high",
},
- }
+ },
+ ],
+ }
+ ]
+ },
+ ),
+ (
+ "acompletion",
+ {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "summarize this"},
+ {
+ "type": "file",
+ "file": {
+ "filename": "document.pdf",
+ "file_data": "data:application/pdf;base64,dGVzdA==",
+ },
+ },
],
}
]
@@ -2405,29 +2426,43 @@ async def test_itpm_rejects_large_audio_payload_that_would_pass_flat_estimate(
{
"role": "user",
"content": [
+ {"type": "input_text", "text": "describe this"},
{
"type": "input_image",
"image_url": "https://example.com/high-resolution.png",
"detail": "high",
- }
+ },
],
}
]
},
),
+ (
+ "aresponses",
+ {"input": "continue", "previous_response_id": "resp-123"},
+ ),
],
)
-async def test_image_content_reserves_full_project_itpm(
+async def test_multimodal_requests_reserve_measured_project_itpm_not_full_limit(
rate_limiter,
call_type,
request_data,
):
+ """
+ Regression: image, file, and previous_response_id requests used to
+ reserve the project's whole ITPM limit up front. Because the atomic
+ check is ``current + increment > limit``, that made every such request
+ 429 as soon as the window carried any usage at all and, while in
+ flight, blocked every other request for the same project + model. They
+ now reserve the token_counter estimate like everything else, so two
+ multimodal requests fit in the same window.
+ """
handler, cache = rate_limiter
model = "bedrock_mantle/claude-opus"
- project_itpm_limit = 1_000
+ project_itpm_limit = 10_000
user_api_key_dict = UserAPIKeyAuth(
- api_key=hash_token("sk-high-resolution-image"),
- project_id="project-high-resolution-image",
+ api_key=hash_token("sk-multimodal-measured"),
+ project_id="project-multimodal-measured",
project_metadata={"model_itpm_limit": {model: project_itpm_limit}},
)
@@ -2437,10 +2472,22 @@ async def test_image_content_reserves_full_project_itpm(
data={"model": model, **request_data},
call_type=call_type,
)
+ first_stash = get_request_stash()
+ assert first_stash is not None
+ first_reservation = first_stash.itpm_reserved_tokens
+ assert 0 < first_reservation < project_itpm_limit // 2
- stash = get_request_stash()
- assert stash is not None
- assert stash.itpm_reserved_tokens == project_itpm_limit
+ _request_stash.set(None)
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={"model": model, **request_data},
+ call_type=call_type,
+ )
+ second_stash = get_request_stash()
+ assert second_stash is not None
+ assert second_stash is not first_stash
+ assert second_stash.itpm_reserved_tokens == first_reservation
@pytest.mark.asyncio
@@ -3191,95 +3238,6 @@ def test_anthropic_messages_usage_reconciles_split_project_quota(rate_limiter):
assert output_tokens == 25
- "request_data",
- [
- {"input": "continue", "previous_response_id": "resp-123"},
- {
- "input": [
- {
- "role": "user",
- "content": [{"type": "input_file", "file_id": "file-123"}],
- }
- ]
- },
- ],
-)
-async def test_unmeasurable_responses_input_reserves_full_project_itpm(
- rate_limiter, request_data
-):
- handler, cache = rate_limiter
- user_api_key_dict = UserAPIKeyAuth(
- api_key=hash_token("sk-unmeasurable-input"),
- project_id="project-unmeasurable-input",
- project_metadata={"model_itpm_limit": {"model": 100}},
- )
- data = {"model": "model", **request_data}
-
- await handler.async_pre_call_hook(
- user_api_key_dict=user_api_key_dict,
- cache=cache,
- data=data,
- call_type="aresponses",
- )
-
- stash = get_request_stash()
- assert stash is not None
- assert stash.itpm_reserved_tokens == 100
-
-
- "media_block",
- [
- {
- "type": "document",
- "source": {
- "type": "base64",
- "media_type": "application/pdf",
- "data": "dGVzdA==",
- },
- },
- {
- "type": "file",
- "file": {
- "filename": "document.pdf",
- "file_data": "data:application/pdf;base64,dGVzdA==",
- },
- },
- {
- "type": "video_url",
- "video_url": {"url": "https://example.com/video.mp4"},
- },
- ],
-)
-async def test_unmeasurable_chat_media_reserves_full_project_itpm(
- rate_limiter,
- media_block,
-):
- handler, cache = rate_limiter
- user_api_key_dict = UserAPIKeyAuth(
- api_key=hash_token("sk-unmeasurable-chat-media"),
- project_id="project-unmeasurable-chat-media",
- project_metadata={"model_itpm_limit": {"model": 100}},
- )
-
- await handler.async_pre_call_hook(
- user_api_key_dict=user_api_key_dict,
- cache=cache,
- data={
- "model": "model",
- "messages": [{"role": "user", "content": [media_block]}],
- },
- call_type="acompletion",
- )
-
- stash = get_request_stash()
- assert stash is not None
- assert stash.itpm_reserved_tokens == 100
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_type",
@@ -3469,18 +3427,7 @@ def test_split_quota_multimodal_guards_handle_non_mapping_inputs(rate_limiter):
assert handler._estimate_audio_block_tokens(
object()
) == handler._estimate_audio_block_tokens({})
- assert handler._contains_unmeasurable_chat_media(object()) is False
- assert handler._contains_image_content(object()) is False
- assert handler._contains_image_content(
- {"inline_data": {"mime_type": "image/png", "data": "dGVzdA=="}}
- )
assert handler._responses_input_to_chat_messages(object()) == ()
- assert (
- handler._requires_conservative_responses_input_reservation(
- object(), "responses"
- )
- is False
- )
assert handler._estimate_precise_input_tokens(object(), model=None) == 0
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index 88a807e39b3..7a099462256 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -1,6 +1,6 @@
{
"LIT001": {
- "limit": 22897
+ "limit": 22895
},
"LIT002": {
"limit": 26889
@@ -27,7 +27,7 @@
"limit": 0
},
"LIT010": {
- "limit": 16687
+ "limit": 16661
},
"LIT011": {
"limit": 5590