diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260722200000_add_project_itpm_otpm_limit/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260722200000_add_project_itpm_otpm_limit/migration.sql new file mode 100644 index 000000000000..df3c351d3354 --- /dev/null +++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260722200000_add_project_itpm_otpm_limit/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable: Add ITPM/OTPM fields to LiteLLM_ProjectTable +ALTER TABLE "LiteLLM_ProjectTable" ADD COLUMN IF NOT EXISTS "model_itpm_limit" JSONB NOT NULL DEFAULT '{}'; +ALTER TABLE "LiteLLM_ProjectTable" ADD COLUMN IF NOT EXISTS "model_otpm_limit" JSONB NOT NULL DEFAULT '{}'; diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma index 23a9c086c736..d0baa6e01108 100644 --- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma +++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma @@ -169,6 +169,8 @@ model LiteLLM_ProjectTable { model_spend Json @default("{}") model_rpm_limit Json @default("{}") model_tpm_limit Json @default("{}") + model_itpm_limit Json @default("{}") + model_otpm_limit Json @default("{}") blocked Boolean @default(false) object_permission_id String? created_at DateTime @default(now()) @map("created_at") diff --git a/litellm/models/project.py b/litellm/models/project.py index 083c7ee3cc52..7bae5a00b0c0 100644 --- a/litellm/models/project.py +++ b/litellm/models/project.py @@ -27,6 +27,8 @@ class LiteLLM_ProjectTable(LiteLLMPydanticObjectBase): model_spend: Optional[dict] = None model_rpm_limit: Optional[dict] = None model_tpm_limit: Optional[dict] = None + model_itpm_limit: dict | None = None + model_otpm_limit: dict | None = None blocked: bool = False object_permission_id: Optional[str] = None created_by: Optional[str] = None @@ -39,3 +41,29 @@ class LiteLLM_ProjectTable(LiteLLMPydanticObjectBase): @property def is_blocked(self) -> bool: return self.blocked + + @property + def merged_metadata(self) -> dict: + """Return metadata dict with dedicated rate-limit columns merged in. + + The ``metadata`` JSONB column holds ad-hoc key/value pairs, while + ``model_itpm_limit``, ``model_otpm_limit``, ``model_rpm_limit``, and + ``model_tpm_limit`` are dedicated first-class columns. Callers that read + rate limits via ``project_metadata.get("model_itpm_limit")`` would + silently get ``None`` if we only exposed the raw ``metadata`` field, so + we merge the dedicated columns in here. Only non-None column values + are included, so a column left at its default None does not shadow any + legacy value stored in the ``metadata`` JSON blob. + """ + base: dict = self.metadata or {} + dedicated = { + k: v + for k, v in { + "model_itpm_limit": self.model_itpm_limit, + "model_otpm_limit": self.model_otpm_limit, + "model_rpm_limit": self.model_rpm_limit, + "model_tpm_limit": self.model_tpm_limit, + }.items() + if v is not None + } + return {**base, **dedicated} diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py index 7df725bf9659..34b6574363e5 100644 --- a/litellm/proxy/_types.py +++ b/litellm/proxy/_types.py @@ -2818,6 +2818,8 @@ class NewProjectRequest(LiteLLM_BudgetTable): models: List[str] = [] model_rpm_limit: Optional[dict] = None model_tpm_limit: Optional[dict] = None + model_itpm_limit: dict | None = None + model_otpm_limit: dict | None = None blocked: bool = False object_permission: Optional[LiteLLM_ObjectPermissionBase] = None @@ -2850,6 +2852,8 @@ class UpdateProjectRequest(LiteLLM_BudgetTable): models: Optional[List[str]] = None model_rpm_limit: Optional[dict] = None model_tpm_limit: Optional[dict] = None + model_itpm_limit: dict | None = None + model_otpm_limit: dict | None = None blocked: Optional[bool] = None budget_id: Optional[str] = None object_permission: Optional[LiteLLM_ObjectPermissionBase] = None @@ -3978,6 +3982,8 @@ class PassThroughEndpointLoggingTypedDict(TypedDict): LiteLLM_ManagementEndpoint_MetadataFields = [ "model_rpm_limit", "model_tpm_limit", + "model_itpm_limit", + "model_otpm_limit", "mcp_rpm_limit", "tag_rpm_limit", "rpm_limit_type", diff --git a/litellm/proxy/auth/auth_utils.py b/litellm/proxy/auth/auth_utils.py index ecb37e67c14a..73f6f912afc4 100644 --- a/litellm/proxy/auth/auth_utils.py +++ b/litellm/proxy/auth/auth_utils.py @@ -990,7 +990,7 @@ def get_key_model_tpm_limit( def get_model_rate_limit_from_metadata( user_api_key_dict: UserAPIKeyAuth, metadata_accessor_key: Literal["team_metadata", "organization_metadata", "project_metadata"], - rate_limit_key: Literal["model_rpm_limit", "model_tpm_limit"], + rate_limit_key: Literal["model_rpm_limit", "model_tpm_limit", "model_itpm_limit", "model_otpm_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) @@ -1077,6 +1077,22 @@ def get_project_model_tpm_limit( return None +def get_project_model_itpm_limit( + user_api_key_dict: UserAPIKeyAuth, +) -> dict[str, int] | None: + if user_api_key_dict.project_metadata: + return user_api_key_dict.project_metadata.get("model_itpm_limit") + return None + + +def get_project_model_otpm_limit( + user_api_key_dict: UserAPIKeyAuth, +) -> dict[str, int] | None: + if user_api_key_dict.project_metadata: + return user_api_key_dict.project_metadata.get("model_otpm_limit") + return None + + def custom_auth_common_checks_warning( *, custom_auth_configured: bool, diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py index 83a8a69511b7..c4a453c7ec2f 100644 --- a/litellm/proxy/auth/user_api_key_auth.py +++ b/litellm/proxy/auth/user_api_key_auth.py @@ -1378,7 +1378,7 @@ async def _user_api_key_auth_builder( proxy_logging_obj=proxy_logging_obj, ) if _jwt_project_obj is not None: - valid_token.project_metadata = _jwt_project_obj.metadata + valid_token.project_metadata = _jwt_project_obj.merged_metadata valid_token.project_alias = _jwt_project_obj.project_alias return cast(UserAPIKeyAuth, valid_token) @@ -1966,7 +1966,7 @@ async def _user_api_key_auth_builder( proxy_logging_obj=proxy_logging_obj, ) if _project_obj is not None: - valid_token.project_metadata = _project_obj.metadata + valid_token.project_metadata = _project_obj.merged_metadata valid_token.project_alias = _project_obj.project_alias global_proxy_spend = None @@ -2326,7 +2326,7 @@ async def _run_centralized_common_checks( ) if project_object is not None: - user_api_key_auth_obj.project_metadata = project_object.metadata + user_api_key_auth_obj.project_metadata = project_object.merged_metadata user_api_key_auth_obj.project_alias = project_object.project_alias skip_budget_checks = _should_skip_budget_checks( @@ -2960,7 +2960,7 @@ async def _run_post_custom_auth_checks( proxy_logging_obj=proxy_logging_obj, ) if _project_obj is not None: - valid_token.project_metadata = _project_obj.metadata + valid_token.project_metadata = _project_obj.merged_metadata valid_token.project_alias = _project_obj.project_alias return valid_token diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.py index 22ea9fe176a9..ce6acc050248 100644 --- a/litellm/proxy/hooks/parallel_request_limiter_v3.py +++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py @@ -44,7 +44,7 @@ ) from litellm.proxy.hooks.rate_limiter_utils import resolve_llm_provider_for_rate_limit from litellm.types.caching import RedisPipelineIncrementOperation -from litellm.types.llms.openai import BaseLiteLLMOpenAIResponseObject +from litellm.types.llms.openai import BaseLiteLLMOpenAIResponseObject, ResponseAPIUsage from litellm.types.utils import ( CallTypes, EmbeddingResponse, @@ -290,6 +290,26 @@ # (baseline floor) and to the smallest configured TPM limit (capped floor for # small per-tenant TPM caps). _TPM_FLOOR_FRACTION = 4 +# Both embeddings and the Responses API put their prompt in data["input"], +# but only embeddings have no output tokens. Every "is this an embedding" +# check on data["input"] must exclude these call types, or a Responses call +# gets misclassified as an embedding and skips output-token reservation/caps. +RESPONSES_API_CALL_TYPES = ("aresponses", "responses") +# litellm.token_counter has no per-type handling for "input_audio" content +# blocks (unlike images, which use use_default_image_token_count) -- it +# silently contributes 0 tokens for them. When the block carries a base64 +# payload, the estimate is derived from the decoded byte count; when the +# block is a reference without a payload (or the payload is missing), this +# flat per-block floor is used instead. +DEFAULT_AUDIO_TOKEN_ESTIMATE = int(os.getenv("LITELLM_DEFAULT_AUDIO_TOKEN_ESTIMATE", 300)) +# Conservative bytes-per-token assumption for size-based audio estimation: +# equivalent to 8 kHz mono PCM-16 (16 000 bytes/s) at 10 tokens/s. Choosing +# the lowest reasonable bitrate means we never under-reserve for higher- +# quality audio recorded at the same wall-clock duration. +_AUDIO_BYTES_PER_TOKEN = 1600 +# Per-block cap so a pathologically large or corrupt payload can't claim an +# unbounded reservation (~10 minutes of audio at 10 tokens/s). +_MAX_AUDIO_TOKENS_PER_BLOCK = 6_000 # Stash for the reserved-token count on the request data dict so success/ # failure callbacks can reconcile against the upfront reservation. TPM_RESERVED_TOKENS_KEY = "_litellm_tpm_reserved_tokens" @@ -307,6 +327,19 @@ # (e.g. async_log_failure_event firing after async_post_call_failure_hook) # does not double-refund. TPM_RESERVATION_RELEASED_KEY = "_litellm_tpm_reservation_released" +# Project-scoped ITPM/OTPM reservation stash, mirroring the TPM_RESERVED_* +# keys above but tracked separately since ITPM and OTPM are reserved from +# different estimates (input tokens vs. max_tokens) and reconciled against +# different actual-usage fields (prompt_tokens vs. completion_tokens). +ITPM_RESERVED_TOKENS_KEY = "_litellm_itpm_reserved_tokens" +ITPM_RESERVED_SCOPES_KEY = "_litellm_itpm_reserved_scopes" +OTPM_RESERVED_TOKENS_KEY = "_litellm_otpm_reserved_tokens" +OTPM_RESERVED_SCOPES_KEY = "_litellm_otpm_reserved_scopes" +# Descriptor "key" values for project-scoped ITPM/OTPM. Distinct from +# "model_per_project" (the combined-TPM descriptor) so both can be enforced +# on the same project+model simultaneously without colliding on cache keys. +PROJECT_ITPM_DESCRIPTOR_KEY = "model_per_project_itpm" +PROJECT_OTPM_DESCRIPTOR_KEY = "model_per_project_otpm" RATE_LIMIT_DESCRIPTORS_KEY = "_litellm_rate_limit_descriptors" # Pre-call RateLimitResponse stashed here so streaming success logging can # mirror ``x-ratelimit-*`` headers into the SLP. Streaming exits @@ -333,6 +366,10 @@ TPM_RESERVED_MODEL_KEY, TPM_RESERVED_SCOPES_KEY, TPM_RESERVATION_RELEASED_KEY, + ITPM_RESERVED_TOKENS_KEY, + ITPM_RESERVED_SCOPES_KEY, + OTPM_RESERVED_TOKENS_KEY, + OTPM_RESERVED_SCOPES_KEY, RATE_LIMIT_DESCRIPTORS_KEY, RATE_LIMIT_RESPONSE_KEY, MAX_PARALLEL_SLOT_ACQUIRED_KEY, @@ -418,6 +455,11 @@ def __init__( self.window_size = int(os.getenv("LITELLM_RATE_LIMIT_WINDOW_SIZE", 60)) + # project_id:model pairs already warned about model_itpm_limit/model_otpm_limit + # configured alongside model_tpm_limit, so the warning is logged once per pair + # rather than per request. + self._project_io_token_conflict_warned: set[str] = set() + # When disabled, TPM is enforced post-call from actual usage (pre-v1.82 # behavior) instead of reserving an estimated budget upfront, shedding # the extra per-request Redis Lua round-trip and the global-lock @@ -478,28 +520,110 @@ def _no_max_tokens_output_floor( return baseline return min(baseline, max(1, min_configured_tpm_limit // _TPM_FLOOR_FRACTION)) + @staticmethod + def _has_explicit_output_cap(data: dict) -> 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 ( + data.get("max_tokens") is not None + or data.get("max_completion_tokens") is not None + or data.get("max_output_tokens") is not None + ) + + @staticmethod + def _apply_implicit_output_cap( + data: dict, + min_configured_limit: int | None, + call_type: str | 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. + """ + capped_floor = _PROXY_MaxParallelRequestsHandler_v3._no_max_tokens_output_floor(min_configured_limit) + baseline_floor = DEFAULT_MAX_TOKENS_ESTIMATE // _TPM_FLOOR_FRACTION + is_embedding = data.get("input") is not None and call_type not in RESPONSES_API_CALL_TYPES + if ( + capped_floor >= baseline_floor + or _PROXY_MaxParallelRequestsHandler_v3._has_explicit_output_cap(data) + or is_embedding + ): + 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 + def _estimate_tokens_for_request( self, data: dict, model: Optional[str] = None, min_configured_tpm_limit: Optional[int] = None, + call_type: str | None = None, ) -> int: """ Estimate total tokens this request will consume so we can reserve them upfront (input + output budget): estimated = input_tokens + max_tokens. - Supports chat (messages), completions (prompt), and embeddings (input). + Supports chat (messages), completions (prompt), embeddings (input), + and the Responses API (also `input`, disambiguated from embeddings + via ``call_type``). + + ``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. + """ + 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, + ) + total_estimated = estimated_input_tokens + max_tokens_estimate + + verbose_proxy_logger.debug( + f"TPM reservation estimate: input={estimated_input_tokens}, " + f"max_tokens={max_tokens_estimate}, total={total_estimated}" + ) + + return total_estimated + + def _estimate_input_and_output_tokens( + self, + data: dict, + min_configured_tpm_limit: int | None = None, + call_type: str | 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. """ messages = data.get("messages") prompt = data.get("prompt") - input_text = data.get("input") # embeddings + input_text = data.get("input") # embeddings and Responses API match (messages, prompt, input_text): case (messages, _, _) if messages: @@ -517,13 +641,23 @@ def _estimate_tokens_for_request( estimated_input_tokens = max(1, total_chars // DEFAULT_CHARS_PER_TOKEN) if total_chars > 0 else 0 - explicit_max_tokens = data.get("max_tokens") or data.get("max_completion_tokens") + explicit_max_tokens = next( + ( + value + for value in (data.get("max_tokens"), data.get("max_completion_tokens"), data.get("max_output_tokens")) + if value is not None + ), + None, + ) + is_responses_call = call_type in RESPONSES_API_CALL_TYPES 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 + case (_, embeddings_input) if embeddings_input and not is_responses_call: + # Embeddings have no output tokens. The Responses API also + # puts its prompt in `input`, but it does have output tokens, + # so it's excluded here and falls through to the floor below. max_tokens_estimate = 0 case _ if total_chars == 0: # Fully contentless request (no messages, prompt, or input). @@ -542,15 +676,7 @@ def _estimate_tokens_for_request( output_floor = self._no_max_tokens_output_floor(min_configured_tpm_limit) max_tokens_estimate = max(estimated_input_tokens, output_floor) - total_estimated = estimated_input_tokens + max_tokens_estimate - - verbose_proxy_logger.debug( - f"TPM reservation estimate: input={estimated_input_tokens}, " - f"max_tokens={max_tokens_estimate} (explicit={explicit_max_tokens is not None}), " - f"total={total_estimated}" - ) - - return total_estimated + return estimated_input_tokens, max_tokens_estimate def _is_redis_cluster(self) -> bool: """ @@ -1561,9 +1687,15 @@ async def reserve_tpm_tokens( TPM-only descriptor/increment list and delegates the all-or-nothing atomicity (Lua on Redis, asyncio-locked DualCache otherwise) to the shared primitive. + + Excludes project ITPM/OTPM descriptors -- those are reserved + separately (different estimate per bucket) via ``reserve_io_tokens``. """ tpm_descriptors: List[RateLimitDescriptor] = [ - d for d in descriptors if (d.get("rate_limit") or {}).get("tokens_per_unit") is not None + d + for d in descriptors + if d["key"] not in (PROJECT_ITPM_DESCRIPTOR_KEY, PROJECT_OTPM_DESCRIPTOR_KEY) + and (d.get("rate_limit") or {}).get("tokens_per_unit") is not None ] if not tpm_descriptors: return RateLimitResponse(overall_code="OK", statuses=[]) @@ -1577,6 +1709,100 @@ async def reserve_tpm_tokens( parent_otel_span=parent_otel_span, ) + async def _refund_reserved_tokens( + self, + scopes: list[tuple[str, str]], + amount: int, + parent_otel_span: Span | None = None, + ) -> None: + """ + Directly decrement previously-reserved token counters for ``scopes`` + by ``amount``. Used to roll back a reservation that already + succeeded once a *different* bucket in the same request turns out to + be over its limit (e.g. ITPM reserved fine, OTPM then hits its + limit -- the ITPM reservation must not be left inflated). + """ + if amount <= 0 or not scopes: + return + pipeline_operations = [ + RedisPipelineIncrementOperation( + key=self.create_rate_limit_keys(scope_key, scope_value, "tokens"), + increment_value=-amount, + ttl=self.window_size, + ) + for scope_key, scope_value in scopes + ] + await self.async_increment_tokens_with_ttl_preservation( + pipeline_operations=pipeline_operations, + parent_otel_span=parent_otel_span, + ) + + async def reserve_io_tokens( + self, + descriptors: list[RateLimitDescriptor], + estimated_input_tokens: int, + estimated_output_tokens: int, + parent_otel_span: Span | None = None, + ) -> tuple[RateLimitResponse, int, int]: + """ + Reserve ``estimated_input_tokens`` against project ITPM descriptors + and ``estimated_output_tokens`` against project OTPM descriptors. + + ITPM and OTPM are reserved from different-sized estimates, so unlike + same-size TPM descriptors they can't share a single + ``atomic_check_and_increment_by_n`` call -- each bucket gets its own + all-or-nothing atomic call. If the OTPM reservation is over limit + after ITPM already succeeded, the ITPM reservation this call made is + rolled back before returning, so a partial reservation never leaks. + + Returns ``(response, itpm_reserved, otpm_reserved)`` -- the latter two + are the amounts actually reserved (0 if that bucket wasn't + configured, or if the reservation failed), for the caller to stash + for post-call reconciliation. + """ + itpm_descriptors = [d for d in descriptors if d["key"] == PROJECT_ITPM_DESCRIPTOR_KEY] + otpm_descriptors = [d for d in descriptors if d["key"] == PROJECT_OTPM_DESCRIPTOR_KEY] + + if not itpm_descriptors and not otpm_descriptors: + return RateLimitResponse(overall_code="OK", statuses=[]), 0, 0 + + statuses: list[RateLimitStatus] = [] + itpm_reserved = 0 + + if itpm_descriptors: + itpm_response = await self.atomic_check_and_increment_by_n( + descriptors=itpm_descriptors, + increments=[{"tokens": estimated_input_tokens} for _ in itpm_descriptors], + parent_otel_span=parent_otel_span, + ) + if itpm_response["overall_code"] == "OVER_LIMIT": + return itpm_response, 0, 0 + itpm_reserved = estimated_input_tokens + statuses.extend(itpm_response["statuses"]) + + if otpm_descriptors: + otpm_response = await self.atomic_check_and_increment_by_n( + descriptors=otpm_descriptors, + increments=[{"tokens": estimated_output_tokens} for _ in otpm_descriptors], + parent_otel_span=parent_otel_span, + ) + if otpm_response["overall_code"] == "OVER_LIMIT": + if itpm_reserved > 0: + await self._refund_reserved_tokens( + scopes=[(d["key"], d["value"]) for d in itpm_descriptors], + amount=itpm_reserved, + parent_otel_span=parent_otel_span, + ) + return otpm_response, 0, 0 + statuses.extend(otpm_response["statuses"]) + return ( + RateLimitResponse(overall_code="OK", statuses=statuses), + itpm_reserved, + estimated_output_tokens, + ) + + return RateLimitResponse(overall_code="OK", statuses=statuses), itpm_reserved, 0 + def create_organization_rate_limit_descriptor( self, user_api_key_dict: UserAPIKeyAuth, requested_model: Optional[str] = None ) -> List[RateLimitDescriptor]: @@ -2275,6 +2501,86 @@ def _add_project_model_rate_limit_descriptor_from_metadata( ) ) + def _warn_project_io_token_and_tpm_coexist_once( + self, + user_api_key_dict: UserAPIKeyAuth, + requested_model: str, + ) -> None: + """Log once per project:model pair when model_itpm_limit/model_otpm_limit + is configured alongside model_tpm_limit. Both are enforced (mirrors the + deployment-level itpm/otpm + tpm/rpm coexistence behavior in + ``model_rate_limit_check.py``); this is purely a heads-up warning. + """ + tpm_limit_for_project_model = ( + get_model_rate_limit_from_metadata(user_api_key_dict, "project_metadata", "model_tpm_limit") or {} + ) + if requested_model not in tpm_limit_for_project_model: + return + warn_key = f"{user_api_key_dict.project_id}:{requested_model}" + if warn_key in self._project_io_token_conflict_warned: + return + self._project_io_token_conflict_warned.add(warn_key) + verbose_proxy_logger.warning( + f"Project '{user_api_key_dict.project_id}' configures model_itpm_limit/model_otpm_limit " + f"alongside model_tpm_limit for model '{requested_model}'; both limit types are enforced" + ) + + def _add_project_io_token_rate_limit_descriptors_from_metadata( + self, + user_api_key_dict: UserAPIKeyAuth, + requested_model: str | None, + descriptors: list[RateLimitDescriptor], + ) -> None: + """Add project-scoped ITPM/OTPM descriptors from project_metadata. + + Enforced independently of, and alongside, the combined ``model_per_project`` + TPM descriptor above -- these give Bedrock Mantle-style separate input/output + token quotas at the project level. + """ + if requested_model is None or user_api_key_dict.project_id is None: + return + + itpm_limit_for_project_model = ( + get_model_rate_limit_from_metadata(user_api_key_dict, "project_metadata", "model_itpm_limit") or {} + ) + otpm_limit_for_project_model = ( + get_model_rate_limit_from_metadata(user_api_key_dict, "project_metadata", "model_otpm_limit") or {} + ) + + model_itpm_limit = itpm_limit_for_project_model.get(requested_model) + model_otpm_limit = otpm_limit_for_project_model.get(requested_model) + + if model_itpm_limit is None and model_otpm_limit is None: + return + + self._warn_project_io_token_and_tpm_coexist_once(user_api_key_dict, requested_model) + + descriptor_value = f"{user_api_key_dict.project_id}:{requested_model}" + if model_itpm_limit is not None: + descriptors.append( + RateLimitDescriptor( + key=PROJECT_ITPM_DESCRIPTOR_KEY, + value=descriptor_value, + rate_limit={ + "requests_per_unit": None, + "tokens_per_unit": model_itpm_limit, + "window_size": self.window_size, + }, + ) + ) + if model_otpm_limit is not None: + descriptors.append( + RateLimitDescriptor( + key=PROJECT_OTPM_DESCRIPTOR_KEY, + value=descriptor_value, + rate_limit={ + "requests_per_unit": None, + "tokens_per_unit": model_otpm_limit, + "window_size": self.window_size, + }, + ) + ) + def _handle_rate_limit_error( self, response: RateLimitResponse, @@ -2319,6 +2625,274 @@ def _handle_rate_limit_error( llm_provider=llm_provider, ) + @staticmethod + def _estimate_audio_block_tokens(block: dict) -> int: + """ + Token estimate for one ``input_audio`` content block. + + When the block carries a base64 ``data`` payload, the estimate comes + from the decoded byte count (``len(b64) * 3 // 4 // _AUDIO_BYTES_PER_TOKEN``), + assuming the lowest reasonable audio bitrate so we never under-reserve + for higher-quality recordings of the same duration. The result is + capped at ``_MAX_AUDIO_TOKENS_PER_BLOCK`` to prevent a pathologically + large payload from claiming an unbounded reservation. + + When no payload is present (reference-only block or missing ``data``), + falls back to ``DEFAULT_AUDIO_TOKEN_ESTIMATE``. + """ + b64_data = (block.get("input_audio") or {}).get("data") + if b64_data and isinstance(b64_data, str): + decoded_bytes = len(b64_data) * 3 // 4 + return min( + max(decoded_bytes // _AUDIO_BYTES_PER_TOKEN, DEFAULT_AUDIO_TOKEN_ESTIMATE), + _MAX_AUDIO_TOKENS_PER_BLOCK, + ) + return DEFAULT_AUDIO_TOKEN_ESTIMATE + + @classmethod + def _estimate_audio_content_tokens(cls, messages: Any) -> int: + """ + Sum of per-block audio token estimates across all ``messages``. + Returns 0 when there are no ``input_audio`` blocks, which the caller + uses to skip the (relatively expensive) strip pass. + """ + if not isinstance(messages, list): + return 0 + total = 0 + for message in messages: + content = message.get("content") if isinstance(message, dict) else None + if not isinstance(content, list): + continue + total += sum( + cls._estimate_audio_block_tokens(block) + for block in content + if isinstance(block, dict) and block.get("type") == "input_audio" + ) + return total + + @staticmethod + def _strip_audio_content_blocks(messages: Any) -> Any: + """ + Drop ``input_audio`` content blocks before passing ``messages`` to + ``token_counter``, which raises ``ValueError`` on them (no per-type + handling, unlike images). The audio contribution is added back + separately via ``DEFAULT_AUDIO_TOKEN_ESTIMATE`` so the rest of the + message (text/images/tools) still gets counted accurately instead of + the whole call falling back to the cheap char-count estimate. + """ + if not isinstance(messages, list): + return messages + sanitized = [] + for message in messages: + if not isinstance(message, dict): + sanitized.append(message) + continue + content = message.get("content") + if not isinstance(content, list): + sanitized.append(message) + continue + filtered_content = [ + block for block in content if not (isinstance(block, dict) and block.get("type") == "input_audio") + ] + sanitized.append({**message, "content": filtered_content}) + return sanitized + + @staticmethod + def _responses_input_to_chat_messages(data: dict) -> list: + """ + Convert a Responses API ``input`` (string or list of input items) into + chat-completion-style messages via the standard LiteLLM transformation + (the same one guardrails use, e.g. ``purview_dlp.py``), so multimodal + ``input_image``/``input_text`` content blocks get counted by + ``token_counter``'s ``messages`` path instead of silently contributing + zero tokens via its ``text`` path, which only joins plain strings. + """ + from litellm.responses.litellm_completion_transformation.transformation import ( + LiteLLMCompletionResponsesConfig, + ) + + return LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages( + input=data.get("input") or "", + responses_api_request=data, + ) + + def _estimate_precise_input_tokens(self, data: dict, model: str | None, call_type: str | None = None) -> int: + """ + Model-aware input token estimate for the project ITPM reservation, + using ``litellm.token_counter`` -- the same approach the + deployment-level itpm/otpm check uses in + ``io_token_rate_limit_check.py``. Unlike the cheap char-count + estimate the combined-TPM path uses, this accounts for image/tool + content and derives per-``input_audio``-block estimates from the + base64 payload size (assuming the lowest reasonable bitrate so + longer recordings always reserve proportionally more), so a burst + of multimodal, tool-heavy, or audio-heavy requests can't each + reserve only the one-token floor and blow past ITPM before + post-call reconciliation catches up. + + For the Responses API, ``input`` is converted to chat messages first + (via ``_responses_input_to_chat_messages``) so its own multimodal + content blocks are counted the same way; ``token_counter``'s ``text`` + argument can only see plain strings in a list, not content blocks. + + Falls back to the cheap char-count estimate if ``token_counter`` + can't resolve a tokenizer for this model (e.g. an unrecognized + custom model name) or otherwise raises -- the audio add-on still + applies on top of the fallback. + """ + from litellm import token_counter + + messages = data.get("messages") + if messages is None and call_type in RESPONSES_API_CALL_TYPES and data.get("input") is not None: + messages = self._responses_input_to_chat_messages(data) + + audio_token_estimate = self._estimate_audio_content_tokens(messages) + countable_messages = self._strip_audio_content_blocks(messages) if audio_token_estimate > 0 else messages + + try: + estimate = max( + 0, + int( + token_counter( + model=model or "", + messages=countable_messages, + text=None if countable_messages is not None else (data.get("prompt") or data.get("input")), + tools=data.get("tools"), + tool_choice=data.get("tool_choice"), + use_default_image_token_count=True, + ) + ), + ) + return estimate + audio_token_estimate + except Exception: # noqa: BLE001 - any tokenizer/model-resolution/transform failure degrades to the cheap estimate, never a 500 + estimated_input_tokens, _ = self._estimate_input_and_output_tokens(data=data, call_type=call_type) + return estimated_input_tokens + audio_token_estimate + + async def _reserve_project_io_tokens_or_raise( + self, + descriptors: list[RateLimitDescriptor], + data: dict, + requested_model: str | None, + user_api_key_dict: UserAPIKeyAuth, + tpm_reservation_scopes: list[tuple[str, str]], + tpm_reservation_amount: int, + call_type: str | None = None, + ) -> None: + """ + Reserve project-scoped ITPM/OTPM tokens (Bedrock Mantle-style + separate input/output token buckets), independently of -- and, when + both are configured, in addition to -- the combined-TPM reservation + the caller already made. Raises (via ``_handle_rate_limit_error``) on + an over-limit reservation, first rolling back the combined-TPM + reservation named by ``tpm_reservation_scopes``/``tpm_reservation_amount`` + if one was made, so a partial reservation never leaks. + """ + io_token_descriptors = [ + d for d in descriptors if d["key"] in (PROJECT_ITPM_DESCRIPTOR_KEY, PROJECT_OTPM_DESCRIPTOR_KEY) + ] + if not io_token_descriptors: + return + + configured_otpm_limits = [ + int(v) + for d in io_token_descriptors + if d["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 = min(configured_otpm_limits) if configured_otpm_limits else None + + _, estimated_output_tokens = self._estimate_input_and_output_tokens( + data=data, + min_configured_tpm_limit=min_configured_otpm_limit, + call_type=call_type, + ) + estimated_input_tokens = self._estimate_precise_input_tokens( + data=data, model=requested_model, call_type=call_type + ) + estimated_input_tokens = max(estimated_input_tokens, 1) + if not self._has_explicit_output_cap(data): + estimated_output_tokens = max(estimated_output_tokens, 1) + + # Hard-cap generation length so an unbounded response can't overshoot + # the OTPM budget before post-call reconciliation runs, mirroring the + # combined-TPM floor cap in the caller. + self._apply_implicit_output_cap( + data=data, + min_configured_limit=min_configured_otpm_limit, + call_type=call_type, + ) + + io_response, itpm_reserved, otpm_reserved = await self.reserve_io_tokens( + descriptors=io_token_descriptors, + estimated_input_tokens=estimated_input_tokens, + estimated_output_tokens=estimated_output_tokens, + parent_otel_span=user_api_key_dict.parent_otel_span, + ) + + if io_response["overall_code"] == "OVER_LIMIT": + # A combined-TPM reservation may have already succeeded above for + # this same request; refund it too, or its counter stays inflated + # until the window's TTL expires. Mark it released so the + # ProxyRateLimitError we're about to raise doesn't get refunded + # a second time when async_post_call_failure_hook sees the same + # (still-stashed) reservation and refunds it again. + if tpm_reservation_amount > 0: + await self._refund_reserved_tokens( + scopes=tpm_reservation_scopes, + amount=tpm_reservation_amount, + parent_otel_span=user_api_key_dict.parent_otel_span, + ) + self._mark_reservation_released(data) + acquisition = self._get_parallel_slot_acquisition(kwargs=data) + if acquisition is not None: + await self._release_parallel_request_slots( + acquisition=acquisition, + parent_otel_span=user_api_key_dict.parent_otel_span, + ) + self._clear_parallel_slot_marker(data) + self._handle_rate_limit_error( + response=io_response, + descriptors=descriptors, + requested_model=requested_model, + ) + + if itpm_reserved > 0: + itpm_scopes = [ + (d["key"], d["value"]) for d in io_token_descriptors if d["key"] == PROJECT_ITPM_DESCRIPTOR_KEY + ] + self._stash_value_in_metadata_channels(data=data, key=ITPM_RESERVED_TOKENS_KEY, value=itpm_reserved) + self._stash_value_in_metadata_channels( + data=data, + key=ITPM_RESERVED_SCOPES_KEY, + value=[[k, v] for k, v in itpm_scopes], + ) + if otpm_reserved > 0: + otpm_scopes = [ + (d["key"], d["value"]) for d in io_token_descriptors if d["key"] == PROJECT_OTPM_DESCRIPTOR_KEY + ] + self._stash_value_in_metadata_channels(data=data, key=OTPM_RESERVED_TOKENS_KEY, value=otpm_reserved) + self._stash_value_in_metadata_channels( + data=data, + key=OTPM_RESERVED_SCOPES_KEY, + value=[[k, v] for k, v in otpm_scopes], + ) + + stored_response = data.get("litellm_proxy_rate_limit_response") + if isinstance(stored_response, dict): + stored_response.setdefault("statuses", []).extend(io_response["statuses"]) + elif io_response["statuses"]: + data["litellm_proxy_rate_limit_response"] = io_response + self._stash_value_in_metadata_channels( + data=data, + key=RATE_LIMIT_RESPONSE_KEY, + value=io_response, + ) + + verbose_proxy_logger.debug( + f"ITPM/OTPM tokens reserved: itpm={itpm_reserved}, otpm={otpm_reserved} for model {requested_model}" + ) + async def async_pre_call_hook( self, user_api_key_dict: UserAPIKeyAuth, @@ -2396,6 +2970,11 @@ async def async_pre_call_hook( requested_model=requested_model, descriptors=descriptors, ) + self._add_project_io_token_rate_limit_descriptors_from_metadata( + user_api_key_dict=user_api_key_dict, + requested_model=requested_model, + descriptors=descriptors, + ) # Org Level Rate Limits descriptors.extend(self.create_organization_rate_limit_descriptor(user_api_key_dict, requested_model)) @@ -2464,28 +3043,33 @@ async def async_pre_call_hook( configured_tpm_limits = [ int(v) for d in descriptors + if d["key"] not in (PROJECT_ITPM_DESCRIPTOR_KEY, PROJECT_OTPM_DESCRIPTOR_KEY) for v in [(d.get("rate_limit") or {}).get("tokens_per_unit")] if v is not None ] has_tpm_limits = bool(configured_tpm_limits) + # Populated on a successful combined-TPM reservation below, so the + # project ITPM/OTPM block further down can roll it back if a + # different bucket in the same request subsequently hits its + # limit. Stays empty/0 whenever no combined-TPM reservation was + # made (or it was over limit, in which case execution never + # reaches the ITPM/OTPM block -- `_handle_rate_limit_error` raises). + tpm_reservation_scopes: list[tuple[str, str]] = [] + tpm_reservation_amount = 0 + if has_tpm_limits and self.tpm_reservation_enabled: min_configured_tpm_limit = 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 = self._no_max_tokens_output_floor(min_configured_tpm_limit) - baseline_floor = DEFAULT_MAX_TOKENS_ESTIMATE // _TPM_FLOOR_FRACTION - has_explicit_max_tokens = ( - data.get("max_tokens") is not None or data.get("max_completion_tokens") is not None - ) - is_embedding = data.get("input") is not None - if capped_floor < baseline_floor and not has_explicit_max_tokens and not is_embedding: - data["max_tokens"] = capped_floor + # 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, + ) # Floor at 1 token so contentless requests (/responses, # tool-call continuations, empty messages) still flow @@ -2499,6 +3083,7 @@ async def async_pre_call_hook( data=data, model=requested_model, min_configured_tpm_limit=min_configured_tpm_limit, + call_type=call_type, ), 1, ) @@ -2535,8 +3120,11 @@ async def async_pre_call_hook( reserved_scopes: List[Tuple[str, str]] = [ (d["key"], d["value"]) for d in descriptors - if (d.get("rate_limit") or {}).get("tokens_per_unit") is not None + if d["key"] not in (PROJECT_ITPM_DESCRIPTOR_KEY, PROJECT_OTPM_DESCRIPTOR_KEY) + and (d.get("rate_limit") or {}).get("tokens_per_unit") is not None ] + tpm_reservation_scopes = reserved_scopes + tpm_reservation_amount = estimated_tokens self._stash_reservation_in_data( data=data, estimated_tokens=estimated_tokens, @@ -2564,6 +3152,16 @@ async def async_pre_call_hook( verbose_proxy_logger.debug(f"TPM tokens reserved: {estimated_tokens} for model {requested_model}") + await self._reserve_project_io_tokens_or_raise( + descriptors=descriptors, + data=data, + requested_model=requested_model, + user_api_key_dict=user_api_key_dict, + tpm_reservation_scopes=tpm_reservation_scopes, + tpm_reservation_amount=tpm_reservation_amount, + call_type=call_type, + ) + # Defense-in-depth: scrub any stash key that escaped onto data # top-level (stale cache hit, router pass, test fixture) before the # body is forwarded to the provider. @@ -2880,6 +3478,158 @@ def _get_reserved_scopes_from_kwargs( scopes.add((entry[0], entry[1])) return scopes + @classmethod + def _get_reserved_itpm_tokens_from_kwargs( + cls, + kwargs: Any, + standard_logging_metadata: dict[str, Any] | None = None, + ) -> int: + candidate = cls._lookup_stashed_value(kwargs, standard_logging_metadata, ITPM_RESERVED_TOKENS_KEY) + try: + return int(candidate or 0) + except (TypeError, ValueError): + return 0 + + @classmethod + def _get_reserved_otpm_tokens_from_kwargs( + cls, + kwargs: Any, + standard_logging_metadata: dict[str, Any] | None = None, + ) -> int: + candidate = cls._lookup_stashed_value(kwargs, standard_logging_metadata, OTPM_RESERVED_TOKENS_KEY) + try: + return int(candidate or 0) + except (TypeError, ValueError): + return 0 + + @classmethod + def _get_reserved_itpm_scopes_from_kwargs( + cls, + kwargs: Any, + standard_logging_metadata: dict[str, Any] | None = None, + ) -> set[tuple[str, str]]: + return cls._narrow_reserved_scopes( + cls._lookup_stashed_value(kwargs, standard_logging_metadata, ITPM_RESERVED_SCOPES_KEY) + ) + + @classmethod + def _get_reserved_otpm_scopes_from_kwargs( + cls, + kwargs: Any, + standard_logging_metadata: dict[str, Any] | None = None, + ) -> set[tuple[str, str]]: + return cls._narrow_reserved_scopes( + cls._lookup_stashed_value(kwargs, standard_logging_metadata, OTPM_RESERVED_SCOPES_KEY) + ) + + @staticmethod + def _narrow_reserved_scopes(candidate: Any) -> set[tuple[str, str]]: + if not isinstance(candidate, list): + return set() + scopes: set[tuple[str, str]] = set() + for entry in candidate: + if ( + isinstance(entry, (list, tuple)) + and len(entry) == 2 + and isinstance(entry[0], str) + and isinstance(entry[1], str) + ): + scopes.add((entry[0], entry[1])) + return scopes + + def _resolve_io_token_reconcile_usage( + self, + response_obj: Any, + ) -> tuple[int, int, bool]: + """ + Resolve ``(billable_input_tokens, completion_tokens, usage_resolved)`` + for ITPM/OTPM reconciliation. Cache-read tokens are excluded from + billable input -- Bedrock Mantle doesn't count them toward ITPM -- + but they're untouched everywhere else (cost/usage logging still sees + the full prompt token count). + """ + usage: Any | None = None + if isinstance( + response_obj, + (ModelResponse, EmbeddingResponse, TextCompletionResponse, BaseLiteLLMOpenAIResponseObject), + ): + usage = getattr(response_obj, "usage", None) + + if isinstance(usage, Usage): + prompt_tokens = usage.prompt_tokens or 0 + completion_tokens = usage.completion_tokens or 0 + cached_tokens = 0 + if usage.prompt_tokens_details is not None: + cached_tokens = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0 + elif isinstance(usage, ResponseAPIUsage): + # Responses API usage uses input_tokens/output_tokens instead of + # prompt_tokens/completion_tokens. + prompt_tokens = usage.input_tokens or 0 + completion_tokens = usage.output_tokens or 0 + cached_tokens = 0 + if usage.input_tokens_details is not None: + cached_tokens = usage.input_tokens_details.cached_tokens or 0 + elif isinstance(usage, dict): + prompt_tokens = usage.get("prompt_tokens", 0) or 0 + completion_tokens = usage.get("completion_tokens", 0) or 0 + prompt_details = usage.get("prompt_tokens_details") or {} + cached_tokens = (prompt_details.get("cached_tokens", 0) or 0) if isinstance(prompt_details, dict) else 0 + else: + return 0, 0, False + + return max(0, prompt_tokens - cached_tokens), completion_tokens, True + + def _build_io_token_reservation_ops( + self, + kwargs: Any, + response_obj: Any, + ) -> list["RedisPipelineIncrementOperation"]: + """ + Reconcile project ITPM/OTPM reservations to actual usage on success: + ITPM to billable input tokens, OTPM to actual completion tokens. + Reuses ``_build_reservation_aware_tpm_ops``'s delta pattern -- ITPM/OTPM + are stored in the same ":tokens" cache bucket as combined TPM, just + under distinct scope keys, so the reservation-aware increment math is + identical; only the usage fields being reconciled against differ. + """ + standard_logging_object = kwargs.get("standard_logging_object") or {} + standard_logging_metadata = standard_logging_object.get("metadata") or {} + + itpm_reserved = self._get_reserved_itpm_tokens_from_kwargs(kwargs, standard_logging_metadata) + otpm_reserved = self._get_reserved_otpm_tokens_from_kwargs(kwargs, standard_logging_metadata) + if itpm_reserved <= 0 and otpm_reserved <= 0: + return [] + + billable_input, completion_tokens, usage_resolved = self._resolve_io_token_reconcile_usage(response_obj) + if not usage_resolved: + # Usage missing (e.g. a response the SDK couldn't parse) -- keep + # the reservation rather than guess; it self-expires at the + # window TTL instead of drifting the counter on a bad guess. + return [] + + ops: list[RedisPipelineIncrementOperation] = [] + if itpm_reserved > 0: + itpm_scopes = self._get_reserved_itpm_scopes_from_kwargs(kwargs, standard_logging_metadata) + ops.extend( + self._build_reservation_aware_tpm_ops( + targets=list(itpm_scopes), + reserved_scopes=itpm_scopes, + actual_tokens=billable_input, + reserved_tokens=itpm_reserved, + ) + ) + if otpm_reserved > 0: + otpm_scopes = self._get_reserved_otpm_scopes_from_kwargs(kwargs, standard_logging_metadata) + ops.extend( + self._build_reservation_aware_tpm_ops( + targets=list(otpm_scopes), + reserved_scopes=otpm_scopes, + actual_tokens=completion_tokens, + reserved_tokens=otpm_reserved, + ) + ) + return ops + @classmethod def _is_reservation_released( cls, @@ -3175,6 +3925,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti response_obj=response_obj, rate_limit_type=rate_limit_type, ) + pipeline_operations.extend(self._build_io_token_reservation_ops(kwargs=kwargs, response_obj=response_obj)) if pipeline_operations: await self.async_increment_tokens_with_ttl_preservation( @@ -3358,12 +4109,43 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti ) ) + # Refund project ITPM/OTPM reservations the same way -- full + # refund, since a failed call has no billable usage to reconcile + # against. + itpm_reserved = ( + 0 if already_released else self._get_reserved_itpm_tokens_from_kwargs(kwargs, standard_logging_metadata) + ) + if itpm_reserved > 0: + itpm_scopes = self._get_reserved_itpm_scopes_from_kwargs(kwargs, standard_logging_metadata) + pipeline_operations.extend( + self._build_reservation_aware_tpm_ops( + targets=list(itpm_scopes), + reserved_scopes=itpm_scopes, + actual_tokens=0, + reserved_tokens=itpm_reserved, + ) + ) + + otpm_reserved = ( + 0 if already_released else self._get_reserved_otpm_tokens_from_kwargs(kwargs, standard_logging_metadata) + ) + if otpm_reserved > 0: + otpm_scopes = self._get_reserved_otpm_scopes_from_kwargs(kwargs, standard_logging_metadata) + pipeline_operations.extend( + self._build_reservation_aware_tpm_ops( + targets=list(otpm_scopes), + reserved_scopes=otpm_scopes, + actual_tokens=0, + reserved_tokens=otpm_reserved, + ) + ) + if pipeline_operations: await self.internal_usage_cache.dual_cache.async_increment_cache_pipeline( increment_list=pipeline_operations, litellm_parent_otel_span=litellm_parent_otel_span, ) - if reserved_tokens > 0: + if reserved_tokens > 0 or itpm_reserved > 0 or otpm_reserved > 0: self._mark_reservation_released(kwargs) except Exception as e: verbose_proxy_logger.exception(f"Error in rate limit failure event: {str(e)}") @@ -3374,29 +4156,68 @@ async def async_release_max_parallel_requests_on_disconnect( request_data: dict | None = None, ) -> None: """ - Release the api-key ``max_parallel_requests`` slot that - ``async_pre_call_hook`` acquired, for a request that ended without - either logging callback firing. + Release the api-key ``max_parallel_requests`` slot and any stashed + ITPM/OTPM token reservations for a request that ended without either + logging callback firing. The slot is normally released by ``async_log_success_event`` (natural stream completion) or ``async_log_failure_event`` (LLM error). When a client cancels a stream mid-flight, the cancellation surfaces as ``asyncio.CancelledError`` / ``GeneratorExit`` and neither callback runs, so without this the slot leaks per cancelled stream until its - TTL prunes it. ``request_data`` carries the stashed acquisition; - its presence (not the key object's current max_parallel_requests - configuration, which can change mid-request) decides whether there - is anything to release. + TTL prunes it. The same lifecycle gap applies to ITPM/OTPM + reservations: they stay inflated until the window TTL, letting a + caller repeatedly cancel streams to exhaust the project's quota. + + ``request_data`` carries the stashed acquisition and reservation + amounts; their presence decides whether there is anything to release. """ acquisition = self._get_parallel_slot_acquisition(kwargs=request_data) - if acquisition is None: + if acquisition is not None: + await self._release_parallel_request_slots( + acquisition=acquisition, + parent_otel_span=None, + ) + self._clear_parallel_slot_marker(request_data) + + if self._is_reservation_released(kwargs=request_data): return - await self._release_parallel_request_slots( - acquisition=acquisition, - parent_otel_span=None, - ) - self._clear_parallel_slot_marker(request_data) + try: + itpm_reserved = self._get_reserved_itpm_tokens_from_kwargs(kwargs=request_data) + otpm_reserved = self._get_reserved_otpm_tokens_from_kwargs(kwargs=request_data) + if itpm_reserved <= 0 and otpm_reserved <= 0: + return + + pipeline_operations: List[RedisPipelineIncrementOperation] = [] + if itpm_reserved > 0: + itpm_scopes = self._get_reserved_itpm_scopes_from_kwargs(kwargs=request_data) + pipeline_operations.extend( + self._build_reservation_aware_tpm_ops( + targets=list(itpm_scopes), + reserved_scopes=itpm_scopes, + actual_tokens=0, + reserved_tokens=itpm_reserved, + ) + ) + if otpm_reserved > 0: + otpm_scopes = self._get_reserved_otpm_scopes_from_kwargs(kwargs=request_data) + pipeline_operations.extend( + self._build_reservation_aware_tpm_ops( + targets=list(otpm_scopes), + reserved_scopes=otpm_scopes, + actual_tokens=0, + reserved_tokens=otpm_reserved, + ) + ) + if pipeline_operations: + await self.internal_usage_cache.dual_cache.async_increment_cache_pipeline( + increment_list=pipeline_operations, + litellm_parent_otel_span=user_api_key_dict.parent_otel_span, + ) + self._mark_reservation_released(request_data) + except Exception as e: # noqa: BLE001 - disconnect cleanup must never raise into the caller + verbose_proxy_logger.exception(f"Error refunding IO token reservations on disconnect: {str(e)}") async def async_post_call_success_hook(self, data: dict, user_api_key_dict: UserAPIKeyAuth, response): """ @@ -3445,17 +4266,18 @@ async def async_post_call_failure_hook( traceback_str: Optional[str] = None, ) -> None: """ - Release the parallel-request slot and any TPM reservation when the - request is rejected after the pre-call hook acquired them but before - the LLM call ran (e.g. a downstream guardrail/auth hook raised). - Without this, those resources are stranded — async_log_failure_event - is a litellm completion-level callback and never fires for proxy-side - rejections, so a leaked slot would occupy the gauge for the full - PARALLEL_REQUEST_SLOT_TTL_SECONDS. + Release the parallel-request slot and any TPM/ITPM/OTPM reservation + when the request is rejected after the pre-call hook acquired them + but before the LLM call ran (e.g. a downstream guardrail/auth hook + raised). Without this, those resources are stranded — + async_log_failure_event is a litellm completion-level callback and + never fires for proxy-side rejections, so a leaked slot would occupy + the gauge for the full PARALLEL_REQUEST_SLOT_TTL_SECONDS. Idempotent: the slot release clears the acquisition marker (and slot - removal is a no-op ZREM on a second run), and the TPM refund is - guarded by TPM_RESERVATION_RELEASED_KEY — if both this hook and + removal is a no-op ZREM on a second run), and the reservation refund + is guarded by TPM_RESERVATION_RELEASED_KEY (shared across the + TPM/ITPM/OTPM buckets) — if both this hook and async_log_failure_event end up running in the same flow, only the first release/refund applies. """ @@ -3471,36 +4293,70 @@ async def async_post_call_failure_hook( if self._is_reservation_released(kwargs=request_data): return reserved_tokens = self._get_reserved_tokens_from_kwargs(kwargs=request_data) - if reserved_tokens <= 0: + itpm_reserved = self._get_reserved_itpm_tokens_from_kwargs(kwargs=request_data) + otpm_reserved = self._get_reserved_otpm_tokens_from_kwargs(kwargs=request_data) + if reserved_tokens <= 0 and itpm_reserved <= 0 and otpm_reserved <= 0: return - # Refund directly against the descriptors we reserved against — - # the pre-call hook stashes them in the request-data metadata - # channels before success/failure callbacks run. - stashed = self._lookup_stashed_value( - kwargs=request_data, - standard_logging_metadata=None, - key=RATE_LIMIT_DESCRIPTORS_KEY, - ) - descriptors: List[RateLimitDescriptor] = stashed if isinstance(stashed, list) else [] ops: List[RedisPipelineIncrementOperation] = [] - for descriptor in descriptors: - rate_limit = descriptor.get("rate_limit") or {} - if rate_limit.get("tokens_per_unit") is None: - continue - ops.append( - RedisPipelineIncrementOperation( - key=self.create_rate_limit_keys( - descriptor["key"], - descriptor["value"], - "tokens", - ), - increment_value=-reserved_tokens, - ttl=self.window_size, + + if reserved_tokens > 0: + # Refund directly against the descriptors we reserved + # against — the pre-call hook stashes them in the + # request-data metadata channels before success/failure + # callbacks run. Excludes the project ITPM/OTPM descriptors, + # which are reserved from different amounts and refunded + # separately below. + stashed = self._lookup_stashed_value( + kwargs=request_data, + standard_logging_metadata=None, + key=RATE_LIMIT_DESCRIPTORS_KEY, + ) + descriptors: List[RateLimitDescriptor] = stashed if isinstance(stashed, list) else [] + for descriptor in descriptors: + if descriptor["key"] in (PROJECT_ITPM_DESCRIPTOR_KEY, PROJECT_OTPM_DESCRIPTOR_KEY): + continue + rate_limit = descriptor.get("rate_limit") or {} + if rate_limit.get("tokens_per_unit") is None: + continue + ops.append( + RedisPipelineIncrementOperation( + key=self.create_rate_limit_keys( + descriptor["key"], + descriptor["value"], + "tokens", + ), + increment_value=-reserved_tokens, + ttl=self.window_size, + ) + ) + + if itpm_reserved > 0: + itpm_scopes = self._get_reserved_itpm_scopes_from_kwargs(kwargs=request_data) + ops.extend( + self._build_reservation_aware_tpm_ops( + targets=list(itpm_scopes), + reserved_scopes=itpm_scopes, + actual_tokens=0, + reserved_tokens=itpm_reserved, + ) + ) + if otpm_reserved > 0: + otpm_scopes = self._get_reserved_otpm_scopes_from_kwargs(kwargs=request_data) + ops.extend( + self._build_reservation_aware_tpm_ops( + targets=list(otpm_scopes), + reserved_scopes=otpm_scopes, + actual_tokens=0, + reserved_tokens=otpm_reserved, ) ) + if ops: - verbose_proxy_logger.debug(f"Releasing reserved TPM tokens on proxy-level rejection: {reserved_tokens}") + verbose_proxy_logger.debug( + f"Releasing reserved tokens on proxy-level rejection: " + f"tpm={reserved_tokens}, itpm={itpm_reserved}, otpm={otpm_reserved}" + ) await self.internal_usage_cache.dual_cache.async_increment_cache_pipeline( increment_list=ops, litellm_parent_otel_span=user_api_key_dict.parent_otel_span, diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prisma index 23a9c086c736..d0baa6e01108 100644 --- a/litellm/proxy/schema.prisma +++ b/litellm/proxy/schema.prisma @@ -169,6 +169,8 @@ model LiteLLM_ProjectTable { model_spend Json @default("{}") model_rpm_limit Json @default("{}") model_tpm_limit Json @default("{}") + model_itpm_limit Json @default("{}") + model_otpm_limit Json @default("{}") blocked Boolean @default(false) object_permission_id String? created_at DateTime @default(now()) @map("created_at") diff --git a/schema.prisma b/schema.prisma index 23a9c086c736..d0baa6e01108 100644 --- a/schema.prisma +++ b/schema.prisma @@ -169,6 +169,8 @@ model LiteLLM_ProjectTable { model_spend Json @default("{}") model_rpm_limit Json @default("{}") model_tpm_limit Json @default("{}") + model_itpm_limit Json @default("{}") + model_otpm_limit Json @default("{}") blocked Boolean @default(false) object_permission_id String? created_at DateTime @default(now()) @map("created_at") diff --git a/tests/test_litellm/models/test_models.py b/tests/test_litellm/models/test_models.py index 786f62449303..0a42e3f045f0 100644 --- a/tests/test_litellm/models/test_models.py +++ b/tests/test_litellm/models/test_models.py @@ -189,6 +189,48 @@ def test_project_creation(self): assert project.project_id == "proj-123" assert not project.is_blocked + def test_merged_metadata_includes_dedicated_rate_limit_columns(self): + project = LiteLLM_ProjectTable( + project_id="proj-123", + metadata={"some_custom_key": "value"}, + model_itpm_limit={"claude-3": 100_000}, + model_otpm_limit={"claude-3": 50_000}, + model_rpm_limit={"claude-3": 10}, + model_tpm_limit={"claude-3": 200_000}, + ) + merged = project.merged_metadata + assert merged["some_custom_key"] == "value" + assert merged["model_itpm_limit"] == {"claude-3": 100_000} + assert merged["model_otpm_limit"] == {"claude-3": 50_000} + assert merged["model_rpm_limit"] == {"claude-3": 10} + assert merged["model_tpm_limit"] == {"claude-3": 200_000} + + def test_merged_metadata_with_no_base_metadata(self): + project = LiteLLM_ProjectTable( + project_id="proj-124", + model_itpm_limit={"gpt-4o": 5_000}, + ) + merged = project.merged_metadata + assert merged["model_itpm_limit"] == {"gpt-4o": 5_000} + assert "model_otpm_limit" not in merged + + def test_merged_metadata_null_column_falls_back_to_metadata_value(self): + project = LiteLLM_ProjectTable( + project_id="proj-125", + metadata={"model_itpm_limit": {"gpt-4o": 9_999}}, + ) + merged = project.merged_metadata + assert merged["model_itpm_limit"] == {"gpt-4o": 9_999} + + def test_merged_metadata_dedicated_column_wins_over_metadata_value(self): + project = LiteLLM_ProjectTable( + project_id="proj-126", + metadata={"model_itpm_limit": {"gpt-4o": 9_999}}, + model_itpm_limit={"gpt-4o": 50_000}, + ) + merged = project.merged_metadata + assert merged["model_itpm_limit"] == {"gpt-4o": 50_000} + class TestTeam: def test_team_creation(self): diff --git a/tests/test_litellm/proxy/auth/test_auth_utils.py b/tests/test_litellm/proxy/auth/test_auth_utils.py index 9f24c662581e..a65b68f9a2e7 100644 --- a/tests/test_litellm/proxy/auth/test_auth_utils.py +++ b/tests/test_litellm/proxy/auth/test_auth_utils.py @@ -22,6 +22,8 @@ get_key_model_tpm_limit, get_key_tag_rpm_limit, get_model_from_request, + get_project_model_itpm_limit, + get_project_model_otpm_limit, get_project_model_rpm_limit, get_project_model_tpm_limit, get_request_route_template, @@ -1428,6 +1430,56 @@ def test_returns_none_when_project_metadata_missing_key(self): assert result is None +class TestGetProjectModelItpmLimit: + """Tests for get_project_model_itpm_limit function.""" + + def test_returns_project_metadata_itpm_limit(self): + user_api_key_dict = UserAPIKeyAuth( + api_key="sk-123", + project_metadata={"model_itpm_limit": {"bedrock_mantle/claude-opus": 20000000}}, + ) + result = get_project_model_itpm_limit(user_api_key_dict) + assert result == {"bedrock_mantle/claude-opus": 20000000} + + def test_returns_none_when_no_project_metadata(self): + user_api_key_dict = UserAPIKeyAuth(api_key="sk-123") + result = get_project_model_itpm_limit(user_api_key_dict) + assert result is None + + def test_returns_none_when_project_metadata_missing_key(self): + user_api_key_dict = UserAPIKeyAuth( + api_key="sk-123", + project_metadata={"other_key": "value"}, + ) + result = get_project_model_itpm_limit(user_api_key_dict) + assert result is None + + +class TestGetProjectModelOtpmLimit: + """Tests for get_project_model_otpm_limit function.""" + + def test_returns_project_metadata_otpm_limit(self): + user_api_key_dict = UserAPIKeyAuth( + api_key="sk-123", + project_metadata={"model_otpm_limit": {"bedrock_mantle/claude-opus": 4000000}}, + ) + result = get_project_model_otpm_limit(user_api_key_dict) + assert result == {"bedrock_mantle/claude-opus": 4000000} + + def test_returns_none_when_no_project_metadata(self): + user_api_key_dict = UserAPIKeyAuth(api_key="sk-123") + result = get_project_model_otpm_limit(user_api_key_dict) + assert result is None + + def test_returns_none_when_project_metadata_missing_key(self): + user_api_key_dict = UserAPIKeyAuth( + api_key="sk-123", + project_metadata={"other_key": "value"}, + ) + result = get_project_model_otpm_limit(user_api_key_dict) + assert result is None + + class TestCheckCompleteCredentials: """Tests for the api_key validation in check_complete_credentials.""" 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 c76e1a60afd0..b5ec62474b73 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 @@ -3101,6 +3101,140 @@ async def mock_should_rate_limit(descriptors, **kwargs): ), f"model_per_project should not be added for unrelated model, got: {descriptor_keys}" +@pytest.mark.asyncio +async def test_project_model_itpm_otpm_limits_enforced_v3(): + """ + Regression test: project-level model_itpm_limit/model_otpm_limit (Bedrock + Mantle-style separate input/output token quotas) must produce their own + rate limit descriptors, distinct from the combined model_per_project TPM + descriptor. + """ + _api_key = hash_token("sk-project-io-test") + local_cache = DualCache() + parallel_request_handler = _PROXY_MaxParallelRequestsHandler( + internal_usage_cache=InternalUsageCache(local_cache) + ) + + captured_descriptors = [] + + async def mock_should_rate_limit(descriptors, **kwargs): + captured_descriptors.extend(descriptors) + return {"overall_code": "OK", "statuses": []} + + parallel_request_handler.should_rate_limit = mock_should_rate_limit + + user_api_key_dict = UserAPIKeyAuth( + api_key=_api_key, + project_id="proj-mantle", + project_metadata={ + "model_itpm_limit": {"bedrock_mantle/claude-opus": 20000000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 4000000}, + }, + ) + + await parallel_request_handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=local_cache, + data={"model": "bedrock_mantle/claude-opus"}, + call_type="", + ) + + descriptor_keys = [d["key"] for d in captured_descriptors] + assert "model_per_project_itpm" in descriptor_keys, descriptor_keys + assert "model_per_project_otpm" in descriptor_keys, descriptor_keys + assert "model_per_project" not in descriptor_keys, descriptor_keys + + itpm_descriptor = next(d for d in captured_descriptors if d["key"] == "model_per_project_itpm") + otpm_descriptor = next(d for d in captured_descriptors if d["key"] == "model_per_project_otpm") + assert itpm_descriptor["value"] == "proj-mantle:bedrock_mantle/claude-opus" + assert itpm_descriptor["rate_limit"]["tokens_per_unit"] == 20000000 + assert otpm_descriptor["value"] == "proj-mantle:bedrock_mantle/claude-opus" + assert otpm_descriptor["rate_limit"]["tokens_per_unit"] == 4000000 + + +@pytest.mark.asyncio +async def test_project_model_itpm_otpm_limits_not_triggered_for_other_model_v3(): + """model_itpm_limit/model_otpm_limit should not fire for a model not in project_metadata.""" + _api_key = hash_token("sk-project-io-test-2") + local_cache = DualCache() + parallel_request_handler = _PROXY_MaxParallelRequestsHandler( + internal_usage_cache=InternalUsageCache(local_cache) + ) + + captured_descriptors = [] + + async def mock_should_rate_limit(descriptors, **kwargs): + captured_descriptors.extend(descriptors) + return {"overall_code": "OK", "statuses": []} + + parallel_request_handler.should_rate_limit = mock_should_rate_limit + + user_api_key_dict = UserAPIKeyAuth( + api_key=_api_key, + project_id="proj-mantle", + project_metadata={ + "model_itpm_limit": {"bedrock_mantle/claude-opus": 20000000}, + }, + ) + + await parallel_request_handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=local_cache, + data={"model": "gpt-4"}, + call_type="", + ) + + descriptor_keys = [d["key"] for d in captured_descriptors] + assert "model_per_project_itpm" not in descriptor_keys, descriptor_keys + assert "model_per_project_otpm" not in descriptor_keys, descriptor_keys + + +@pytest.mark.asyncio +async def test_project_model_itpm_and_tpm_limits_coexist_v3(): + """ + When a project configures model_itpm_limit/model_otpm_limit alongside + model_tpm_limit for the same model, both limit types are enforced + simultaneously (mirrors the deployment-level itpm/otpm + tpm/rpm + coexistence behavior) -- the combined TPM descriptor is not suppressed. + """ + _api_key = hash_token("sk-project-io-test-3") + local_cache = DualCache() + parallel_request_handler = _PROXY_MaxParallelRequestsHandler( + internal_usage_cache=InternalUsageCache(local_cache) + ) + + captured_descriptors = [] + + async def mock_should_rate_limit(descriptors, **kwargs): + captured_descriptors.extend(descriptors) + return {"overall_code": "OK", "statuses": []} + + parallel_request_handler.should_rate_limit = mock_should_rate_limit + + user_api_key_dict = UserAPIKeyAuth( + api_key=_api_key, + project_id="proj-mantle", + project_metadata={ + "model_tpm_limit": {"bedrock_mantle/claude-opus": 1000}, + "model_itpm_limit": {"bedrock_mantle/claude-opus": 20000000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 4000000}, + }, + ) + + await parallel_request_handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=local_cache, + data={"model": "bedrock_mantle/claude-opus"}, + call_type="", + ) + + descriptor_keys = [d["key"] for d in captured_descriptors] + assert "model_per_project" in descriptor_keys, descriptor_keys + assert "model_per_project_itpm" in descriptor_keys, descriptor_keys + assert "model_per_project_otpm" in descriptor_keys, descriptor_keys + assert ("proj-mantle:bedrock_mantle/claude-opus") in parallel_request_handler._project_io_token_conflict_warned + + @pytest.mark.asyncio async def test_pre_call_hook_does_not_leak_internal_stash_to_request_body(): """Regression for #27001: stash keys must stay in metadata, never on diff --git a/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py b/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py index b02f6c15168d..ffe0cc1cc27b 100644 --- a/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py +++ b/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py @@ -23,6 +23,13 @@ from litellm.caching.caching import DualCache from litellm.proxy._types import UserAPIKeyAuth from litellm.proxy.hooks.parallel_request_limiter_v3 import ( + ITPM_RESERVED_SCOPES_KEY, + ITPM_RESERVED_TOKENS_KEY, + MAX_PARALLEL_SLOT_ACQUIRED_KEY, + OTPM_RESERVED_SCOPES_KEY, + OTPM_RESERVED_TOKENS_KEY, + PROJECT_ITPM_DESCRIPTOR_KEY, + PROJECT_OTPM_DESCRIPTOR_KEY, RATE_LIMIT_DESCRIPTORS_KEY, TPM_RESERVATION_RELEASED_KEY, TPM_RESERVED_MODEL_KEY, @@ -31,7 +38,8 @@ _PROXY_MaxParallelRequestsHandler_v3 as RateLimitHandler, ) from litellm.proxy.utils import InternalUsageCache, hash_token -from litellm.types.utils import ModelResponse, Usage +from litellm.types.llms.openai import InputTokensDetails, ResponseAPIUsage, ResponsesAPIResponse +from litellm.types.utils import ModelResponse, PromptTokensDetailsWrapper, Usage @pytest.fixture @@ -567,6 +575,47 @@ async def test_estimate_tokens_uses_max_tokens_when_explicit(rate_limiter): assert estimate == 4 + 25 +@pytest.mark.asyncio +async def test_estimate_tokens_honors_explicit_zero_max_tokens(rate_limiter): + """ + Regression for a Greptile finding: explicit_max_tokens was resolved via + `data.get("max_tokens") or data.get("max_completion_tokens") or + data.get("max_output_tokens")`, so an explicit 0 in the first field was + falsy and fell through to the next field (or the no-max_tokens floor), + silently discarding a caller's explicit zero-output request. + """ + handler, _cache = rate_limiter + + estimate = handler._estimate_tokens_for_request( + data={ + "messages": [{"role": "user", "content": "abcd" * 4}], # 16 chars ~ 4 tokens + "max_tokens": 0, + } + ) + assert estimate == 4, f"expected input-only reservation (4) for an explicit max_tokens=0, got {estimate}" + + +@pytest.mark.asyncio +async def test_estimate_tokens_honors_explicit_zero_max_output_tokens_for_responses(rate_limiter): + """ + Same regression as above, for the Responses API's max_output_tokens + field specifically: a project with a small OTPM limit configured must + not reject (or over-reserve for) a Responses call that explicitly asks + for zero output tokens. + """ + handler, _cache = rate_limiter + + estimate = handler._estimate_tokens_for_request( + data={ + "input": "describe this image in detail", # 29 chars ~ 7 tokens + "max_output_tokens": 0, + }, + min_configured_tpm_limit=40, + call_type="aresponses", + ) + assert estimate == 7, f"expected input-only reservation (7) for an explicit max_output_tokens=0, got {estimate}" + + @pytest.mark.asyncio async def test_estimate_tokens_zero_for_empty_embeddings(rate_limiter): """Embeddings have no output budget — reservation should equal input only.""" @@ -1192,5 +1241,1441 @@ async def test_small_tpm_cap_preserves_explicit_max_tokens(rate_limiter): assert data["max_tokens"] == 500 +@pytest.mark.asyncio +async def test_project_otpm_reservation_prevents_concurrent_bypass(rate_limiter): + """ + Bedrock Mantle-style OTPM: with a 100 OTPM limit and 5 concurrent + requests each reserving 50+ output tokens, upfront reservation must + reject the late arrivals -- not let all 5 through. Exercises the + in-memory fallback in ``atomic_check_and_increment_by_n`` for the + project-scoped ITPM/OTPM descriptors specifically. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-otpm-bypass"), + project_id="proj-mantle-bypass", + project_metadata={ + "model_otpm_limit": {"bedrock_mantle/claude-opus": 100}, + }, + ) + + request_data = { + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hello"}], + "max_tokens": 50, + } + + async def make_request(request_id: int) -> Dict[str, Any]: + data = request_data.copy() + try: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + return {"request_id": request_id, "success": True} + except Exception as e: + return { + "request_id": request_id, + "success": False, + "status_code": getattr(e, "status_code", None), + } + + results = await asyncio.gather(*[make_request(i) for i in range(5)]) + + successful = [r for r in results if r["success"]] + rate_limited = [r for r in results if not r["success"] and r.get("status_code") == 429] + + assert len(rate_limited) > 0, ( + f"Expected some OTPM-rate-limited requests but all {len(successful)} succeeded." + ) + + +@pytest.mark.asyncio +async def test_project_otpm_over_limit_rolls_back_itpm_reservation(rate_limiter): + """ + When ITPM reserves fine but OTPM is then over limit, the ITPM + reservation this same pre-call already made must be rolled back -- + otherwise it leaks until the window's TTL, silently shrinking the ITPM + budget for every other request in that minute. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-otpm-rollback"), + project_id="proj-mantle-rollback", + project_metadata={ + "model_itpm_limit": {"bedrock_mantle/claude-opus": 1000000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 10}, + }, + ) + + itpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project_itpm", + value="proj-mantle-rollback:bedrock_mantle/claude-opus", + rate_limit_type="tokens", + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hello"}], + "max_tokens": 500, # blows past the 10-token OTPM limit + } + + with pytest.raises(Exception) as exc_info: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + assert getattr(exc_info.value, "status_code", None) == 429 + + cached_value = await cache.async_get_cache(key=itpm_counter_key, local_only=True) + assert int(cached_value or 0) == 0, ( + f"ITPM reservation leaked after OTPM rejection: counter={cached_value}" + ) + + +@pytest.mark.asyncio +async def test_project_itpm_reconciled_on_success_excludes_cached_tokens(rate_limiter): + """ + On success, ITPM reconciles to billable input tokens (prompt_tokens + minus cached_tokens) -- not raw prompt_tokens. Cached prompt-read tokens + are free under Bedrock Mantle and must not count against the ITPM quota, + even though they still appear in usage/cost logging elsewhere. + """ + handler, _cache = rate_limiter + + itpm_scope = ("model_per_project_itpm", "proj-mantle:model") + otpm_scope = ("model_per_project_otpm", "proj-mantle:model") + + mock_kwargs = { + "standard_logging_object": { + "metadata": { + ITPM_RESERVED_TOKENS_KEY: 100, + ITPM_RESERVED_SCOPES_KEY: [list(itpm_scope)], + OTPM_RESERVED_TOKENS_KEY: 60, + OTPM_RESERVED_SCOPES_KEY: [list(otpm_scope)], + } + }, + } + + mock_response = ModelResponse( + id="test", + object="chat.completion", + created=int(datetime.now().timestamp()), + model="bedrock_mantle/claude-opus", + usage=Usage( + prompt_tokens=80, + completion_tokens=40, + total_tokens=120, + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=30), + ), + choices=[], + ) + + increments = [] + + async def mock_increment(increment_list, **kwargs): + for op in increment_list: + increments.append({"key": op["key"], "increment": op["increment_value"]}) + + handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = mock_increment + + await handler.async_log_success_event( + kwargs=mock_kwargs, + response_obj=mock_response, + start_time=datetime.now(), + end_time=datetime.now(), + ) + + itpm_adjustments = [i for i in increments if "model_per_project_itpm" in i["key"]] + otpm_adjustments = [i for i in increments if "model_per_project_otpm" in i["key"]] + + # billable_input = 80 - 30 cached = 50; delta = 50 - 100 reserved = -50 + assert any(i["increment"] == -50 for i in itpm_adjustments), ( + f"Expected a -50 ITPM adjustment (50 billable - 100 reserved), got: {itpm_adjustments}" + ) + # delta = 40 actual completion - 60 reserved = -20 + assert any(i["increment"] == -20 for i in otpm_adjustments), ( + f"Expected a -20 OTPM adjustment (40 actual - 60 reserved), got: {otpm_adjustments}" + ) + + +@pytest.mark.asyncio +async def test_project_itpm_otpm_released_on_failure(rate_limiter): + """On failure, the full ITPM and OTPM reservations must be refunded.""" + handler, _cache = rate_limiter + + itpm_scope = ("model_per_project_itpm", "proj-mantle:model") + otpm_scope = ("model_per_project_otpm", "proj-mantle:model") + + mock_kwargs = { + "standard_logging_object": { + "metadata": { + ITPM_RESERVED_TOKENS_KEY: 100, + ITPM_RESERVED_SCOPES_KEY: [list(itpm_scope)], + OTPM_RESERVED_TOKENS_KEY: 60, + OTPM_RESERVED_SCOPES_KEY: [list(otpm_scope)], + } + }, + } + + increments = [] + + async def mock_increment(increment_list, **kwargs): + for op in increment_list: + increments.append({"key": op["key"], "increment": op["increment_value"]}) + + handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = mock_increment + + await handler.async_log_failure_event( + kwargs=mock_kwargs, + response_obj=None, + start_time=datetime.now(), + end_time=datetime.now(), + ) + + itpm_releases = [i for i in increments if "model_per_project_itpm" in i["key"]] + otpm_releases = [i for i in increments if "model_per_project_otpm" in i["key"]] + + assert any(i["increment"] == -100 for i in itpm_releases), itpm_releases + assert any(i["increment"] == -60 for i in otpm_releases), otpm_releases + + +@pytest.mark.asyncio +async def test_proxy_rejection_refunds_itpm_otpm_by_their_own_amount_not_combined(rate_limiter): + """ + Regression for a Greptile-flagged bug: when a project configures both a + combined model_tpm_limit and split model_itpm_limit/model_otpm_limit for + the same model, async_post_call_failure_hook's proxy-side refund path + used to decrement every token descriptor -- including the ITPM/OTPM + ones -- by the flat combined reservation amount, instead of each + bucket's own reserved amount. That drives the split counters negative + (or under-refunds them) instead of returning them to exactly zero. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-mixed-tpm-io") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-mixed", + project_metadata={ + "model_tpm_limit": {"bedrock_mantle/claude-opus": 100000}, + "model_itpm_limit": {"bedrock_mantle/claude-opus": 100000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 100000}, + }, + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hello there, this is a test message"}], + "max_tokens": 60, + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + + tpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project", value="proj-mixed:bedrock_mantle/claude-opus", rate_limit_type="tokens" + ) + itpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project_itpm", value="proj-mixed:bedrock_mantle/claude-opus", rate_limit_type="tokens" + ) + otpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project_otpm", value="proj-mixed:bedrock_mantle/claude-opus", rate_limit_type="tokens" + ) + + tpm_reserved = int(await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0) + itpm_reserved = int(await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0) + otpm_reserved = int(await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0) + assert tpm_reserved > 0 and itpm_reserved > 0 and otpm_reserved > 0 + + await handler.async_post_call_failure_hook( + request_data=data, + original_exception=Exception("guardrail rejected"), + user_api_key_dict=user_api_key_dict, + ) + + tpm_after = int(await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0) + itpm_after = int(await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0) + otpm_after = int(await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0) + + assert tpm_after == 0, f"combined TPM counter leaked: {tpm_after}" + assert itpm_after == 0, f"ITPM counter corrupted by combined-amount refund: {itpm_after}" + assert otpm_after == 0, f"OTPM counter corrupted by combined-amount refund: {otpm_after}" + + +@pytest.mark.asyncio +async def test_proxy_rejection_refunds_itpm_otpm_only_reservation_with_no_combined_tpm(rate_limiter): + """ + Regression for the second half of the same bug: with only + model_itpm_limit/model_otpm_limit configured (no model_tpm_limit), the + combined reserved_tokens is 0, and the proxy-side refund path used to + return immediately on that -- leaking the ITPM/OTPM reservations until + the rate-limit window's TTL expired. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-io-only") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-io-only", + project_metadata={ + "model_itpm_limit": {"bedrock_mantle/claude-opus": 100000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 100000}, + }, + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hello there, this is a test message"}], + "max_tokens": 60, + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + + itpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project_itpm", value="proj-io-only:bedrock_mantle/claude-opus", rate_limit_type="tokens" + ) + otpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project_otpm", value="proj-io-only:bedrock_mantle/claude-opus", rate_limit_type="tokens" + ) + assert int(await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0) > 0 + assert int(await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0) > 0 + + await handler.async_post_call_failure_hook( + request_data=data, + original_exception=Exception("guardrail rejected"), + user_api_key_dict=user_api_key_dict, + ) + + itpm_after = int(await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0) + otpm_after = int(await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0) + assert itpm_after == 0, f"ITPM-only reservation leaked on proxy rejection: {itpm_after}" + assert otpm_after == 0, f"OTPM-only reservation leaked on proxy rejection: {otpm_after}" + + +@pytest.mark.asyncio +async def test_otpm_rejection_does_not_double_refund_combined_tpm(rate_limiter): + """ + Regression for a High-severity review finding: when the project ITPM + reservation succeeds but OTPM is then over limit, + _reserve_project_io_tokens_or_raise rolls back the combined-TPM + reservation that already succeeded earlier in the same pre-call, then + raises. If it doesn't also mark that reservation released, + async_post_call_failure_hook -- which fires next in the real request + lifecycle, since raising from async_pre_call_hook triggers it -- sees + the same still-stashed reservation and refunds it a second time, + driving the combined TPM counter negative and letting a caller push + past the project's real TPM budget by repeatedly triggering OTPM + rejections. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-double-refund") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-double-refund", + project_metadata={ + "model_tpm_limit": {"bedrock_mantle/claude-opus": 100000}, + "model_itpm_limit": {"bedrock_mantle/claude-opus": 100000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 5}, + }, + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hello there, this is a test message"}], + "max_tokens": 60, # blows past the 5-token OTPM limit + } + + tpm_counter_key = handler.create_rate_limit_keys( + key="model_per_project", value="proj-double-refund:bedrock_mantle/claude-opus", rate_limit_type="tokens" + ) + + with pytest.raises(Exception) as exc_info: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + assert getattr(exc_info.value, "status_code", None) == 429 + + tpm_after_pre_call = int(await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0) + assert tpm_after_pre_call == 0, f"combined TPM reservation not rolled back: {tpm_after_pre_call}" + + # In the real request lifecycle, async_post_call_failure_hook fires next + # for a pre-call rejection. It must not refund the same reservation again. + await handler.async_post_call_failure_hook( + request_data=data, + original_exception=exc_info.value, + user_api_key_dict=user_api_key_dict, + ) + + tpm_after_failure_hook = int(await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0) + assert tpm_after_failure_hook == 0, ( + f"combined TPM counter went negative from a double refund: {tpm_after_failure_hook}" + ) + + +@pytest.mark.asyncio +async def test_itpm_reservation_accounts_for_image_content_not_just_text(rate_limiter): + """ + Regression for a Medium-severity review finding: the ITPM reservation + used to estimate input tokens from message text length alone, so a + request with a tiny text prompt but real image content would reserve + almost nothing, letting a burst of such requests blow past the + configured ITPM limit before post-call usage reconciliation catches up. + _estimate_precise_input_tokens uses litellm.token_counter (with + use_default_image_token_count=True, so this test makes no network call) + to account for image content instead of only text length. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-multimodal-itpm") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-multimodal", + project_metadata={ + # Tighter than the ~250-token default image estimate, but far + # bigger than the handful of tokens the bare text "hi" would + # cost under the old char-count-only estimate. + "model_itpm_limit": {"bedrock_mantle/claude-opus": 50}, + }, + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "hi"}, + { + "type": "image_url", + "image_url": {"url": "https://example.com/some-image.png"}, + }, + ], + } + ], + } + + with pytest.raises(Exception) as exc_info: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + assert getattr(exc_info.value, "status_code", None) == 429, ( + "Expected the image content to push the ITPM reservation over the " + "50-token limit; if this doesn't raise, the estimate is undercounting " + "non-text content again." + ) + + +@pytest.mark.asyncio +async def test_responses_api_not_misclassified_as_embedding_for_output_estimate(rate_limiter): + """ + Regression for a High-severity review finding: the Responses API also + puts its prompt in data["input"], the same field embeddings use, so the + output-token estimate treated every Responses call as an embedding and + reserved zero output tokens. call_type now disambiguates the two: the + same input-only payload gets zero output tokens for an embedding call + but a real floor for a Responses API call. + """ + handler, _cache = rate_limiter + + data = {"input": "describe this image in detail"} + + _, embedding_output_estimate = handler._estimate_input_and_output_tokens(data=data, call_type="aembedding") + assert embedding_output_estimate == 0 + + _, responses_output_estimate = handler._estimate_input_and_output_tokens(data=data, call_type="aresponses") + assert responses_output_estimate > 0, ( + "Responses API call was misclassified as an embedding and reserved zero output tokens" + ) + + +@pytest.mark.asyncio +async def test_responses_api_usage_reconciles_using_input_output_tokens_fields(rate_limiter): + """ + Regression for the other half of the same finding: ResponseAPIUsage + exposes input_tokens/output_tokens, not prompt_tokens/completion_tokens. + Before this fix, _resolve_io_token_reconcile_usage couldn't resolve + Responses API usage at all, so the reservation was silently kept as-is + instead of being trued up to the much larger actual usage. + """ + handler, _cache = rate_limiter + + itpm_scope = ("model_per_project_itpm", "proj-responses:model") + otpm_scope = ("model_per_project_otpm", "proj-responses:model") + + mock_kwargs = { + "standard_logging_object": { + "metadata": { + ITPM_RESERVED_TOKENS_KEY: 10, + ITPM_RESERVED_SCOPES_KEY: [list(itpm_scope)], + OTPM_RESERVED_TOKENS_KEY: 10, + OTPM_RESERVED_SCOPES_KEY: [list(otpm_scope)], + } + }, + } + + mock_response = ResponsesAPIResponse( + id="resp_test", + created_at=int(datetime.now().timestamp()), + output=[], + usage=ResponseAPIUsage(input_tokens=80, output_tokens=400, total_tokens=480), + ) + + increments = [] + + async def mock_increment(increment_list, **kwargs): + for op in increment_list: + increments.append({"key": op["key"], "increment": op["increment_value"]}) + + handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = mock_increment + + await handler.async_log_success_event( + kwargs=mock_kwargs, + response_obj=mock_response, + start_time=datetime.now(), + end_time=datetime.now(), + ) + + itpm_adjustments = [i for i in increments if "model_per_project_itpm" in i["key"]] + otpm_adjustments = [i for i in increments if "model_per_project_otpm" in i["key"]] + + # delta = 80 actual input - 10 reserved = +70 + assert any(i["increment"] == 70 for i in itpm_adjustments), ( + f"ITPM reservation was never trued up to actual Responses API usage: {itpm_adjustments}" + ) + # delta = 400 actual output - 10 reserved = +390 + assert any(i["increment"] == 390 for i in otpm_adjustments), ( + f"OTPM reservation was never trued up to actual Responses API usage: {otpm_adjustments}" + ) + + +@pytest.mark.asyncio +async def test_itpm_reservation_accounts_for_audio_content_not_just_text(rate_limiter): + """ + Regression for the audio half of a Medium-severity review finding: + litellm.token_counter has no per-type handling for `input_audio` + content blocks (unlike images, which it does count via + use_default_image_token_count), so it silently contributes 0 tokens for + them. Without DEFAULT_AUDIO_TOKEN_ESTIMATE, a burst of audio-heavy + requests with minimal text would each reserve only the one-token floor + and blow past the project ITPM limit before post-call reconciliation. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-audio-itpm") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-audio", + project_metadata={ + # Tighter than DEFAULT_AUDIO_TOKEN_ESTIMATE (300), but far bigger + # than the handful of tokens the bare text "hi" would cost. + "model_itpm_limit": {"bedrock_mantle/claude-opus": 50}, + }, + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "hi"}, + { + "type": "input_audio", + "input_audio": {"data": "base64-audio-bytes", "format": "wav"}, + }, + ], + } + ], + } + + with pytest.raises(Exception) as exc_info: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + assert getattr(exc_info.value, "status_code", None) == 429, ( + "Expected the audio content to push the ITPM reservation over the " + "50-token limit; if this doesn't raise, audio content isn't being " + "counted again." + ) + + +def test_audio_token_estimate_scales_with_payload_size(): + """ + Regression for veria-ai Low finding: audio token reservation was flat + 300 per block regardless of duration. A short clip and a long clip both + reserved the same amount, letting a caller hide long audio in one block + to exhaust ITPM quota while reserving almost nothing. + + The estimate must now grow proportionally with the base64 payload size + (len(b64) * 3 // 4 // _AUDIO_BYTES_PER_TOKEN), floored at + DEFAULT_AUDIO_TOKEN_ESTIMATE so reference-only blocks and genuinely + short clips still get a non-trivial reservation. + + To exceed the floor the decoded payload must be > 300 * 1600 = 480 000 + bytes. We synthesise a fake b64-length string of 650 000 chars + (decoded ≈ 487 500 bytes → 304 tokens) to avoid actually allocating + and encoding ~480 kB of audio in every test run. + """ + large_b64 = "A" * 650_000 + small_b64 = "A" * 1_000 + + large_block = {"type": "input_audio", "input_audio": {"data": large_b64, "format": "wav"}} + small_block = {"type": "input_audio", "input_audio": {"data": small_b64, "format": "wav"}} + no_data_block = {"type": "input_audio", "input_audio": {"format": "wav"}} + + large_estimate = RateLimitHandler._estimate_audio_block_tokens(large_block) + small_estimate = RateLimitHandler._estimate_audio_block_tokens(small_block) + no_data_estimate = RateLimitHandler._estimate_audio_block_tokens(no_data_block) + + assert large_estimate > small_estimate, ( + f"Large payload ({large_estimate}) must reserve more than small payload " + f"({small_estimate}); flat-rate bug is back" + ) + assert no_data_estimate >= 300, ( + f"Reference-only block (no data) must use the DEFAULT_AUDIO_TOKEN_ESTIMATE floor; " + f"got {no_data_estimate}" + ) + assert small_estimate >= 300, ( + f"Small payload must be floored at DEFAULT_AUDIO_TOKEN_ESTIMATE=300; " + f"got {small_estimate}" + ) + + +@pytest.mark.asyncio +async def test_itpm_rejects_large_audio_payload_that_would_pass_flat_estimate(rate_limiter): + """ + Regression: a caller placing a long audio clip in one block previously + reserved only 300 tokens (the flat estimate). With the size-proportional + estimate, the same clip now reserves proportionally more and must trip + the ITPM limit when the limit is tuned to exactly expose the difference. + + 1 100 000 b64 chars → decoded ≈ 825 000 bytes → 825 000 // 1600 ≈ 515 + tokens > the 400-token limit. The flat estimate (300) would have passed. + """ + handler, cache = rate_limiter + + large_b64 = "A" * 1_100_000 + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-large-audio"), + project_id="proj-large-audio", + project_metadata={ + "model_itpm_limit": {"bedrock_mantle/claude-opus": 400}, + }, + ) + + data = { + "model": "bedrock_mantle/claude-opus", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "transcribe this"}, + { + "type": "input_audio", + "input_audio": {"data": large_b64, "format": "wav"}, + }, + ], + } + ], + } + + with pytest.raises(Exception) as exc_info: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + assert getattr(exc_info.value, "status_code", None) == 429, ( + "Large audio payload must exceed the 400-token ITPM limit under the " + "size-proportional estimate; the old flat-rate estimate (300 tokens) " + "would have passed this limit silently" + ) + + +@pytest.mark.asyncio +async def test_itpm_otpm_refunded_on_stream_disconnect(rate_limiter): + """ + Regression for Medium-severity veria-ai finding: stream cancellation + left ITPM/OTPM reservations charged. + + async_release_max_parallel_requests_on_disconnect previously only + released the parallel slot and ignored any stashed ITPM/OTPM amounts, + letting a caller repeatedly start and cancel streams to exhaust the + project quota. The fix must refund both buckets and mark the reservation + released so async_log_failure_event can't double-refund if it fires later. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-disconnect-test") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-disconnect", + project_metadata={ + "model_itpm_limit": {"bedrock_mantle/claude-opus": 1000}, + "model_otpm_limit": {"bedrock_mantle/claude-opus": 500}, + }, + ) + + data: Dict[str, Any] = { + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hello"}], + "max_tokens": 50, + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + + itpm_reserved = data.get(ITPM_RESERVED_TOKENS_KEY) or ( + data.get("metadata", {}) or {} + ).get(ITPM_RESERVED_TOKENS_KEY) + otpm_reserved = data.get(OTPM_RESERVED_TOKENS_KEY) or ( + data.get("metadata", {}) or {} + ).get(OTPM_RESERVED_TOKENS_KEY) + assert itpm_reserved is not None and int(itpm_reserved) > 0, "pre-call hook must stash an ITPM reservation" + assert otpm_reserved is not None and int(otpm_reserved) > 0, "pre-call hook must stash an OTPM reservation" + + increment_calls: list[dict] = [] + + async def mock_increment(increment_list, litellm_parent_otel_span=None): + for op in increment_list: + increment_calls.append({"key": op["key"], "increment": op["increment_value"]}) + + handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = mock_increment + + await handler.async_release_max_parallel_requests_on_disconnect( + user_api_key_dict=user_api_key_dict, + request_data=data, + ) + + itpm_refunds = [c for c in increment_calls if "model_per_project_itpm" in c["key"] and c["increment"] < 0] + otpm_refunds = [c for c in increment_calls if "model_per_project_otpm" in c["key"] and c["increment"] < 0] + + assert itpm_refunds, "disconnect must refund ITPM reservation; counter stays inflated otherwise" + assert otpm_refunds, "disconnect must refund OTPM reservation; counter stays inflated otherwise" + + assert RateLimitHandler._is_reservation_released(kwargs=data), ( + "disconnect must mark reservation released so failure callbacks can't double-refund" + ) + + +@pytest.mark.asyncio +async def test_responses_api_otpm_output_cap_applied_not_skipped_as_embedding(rate_limiter): + """ + Regression for a Greptile P1 finding: _reserve_project_io_tokens_or_raise + classified any request with data["input"] set as an embedding (no output + tokens), which also misclassifies the Responses API -- it puts its prompt + in "input" too, but does generate output. That skipped the output cap + applied whenever the configured OTPM limit is small enough to need it, + letting an unbounded Responses generation blow past OTPM before + post-call reconciliation catches up. + + The cap must land on data["max_output_tokens"], not data["max_tokens"]: + the Responses-to-chat-completion transformation only reads + max_output_tokens, so a max_tokens cap is silently dropped before + provider dispatch (a second Greptile finding on the same code path). + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-responses-otpm-cap") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-responses-otpm", + project_metadata={ + "model_otpm_limit": {"bedrock_mantle/claude-opus": 40}, + }, + ) + + data: Dict[str, Any] = { + "model": "bedrock_mantle/claude-opus", + "input": "describe this image in detail", + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="aresponses", + ) + + assert data.get("max_output_tokens") is not None, ( + "Responses call was misclassified as an embedding and skipped the OTPM output cap" + ) + assert data["max_output_tokens"] <= 10, f"expected the OTPM-derived floor (<=10), got {data['max_output_tokens']}" + assert data.get("max_tokens") is None, ( + "OTPM output cap was written to max_tokens, which the Responses transformation ignores" + ) + + +@pytest.mark.asyncio +async def test_explicit_zero_output_responses_call_not_rejected_when_otpm_exhausted(rate_limiter): + """ + Regression for a Greptile finding: estimated_output_tokens was + unconditionally floored to max(estimated_output_tokens, 1), overriding + an explicit max_output_tokens=0 with an implicit reservation of 1. A + Responses call that explicitly asks for zero output tokens must not be + rejected just because the project's OTPM bucket is already exhausted -- + it reserves nothing on the output side. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-responses-zero-output"), + project_id="proj-responses-zero-output", + project_metadata={ + "model_otpm_limit": {"bedrock_mantle/claude-opus": 5}, + }, + ) + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data={ + "model": "bedrock_mantle/claude-opus", + "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 5, + }, + call_type="", + ) + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data={ + "model": "bedrock_mantle/claude-opus", + "input": "describe this image in detail", + "max_output_tokens": 0, + }, + call_type="aresponses", + ) + + +@pytest.mark.asyncio +async def test_responses_api_combined_tpm_output_cap_applied_not_skipped_as_embedding(rate_limiter): + """ + Regression for the same misclassification bug in the combined-TPM + output-cap block of async_pre_call_hook (a second, independent + `is_embedding = data.get("input") is not None` check). A project with + only a combined model_tpm_limit (no split itpm/otpm) configured small + enough to need the output cap must still apply it to a Responses call, + and must write it to max_output_tokens for the same reason as the OTPM + case above. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-responses-tpm-cap") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + project_id="proj-responses-tpm", + project_metadata={ + "model_tpm_limit": {"bedrock_mantle/claude-opus": 40}, + }, + ) + + data: Dict[str, Any] = { + "model": "bedrock_mantle/claude-opus", + "input": "describe this image in detail", + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="aresponses", + ) + + assert data.get("max_output_tokens") is not None, ( + "Responses call was misclassified as an embedding and skipped the combined-TPM output cap" + ) + assert data["max_output_tokens"] <= 10, f"expected the TPM-derived floor (<=10), got {data['max_output_tokens']}" + assert data.get("max_tokens") is None, ( + "combined-TPM output cap was written to max_tokens, which the Responses transformation ignores" + ) + + +@pytest.mark.asyncio +async def test_responses_api_multimodal_input_counts_image_content(rate_limiter): + """ + Regression for a Low-severity veria-ai finding: the Responses API's + `input` is commonly a list of message/content-block dicts, but + litellm.token_counter's `text` argument only joins plain string entries + in a list and silently drops everything else -- so an `input_image` + block contributed ~0 tokens to the ITPM estimate instead of the real + image token count. _estimate_precise_input_tokens now converts Responses + `input` to chat messages first (via the standard + transform_responses_api_input_to_messages helper) so image content is + counted the same way a chat completion's image content already is. + """ + handler, _cache = rate_limiter + + text_only_estimate = handler._estimate_precise_input_tokens( + data={"input": "hi"}, + model="bedrock_mantle/claude-opus", + call_type="aresponses", + ) + + multimodal_estimate = handler._estimate_precise_input_tokens( + data={ + "input": [ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "hi"}, + {"type": "input_image", "image_url": "https://example.com/some-image.png"}, + ], + } + ], + }, + model="bedrock_mantle/claude-opus", + call_type="aresponses", + ) + + assert multimodal_estimate > text_only_estimate + 100, ( + "Responses API input_image content block was not counted; got " + f"text_only={text_only_estimate}, multimodal={multimodal_estimate}" + ) + + +@pytest.mark.asyncio +async def test_refund_reserved_tokens_noop_when_amount_zero(rate_limiter): + """_refund_reserved_tokens returns immediately without calling Redis when amount=0.""" + handler, _cache = rate_limiter + + calls = [] + + async def mock_increment(pipeline_operations, **kwargs): + calls.extend(pipeline_operations) + + handler.async_increment_tokens_with_ttl_preservation = mock_increment + + await handler._refund_reserved_tokens( + scopes=[("api_key", "sk-test")], + amount=0, + ) + + assert not calls, "No Redis ops expected when amount is zero" + + +@pytest.mark.asyncio +async def test_reserve_io_tokens_noop_when_no_itpm_otpm_descriptors(rate_limiter): + """reserve_io_tokens returns OK immediately when no ITPM/OTPM descriptors present.""" + handler, _cache = rate_limiter + + non_io_descriptor = { + "key": "api_key", + "value": "sk-test", + "rate_limit": {"tokens_per_unit": 1000, "window_size": 60}, + } + response, itpm_reserved, otpm_reserved = await handler.reserve_io_tokens( + descriptors=[non_io_descriptor], + estimated_input_tokens=50, + estimated_output_tokens=50, + ) + + assert response["overall_code"] == "OK" + assert itpm_reserved == 0 + assert otpm_reserved == 0 + + +@pytest.mark.asyncio +async def test_reserve_io_tokens_itpm_only_no_otpm(rate_limiter): + """When only ITPM descriptors are present (no OTPM), returns itpm_reserved with otpm=0.""" + handler, cache = rate_limiter + + itpm_descriptor = { + "key": PROJECT_ITPM_DESCRIPTOR_KEY, + "value": "proj-a:model", + "rate_limit": {"tokens_per_unit": 10000, "window_size": 60}, + } + response, itpm_reserved, otpm_reserved = await handler.reserve_io_tokens( + descriptors=[itpm_descriptor], + estimated_input_tokens=100, + estimated_output_tokens=50, + ) + + assert response["overall_code"] == "OK" + assert itpm_reserved == 100 + assert otpm_reserved == 0 + + +@pytest.mark.asyncio +async def test_warn_project_io_token_conflict_suppressed_after_first(rate_limiter): + """_warn_project_io_token_and_tpm_coexist_once logs only once per project:model pair.""" + handler, _cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-warn"), + project_id="proj-warn", + project_metadata={"model_tpm_limit": {"gpt-4o": 1000}}, + ) + model = "gpt-4o" + + warnings = [] + + import logging + + class _Capture(logging.Handler): + def emit(self, record): + warnings.append(record.getMessage()) + + import litellm.proxy.hooks.parallel_request_limiter_v3 as _mod + + handler_log = _mod.verbose_proxy_logger + cap = _Capture() + handler_log.addHandler(cap) + try: + handler._warn_project_io_token_and_tpm_coexist_once(user_api_key_dict, model) + first_count = len(warnings) + handler._warn_project_io_token_and_tpm_coexist_once(user_api_key_dict, model) + assert len(warnings) == first_count, ( + "Second call for the same key should be suppressed (already-warned guard not hit)" + ) + finally: + handler_log.removeHandler(cap) + + +def test_strip_audio_content_blocks_passthrough_non_list_messages(): + """Non-list input is returned unchanged (early return on line 2605).""" + result = RateLimitHandler._strip_audio_content_blocks("not a list") + assert result == "not a list" + + +def test_strip_audio_content_blocks_passthrough_non_dict_message(): + """Non-dict entries in the message list are appended unchanged.""" + messages = ["plain string message"] + result = RateLimitHandler._strip_audio_content_blocks(messages) + assert result == ["plain string message"] + + +def test_strip_audio_content_blocks_passthrough_non_list_content(): + """Messages with non-list content (e.g. plain string) pass through unchanged.""" + messages = [{"role": "user", "content": "hello"}] + result = RateLimitHandler._strip_audio_content_blocks(messages) + assert result == [{"role": "user", "content": "hello"}] + + +@pytest.mark.asyncio +async def test_otpm_rejection_releases_stashed_parallel_slot(rate_limiter): + """ + When OTPM is over limit and a parallel slot was already acquired, the + disconnect cleanup path in _reserve_project_io_tokens_or_raise must + release that slot. Exercises lines 2773-2777. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-otpm-slot"), + project_id="proj-slot", + project_metadata={"model_otpm_limit": {"m": 5}}, + ) + + data: Dict[str, Any] = { + "model": "m", + "messages": [{"role": "user", "content": "hello"}], + "max_tokens": 50, + } + + slot_released = [] + + async def mock_release(acquisition, parent_otel_span=None): + slot_released.append(acquisition) + + handler._release_parallel_request_slots = mock_release + + data.setdefault("metadata", {})[MAX_PARALLEL_SLOT_ACQUIRED_KEY] = { + "slot_id": "test-slot-id", + "counter_keys": ["some-key"], + } + + otpm_descriptor = { + "key": PROJECT_OTPM_DESCRIPTOR_KEY, + "value": "proj-slot:m", + "rate_limit": {"tokens_per_unit": 5, "window_size": 60}, + } + + with pytest.raises(Exception) as exc_info: + await handler._reserve_project_io_tokens_or_raise( + descriptors=[otpm_descriptor], + data=data, + requested_model="m", + user_api_key_dict=user_api_key_dict, + tpm_reservation_scopes=[], + tpm_reservation_amount=0, + ) + assert getattr(exc_info.value, "status_code", None) == 429 + assert slot_released, "Parallel slot must be released when OTPM rejects" + + +@pytest.mark.asyncio +async def test_itpm_only_status_stored_when_no_prior_rate_limit_response(rate_limiter): + """ + When only ITPM is configured (no combined TPM/RPM to pre-populate + litellm_proxy_rate_limit_response), a successful ITPM reservation must + store its status in data so post-call headers can read it. + Covers the elif branch at lines 2809-2811. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-itpm-only-store"), + project_id="proj-store", + ) + + data: Dict[str, Any] = {"model": "m", "messages": []} + + itpm_descriptor = { + "key": PROJECT_ITPM_DESCRIPTOR_KEY, + "value": "proj-store:m", + "rate_limit": {"tokens_per_unit": 100000, "window_size": 60}, + } + + await handler._reserve_project_io_tokens_or_raise( + descriptors=[itpm_descriptor], + data=data, + requested_model="m", + user_api_key_dict=user_api_key_dict, + tpm_reservation_scopes=[], + tpm_reservation_amount=0, + ) + + stored = data.get("litellm_proxy_rate_limit_response") + assert stored is not None, "ITPM status must be stored in litellm_proxy_rate_limit_response" + assert stored.get("statuses"), "Stored response must contain statuses" + + +def test_get_reserved_itpm_tokens_returns_zero_for_non_numeric(rate_limiter): + """Corrupted ITPM stash (non-numeric string) returns 0, not ValueError.""" + handler, _cache = rate_limiter + + kwargs = {"metadata": {ITPM_RESERVED_TOKENS_KEY: "not-a-number"}} + result = handler._get_reserved_itpm_tokens_from_kwargs(kwargs) + assert result == 0 + + +def test_get_reserved_otpm_tokens_returns_zero_for_non_numeric(rate_limiter): + """Corrupted OTPM stash (non-numeric string) returns 0, not ValueError.""" + handler, _cache = rate_limiter + + kwargs = {"metadata": {OTPM_RESERVED_TOKENS_KEY: "bad"}} + result = handler._get_reserved_otpm_tokens_from_kwargs(kwargs) + assert result == 0 + + +def test_narrow_reserved_scopes_returns_empty_for_non_list(): + """Non-list candidate (None, int, str) returns an empty set.""" + assert RateLimitHandler._narrow_reserved_scopes(None) == set() + assert RateLimitHandler._narrow_reserved_scopes(42) == set() + assert RateLimitHandler._narrow_reserved_scopes("oops") == set() + + +def test_resolve_io_token_usage_responses_api_with_cached_tokens(rate_limiter): + """ + ResponsesAPIResponse whose usage.input_tokens_details.cached_tokens is set + subtracts the cached portion from billable input. Covers line 3501. + """ + handler, _cache = rate_limiter + + response_obj = ResponsesAPIResponse( + id="resp_cached", + created_at=int(datetime.now().timestamp()), + output=[], + usage=ResponseAPIUsage( + input_tokens=100, + output_tokens=50, + total_tokens=150, + input_tokens_details=InputTokensDetails(cached_tokens=25), + ), + ) + billable_input, completion_tokens, resolved = handler._resolve_io_token_reconcile_usage(response_obj) + + assert resolved is True + assert billable_input == 75, f"Expected 100 - 25 cached = 75, got {billable_input}" + assert completion_tokens == 50 + + +def test_resolve_io_token_usage_dict_format(rate_limiter): + """ + Dict-shaped usage on a ModelResponse (older SDK versions or raw dicts in + the usage field) is parsed correctly. Covers lines 3502-3506. + """ + handler, _cache = rate_limiter + + response_obj = ModelResponse.model_construct( + usage={ + "prompt_tokens": 80, + "completion_tokens": 40, + "prompt_tokens_details": {"cached_tokens": 20}, + } + ) + billable_input, completion_tokens, resolved = handler._resolve_io_token_reconcile_usage(response_obj) + + assert resolved is True + assert billable_input == 60, f"Expected 80 - 20 cached = 60, got {billable_input}" + assert completion_tokens == 40 + + +def test_resolve_io_token_usage_unknown_type_returns_unresolved(rate_limiter): + """ + A ModelResponse whose usage attribute is not a Usage, ResponseAPIUsage, + or dict (e.g. a plain int) returns (0, 0, False) so the reservation is + kept rather than guessed. Covers lines 3507-3508. + """ + handler, _cache = rate_limiter + + response_obj = ModelResponse.model_construct(usage=42) + billable_input, completion_tokens, resolved = handler._resolve_io_token_reconcile_usage(response_obj) + + assert resolved is False + assert billable_input == 0 + assert completion_tokens == 0 + + +@pytest.mark.asyncio +async def test_build_io_token_reservation_ops_skips_unresolvable_usage(rate_limiter): + """ + When response_obj has no parseable usage, _build_io_token_reservation_ops + returns [] to keep the reservation as-is rather than zeroing it out on a + bad guess. Covers line 3538. + """ + handler, _cache = rate_limiter + + itpm_scope = ("model_per_project_itpm", "proj-b:model") + mock_kwargs = { + "standard_logging_object": { + "metadata": { + ITPM_RESERVED_TOKENS_KEY: 50, + ITPM_RESERVED_SCOPES_KEY: [list(itpm_scope)], + } + }, + } + + ops = handler._build_io_token_reservation_ops( + kwargs=mock_kwargs, + response_obj=object(), + ) + + assert ops == [], f"Expected empty ops for unresolvable usage, got {ops}" + + +@pytest.mark.asyncio +async def test_disconnect_cleanup_noop_when_reservation_already_released(rate_limiter): + """ + async_release_max_parallel_requests_on_disconnect returns immediately + without touching the IO reservation when the released marker is set. + Covers the early-return guard at line 4113. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-already-released"), + project_id="proj-released", + project_metadata={"model_itpm_limit": {"m": 1000}}, + ) + + data: Dict[str, Any] = { + "model": "m", + "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 10, + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + + RateLimitHandler._mark_reservation_released(data) + + increments = [] + + async def mock_increment(increment_list, **kwargs): + increments.extend(increment_list) + + handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = mock_increment + + await handler.async_release_max_parallel_requests_on_disconnect( + user_api_key_dict=user_api_key_dict, + request_data=data, + ) + + itpm_refunds = [i for i in increments if "model_per_project_itpm" in i["key"]] + assert not itpm_refunds, ( + "Disconnect cleanup must be a no-op when reservation is already released" + ) + + +@pytest.mark.asyncio +async def test_post_call_failure_skips_rpm_only_descriptor_in_tpm_refund(rate_limiter): + """ + async_post_call_failure_hook skips descriptors without tokens_per_unit + (e.g. an RPM-only api_key scope) when building the combined-TPM refund ops, + so a key with rpm_limit but no tpm_limit doesn't receive a spurious refund + that would drive its counter negative. Covers the continue guard at line 4250. + """ + handler, cache = rate_limiter + + api_key = hash_token("sk-rpm-only-desc") + user_api_key_dict = UserAPIKeyAuth( + api_key=api_key, + rpm_limit=100, + project_id="proj-rpm-only-desc", + project_metadata={"model_tpm_limit": {"gpt-3.5-turbo": 100000}}, + ) + + data = { + "model": "gpt-3.5-turbo", + "messages": [{"role": "user", "content": "hello"}], + "max_tokens": 20, + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + + rpm_counter_key = handler.create_rate_limit_keys( + key="api_key", value=api_key, rate_limit_type="requests" + ) + rpm_tokens_key = handler.create_rate_limit_keys( + key="api_key", value=api_key, rate_limit_type="tokens" + ) + + await handler.async_post_call_failure_hook( + request_data=data, + original_exception=Exception("rejected"), + user_api_key_dict=user_api_key_dict, + ) + + api_key_tokens_after = int( + await cache.async_get_cache(key=rpm_tokens_key, local_only=True) or 0 + ) + assert api_key_tokens_after >= 0, ( + f"RPM-only api_key scope must not receive a negative TPM refund; " + f"got {api_key_tokens_after}" + ) + + +@pytest.mark.asyncio +async def test_itpm_otpm_refund_exception_swallowed_on_disconnect(rate_limiter): + """ + If the Redis pipeline raises during the ITPM/OTPM refund on disconnect, + the exception must not propagate out of + async_release_max_parallel_requests_on_disconnect. Covers lines 4149-4150. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-exc"), + project_id="proj-exc", + project_metadata={ + "model_itpm_limit": {"m": 1000}, + }, + ) + + data: Dict[str, Any] = { + "model": "m", + "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 10, + } + + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="", + ) + + async def raise_on_pipeline(**kwargs): + raise RuntimeError("Redis exploded") + + handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = raise_on_pipeline + + await handler.async_release_max_parallel_requests_on_disconnect( + user_api_key_dict=user_api_key_dict, + request_data=data, + ) + + +@pytest.mark.asyncio +async def test_max_output_tokens_prevents_cap_injection(rate_limiter): + """ + Regression for veria-ai comment: when a Responses API request supplies + max_output_tokens (the canonical Responses output bound) but not max_tokens + or max_completion_tokens, the has_explicit_max_tokens check was False, so + the code injected data["max_tokens"] = capped_floor and silently truncated + the response. + + With the fix, max_output_tokens is included in the explicit-cap check and + data["max_tokens"] must NOT be injected when max_output_tokens is already + set. + """ + handler, cache = rate_limiter + + user_api_key_dict = UserAPIKeyAuth( + api_key=hash_token("sk-max-output-tokens"), + project_id="proj-responses-max-output", + project_metadata={ + "model_otpm_limit": {"mock-model": 100}, + }, + ) + + data: dict = { + "model": "mock-model", + "input": "Summarise the document", + "max_output_tokens": 80, + "litellm_call_id": "test-max-output-tokens", + "metadata": {}, + } + + try: + await handler.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="responses", + ) + except Exception: + pass + + assert "max_tokens" not in data, ( + "data['max_tokens'] must not be injected when max_output_tokens is already " + "set; the cap injection was overriding the caller's explicit output bound" + ) + + if __name__ == "__main__": pytest.main([__file__, "-v", "-s"]) diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 203057f23f14..a0ff232013a2 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -25925,6 +25925,14 @@ export interface components { metadata?: { [key: string]: unknown; } | null; + /** Model Itpm Limit */ + model_itpm_limit?: { + [key: string]: unknown; + } | null; + /** Model Otpm Limit */ + model_otpm_limit?: { + [key: string]: unknown; + } | null; /** Model Rpm Limit */ model_rpm_limit?: { [key: string]: unknown; @@ -28012,10 +28020,18 @@ export interface components { metadata?: { [key: string]: unknown; } | null; + /** Model Itpm Limit */ + model_itpm_limit?: { + [key: string]: unknown; + } | null; /** Model Max Budget */ model_max_budget?: { [key: string]: unknown; } | null; + /** Model Otpm Limit */ + model_otpm_limit?: { + [key: string]: unknown; + } | null; /** Model Rpm Limit */ model_rpm_limit?: { [key: string]: unknown; @@ -28073,6 +28089,14 @@ export interface components { metadata?: { [key: string]: unknown; } | null; + /** Model Itpm Limit */ + model_itpm_limit?: { + [key: string]: unknown; + } | null; + /** Model Otpm Limit */ + model_otpm_limit?: { + [key: string]: unknown; + } | null; /** Model Rpm Limit */ model_rpm_limit?: { [key: string]: unknown; @@ -32239,10 +32263,18 @@ export interface components { metadata?: { [key: string]: unknown; } | null; + /** Model Itpm Limit */ + model_itpm_limit?: { + [key: string]: unknown; + } | null; /** Model Max Budget */ model_max_budget?: { [key: string]: unknown; } | null; + /** Model Otpm Limit */ + model_otpm_limit?: { + [key: string]: unknown; + } | null; /** Model Rpm Limit */ model_rpm_limit?: { [key: string]: unknown;