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]

Resolving merge conflicts and verai comment for batch

Shivi Jaina9227057a16f
diff --cc litellm/proxy/_types.py
index b4aab95e2d4,385f39e02a4..07765ae9497
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@@ -4076,8 -4193,8 +4197,10 @@@ class PassThroughEndpointLoggingTypedDi
LiteLLM_ManagementEndpoint_MetadataFields: Final = [
"model_rpm_limit",
"model_tpm_limit",
+ "model_itpm_limit",
+ "model_otpm_limit",
+ "default_estimated_output_tokens",
+ "default_estimated_output_tokens_per_model",
"mcp_rpm_limit",
"tag_rpm_limit",
"rpm_limit_type",
diff --cc litellm/proxy/hooks/batch_rate_limiter.py
index d164af66cad,7e33583fc9d..3091b0f6973
--- a/litellm/proxy/hooks/batch_rate_limiter.py
+++ b/litellm/proxy/hooks/batch_rate_limiter.py
@@@ -44,6 -44,6 +44,7 @@@ from litellm.proxy.common_utils.proxy_r
ProxyRateLimitError,
map_v3_rate_limit_type,
)
++from litellm.proxy.hooks.parallel_request_limiter_v3 import PROJECT_OTPM_DESCRIPTOR_KEY
from litellm.proxy.hooks.rate_limiter_utils import resolve_llm_provider_for_rate_limit
if TYPE_CHECKING:
@@@ -83,6 -83,6 +84,7 @@@ class BatchFileUsage(BaseModel)
total_tokens: int
request_count: int
++ output_tokens: int = 0
class _PROXY_BatchRateLimiter(CustomLogger):
@@@ -198,13 -198,13 +200,26 @@@
user_api_key_dict: UserAPIKeyAuth,
data: dict,
) -> list["RateLimitDescriptor"]:
-- return self.parallel_request_limiter._create_rate_limit_descriptors(
++ """Build the descriptor list a batch submission is charged against.
++
++ Includes the project-scoped ITPM/OTPM descriptors alongside the
++ standard key/user/team/model ones so a project caller can't bypass
++ its configured token quotas by submitting a batch instead of a
++ synchronous request.
++ """
++ descriptors: Final = self.parallel_request_limiter._create_rate_limit_descriptors(
user_api_key_dict=user_api_key_dict,
data=data,
rpm_limit_type=None,
tpm_limit_type=None,
model_has_failures=False,
)
++ self.parallel_request_limiter._add_project_io_token_rate_limit_descriptors_from_metadata(
++ user_api_key_dict=user_api_key_dict,
++ requested_model=self._get_batch_routing_model(data),
++ descriptors=descriptors,
++ )
++ return descriptors
def _should_skip_batch_input_file_processing(
self,
@@@ -297,6 -297,6 +312,30 @@@
return False
return True
++ def _estimate_entry_output_tokens(
++ self,
++ entry: dict,
++ min_configured_otpm_limit: int | None,
++ ) -> int:
++ """Conservative per-row output-token estimate for the project OTPM reservation.
++
++ Batch completion never reconciles actual usage back into the rate
++ limiter, so this pre-call estimate is the only OTPM enforcement a
++ batch gets. Mirrors the real-time no-``max_tokens`` floor so a row
++ that omits ``max_tokens`` can't be used to bypass OTPM the way an
++ unbounded streaming request could.
++ """
++ body: Final = entry.get("body", {}) or {}
++ if body.get("input") is not None and body.get("messages") is None and body.get("prompt") is None:
++ return 0 # embeddings: no output tokens
++ explicit_cap = body.get("max_tokens", body.get("max_completion_tokens"))
++ if explicit_cap is not None:
++ try:
++ return max(0, int(explicit_cap))
++ except (TypeError, ValueError):
++ pass
++ return self.parallel_request_limiter._no_max_tokens_output_floor(min_configured_otpm_limit)
++
@staticmethod
def _has_applicable_batch_rate_limits(
descriptors: list["RateLimitDescriptor"],
@@@ -407,9 -407,9 +446,14 @@@
f"Limit resets at: {reset_time_formatted}"
)
else: # tokens
++ batch_token_count = (
++ batch_usage.output_tokens
++ if descriptor.get("key") == PROJECT_OTPM_DESCRIPTOR_KEY
++ else batch_usage.total_tokens
++ )
detail = (
f"Batch rate limit exceeded for {descriptor.get('key', 'unknown')}: {descriptor.get('value', 'unknown')}. "
-- f"Batch contains {batch_usage.total_tokens} tokens but only {remaining_display} tokens remaining "
++ f"Batch contains {batch_token_count} tokens but only {remaining_display} tokens remaining "
f"out of {current_limit} TPM limit. "
f"Limit resets at: {reset_time_formatted}"
)
@@@ -452,11 -452,11 +496,15 @@@
data=data,
)
-- increment: Final[dict[Literal["requests", "tokens"], int]] = {
-- "requests": batch_usage.request_count,
-- "tokens": batch_usage.total_tokens,
-- }
-- increments: Final[list[dict[Literal["requests", "tokens"], int]]] = [increment for _ in descriptors]
++ increments: Final[list[dict[Literal["requests", "tokens"], int]]] = [
++ {
++ "requests": batch_usage.request_count,
++ "tokens": batch_usage.output_tokens
++ if d.get("key") == PROJECT_OTPM_DESCRIPTOR_KEY
++ else batch_usage.total_tokens,
++ }
++ for d in descriptors
++ ]
rate_limit_response: Final = await self.parallel_request_limiter.atomic_check_and_increment_by_n(
descriptors=descriptors,
@@@ -482,6 -482,6 +530,7 @@@
custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",
user_api_key_dict: UserAPIKeyAuth | None = None,
data: dict | None = None,
++ descriptors: list["RateLimitDescriptor"] | None = None,
) -> BatchFileUsage:
"""
Count number of requests and tokens in a batch input file.
@@@ -490,10 -490,10 +539,20 @@@
file_id: The file ID to read
custom_llm_provider: The custom LLM provider to use for token encoding
user_api_key_dict: User authentication information for file access (required for managed files)
++ descriptors: Rate limit descriptors already computed for this batch, so the
++ configured project OTPM limit can scale the no-``max_tokens`` output floor
Returns:
-- BatchFileUsage with total_tokens and request_count
++ BatchFileUsage with total_tokens, output_tokens, and request_count
"""
++ otpm_limits: Final = [
++ int(v)
++ for d in (descriptors or [])
++ if d.get("key") == PROJECT_OTPM_DESCRIPTOR_KEY
++ for v in [(d.get("rate_limit") or {}).get("tokens_per_unit")]
++ if v is not None
++ ]
++ min_configured_otpm_limit: Final = min(otpm_limits) if otpm_limits else None
try:
# Check if this is a managed file (base64 encoded unified file ID)
from litellm.proxy.openai_files_endpoints.common_utils import (
@@@ -546,6 -546,6 +605,7 @@@
# the counter can't measure is estimated, not hard-rejected.
models: Final[set] = set()
total_tokens = 0
++ output_tokens = 0
request_count = 0
for raw_line in _iter_batch_input_lines(file_content_bytes):
request_count += 1
@@@ -553,11 -553,11 +613,19 @@@
entry = json.loads(raw_line)
except Exception:
total_tokens += _estimate_batch_entry_tokens(raw_line)
++ output_tokens += self.parallel_request_limiter._no_max_tokens_output_floor(
++ min_configured_otpm_limit
++ )
continue
if isinstance(entry, dict):
model = (entry.get("body") or {}).get("model")
if model:
models.add(model)
++ output_tokens += self._estimate_entry_output_tokens(entry, min_configured_otpm_limit)
++ else:
++ output_tokens += self.parallel_request_limiter._no_max_tokens_output_floor(
++ min_configured_otpm_limit
++ )
try:
total_tokens += _count_entry_tokens(entry)
except Exception:
@@@ -578,6 -578,6 +646,7 @@@
return BatchFileUsage(
total_tokens=total_tokens,
request_count=request_count,
++ output_tokens=output_tokens,
)
except HTTPException as e:
@@@ -814,6 -814,6 +883,7 @@@
custom_llm_provider=custom_llm_provider,
user_api_key_dict=user_api_key_dict,
data=data,
++ descriptors=batch_rate_limit_descriptors,
)
verbose_proxy_logger.debug(
diff --cc litellm/proxy/hooks/parallel_request_limiter_v3.py
index e6cb54393ab,f62dbec2e85..1c7ae1ea9f8
--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py
+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py
@@@ -18,16 -18,13 +18,15 @@@ from typing import
Final,
Literal,
Protocol,
+ TypeAlias,
TypedDict,
- Union,
- cast,
)
+from typing_extensions import NotRequired
+
from litellm import DualCache
from litellm._logging import verbose_proxy_logger
- from litellm.constants import DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE
+ from litellm.constants import DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE, INTERNAL_CALL_ORIGIN_METADATA_KEY
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.prompt_templates.common_utils import (
get_str_from_messages,
@@@ -418,10 -353,42 +427,46 @@@ class RateLimitResponseWithDescriptors(
response: RateLimitResponse
+class _RateLimitDescriptorSink(Protocol):
+ def append(self, descriptor: RateLimitDescriptor, /) -> None: ...
+
+
+ class WindowKeyMetadata(TypedDict):
+ requests_limit: int | None
+ tokens_limit: int | None
+ window_size: int
+ descriptor_key: str
+
+
+ class AtomicCounterMeta(TypedDict):
+ descriptor_key: str
+ current_limit: int
+ rate_limit_type: Literal["requests", "tokens"]
+ window_key: str
+ counter_key: str
+ increment: int
+ ttl: int
+ window_size: int
+
+
+ class AtomicCounterState(TypedDict):
+ window_expired: bool
+ current: int
+
+
+ DescriptorAtomicGroup: TypeAlias = tuple[list[str], list[int], list[AtomicCounterMeta]]
+
+
+ class CallTypeRateLimiter(Protocol):
+ async def async_pre_call_hook(
+ self,
+ user_api_key_dict: UserAPIKeyAuth,
+ cache: DualCache,
+ data: dict[str, object],
+ call_type: str,
+ ) -> Exception | str | dict[str, object] | None: ...
+
+
@dataclass(slots=True)
class RequestRateLimiterStash:
"""
@@@ -608,154 -559,12 +653,161 @@@ class _PROXY_MaxParallelRequestsHandler
return baseline
return min(baseline, max(1, min_configured_tpm_limit // _TPM_FLOOR_FRACTION))
+ @staticmethod
+ def _is_embedding_request(data: object, call_type: str | None) -> bool:
+ if call_type in EMBEDDING_API_CALL_TYPES:
+ return True
+ if call_type in RESPONSES_API_CALL_TYPES:
+ return False
+ if call_type:
+ return False
+ if not isinstance(data, dict):
+ return False
+ return data.get("input") is not None
+
+ @staticmethod
+ def _translate_google_genai_native_request(
+ data: object,
+ call_type: str | None,
+ ) -> Mapping[str, object] | None:
+ contents = data.get("contents") if isinstance(data, dict) else None
+ if (
+ not isinstance(data, dict)
+ or call_type not in GOOGLE_GENAI_NATIVE_CALL_TYPES
+ or not isinstance(contents, (dict, list))
+ ):
+ return None
+ from litellm.google_genai.adapters.transformation import GoogleGenAIAdapter
+
+ config = data.get("config") if "config" in data else data.get("generationConfig")
+ translated_request = GoogleGenAIAdapter().translate_generate_content_to_completion(
+ model=data.get("model") if isinstance(data.get("model"), str) else "",
+ contents=contents,
+ config=config if isinstance(config, dict) else None,
+ systemInstruction=data.get("systemInstruction"),
+ system_instruction=data.get("system_instruction"),
+ tools=data.get("tools"),
+ toolConfig=data.get("toolConfig"),
+ tool_config=data.get("tool_config"),
+ )
+ return translated_request
+
+ @staticmethod
+ def _get_explicit_output_cap(data: object, call_type: str | None) -> int | None:
+ if not isinstance(data, dict):
+ return None
+ if call_type in GOOGLE_GENAI_NATIVE_CALL_TYPES:
+ config = data.get("config") if "config" in data else data.get("generationConfig")
+ values = tuple(
+ int(config[field])
+ for field in ("maxOutputTokens", "max_output_tokens")
+ if isinstance(config, dict) and isinstance(config.get(field), (int, float, str))
+ )
+ return max(values, default=None)
+ if call_type in RESPONSES_API_CALL_TYPES:
+ value = data.get("max_output_tokens")
+ if value is None:
+ return None
+ if not isinstance(value, (int, float, str)):
+ return None
+ return max(RESPONSES_API_MIN_OUTPUT_TOKENS, int(value))
+ if call_type in EMBEDDING_API_CALL_TYPES:
+ return None
+ fields = (
+ ("max_tokens", "max_completion_tokens")
+ if call_type
+ else ("max_tokens", "max_completion_tokens", "max_output_tokens")
+ )
+ values = tuple(int(data[field]) for field in fields if isinstance(data.get(field), (int, float, str)))
+ return max(values, default=None)
+
+ @classmethod
+ def _has_explicit_output_cap(cls, data: object, call_type: str | None) -> bool:
+ """Whether the caller explicitly set an output-token cap.
+
+ Checked via ``is not None`` (not truthiness) so an explicit 0 --
+ a legitimate zero-output request -- counts as explicit.
+ """
+ return cls._get_explicit_output_cap(data, call_type) is not None
+
+ @staticmethod
+ def _get_output_candidate_count(data: object, call_type: str | None = None) -> int:
+ if not isinstance(data, dict):
+ return 1
+ config = (
+ (data.get("config") if "config" in data else data.get("generationConfig"))
+ if call_type in GOOGLE_GENAI_NATIVE_CALL_TYPES
+ else None
+ )
+ candidate_values = (
+ data.get("n"),
+ data.get("best_of"),
+ config.get("candidateCount") if isinstance(config, dict) else None,
+ config.get("candidate_count") if isinstance(config, dict) else None,
+ )
+ candidate_count = 1
+ for value in candidate_values:
+ try:
+ candidate_count = max(candidate_count, int(value or 1))
+ except (TypeError, ValueError):
+ continue
+ return candidate_count
+
+ @staticmethod
+ def _apply_implicit_output_cap(
+ data: object,
+ min_configured_limit: int | None,
+ call_type: str | None,
++ configured_output_tokens: int | None = None,
+ ) -> None:
+ """Hard-cap generation length when the request has no explicit cap.
+
+ Guards against an unbounded response overshooting a small TPM/OTPM
+ budget before post-call reconciliation runs. Skips requests that
+ already set an explicit cap and embeddings, which have no generation
+ budget. The Responses API only honors ``max_output_tokens`` (its
+ underlying chat-completion transformation ignores ``max_tokens``), so
+ the cap must be written to that field for Responses call types.
++
++ ``configured_output_tokens`` is the operator-declared per-tenant
++ estimate; when it exceeds the safety floor, the cap is raised to that
++ value instead of clamping every tenant to the same floor.
+ """
+ if not isinstance(data, dict):
+ return
+ capped_floor = _PROXY_MaxParallelRequestsHandler_v3._no_max_tokens_output_floor(min_configured_limit)
+ if call_type in RESPONSES_API_CALL_TYPES:
+ capped_floor = max(capped_floor, RESPONSES_API_MIN_OUTPUT_TOKENS)
+ baseline_floor = DEFAULT_MAX_TOKENS_ESTIMATE // _TPM_FLOOR_FRACTION
+ is_embedding = _PROXY_MaxParallelRequestsHandler_v3._is_embedding_request(data, call_type)
+ if (
+ capped_floor >= baseline_floor
+ or _PROXY_MaxParallelRequestsHandler_v3._has_explicit_output_cap(data, call_type)
+ or is_embedding
+ ):
+ return
++ effective_cap = max(capped_floor, configured_output_tokens or 0)
+ if call_type in GOOGLE_GENAI_NATIVE_CALL_TYPES:
+ config_field = "config" if "config" in data or "generationConfig" not in data else "generationConfig"
+ config = data.get(config_field)
+ if config is None or isinstance(config, dict):
+ data[config_field] = { # mutable-ok: downstream native routing requires a mutable request config
+ **(config or {}), # mutable-ok: downstream native routing requires a mutable request config
- "maxOutputTokens": capped_floor,
++ "maxOutputTokens": effective_cap,
+ }
+ return
+ cap_field = "max_output_tokens" if call_type in RESPONSES_API_CALL_TYPES else "max_tokens"
+ existing_cap = data.get(cap_field)
- if existing_cap is None or capped_floor < existing_cap:
- data[cap_field] = capped_floor
++ if existing_cap is None or effective_cap < existing_cap:
++ data[cap_field] = effective_cap
+
def _estimate_tokens_for_request(
self,
data: dict,
model: str | None = None,
min_configured_tpm_limit: int | None = None,
+ call_type: str | None = None,
+ configured_output_tokens: int | None = None,
) -> int:
"""
Estimate total tokens this request will consume so we can reserve them
@@@ -771,89 -578,41 +823,101 @@@
provided, the no-``max_tokens`` output-budget floor is capped at a
fraction of that limit so small TPM caps remain usable. Omit to
preserve the unconstrained floor.
+
+ ``configured_output_tokens`` is the operator-declared estimate resolved
+ from key or team metadata. When provided it replaces the heuristic
+ floor entirely, so the reservation reflects what this tenant's model
+ actually emits rather than one constant shared by every tenant.
"""
- messages = data.get("messages")
- prompt: Final = data.get("prompt")
- input_text: Final = data.get("input") # embeddings
+ estimated_input_tokens, max_tokens_estimate = self._estimate_input_and_output_tokens(
+ data=data,
+ min_configured_tpm_limit=min_configured_tpm_limit,
+ call_type=call_type,
++ configured_output_tokens=configured_output_tokens,
+ )
+ total_estimated: Final = estimated_input_tokens + max_tokens_estimate
+
+ verbose_proxy_logger.debug(
+ "TPM reservation estimate: input=%s, max_tokens=%s, total=%s",
+ estimated_input_tokens,
+ max_tokens_estimate,
+ total_estimated,
+ )
+
+ return total_estimated
+
+ def _estimate_input_and_output_tokens(
+ self,
+ data: object,
+ min_configured_tpm_limit: int | None = None,
+ call_type: str | None = None,
++ configured_output_tokens: int | None = None,
+ ) -> tuple[int, int]:
+ """
+ Estimate input tokens and output (max_tokens) budget separately, so
+ callers needing independent ITPM/OTPM reservations (rather than one
+ combined TPM reservation) can use each half on its own.
+
+ ``min_configured_tpm_limit`` is the smallest ``tokens_per_unit`` among
+ the TPM-bearing descriptors this request will be charged against. When
+ provided, the no-``max_tokens`` output-budget floor is capped at a
+ fraction of that limit so small TPM caps remain usable. Omit to
+ preserve the unconstrained floor.
+
+ ``call_type`` disambiguates embeddings from the Responses API: both
+ put their prompt in ``data["input"]``, but only embeddings have no
+ output tokens. Unset (the default) preserves the historical
+ "any `input` means zero output" behavior for callers that don't have
+ a call type to pass.
++
++ ``configured_output_tokens`` is the operator-declared estimate resolved
++ from key or team metadata. When provided it replaces the heuristic
++ floor entirely, so the reservation reflects what this tenant's model
++ actually emits rather than one constant shared by every tenant.
+ """
+ if not isinstance(data, dict):
+ return 0, 0
+ translated_data: Final = self._translate_google_genai_native_request(data, call_type)
+ estimable_data: Final = translated_data if translated_data is not None else data
+ messages = estimable_data.get("messages")
+ prompt = estimable_data.get("prompt")
+ input_text = estimable_data.get("input")
+
+ if call_type in RESPONSES_API_CALL_TYPES or call_type in EMBEDDING_API_CALL_TYPES:
+ messages = None
+ prompt = None
+ elif call_type in TEXT_COMPLETION_API_CALL_TYPES:
+ messages = None
+ input_text = None
+ elif call_type:
+ prompt = None
+ input_text = None
match (messages, prompt, input_text):
- case (messages, _, _) if messages:
- total_chars = len(get_str_from_messages(messages))
- case (_, str() as p, _):
- total_chars = len(p)
- case (_, list() as p, _):
- total_chars = sum(len(str(item)) for item in p)
- case (_, _, str() as t):
- total_chars = len(t)
- case (_, _, list() as t):
- total_chars = sum(len(str(item)) for item in t)
+ case (selected_messages, _, _) if selected_messages:
+ total_chars = len(get_str_from_messages(selected_messages))
+ case (_, str() as selected_prompt, _):
+ total_chars = len(selected_prompt)
+ case (_, list() as selected_prompt, _):
+ total_chars = sum(len(str(item)) for item in selected_prompt)
+ case (_, _, str() as selected_input):
+ total_chars = len(selected_input)
+ case (_, _, list() as selected_input):
+ total_chars = sum(len(str(item)) for item in selected_input)
case _:
total_chars = 0
estimated_input_tokens: Final = max(1, total_chars // DEFAULT_CHARS_PER_TOKEN) if total_chars > 0 else 0
- explicit_max_tokens: Final = data.get("max_tokens") or data.get("max_completion_tokens")
+ explicit_max_tokens: Final = self._get_explicit_output_cap(data, call_type)
+ is_embedding: Final = self._is_embedding_request(data, call_type)
- match (explicit_max_tokens, input_text):
- case (mt, _) if mt is not None:
- max_tokens_estimate = int(mt)
- case (_, embeddings_input) if embeddings_input:
- # Embeddings have no output tokens
+ match (explicit_max_tokens, is_embedding):
+ case (_, True):
max_tokens_estimate = 0
+ case (mt, _) if mt is not None:
+ max_tokens_estimate = mt
- case _ if total_chars == 0:
+ case _ if total_chars == 0 and configured_output_tokens is None:
# Fully contentless request (no messages, prompt, or input).
# Don't apply the conservative output-budget floor here — it
# would over-reserve and could push small TPM limits into a
@@@ -867,13 -626,24 +931,17 @@@
# the smallest TPM limit this request will be charged against,
# so a small per-tenant TPM cap can't be tripped by the floor
# alone.
- output_floor: Final = self._no_max_tokens_output_floor(min_configured_tpm_limit)
+ output_floor = self._no_max_tokens_output_floor(min_configured_tpm_limit)
+ if call_type in RESPONSES_API_CALL_TYPES:
+ output_floor = max(output_floor, RESPONSES_API_MIN_OUTPUT_TOKENS)
- max_tokens_estimate = max(estimated_input_tokens, output_floor)
+ max_tokens_estimate = (
+ configured_output_tokens
+ if configured_output_tokens is not None
+ else max(estimated_input_tokens, output_floor)
+ )
- total_estimated: Final = estimated_input_tokens + max_tokens_estimate
-
- verbose_proxy_logger.debug(
- "TPM reservation estimate: input=%s, max_tokens=%s (explicit=%s), total=%s",
- estimated_input_tokens,
- max_tokens_estimate,
- explicit_max_tokens is not None,
- total_estimated,
- )
-
- return total_estimated
+ max_tokens_estimate *= self._get_output_candidate_count(data, call_type)
+ return estimated_input_tokens, max_tokens_estimate
def _is_redis_cluster(self) -> bool:
"""
@@@ -1661,10 -1457,9 +1755,11 @@@
descriptor i, refund descriptors 0..i-1's increments. On Lua failure
mid-loop, refund applied increments and fall back to in-memory.
"""
+ if not descriptor_groups:
+ return RateLimitResponse(overall_code="OK", statuses=[])
- applied: Final[list[list[dict[str, Any]]]] = []
+ applied: Final[list[list[AtomicCounterMeta]]] = []
statuses: Final[list[RateLimitStatus]] = []
+ raw: list[CacheCounterValue]
for _idx, (keys, args, meta) in enumerate(descriptor_groups):
try:
@@@ -3425,15 -2586,24 +3518,21 @@@
if has_tpm_limits and self.tpm_reservation_enabled:
min_configured_tpm_limit: Final = min(configured_tpm_limits)
- # When the configured TPM cap is small enough to constrain the
- # no-max_tokens floor, also hard-cap the model output via
- # data["max_tokens"] so concurrent unbounded generations can't
- # spend past the limit before post-call reconciliation runs.
- # Skip when the request already sets max_tokens or has no
- # generation budget at all (embeddings).
- capped_floor: Final = self._no_max_tokens_output_floor(min_configured_tpm_limit)
- baseline_floor: Final = DEFAULT_MAX_TOKENS_ESTIMATE // _TPM_FLOOR_FRACTION
- has_explicit_max_tokens: Final = (
- data.get("max_tokens") is not None or data.get("max_completion_tokens") is not None
- )
- is_embedding: Final = data.get("input") is not None
+ configured_output_tokens: Final = get_estimated_output_tokens(
+ user_api_key_dict=user_api_key_dict,
+ model_name=requested_model,
+ )
- if capped_floor < baseline_floor and not has_explicit_max_tokens and not is_embedding:
- data["max_tokens"] = max(capped_floor, configured_output_tokens or 0)
++
+ # When the configured TPM cap is small enough to constrain the
+ # no-max_tokens floor, also hard-cap the model output so
+ # concurrent unbounded generations can't spend past the limit
+ # before post-call reconciliation runs.
+ self._apply_implicit_output_cap(
+ data=data,
+ min_configured_limit=min_configured_tpm_limit,
+ call_type=call_type,
++ configured_output_tokens=configured_output_tokens,
+ )
# Floor at 1 token so contentless requests (/responses,
# tool-call continuations, empty messages) still flow
@@@ -3447,7 -2617,7 +3546,8 @@@
data=data,
model=requested_model,
min_configured_tpm_limit=min_configured_tpm_limit,
+ call_type=call_type,
+ configured_output_tokens=configured_output_tokens,
),
1,
)
diff --cc tests/test_litellm/proxy/hooks/test_batch_file_validation.py
index 7ff1bc11d81,7ff1bc11d81..c2e1ed4a0c1
--- a/tests/test_litellm/proxy/hooks/test_batch_file_validation.py
+++ b/tests/test_litellm/proxy/hooks/test_batch_file_validation.py
@@@ -1382,6 -1382,6 +1382,121 @@@ async def test_check_and_increment_comp
parallel_request_limiter._create_rate_limit_descriptors.assert_called_once()
++async def test_pre_call_enforces_project_otpm_limit_for_batch():
++ """VERIA regression: ``_create_batch_rate_limit_descriptors`` only asked
++ for the generic key/user/team/model descriptors, so a project caller
++ could submit a batch that consumed none of its configured project OTPM
++ quota. The project OTPM descriptor must now be present and charged with
++ the batch's estimated *output* tokens, not its input tokens."""
++ from litellm import DualCache
++ from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
++ from litellm.proxy.hooks.parallel_request_limiter_v3 import (
++ _PROXY_MaxParallelRequestsHandler_v3,
++ )
++ from litellm.proxy.utils import InternalUsageCache
++
++ local_cache = DualCache()
++ parallel_request_limiter = _PROXY_MaxParallelRequestsHandler_v3(
++ internal_usage_cache=InternalUsageCache(local_cache)
++ )
++ rate_limiter = _PROXY_BatchRateLimiter(
++ internal_usage_cache=InternalUsageCache(local_cache),
++ parallel_request_limiter=parallel_request_limiter,
++ )
++
++ user = UserAPIKeyAuth(
++ api_key="sk-project-batch-otpm",
++ models=["*"],
++ project_id="proj-mantle-batch",
++ project_metadata={"model_otpm_limit": {"gpt-4o-mini": 50}},
++ )
++
++ # Two rows each declaring max_tokens=40: 80 output tokens total, over the
++ # configured 50-token project OTPM limit but negligible input tokens.
++ mock_content = MagicMock()
++ mock_content.content = (
++ b'{"body": {"model": "gpt-4o-mini", "max_tokens": 40, '
++ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
++ b'{"body": {"model": "gpt-4o-mini", "max_tokens": 40, '
++ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
++ )
++
++ with (
++ patch("litellm.proxy.proxy_server.general_settings", {}),
++ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),
++ patch(
++ "litellm.proxy.openai_files_endpoints.common_utils.get_credentials_for_model",
++ return_value={"custom_llm_provider": "openai"},
++ ),
++ patch("litellm.afile_content", new=AsyncMock(return_value=mock_content)),
++ ):
++ with pytest.raises(HTTPException) as exc:
++ await rate_limiter.async_pre_call_hook(
++ user_api_key_dict=user,
++ cache=local_cache,
++ data={"input_file_id": "file-abc123", "model": "gpt-4o-mini"},
++ call_type="acreate_batch",
++ )
++
++ assert exc.value.status_code == 429
++ assert "model_per_project_otpm" in str(exc.value.detail)
++
++
++async def test_pre_call_enforces_project_itpm_limit_for_batch():
++ """Companion to the OTPM regression above: a project's ITPM quota must
++ also apply to batch submissions."""
++ from litellm import DualCache
++ from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
++ from litellm.proxy.hooks.parallel_request_limiter_v3 import (
++ _PROXY_MaxParallelRequestsHandler_v3,
++ )
++ from litellm.proxy.utils import InternalUsageCache
++
++ local_cache = DualCache()
++ parallel_request_limiter = _PROXY_MaxParallelRequestsHandler_v3(
++ internal_usage_cache=InternalUsageCache(local_cache)
++ )
++ rate_limiter = _PROXY_BatchRateLimiter(
++ internal_usage_cache=InternalUsageCache(local_cache),
++ parallel_request_limiter=parallel_request_limiter,
++ )
++
++ user = UserAPIKeyAuth(
++ api_key="sk-project-batch-itpm",
++ models=["*"],
++ project_id="proj-mantle-batch",
++ project_metadata={"model_itpm_limit": {"gpt-4o-mini": 1}},
++ )
++
++ mock_content = MagicMock()
++ mock_content.content = (
++ b'{"body": {"model": "gpt-4o-mini", "max_tokens": 1, '
++ b'"messages": [{"role": "user", "content": "well over one token of input"}]}}\n'
++ )
++
++ with (
++ patch("litellm.proxy.proxy_server.general_settings", {}),
++ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),
++ patch(
++ "litellm.proxy.openai_files_endpoints.common_utils.get_credentials_for_model",
++ return_value={"custom_llm_provider": "openai"},
++ ),
++ patch("litellm.afile_content", new=AsyncMock(return_value=mock_content)),
++ ):
++ with pytest.raises(HTTPException) as exc:
++ await rate_limiter.async_pre_call_hook(
++ user_api_key_dict=user,
++ cache=local_cache,
++ data={"input_file_id": "file-abc123", "model": "gpt-4o-mini"},
++ call_type="acreate_batch",
++ )
++
++ assert exc.value.status_code == 429
++ assert "model_per_project_itpm" in str(exc.value.detail)
++
++
@pytest.mark.asyncio
async def test_count_input_file_usage_raises_on_non_bytes_content():
from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
diff --cc tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
index 872b447ad2d,59434290c48..ac0396c11c1
--- a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
+++ b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
@@@ -5230,3 -5102,494 +5232,494 @@@ async def test_reserve_tpm_tokens_never
f"reservation pass, got: {response}"
)
assert [s["rate_limit_type"] for s in response["statuses"]] == ["tokens"]
+
+
+ STATIC_OUTPUT_FLOOR = 1024
+ ONE_TOKEN_PROMPT = [{"role": "user", "content": "hello"}]
+ ONE_TOKEN_PROMPT_INPUT_ESTIMATE = 1
+
+
+ async def _reserved_tokens_for(
+ handler,
+ local_cache,
+ user_api_key_dict,
+ data,
+ call_type="completion",
+ ):
+ """Drive the pre-call hook and read back what landed on the :tokens counter."""
+ tokens_key = handler.create_rate_limit_keys(
+ key="api_key", value=user_api_key_dict.api_key, rate_limit_type="tokens"
+ )
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=local_cache,
+ data=data,
+ call_type=call_type,
+ )
+ return int(await local_cache.async_get_cache(key=tokens_key) or 0)
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "key_metadata, team_metadata, expected_output_estimate, tier",
+ [
+ (
+ {
+ "default_estimated_output_tokens_per_model": {"gpt-4o-mini": 3001},
+ "default_estimated_output_tokens": 2002,
+ },
+ {
+ "default_estimated_output_tokens_per_model": {"gpt-4o-mini": 1503},
+ "default_estimated_output_tokens": 777,
+ },
+ 3001,
+ "key per-model wins over every other tier",
+ ),
+ (
+ {"default_estimated_output_tokens": 2002},
+ {
+ "default_estimated_output_tokens_per_model": {"gpt-4o-mini": 1503},
+ "default_estimated_output_tokens": 777,
+ },
+ 2002,
+ "key global wins over team config",
+ ),
+ (
+ {"default_estimated_output_tokens_per_model": {"some-other-model": 9999}},
+ {
+ "default_estimated_output_tokens_per_model": {"gpt-4o-mini": 1503},
+ "default_estimated_output_tokens": 777,
+ },
+ 1503,
+ "team per-model wins when the key has no applicable entry",
+ ),
+ (
+ {},
+ {"default_estimated_output_tokens": 777},
+ 777,
+ "team global is the last configured tier",
+ ),
+ ({}, {}, STATIC_OUTPUT_FLOOR, "unconfigured falls back to the static floor"),
+ (
+ {"unrelated": "value"},
+ {"unrelated": "value"},
+ STATIC_OUTPUT_FLOOR,
+ "unrelated metadata changes nothing",
+ ),
+ (
+ {"default_estimated_output_tokens": "not-a-number"},
+ {},
+ STATIC_OUTPUT_FLOOR,
+ "malformed config falls back to the static floor instead of erroring",
+ ),
+ (
+ {"default_estimated_output_tokens": 0},
+ {},
+ STATIC_OUTPUT_FLOOR,
+ "a non-positive estimate is rejected, not reserved",
+ ),
+ ],
+ )
+ async def test_estimated_output_tokens_resolution_precedence(
+ monkeypatch, key_metadata, team_metadata, expected_output_estimate, tier
+ ):
+ """The no-max_tokens output reservation resolves per key / team / model.
+
+ Every configured value here is distinct from the static 1024 floor and
+ from the input estimate, so the reserved amount identifies which tier the
+ resolver picked.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token(f"sk-estimate-{expected_output_estimate}-{tier}"),
+ tpm_limit=1_000_000,
+ metadata=key_metadata,
+ team_metadata=team_metadata,
+ )
+
+ reserved = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ user_api_key_dict,
+ {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT},
+ )
+
+ assert reserved == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + expected_output_estimate, tier
+
+
+ @pytest.mark.asyncio
+ async def test_request_max_tokens_outranks_configured_estimate(monkeypatch):
+ """An explicit request-level max_tokens stays the top of the precedence order."""
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-explicit-max-tokens"),
+ tpm_limit=1_000_000,
+ metadata={"default_estimated_output_tokens": 2002},
+ )
+
+ reserved = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ user_api_key_dict,
+ {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT, "max_tokens": 42},
+ )
+
+ assert reserved == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + 42
+
+
+ @pytest.mark.asyncio
+ async def test_configured_estimate_does_not_apply_to_embeddings(monkeypatch):
+ """Embeddings generate no output, so a declared output estimate must not be reserved."""
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-embeddings"),
+ tpm_limit=1_000_000,
+ metadata={"default_estimated_output_tokens": 2002},
+ )
+
+ reserved = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ user_api_key_dict,
+ {"model": "text-embedding-3-small", "input": "hello"},
- call_type="embeddings",
++ call_type="embedding",
+ )
+
+ assert reserved == ONE_TOKEN_PROMPT_INPUT_ESTIMATE
+
+
+ @pytest.mark.asyncio
+ async def test_configured_estimate_applies_to_contentless_requests(monkeypatch):
+ """A declared estimate describes generation, so it holds even with no prompt body.
+
+ Without config such a request reserves the 1-token floor only; the
+ declaration is what makes concurrent tool-call continuations countable.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ configured = UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-contentless-configured"),
+ tpm_limit=1_000_000,
+ metadata={"default_estimated_output_tokens": 2002},
+ )
+ unconfigured = UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-contentless-plain"),
+ tpm_limit=1_000_000,
+ )
+
+ assert (
+ await _reserved_tokens_for(
+ handler, local_cache, configured, {"model": "gpt-4o-mini", "messages": []}
+ )
+ == 2002
+ )
+ assert (
+ await _reserved_tokens_for(
+ handler, local_cache, unconfigured, {"model": "gpt-4o-mini", "messages": []}
+ )
+ == 1
+ )
+
+
+ @pytest.mark.asyncio
+ async def test_declared_estimate_never_tightens_the_small_tpm_clamp(monkeypatch):
+ """The small-TPM clamp can only be loosened by a declaration, never tightened.
+
+ That clamp is the one place the proxy rewrites the caller's generation
+ budget, and it only fires below a 4096 TPM limit. A declaration above it
+ raises it, so the tenant is not truncated below what they said their
+ model emits; a declaration below it changes nothing, because an estimate
+ describes the typical response and must not become a hard cap that
+ truncates the tail. The reservation tracks whatever the clamp settles on,
+ so a small tenant can never generate more than was reserved.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ raised_data: Dict[str, Any] = {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT}
+ raised_reserved = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-hard-cap-raised"),
+ tpm_limit=2000,
+ metadata={"default_estimated_output_tokens": 900},
+ ),
+ raised_data,
+ )
+ assert raised_data["max_tokens"] == 900
+ assert raised_reserved == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + 900
+
+ lowered_data: Dict[str, Any] = {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT}
+ lowered_reserved = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-hard-cap-lowered"),
+ tpm_limit=2000,
+ metadata={"default_estimated_output_tokens": 120},
+ ),
+ lowered_data,
+ )
+ assert lowered_data["max_tokens"] == 500
+ assert lowered_reserved == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + 500
+
+ unconfigured_data: Dict[str, Any] = {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT}
+ unconfigured_reserved = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-hard-cap-plain"),
+ tpm_limit=2000,
+ ),
+ unconfigured_data,
+ )
+ assert unconfigured_data["max_tokens"] == 500
+ assert unconfigured_reserved == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + 500
+
+
+ @pytest.mark.asyncio
+ async def test_one_malformed_estimate_field_does_not_discard_the_other(monkeypatch):
+ """Each declared field is validated on its own.
+
+ A per-model map with a bad entry must not take a valid global estimate
+ down with it, and a bad global must not hide a valid per-model entry.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+
+ broken_map = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-broken-map"),
+ tpm_limit=1_000_000,
+ metadata={
+ "default_estimated_output_tokens_per_model": {"gpt-4o-mini": "huge"},
+ "default_estimated_output_tokens": 2002,
+ },
+ ),
+ {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT},
+ )
+ assert broken_map == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + 2002
+
+ broken_global = await _reserved_tokens_for(
+ handler,
+ local_cache,
+ UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-broken-global"),
+ tpm_limit=1_000_000,
+ metadata={
+ "default_estimated_output_tokens_per_model": {"gpt-4o-mini": 3001},
+ "default_estimated_output_tokens": -5,
+ },
+ ),
+ {"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT},
+ )
+ assert broken_global == ONE_TOKEN_PROMPT_INPUT_ESTIMATE + 3001
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("declared", [100_000, 5000])
+ async def test_declared_estimate_over_the_tpm_budget_is_honored_and_explained(monkeypatch, caplog, declared):
+ """A declaration bigger than the budget must not be silently shrunk.
+
+ Capping it against the TPM limit would re-admit exactly the traffic this
+ feature exists to hold back, so the request is refused instead and the
+ reservation is explained rather than leaving an unexplained 429 loop.
+
+ ``declared == tpm_limit`` is the boundary case: the declaration alone
+ equals the limit, so only adding the input estimate tips the reservation
+ over. Comparing the declaration against the limit rather than the
+ reservation would refuse this request while saying nothing.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token(f"sk-estimate-over-budget-{declared}"),
+ tpm_limit=5000,
+ metadata={"default_estimated_output_tokens": declared},
+ )
+
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):
+ with pytest.raises(HTTPException) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=local_cache,
+ data={"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT},
+ call_type="completion",
+ )
+
+ assert exc_info.value.status_code == 429
+ explained = [
+ record.getMessage()
+ for record in caplog.records
+ if "cannot be admitted even against an empty window" in record.getMessage()
+ ]
+ assert len(explained) == 1, f"expected exactly one explanation, got {explained}"
+ assert str(declared) in explained[0]
+ assert str(ONE_TOKEN_PROMPT_INPUT_ESTIMATE + declared) in explained[0]
+ assert "5000" in explained[0]
+
+
+ @pytest.mark.asyncio
+ async def test_a_key_that_declared_nothing_is_never_blamed_for_a_declaration(monkeypatch, caplog):
+ """A request can outgrow its budget on prompt size alone, with no declaration.
+
+ The heuristic path reserves input plus the injected clamp, so a long
+ prompt against a small limit is refused without anyone having declared
+ anything. Blaming the declared field there would point an operator at a
+ setting they never set, to fix a 429 whose real cause is prompt size.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):
+ with pytest.raises(HTTPException) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(
+ api_key=hash_token("sk-undeclared-long-prompt"),
+ tpm_limit=1000,
+ ),
+ cache=local_cache,
+ data={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "x" * 3600}]},
+ call_type="completion",
+ )
+
+ assert exc_info.value.status_code == 429
+ assert not [
+ record for record in caplog.records if "cannot be admitted even against an empty window" in record.getMessage()
+ ]
+
+
+ @pytest.mark.asyncio
+ async def test_declared_estimate_inside_the_tpm_budget_is_not_explained(monkeypatch, caplog):
+ """The explanation is for requests that cannot fit, not for every request.
+
+ Without this, a correctly configured key would emit one line per call.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):
+ await handler.async_pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(
+ api_key=hash_token("sk-estimate-within-budget"),
+ tpm_limit=5000,
+ metadata={"default_estimated_output_tokens": 1000},
+ ),
+ cache=local_cache,
+ data={"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT},
+ call_type="completion",
+ )
+
+ assert not [
+ record for record in caplog.records if "cannot be admitted even against an empty window" in record.getMessage()
+ ]
+
+
+ @pytest.mark.asyncio
+ async def test_configured_estimate_blocks_the_overrun_the_static_floor_admits(monkeypatch):
+ """Concurrent unbounded requests must stop at the declared budget.
+
+ A key with tpm_limit=8000 whose model really emits ~3000 output tokens
+ admits 7 concurrent requests under the 1024 floor (7 * 1025 <= 8000), so
+ once they all report actual usage the window carries ~21000 tokens
+ against an 8000 limit. Declaring the real output size admits only the two
+ requests the budget actually covers.
+ """
+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)
+
+ async def admitted(metadata):
+ local_cache = DualCache()
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token(f"sk-overrun-{metadata}"),
+ tpm_limit=8000,
+ metadata=metadata,
+ )
+ accepted = 0
+ for _ in range(10):
+ try:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=local_cache,
+ data={"model": "gpt-4o-mini", "messages": ONE_TOKEN_PROMPT},
+ call_type="completion",
+ )
+ except HTTPException:
+ break
+ accepted += 1
+ return accepted
+
+ assert await admitted({}) == 7
+ assert await admitted({"default_estimated_output_tokens": 3000}) == 2
+
+
+ def test_internal_call_origin_success_ops_are_skipped():
+ """Internal sub-calls (auto-router classifier, shadow eval shadow/judge) bill spend
+ to the caller's key but must not consume its TPM counters: the same kwargs charge
+ ops without the origin stamp and none with it."""
+ handler = _PROXY_MaxParallelRequestsHandler(
+ internal_usage_cache=InternalUsageCache(DualCache())
+ )
+ response = ModelResponse(
+ id="internal-origin-tpm",
+ object="chat.completion",
+ created=int(datetime.now().timestamp()),
+ model="gpt-4o-mini",
+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),
+ choices=[],
+ )
+
+ def _kwargs(metadata: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ "standard_logging_object": {
+ "metadata": {"user_api_key_hash": hash_token("sk-internal-origin")}
+ },
+ "litellm_params": {"metadata": metadata},
+ "model": "gpt-4o-mini",
+ }
+
+ charged = handler._build_success_event_pipeline_operations(
+ kwargs=_kwargs({}), response_obj=response, rate_limit_type="output"
+ )
+ skipped = handler._build_success_event_pipeline_operations(
+ kwargs=_kwargs({INTERNAL_CALL_ORIGIN_METADATA_KEY: "shadow_eval_judge"}),
+ response_obj=response,
+ rate_limit_type="output",
+ )
+
+ assert charged
+ assert skipped == []