The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(router): let a deployment set a timeout per service_tier (#47406)
Kerry Lu62ce515d15fd
diff --git a/litellm/litellm_core_utils/request_timeout_resolver.py b/litellm/litellm_core_utils/request_timeout_resolver.pyindex a32651fedee..0e011dc06a0 100644--- a/litellm/litellm_core_utils/request_timeout_resolver.py+++ b/litellm/litellm_core_utils/request_timeout_resolver.py@@ -12,10 +12,15 @@ tell "user asked for this" from "nobody set it". This resolver answers that:from __future__ import annotations-from typing import Final+from collections.abc import Mapping+from typing import Final, Literal, Protocol++from pydantic import TypeAdapterfrom litellm.constants import DEFAULT_REQUEST_TIMEOUT_SECONDS+_TIMEOUTS_BY_SERVICE_TIER: Final[TypeAdapter[Mapping[str, float] | None]] = TypeAdapter(Mapping[str, float] | None)+def get_configured_request_timeout() -> float | None:"""Return the explicitly-configured ``litellm.request_timeout``, else ``None``."""@@ -27,3 +32,19 @@ def get_configured_request_timeout() -> float | None:if timeout != float(DEFAULT_REQUEST_TIMEOUT_SECONDS):return timeoutreturn None+++class _DeploymentParams(Protocol):+ def get(self, key: str, /) -> object: ...+++def get_service_tier_timeout(+ service_tier: object,+ litellm_params: _DeploymentParams,+ key: Literal["timeout_by_service_tier", "stream_timeout_by_service_tier"],+) -> float | None:+ """Return the deployment's ``key`` timeout for the request's ``service_tier``, else ``None``."""+ if not isinstance(service_tier, str):+ return None+ timeouts: Final = _TIMEOUTS_BY_SERVICE_TIER.validate_python(litellm_params.get(key))+ return None if timeouts is None else timeouts.get(service_tier)diff --git a/litellm/passthrough/timeout_utils.py b/litellm/passthrough/timeout_utils.pyindex f600c7817f2..ce13552ff49 100644--- a/litellm/passthrough/timeout_utils.py+++ b/litellm/passthrough/timeout_utils.py@@ -5,7 +5,10 @@ from typing import Finalfrom pydantic import TypeAdapter-from litellm.litellm_core_utils.request_timeout_resolver import get_configured_request_timeout+from litellm.litellm_core_utils.request_timeout_resolver import (+ get_configured_request_timeout,+ get_service_tier_timeout,+)DEFAULT_PASS_THROUGH_REQUEST_TIMEOUT_SECONDS: Final = 600.0@@ -50,21 +53,27 @@ def resolve_llm_passthrough_timeout(Anthropic /v1/messages).Non-streaming precedence: kwargs timeout/request_timeout -> litellm_params- timeout/request_timeout -> router_timeout -> litellm.request_timeout (litellm_settings.request_timeout,+ timeout_by_service_tier[kwargs service_tier] -> litellm_params timeout/request_timeout -> router_timeout -> litellm.request_timeout (litellm_settings.request_timeout,when explicitly set) -> general_settings.pass_through_request_timeout -> 600s default.Streaming (``kwargs["stream"]`` truthy) resolves ``stream_timeout`` at every level beforeany generic timeout, matching ``Router._get_stream_timeout`` on the completion route:- kwargs stream_timeout -> litellm_params stream_timeout -> router_stream_timeout, then the- non-streaming chain above.+ kwargs stream_timeout -> litellm_params stream_timeout_by_service_tier[kwargs service_tier] ->+ litellm_params stream_timeout -> router_stream_timeout, then the non-streaming chain above.Only the first set value is validated as seconds, so a value in a lower-precedencefield never fails the call."""request: Final = kwargs if kwargs is not None else _NO_PARAMSdeployment: Final = litellm_params if litellm_params is not None else _NO_PARAMS+ service_tier: Final = request.get("service_tier")stream_candidates: Final = (- (request.get("stream_timeout"), deployment.get("stream_timeout"), router_stream_timeout)+ (+ request.get("stream_timeout"),+ get_service_tier_timeout(service_tier, deployment, "stream_timeout_by_service_tier"),+ deployment.get("stream_timeout"),+ router_stream_timeout,+ )if request.get("stream")else ())@@ -72,6 +81,7 @@ def resolve_llm_passthrough_timeout(*stream_candidates,request.get("timeout"),request.get("request_timeout"),+ get_service_tier_timeout(service_tier, deployment, "timeout_by_service_tier"),deployment.get("timeout"),deployment.get("request_timeout"),router_timeout,diff --git a/litellm/router.py b/litellm/router.pyindex af79fa763c4..5bf46c68b20 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -118,6 +118,7 @@ from litellm.litellm_core_utils.ptu_pricing import ()from litellm.litellm_core_utils.request_timeout_resolver import (get_configured_request_timeout,+ get_service_tier_timeout,)from litellm.litellm_core_utils.secret_redaction import redact_stringfrom litellm.litellm_core_utils.sensitive_data_masker import (@@ -4773,6 +4774,7 @@ class Router:"""Helper to get stream timeout from kwargs or deployment params"""return (kwargs.get("stream_timeout", None) # the params dynamically set by user+ or get_service_tier_timeout(kwargs.get("service_tier"), data, "stream_timeout_by_service_tier")or data.get("stream_timeout", None) # timeout set on litellm_params for this deploymentor self.stream_timeout # timeout set on routeror self.request_timeout # litellm_settings.request_timeout (per-attempt)@@ -4786,6 +4788,7 @@ class Router:return (kwargs.get("timeout", None) # the params dynamically set by useror kwargs.get("request_timeout", None) # the params dynamically set by user+ or get_service_tier_timeout(kwargs.get("service_tier"), data, "timeout_by_service_tier")or data.get("timeout", None) # timeout set on litellm_params for this deploymentor data.get("request_timeout", None) # timeout set on litellm_params for this deploymentor self.request_timeout # litellm_settings.request_timeout (per-attempt)diff --git a/litellm/types/litellm_params.py b/litellm/types/litellm_params.pyindex b05d25462aa..978eb9c4557 100644--- a/litellm/types/litellm_params.py+++ b/litellm/types/litellm_params.py@@ -77,6 +77,8 @@ class ProviderConnection:request_timeout: float | None = Noneforce_timeout: float | None = Nonestream_timeout: float | str | None = None+ timeout_by_service_tier: Mapping[str, float] | None = None+ stream_timeout_by_service_tier: Mapping[str, float] | None = Nonemax_retries: int | None = Nonetenant_id: str | None = Noneclient_id: str | None = Nonediff --git a/litellm/types/router.py b/litellm/types/router.pyindex 46617e1b753..f83127806db 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -505,6 +505,9 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):timeout: float | str | httpx.Timeout | SDKTimeout | None = None # if str, pass in as os.environ/# read timeout of a live stream, a faked stream takes the longer of this and timeout. If str, pass in as os.environ/stream_timeout: float | str | None = None+ # per service_tier overrides of timeout / stream_timeout, used when the request's service_tier matches a key+ timeout_by_service_tier: Mapping[str, float] | None = None+ stream_timeout_by_service_tier: Mapping[str, float] | None = Nonemax_retries: int | None = Nonedrop_params: bool | str | None = Noneorganization: str | None = None # for openai orgs@@ -709,6 +712,8 @@ class LiteLLMParamsTypedDict(TypedDict, total=False):responses_api_version: ReadOnly[str | None]timeout: float | str | httpx.Timeout | SDKTimeout | None # writable-ok: preserve timeout updatesstream_timeout: float | str | None+ timeout_by_service_tier: ReadOnly[Mapping[str, float] | None]+ stream_timeout_by_service_tier: ReadOnly[Mapping[str, float] | None]max_retries: int | Noneorganization: list | str | None # for openai orgsprovider_affinity_header: ReadOnly[str | None]diff --git a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.pyindex 5412ea56ac0..4c3c7ae0f0a 100644--- a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py+++ b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py@@ -1857,6 +1857,32 @@ def test_resolve_llm_passthrough_timeout_validates_only_the_winning_value(assert resolve_llm_passthrough_timeout(kwargs=kwargs, litellm_params=litellm_params) == expected+def test_resolve_llm_passthrough_timeout_uses_the_deployment_timeout_for_the_requests_service_tier():+ litellm_params = {+ "timeout": 610,+ "stream_timeout": 30,+ "timeout_by_service_tier": {"flex": 900},+ "stream_timeout_by_service_tier": {"flex": 950},+ }+ assert resolve_llm_passthrough_timeout(kwargs={"service_tier": "flex"}, litellm_params=litellm_params) == 900.0+ assert resolve_llm_passthrough_timeout(kwargs={"service_tier": "default"}, litellm_params=litellm_params) == 610.0+ assert (+ resolve_llm_passthrough_timeout(kwargs={"service_tier": "flex", "timeout": 20}, litellm_params=litellm_params)+ == 20.0+ )+ assert (+ resolve_llm_passthrough_timeout(kwargs={"service_tier": "flex", "stream": True}, litellm_params=litellm_params)+ == 950.0+ )+ assert (+ resolve_llm_passthrough_timeout(+ kwargs={"service_tier": "flex", "stream": True},+ litellm_params={"timeout": 610, "stream_timeout": 30, "timeout_by_service_tier": {"flex": 900}},+ )+ == 30.0+ )++def test_resolve_llm_passthrough_timeout_rejects_a_non_numeric_winner():with pytest.raises(ValidationError):resolve_llm_passthrough_timeout(kwargs={"timeout": httpx.Timeout(30.0)})diff --git a/tests/unit/test_router/test_router_timeout.py b/tests/unit/test_router/test_router_timeout.pyindex 3265179a513..8fc32620f71 100644--- a/tests/unit/test_router/test_router_timeout.py+++ b/tests/unit/test_router/test_router_timeout.py@@ -153,6 +153,62 @@ def test_unit_test_streaming_timeout(stream):assert stream_timeout_val == normal_timeout+ "request_kwargs, expected_timeout",+ [+ ({"service_tier": "flex"}, 900.0),+ ({"service_tier": "default"}, 610.0),+ ({}, 610.0),+ ({"service_tier": "flex", "timeout": 20}, 20),+ ({"service_tier": "flex", "stream": True}, 950.0),+ ({"service_tier": "default", "stream": True}, 610.0),+ ({"service_tier": "flex", "stream": True, "stream_timeout": 30}, 30),+ ],+)+def test_the_deployment_timeout_for_the_requests_service_tier_wins_over_its_general_timeout(+ request_kwargs: dict[str, object], expected_timeout: float+) -> None:+ router: Final = Router(+ model_list=[+ {+ "model_name": "openai-gpt-5.1",+ "litellm_params": {+ "model": "openai/gpt-5.1",+ "api_key": "sk-test",+ "timeout": 610,+ "stream_timeout": 610,+ "timeout_by_service_tier": {"flex": 900},+ "stream_timeout_by_service_tier": {"flex": 950},+ },+ }+ ]+ )+ deployment_params: Final = router.model_list[0]["litellm_params"]++ assert router._get_timeout(kwargs=request_kwargs, data=deployment_params) == expected_timeout+++def test_a_stream_keeps_the_deployment_stream_timeout_when_only_the_request_timeout_map_names_its_tier() -> None:+ router: Final = Router(+ model_list=[+ {+ "model_name": "openai-gpt-5.1",+ "litellm_params": {+ "model": "openai/gpt-5.1",+ "api_key": "sk-test",+ "timeout": 610,+ "stream_timeout": 30,+ "timeout_by_service_tier": {"flex": 900},+ },+ }+ ]+ )+ deployment_params: Final = router.model_list[0]["litellm_params"]++ assert router._get_timeout(kwargs={"service_tier": "flex", "stream": True}, data=deployment_params) == 30.0+ assert router._get_timeout(kwargs={"service_tier": "flex"}, data=deployment_params) == 900.0++async def _drain_responses_stream(router: Router) -> None:response: Final = await router.aresponses(model="gpt", input="hi", stream=True)_ = [event async for event in response]diff --git a/tests/unit/types/test_litellm_params.py b/tests/unit/types/test_litellm_params.pyindex ce763378656..e88d757519c 100644--- a/tests/unit/types/test_litellm_params.py+++ b/tests/unit/types/test_litellm_params.py@@ -75,6 +75,8 @@ CONNECTION_NAMES: Final = ("request_timeout","force_timeout","stream_timeout",+ "timeout_by_service_tier",+ "stream_timeout_by_service_tier","max_retries","tenant_id","client_id",diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex daffc3c0c41..733a093bcac 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -35424,6 +35424,10 @@ export interface components {} | null;/** Stream Timeout */stream_timeout?: number | string | null;+ /** Stream Timeout By Service Tier */+ stream_timeout_by_service_tier?: {+ [key: string]: number;+ } | null;/** Tag Regex */tag_regex?: string[] | null;/** Tags */@@ -35436,6 +35440,10 @@ export interface components {}[] | null;/** Timeout */timeout?: number | string | null;+ /** Timeout By Service Tier */+ timeout_by_service_tier?: {+ [key: string]: number;+ } | null;/** Token Exchange Audience */token_exchange_audience?: string | null;/** Token Exchange Endpoint */@@ -50666,6 +50674,10 @@ export interface components {} | null;/** Stream Timeout */stream_timeout?: number | string | null;+ /** Stream Timeout By Service Tier */+ stream_timeout_by_service_tier?: {+ [key: string]: number;+ } | null;/** Tag Regex */tag_regex?: string[] | null;/** Tags */@@ -50678,6 +50690,10 @@ export interface components {}[] | null;/** Timeout */timeout?: number | string | null;+ /** Timeout By Service Tier */+ timeout_by_service_tier?: {+ [key: string]: number;+ } | null;/** Token Exchange Audience */token_exchange_audience?: string | null;/** Token Exchange Endpoint */