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
fix(router)!: bound fake-streamed calls by the request timeout, not stream_timeout (#47162)
Mateo Wang16645cc96332
diff --git a/litellm/litellm_core_utils/completion_timeout.py b/litellm/litellm_core_utils/completion_timeout.pyindex e6f18257138..a2e7780ded0 100644--- a/litellm/litellm_core_utils/completion_timeout.py+++ b/litellm/litellm_core_utils/completion_timeout.py@@ -2,15 +2,25 @@from __future__ import annotations-from collections.abc import Callable+from collections.abc import Callable, Mapping+from enum import Enum+from functools import partial+from types import MappingProxyTypefrom typing import Finalimport httpxfrom openai import Timeout as SDKTimeout+from typing_extensions import assert_neverfrom litellm.constants import COMPLETION_HTTP_FALLBACK_SECONDS+class StreamKind(Enum):+ NOT_STREAMED = "not_streamed"+ LIVE = "live"+ FAKED = "faked"++class CompletionTimeout:"""Resolves HTTP timeout for ``completion()`` from model vs global settings."""@@ -36,17 +46,91 @@ class CompletionTimeout:return COMPLETION_HTTP_FALLBACK_SECONDSreturn float(global_timeout)+ @staticmethod+ def _longer_limit(first: float | None, second: float | None) -> float | None:+ return None if first is None or second is None else max(first, second)++ @staticmethod+ def _longer(first: float | httpx.Timeout, second: float | httpx.Timeout) -> float | httpx.Timeout:+ if not isinstance(first, httpx.Timeout) and not isinstance(second, httpx.Timeout):+ return max(first, second)+ first_limits: Final = httpx.Timeout(first)+ second_limits: Final = httpx.Timeout(second)+ longer: Final = CompletionTimeout._longer_limit+ return httpx.Timeout(+ connect=longer(first_limits.connect, second_limits.connect),+ read=longer(first_limits.read, second_limits.read),+ write=longer(first_limits.write, second_limits.write),+ pool=longer(first_limits.pool, second_limits.pool),+ )++ @staticmethod+ def for_stream(+ stream_kind: StreamKind, request_timeout: float | httpx.Timeout, stream_timeout: float | httpx.Timeout | None+ ) -> float | httpx.Timeout:+ """+ ``stream_timeout`` bounds each read of a live stream, so it replaces the request timeout there. A fake+ stream is one non-streaming request whose first byte arrives when generation ends, so it takes the longer+ of each limit and never fails sooner than the same call would with either one alone.+ """+ if stream_timeout is None:+ return request_timeout+ match stream_kind:+ case StreamKind.NOT_STREAMED:+ return request_timeout+ case StreamKind.LIVE:+ return stream_timeout+ case StreamKind.FAKED:+ return CompletionTimeout._longer(request_timeout, stream_timeout)+ case _:+ assert_never(stream_kind)++ @staticmethod+ def as_limit(timeout: object) -> float | httpx.Timeout:+ if isinstance(timeout, (httpx.Timeout, SDKTimeout)):+ return CompletionTimeout.normalize(timeout)+ if isinstance(timeout, (float, int, str)):+ return float(timeout)+ raise TypeError(f"timeout must be a number or an httpx.Timeout, got {type(timeout).__name__}")++ @staticmethod+ def stream_request_kwargs(non_stream_timeout: object, stream_timeout: object) -> Mapping[str, object]:+ if stream_timeout is None:+ return MappingProxyType({"timeout": non_stream_timeout})+ return MappingProxyType(+ {+ "timeout": None+ if non_stream_timeout is None+ else CompletionTimeout.for_stream(+ StreamKind.FAKED,+ CompletionTimeout.as_limit(non_stream_timeout),+ CompletionTimeout.as_limit(stream_timeout),+ ),+ "stream_timeout": stream_timeout,+ }+ )++ @staticmethod+ def _coerce(+ timeout: object, custom_llm_provider: str, supports_httpx_timeout: Callable[[str], bool]+ ) -> float | httpx.Timeout:+ limit: Final = CompletionTimeout.as_limit(timeout)+ if not isinstance(limit, httpx.Timeout) or supports_httpx_timeout(custom_llm_provider):+ return limit+ return float(limit.read) if limit.read is not None else COMPLETION_HTTP_FALLBACK_SECONDS+@staticmethoddef resolve(model_timeout: float | str | httpx.Timeout | SDKTimeout | None,- kwargs: dict,+ kwargs: Mapping[str, object],custom_llm_provider: str,*,global_timeout: float | str | None,supports_httpx_timeout: Callable[[str], bool],+ stream_kind: StreamKind,) -> float | httpx.Timeout:"""- Resolution order (first non-None wins):+ Request timeout resolution order (first non-None wins):1. ``model_timeout`` (call argument / merged ``litellm_params``)2. ``kwargs["timeout"]``@@ -54,24 +138,20 @@ class CompletionTimeout:4. ``global_timeout`` (the explicitly-configured ``litellm.request_timeout``),or 600 when nothing was configured.+ A stream then applies ``kwargs["stream_timeout"]`` per :meth:`for_stream`.Coerce :class:`httpx.Timeout` when the provider does not support it."""- resolved: float | str | httpx.Timeout | SDKTimeout- if model_timeout is not None:- resolved = model_timeout- elif kwargs.get("timeout") is not None:- resolved = kwargs["timeout"]- elif kwargs.get("request_timeout") is not None:- resolved = kwargs["request_timeout"]- else:- resolved = CompletionTimeout._fallback_when_no_explicit_timeout(global_timeout)-- if isinstance(resolved, (httpx.Timeout, SDKTimeout)):- normalized: Final = CompletionTimeout.normalize(resolved)- if supports_httpx_timeout(custom_llm_provider):- return normalized- read_timeout: Final = normalized.read- return (- float(read_timeout) if read_timeout is not None else COMPLETION_HTTP_FALLBACK_SECONDS- ) # default 10 min timeout- return float(resolved)+ coerce: Final = partial(+ CompletionTimeout._coerce,+ custom_llm_provider=custom_llm_provider,+ supports_httpx_timeout=supports_httpx_timeout,+ )+ non_stream_candidates: Final = (model_timeout, kwargs.get("timeout"), kwargs.get("request_timeout"))+ explicit: Final = next((candidate for candidate in non_stream_candidates if candidate is not None), None)+ request_timeout: Final = coerce(+ explicit if explicit is not None else CompletionTimeout._fallback_when_no_explicit_timeout(global_timeout)+ )+ stream_timeout: Final = None if stream_kind is StreamKind.NOT_STREAMED else kwargs.get("stream_timeout")+ return CompletionTimeout.for_stream(+ stream_kind, request_timeout, None if stream_timeout is None else coerce(stream_timeout)+ )diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 99ebf479b20..b6bdc21bc05 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -19,7 +19,7 @@ from functools import lru_cachefrom types import MappingProxyType, TracebackTypefrom typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, cast-from httpx import Response+from httpx import Response, Timeoutfrom pydantic import BaseModel, JsonValue, TypeAdapterimport litellm@@ -671,6 +671,7 @@ class Logging(LiteLLMLoggingBaseClass):self.message_copy_duration_ms: float = (time.time() - _copy_start) * 1000self.callback_duration_ms: float = 0.0self.stream = stream+ self.applied_timeout: float | Timeout | None = Noneself.start_time = start_time # log the call start timeself.call_type = call_typeself.relays_llm_passthrough: Final = call_type in (@@ -1056,6 +1057,11 @@ class Logging(LiteLLMLoggingBaseClass):if "custom_llm_provider" in self.model_call_details:self.custom_llm_provider = self.model_call_details["custom_llm_provider"]+ def record_applied_timeout(self, timeout: float | Timeout) -> None:+ self.applied_timeout = timeout+ self.litellm_params["timeout"] = timeout+ self.model_call_details["litellm_params"] = self.litellm_params+def update_from_kwargs(self,kwargs: dict,diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 1bccef7dd9e..3aa925db70e 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -2239,24 +2239,25 @@ class BaseLLMHTTPHandler:stream: bool,custom_llm_provider: str,) -> float | httpx.Timeout | None:- from litellm.litellm_core_utils.completion_timeout import CompletionTimeout+ from litellm.litellm_core_utils.completion_timeout import CompletionTimeout, StreamKindfrom litellm.litellm_core_utils.request_timeout_resolver import (get_configured_request_timeout,)from litellm.utils import supports_httpx_timeoutstream_timeout: Final = litellm_params.get("stream_timeout") if stream else None- model_timeout: Final = stream_timeout if stream_timeout is not None else litellm_params.get("timeout")+ model_timeout: Final = litellm_params.get("timeout")request_timeout: Final = litellm_params.get("request_timeout")global_timeout: Final = get_configured_request_timeout()- if model_timeout is None and request_timeout is None and global_timeout is None:+ if stream_timeout is None and model_timeout is None and request_timeout is None and global_timeout is None:return Nonereturn CompletionTimeout.resolve(model_timeout,- {"request_timeout": request_timeout},+ {"stream_timeout": stream_timeout, "request_timeout": request_timeout},custom_llm_provider,global_timeout=global_timeout,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.LIVE if stream else StreamKind.NOT_STREAMED,)async def async_anthropic_messages_handler(@@ -2410,6 +2411,13 @@ class BaseLLMHTTPHandler:},)+ applied_timeout: Final = self._resolve_anthropic_messages_timeout(+ litellm_params=litellm_params,+ stream=stream or False,+ custom_llm_provider=custom_llm_provider,+ )+ if applied_timeout is not None:+ logging_obj.record_applied_timeout(applied_timeout)response: Final = await self._async_post_anthropic_messages_with_http_error_retry(async_httpx_client=async_httpx_client,request_url=request_url,@@ -2422,11 +2430,7 @@ class BaseLLMHTTPHandler:litellm_params=litellm_params,api_key=api_key,model=model,- timeout=self._resolve_anthropic_messages_timeout(- litellm_params=litellm_params,- stream=stream or False,- custom_llm_provider=custom_llm_provider,- ),+ timeout=applied_timeout,)# used for logging + cost trackingdiff --git a/litellm/llms/microsoft_365_copilot/chat/transformation.py b/litellm/llms/microsoft_365_copilot/chat/transformation.pyindex 6b7366685fd..0a40790001c 100644--- a/litellm/llms/microsoft_365_copilot/chat/transformation.py+++ b/litellm/llms/microsoft_365_copilot/chat/transformation.py@@ -109,6 +109,11 @@ class Microsoft365CopilotChatConfig(BaseConfig):def get_supported_openai_params(self, model: str) -> list[str]: # mutable-ok: BaseConfig requires a list returnreturn ["stream", "max_tokens", "max_completion_tokens"]+ def should_fake_stream(+ self, model: str | None, stream: bool | None, custom_llm_provider: str | None = None+ ) -> bool:+ return True+def transform_request(self,model: str,diff --git a/litellm/main.py b/litellm/main.pyindex 85d00f28025..9cad1f82c7e 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -77,7 +77,7 @@ from litellm.litellm_core_utils.audio_utils.utils import (from litellm.litellm_core_utils.chat_completion_agentic_loop import (maybe_run_chat_completion_agentic_loop,)-from litellm.litellm_core_utils.completion_timeout import CompletionTimeout+from litellm.litellm_core_utils.completion_timeout import CompletionTimeout, StreamKindfrom litellm.litellm_core_utils.dd_tracing import tracerfrom litellm.litellm_core_utils.get_litellm_params import (AWS_CREDENTIAL_KWARGS_KEYS,@@ -530,7 +530,14 @@ async def acompletion(mock_timeout = kwargs.get("mock_timeout", None)if mock_timeout is True:- await _handle_mock_timeout_async(mock_timeout, timeout, model)+ stream_timeout: Final = kwargs.get("stream_timeout")+ await _handle_mock_timeout_async(+ mock_timeout,+ stream_timeout+ if stream is True and isinstance(stream_timeout, int | float | str | httpx.Timeout)+ else timeout,+ model,+ )loop: Final = asyncio.get_event_loop()custom_llm_provider = kwargs.get("custom_llm_provider", None)@@ -1135,6 +1142,52 @@ def _drop_anthropic_only_tool_keys(tools: list[dict[str, object]] | None) -> lisreturn [_without_anthropic_only_tool_keys(tool) if isinstance(tool, dict) else tool for tool in tools]+def _azure_completion_fakes_stream(model: str, base_model: str | None) -> bool:+ if not litellm.AzureOpenAIO1Config().is_o_series_model(model=base_model or model):+ return False+ o_series_handler_config: Final = ProviderConfigManager.get_provider_chat_config(+ model=model, provider=LlmProviders.AZURE+ )+ return o_series_handler_config is not None and o_series_handler_config.should_fake_stream(+ model=model, stream=True, custom_llm_provider=LlmProviders.AZURE.value+ )+++def _completion_fakes_stream(+ model: str,+ custom_llm_provider: str | None,+ provider_config: BaseConfig | None,+ optional_params: Mapping[str, object],+ *,+ base_model: str | None,+ bridges_to_responses_api: bool,+) -> bool:+ if optional_params.get("fake_stream") is True:+ return True+ if custom_llm_provider is None:+ return False+ if bridges_to_responses_api:+ responses_config: Final = ProviderConfigManager.get_provider_responses_api_config(+ provider=custom_llm_provider, model=model+ )+ return responses_config is not None and responses_config.should_fake_stream(+ model=model, stream=True, custom_llm_provider=custom_llm_provider+ )+ if (+ custom_llm_provider == LlmProviders.VERTEX_AI.value+ and get_vertex_ai_model_route(model=model, litellm_params={"base_model": base_model})+ == VertexAIModelRoute.GEMMA+ ):+ return True+ if isinstance(provider_config, litellm.AmazonAI21Config):+ return True+ if custom_llm_provider == LlmProviders.AZURE.value:+ return _azure_completion_fakes_stream(model, base_model)+ return provider_config is not None and provider_config.should_fake_stream(+ model=model, stream=True, custom_llm_provider=custom_llm_provider+ )++class _ProxyAuthHeadersProvider(Protocol):def get_auth_headers(self) -> Mapping[str, str]: ...@@ -5574,15 +5627,6 @@ def completion("aws_region_name", None) # support region-based pricing for bedrock- ### TIMEOUT LOGIC ###- timeout = CompletionTimeout.resolve(- timeout,- kwargs,- custom_llm_provider,- global_timeout=get_configured_request_timeout(),- supports_httpx_timeout=supports_httpx_timeout,- )-### REGISTER CUSTOM MODEL PRICING -- IF GIVEN ###if ((input_cost_per_token is not None and output_cost_per_token is not None)@@ -5713,6 +5757,33 @@ def completion(model_info=_MODEL_INFO_ADAPTER.validate_python(model_info) if isinstance(model_info, dict) else None,**non_default_params,)+ stream_kind: Final = (+ (+ StreamKind.FAKED+ if _completion_fakes_stream(+ model,+ custom_llm_provider,+ provider_config,+ optional_params,+ base_model=base_model if isinstance(base_model, str) else None,+ bridges_to_responses_api=bridges_to_responses_api is True,+ )+ else StreamKind.LIVE+ )+ if stream is True+ else StreamKind.NOT_STREAMED+ )++ ### TIMEOUT LOGIC ###+ timeout = CompletionTimeout.resolve(+ timeout,+ kwargs,+ custom_llm_provider,+ global_timeout=get_configured_request_timeout(),+ supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=stream_kind,+ )+ logging.record_applied_timeout(timeout)processed_non_default_params: Final = pre_process_non_default_params(model=model,passed_params=optional_param_args,diff --git a/litellm/messages/dispatch.py b/litellm/messages/dispatch.pyindex cbf3ff6a04d..cb6ed8d5c75 100644--- a/litellm/messages/dispatch.py+++ b/litellm/messages/dispatch.py@@ -50,6 +50,13 @@ _PYTHON_AMESSAGES: Final = _python_amessages()_AMESSAGES: Final = signature(_PYTHON_AMESSAGES)+def _native_kwargs(fields: Mapping[str, object], kwargs: Mapping[str, object]) -> Mapping[str, object]:+ stream_timeout: Final = kwargs.get("stream_timeout")+ if fields.get("stream") is not True or stream_timeout is None:+ return kwargs+ return {**kwargs, "timeout": stream_timeout}++def _public_request(legacy: inspect.Signature, args: tuple[object, ...], kwargs: Mapping[str, object]) -> NativeCall | None:@@ -61,7 +68,7 @@ def _public_request(max_tokens: Final = fields.get("max_tokens")if not isinstance(model, str) or messages is None or not isinstance(max_tokens, int):return None- return native_call(legacy, args, kwargs)+ return native_call(legacy, args, _native_kwargs(fields, kwargs))def _resolved_provider(request: NativeCall) -> str | None:diff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex ec1786b529a..e775e155dea 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -28,6 +28,7 @@ from litellm.integrations.anthropic_cache_control_hook import (configured_injection_points,)from litellm.litellm_core_utils.asyncify import run_async_function+from litellm.litellm_core_utils.completion_timeout import CompletionTimeout, StreamKindfrom litellm.litellm_core_utils.core_helpers import normalize_drop_paramsfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup@@ -1654,6 +1655,17 @@ def responses(if custom_llm_provider is None:raise ValueError("custom_llm_provider is required but passed as None")+ fake_stream: Final = responses_api_provider_config.should_fake_stream(+ model=model, stream=stream, custom_llm_provider=custom_llm_provider+ )+ applied_timeout: Final = CompletionTimeout.for_stream(+ (StreamKind.FAKED if fake_stream else StreamKind.LIVE) if stream is True else StreamKind.NOT_STREAMED,+ CompletionTimeout.as_limit(timeout or request_timeout),+ None+ if stream is not True or litellm_params.stream_timeout is None+ else float(litellm_params.stream_timeout),+ )+ litellm_logging_obj.record_applied_timeout(applied_timeout)response = base_llm_http_handler.response_api_handler(model=model,input=input,@@ -1664,12 +1676,10 @@ def responses(logging_obj=litellm_logging_obj,extra_headers=effective_extra_headers,extra_body=extra_body,- timeout=timeout or request_timeout,+ timeout=applied_timeout,_is_async=_is_async,client=kwargs.get("client"),- fake_stream=responses_api_provider_config.should_fake_stream(- model=model, stream=stream, custom_llm_provider=custom_llm_provider- ),+ fake_stream=fake_stream,litellm_metadata=kwargs.get("litellm_metadata", {}),shared_session=kwargs.get("shared_session"),)diff --git a/litellm/router.py b/litellm/router.pyindex e363f41ccde..c30108b4e38 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -81,6 +81,7 @@ from litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.otel.routing import routing_decision_attributesfrom litellm.integrations.otel.runtime import phase_attributes, phase_event, phase_spanfrom litellm.litellm_core_utils.asyncify import run_async_function+from litellm.litellm_core_utils.completion_timeout import CompletionTimeoutfrom litellm.litellm_core_utils.core_helpers import (coerce_token_limit,get_litellm_metadata_from_kwargs,@@ -347,6 +348,7 @@ from litellm.types.router import (DiscoveredDeploymentModelInfo,FallbackAccessCheck,FallbackBudgetCheck,+ GenericLiteLLMParams,GuardrailTypedDict,LiteLLM_Params,LiteLLMParamsTypedDict,@@ -511,6 +513,7 @@ _CLAUDE_CODE_SESSION_ROUTER_TTL_SECONDS: Final = 3600CLAUDE_CODE_SESSION_ROUTER_BINDING_TARGET: Final = "claude_code_session_router_binding"_PRE_CALL_CHECK_FILTERED_PARAMS: Final = frozenset({"response_format"})+_STREAM_TIMEOUT_AWARE_GENERIC_HANDLERS: Final = frozenset({"anthropic_messages", "aresponses", "responses"})_RUNTIME_TOGGLEABLE_PRE_CALL_CHECKS: Final[Mapping[str, type[CustomLogger]]] = MappingProxyType({"prompt_caching": PromptCachingDeploymentCheck,@@ -549,6 +552,10 @@ _SILENT_MODEL_ADAPTER: Final = TypeAdapter(str | list[str])_RESOLVED_RETRY_POLICY_ADAPTER: Final = TypeAdapter(RetryPolicy | None)_ROUTING_KWARGS_ADAPTER: Final[TypeAdapter[Mapping[str, object] | None]] = TypeAdapter(Mapping[str, object] | None)_FALLBACK_HOP_ADAPTER: Final = TypeAdapter(Mapping[str, object])+_REQUEST_KWARGS_ADAPTER: Final = TypeAdapter(Mapping[str, object])+_DEPLOYMENT_PARAMS_ADAPTER: Final[TypeAdapter[Mapping[str, object] | GenericLiteLLMParams]] = TypeAdapter(+ Mapping[str, object] | GenericLiteLLMParams+)_OPAQUE_VALUE_ADAPTER: Final = TypeAdapter(object)_DEPLOYMENT_SELECTED_EVENT: Final = "litellm.request.deployment_selected"_CONTENT_BLOCKS_ADAPTER: Final = TypeAdapter(list[dict[str, object]])@@ -2946,7 +2953,7 @@ class Router:).start()kwargs.setdefault("messages", messages)- self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs)+ self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs, splits_stream_timeout=True)kwargs.pop("silent_model", None) # Ensure it's not in kwargs eithermodel_name = litellm_params["model"]potential_model_client: Final = self._get_client(deployment=deployment, kwargs=kwargs)@@ -4289,7 +4296,7 @@ class Router:)kwargs.setdefault("messages", messages)- self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs)+ self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs, splits_stream_timeout=True)kwargs.pop("silent_model", None) # Ensure it's not in kwargs eithermodel_name = litellm_params["model"]@@ -4554,6 +4561,7 @@ class Router:deployment: dict,kwargs: dict,function_name: str | None = None,+ splits_stream_timeout: bool = False,) -> None:"""4 jobs:@@ -4671,14 +4679,35 @@ class Router:if self.request_timeout is not Noneelse self.default_litellm_params.get("stream_timeout"))- kwargs["timeout"] = resolve_llm_passthrough_timeout(- kwargs=kwargs,+ passthrough_timeout: Final = partial(+ resolve_llm_passthrough_timeout,litellm_params=deployment["litellm_params"],router_timeout=_router_timeout,router_stream_timeout=_router_stream_timeout,)+ kwargs.update(+ CompletionTimeout.stream_request_kwargs(+ passthrough_timeout(kwargs={**kwargs, "stream": False}), passthrough_timeout(kwargs=kwargs)+ )+ if splits_stream_timeout and kwargs.get("stream")+ else {"timeout": passthrough_timeout(kwargs=kwargs)}+ )+ elif splits_stream_timeout:+ request_kwargs: Final = _REQUEST_KWARGS_ADAPTER.validate_python(kwargs)+ deployment_params: Final = _DEPLOYMENT_PARAMS_ADAPTER.validate_python(deployment["litellm_params"])+ kwargs.update(+ CompletionTimeout.stream_request_kwargs(+ self._get_non_stream_timeout(kwargs=request_kwargs, data=deployment_params),+ self._get_stream_timeout(kwargs=request_kwargs, data=deployment_params)+ if request_kwargs.get("stream")+ else None,+ )+ )else:- kwargs["timeout"] = self._get_timeout(kwargs=kwargs, data=deployment["litellm_params"])+ kwargs["timeout"] = self._get_timeout(+ kwargs=_REQUEST_KWARGS_ADAPTER.validate_python(kwargs),+ data=_DEPLOYMENT_PARAMS_ADAPTER.validate_python(deployment["litellm_params"]),+ )self._update_kwargs_with_default_litellm_params(kwargs=kwargs, metadata_variable_name=metadata_variable_name)hop_kwargs: Final = _FALLBACK_HOP_ADAPTER.validate_python(kwargs)@@ -4715,7 +4744,9 @@ class Router:return model_client- def _get_stream_timeout(self, kwargs: dict, data: dict) -> float | int | None:+ def _get_stream_timeout(+ self, kwargs: Mapping[str, object], data: Mapping[str, object] | GenericLiteLLMParams+ ) -> object:"""Helper to get stream timeout from kwargs or deployment params"""return (kwargs.get("stream_timeout", None) # the params dynamically set by user@@ -4725,9 +4756,11 @@ class Router:or self.default_litellm_params.get("stream_timeout", None))- def _get_non_stream_timeout(self, kwargs: dict, data: dict) -> float | int | None:+ def _get_non_stream_timeout(+ self, kwargs: Mapping[str, object], data: Mapping[str, object] | GenericLiteLLMParams+ ) -> object:"""Helper to get non-stream timeout from kwargs or deployment params"""- timeout: Final = (+ return (kwargs.get("timeout", None) # the params dynamically set by useror kwargs.get("request_timeout", None) # the params dynamically set by useror data.get("timeout", None) # timeout set on litellm_params for this deployment@@ -4736,18 +4769,11 @@ class Router:or self.timeout # timeout set on router (router_settings.timeout)or self.default_litellm_params.get("timeout", None))- return timeout- def _get_timeout(self, kwargs: dict, data: dict) -> float | int | None:+ def _get_timeout(self, kwargs: Mapping[str, object], data: Mapping[str, object] | GenericLiteLLMParams) -> object:"""Helper to get timeout from kwargs or deployment params"""- timeout: float | int | None = None- if kwargs.get("stream", False):- timeout = self._get_stream_timeout(kwargs=kwargs, data=data)- if timeout is None:- timeout = self._get_non_stream_timeout(- kwargs=kwargs, data=data- ) # default to this if no stream specific timeout set- return timeout+ stream_timeout: Final = self._get_stream_timeout(kwargs=kwargs, data=data) if kwargs.get("stream") else None+ return stream_timeout if stream_timeout is not None else self._get_non_stream_timeout(kwargs=kwargs, data=data)async def abatch_completion(self,@@ -5089,6 +5115,8 @@ class Router:})litellm_logging_object = cast(LiteLLMLogging, litellm_logging_object)+ caller_timeout: Final = kwargs.get("timeout") or kwargs.get("request_timeout")+ caller_stream_timeout: Final = kwargs.get("stream_timeout")specific_deployment: Final = kwargs.pop("specific_deployment", None)prompt_management_deployment: Final = await self.async_get_available_deployment(model=model,@@ -5097,7 +5125,9 @@ class Router:request_kwargs=kwargs,)- self._update_kwargs_with_deployment(deployment=prompt_management_deployment, kwargs=kwargs)+ self._update_kwargs_with_deployment(+ deployment=prompt_management_deployment, kwargs=kwargs, splits_stream_timeout=True+ )data: Final = prompt_management_deployment["litellm_params"].copy()litellm_model: Final = data.get("model", None)@@ -5159,7 +5189,21 @@ class Router:kwargs.pop("original_function")return await litellm.acompletion(**kwargs)- return await self.async_function_with_fallbacks(**kwargs)+ target_group_timeouts: Final = {+ key: value+ for key, value in (+ ("timeout", caller_timeout if caller_timeout is not None else filtered_data.get("timeout")),+ (+ "stream_timeout",+ caller_stream_timeout if caller_stream_timeout is not None else filtered_data.get("stream_timeout"),+ ),+ )+ if value is not None+ }+ return await self.async_function_with_fallbacks(+ **{key: value for key, value in kwargs.items() if key not in ("timeout", "stream_timeout")},+ **target_group_timeouts,+ )def image_generation(self, prompt: str, model: str, **kwargs):try:@@ -5596,7 +5640,7 @@ class Router:specific_deployment=kwargs.pop("specific_deployment", None),request_kwargs=kwargs,)- self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs)+ self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs, splits_stream_timeout=True)data: Final = deployment["litellm_params"].copy()model_name: Final = data["model"]@@ -5666,7 +5710,7 @@ class Router:specific_deployment=kwargs.pop("specific_deployment", None),request_kwargs=kwargs,)- self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs)+ self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs, splits_stream_timeout=True)data: Final = deployment["litellm_params"].copy()model_name: Final = data["model"]@@ -5901,7 +5945,13 @@ class Router:return await original_generic_function(model=model, **kwargs)raise e- self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs, function_name=function_name)+ self._update_kwargs_with_deployment(+ deployment=deployment,+ kwargs=kwargs,+ function_name=function_name,+ splits_stream_timeout=getattr(original_generic_function, "__name__", None)+ in _STREAM_TIMEOUT_AWARE_GENERIC_HANDLERS,+ )data: Final = deployment["litellm_params"].copy()model_name: Final = data["model"]@@ -6613,7 +6663,12 @@ class Router:specific_deployment=kwargs.pop("specific_deployment", None),request_kwargs=kwargs,)- self._update_kwargs_with_deployment(deployment=deployment, kwargs=kwargs, function_name="generic_api_call")+ self._update_kwargs_with_deployment(+ deployment=deployment,+ kwargs=kwargs,+ function_name="generic_api_call",+ splits_stream_timeout=handler_name in _STREAM_TIMEOUT_AWARE_GENERIC_HANDLERS,+ )data: Final = deployment["litellm_params"].copy()model_name: Final = data["model"]diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 96add8bb2a1..1bd1c2e5502 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -502,7 +502,8 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):itpm: int | None = Noneotpm: int | None = Nonetimeout: float | str | httpx.Timeout | SDKTimeout | None = None # if str, pass in as os.environ/- stream_timeout: float | str | None = None # timeout when making stream=True calls, 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 = Nonemax_retries: int | None = Nonedrop_params: bool | str | None = Noneorganization: str | None = None # for openai orgsdiff --git a/litellm/utils.py b/litellm/utils.pyindex d6bdee4697b..9136e3f12d6 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -1482,15 +1482,16 @@ def _get_wrapper_num_retries(kwargs: dict[str, Any], exception: Exception) -> tureturn num_retries, kwargs-def _get_wrapper_timeout(kwargs: dict[str, object], exception: Exception) -> float | int | httpx.Timeout | None:- """- Get the timeout from the kwargs- Used for the wrapper functions.- """-- timeout: Final = cast(float | int | httpx.Timeout | None, kwargs.get("timeout", None))+def _get_wrapper_timeout(kwargs: dict[str, object]) -> object:+ from litellm.litellm_core_utils.litellm_logging import Logging- return timeout+ if kwargs.get("stream") is not True:+ return kwargs.get("timeout")+ logging_obj: Final = kwargs.get("litellm_logging_obj")+ if isinstance(logging_obj, Logging) and logging_obj.applied_timeout is not None:+ return logging_obj.applied_timeout+ stream_timeout: Final = kwargs.get("stream_timeout")+ return kwargs.get("timeout") if stream_timeout is None else stream_timeoutdef check_coroutine(value) -> bool:@@ -2353,7 +2354,7 @@ def client(original_function):if deployment_num_retries is not None:setattr(e, "num_retries", deployment_num_retries)- timeout: Final = _get_wrapper_timeout(kwargs=kwargs, exception=e)+ timeout: Final = _get_wrapper_timeout(kwargs=kwargs)setattr(e, "timeout", timeout)raise ediff --git a/tests/integration/providers/test_bedrock_stream_timeout_wire.py b/tests/integration/providers/test_bedrock_stream_timeout_wire.pyindex 631232a0420..66267ca80ce 100644--- a/tests/integration/providers/test_bedrock_stream_timeout_wire.py+++ b/tests/integration/providers/test_bedrock_stream_timeout_wire.py@@ -22,6 +22,8 @@ _CONVERSE_MODEL_ID: Final = "global.moonshotai.kimi-k3"_CONVERSE_MODEL: Final = f"bedrock/converse/{_CONVERSE_MODEL_ID}"_INVOKE_MODEL_ID: Final = "anthropic.claude-3-haiku-20240307-v1:0"_INVOKE_MODEL: Final = f"bedrock/invoke/{_INVOKE_MODEL_ID}"+_FAKED_MODEL_ID: Final = "ai21.jamba-1-5-mini-v1:0"+_FAKED_MODEL: Final = f"bedrock/converse/{_FAKED_MODEL_ID}"_EVENT_STREAM: Final = "application/vnd.amazon.eventstream"_ANSWER_HEAD: Final = "scripted answer part one "_ANSWER_TAIL: Final = "scripted answer part two"@@ -31,6 +33,9 @@ _USER_TURN: Final[dict[str, JsonValue]] = {"role": "user", "content": _PROMPT}_TIMEOUT_SECONDS: Final = 1_PAUSE_SECONDS: Final = 3.0_HOLD_SECONDS: Final = 40.0+_GENERATION_SECONDS: Final = 3.0+_LONG_TIMEOUT_SECONDS: Final = 6+_BOTH_LIMITS_TIMEOUT_SECONDS: Final = 2_CLIENT_WINDOW: Final = 10.0_RETRY_WINDOW: Final = 25.0_SHORT_WINDOW: Final = 3.0@@ -65,8 +70,8 @@ _INVOKE_RESPONSE: Final = json.dumps(}).encode()-Endpoint = Literal["chat", "messages", "responses"]-Mode = Literal["fast", "stall", "pause", "cut"]+Endpoint = Literal["chat", "messages", "responses", "completions"]+Mode = Literal["fast", "stall", "pause", "cut", "slow"]def _frame(event_type: str, payload: Mapping[str, JsonValue]) -> bytes:@@ -136,6 +141,8 @@ class _Peer:target: Final = unquote(request.target)if self.mode == "stall":self.release.wait(timeout=_HOLD_SECONDS)+ if self.mode == "slow":+ self.release.wait(timeout=_GENERATION_SECONDS)if not _is_stream(target):return Reply(body=_json_for(target))frames: Final = _frames_for(target)@@ -163,6 +170,10 @@ def _converse(scenario: Scenario, wire: Wire, **extra: JsonValue) -> str:return scenario.model(model=_CONVERSE_MODEL, api_base=wire.url, **_AWS, **extra)+def _faked(scenario: Scenario, wire: Wire, **extra: JsonValue) -> str:+ return scenario.model(model=_FAKED_MODEL, api_base=wire.url, **_AWS, **extra)++def _invoke(scenario: Scenario, wire: Wire, **extra: JsonValue) -> str:return scenario.model(model=_INVOKE_MODEL, api_base=wire.url, aws_bedrock_runtime_endpoint=wire.url, **_AWS, **extra@@ -205,6 +216,8 @@ def _path(endpoint: Endpoint) -> str:return "/v1/messages"case "responses":return "/v1/responses"+ case "completions":+ return "/v1/completions"def _body(endpoint: Endpoint, model: str, *, stream: bool = True, **extra: JsonValue) -> dict[str, JsonValue]:@@ -215,6 +228,8 @@ def _body(endpoint: Endpoint, model: str, *, stream: bool = True, **extra: JsonVreturn {"model": model, "messages": [_USER_TURN], "max_tokens": 16, "stream": stream, **_EXTRA, **extra}case "responses":return {"model": model, "input": _PROMPT, "stream": stream, **_EXTRA, **extra}+ case "completions":+ return {"model": model, "prompt": _PROMPT, "stream": stream, **_EXTRA, **extra}@dataclass(frozen=True, slots=True)@@ -318,6 +333,11 @@ def _received(wire: Wire, expected: int) -> None:assert len(wire.drain()) == expected+def _received_targets(wire: Wire, expected: int) -> tuple[str, ...]:+ eventually(wire.received.qsize, lambda size: size == expected, 10)+ return tuple(unquote(request.target) for request in wire.drain())++def _model_identity(gateway: Gateway, model: str) -> str:entries: Final = _MODELS.validate_python(gateway.get("/model/info")["data"])(entry,) = tuple(item for item in entries if item["model_name"] == model)@@ -441,6 +461,39 @@ def test_h13_an_invoke_stream_cut_off_mid_answer_reports_the_timeout_in_band(gat_received(wire, 1)[email protected]("endpoint", ("chat", "messages", "responses", "completions"))+def test_f1_to_f4_a_faked_stream_slower_than_its_stream_timeout_is_answered_within_the_deployment_timeout(+ gateway: Gateway, endpoint: Endpoint+) -> None:+ with _peer("slow") as wire, gateway.scenario() as scenario:+ model: Final = _faked(scenario, wire, timeout=_LONG_TIMEOUT_SECONDS, stream_timeout=_TIMEOUT_SECONDS)+ _assert_answered(_streamed(gateway, endpoint, _body(endpoint, model)))+ (target,) = _received_targets(wire, 1)+ assert target.endswith("/converse"), target+++def test_f5_a_faked_stream_slower_than_both_limits_times_out_at_the_deployment_timeout(gateway: Gateway) -> None:+ with _peer("stall") as wire, gateway.scenario() as scenario:+ model: Final = _faked(scenario, wire, timeout=_BOTH_LIMITS_TIMEOUT_SECONDS, stream_timeout=_TIMEOUT_SECONDS)+ served: Final = _streamed(gateway, "chat", _body("chat", model))+ _assert_timed_out(served.status, served.text, _BOTH_LIMITS_TIMEOUT_SECONDS)+ assert served.headers.get("x-litellm-timeout") == f"{_BOTH_LIMITS_TIMEOUT_SECONDS:.1f}", served.headers+ _received(wire, 1)+ _failure_rows(model, 1)++[email protected]("endpoint", ("chat", "messages", "responses"))+def test_c11_to_c13_a_live_stream_slower_than_its_stream_timeout_still_fails_at_the_stream_timeout(+ gateway: Gateway, endpoint: Endpoint+) -> None:+ with _peer("slow") as wire, gateway.scenario() as scenario:+ model: Final = _converse(scenario, wire, timeout=_LONG_TIMEOUT_SECONDS, stream_timeout=_TIMEOUT_SECONDS)+ served: Final = _streamed(gateway, endpoint, _body(endpoint, model))+ _assert_timed_out(served.status, served.text)+ (target,) = _received_targets(wire, 1)+ assert _is_stream(target), target++def test_c1_chat_without_streaming_already_fails_at_the_deployment_timeout(gateway: Gateway) -> None:with _peer("stall") as wire, gateway.scenario() as scenario:model: Final = _converse(scenario, wire, timeout=_TIMEOUT_SECONDS)diff --git a/tests/integration/streaming/test_interception_converted_stream_options.py b/tests/integration/streaming/test_interception_converted_stream_options.pyindex b9d39b02afd..83a3af06355 100644--- a/tests/integration/streaming/test_interception_converted_stream_options.py+++ b/tests/integration/streaming/test_interception_converted_stream_options.py@@ -8,7 +8,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom queue import SimpleQueuefrom types import MappingProxyType-from typing import Final+from typing import Final, Literal, TypeAliasfrom urllib.parse import urlsplitimport anthropic@@ -549,6 +549,75 @@ def test_converted_chat_stream_with_usage_replays_the_single_call_usage(_assert_landed_once(deployment.model, frozenset({identity}), rows=1)+_SLOW_REPLY_SECONDS: Final = 3.0+_SHORT_TIMEOUT_SECONDS: Final = 1+_LONG_STREAM_TIMEOUT_SECONDS: Final = 10+_MESSAGES_SEARCH_TOOL: Final[Mapping[str, JsonValue]] = MappingProxyType(+ {"name": iv.SEARCH_TOOL, "description": "Search the web", "input_schema": dict(_PARAMETERS)}+)+_MESSAGES_LOOKUP_TOOL: Final[Mapping[str, JsonValue]] = MappingProxyType(+ {"name": "lookup", "description": "Look up an order", "input_schema": dict(_PARAMETERS)}+)++_ConvertedEndpoint: TypeAlias = Literal["chat", "messages"]+++def _slowly(request: Request) -> Reply:+ threading.Event().wait(_SLOW_REPLY_SECONDS)+ return iv.respond(request)+++def _messages_text(stream: _Stream) -> str:+ if stream.text.startswith("{"):+ blocks: Final = rv.ITEMS.validate_python(iv.JSON_OBJECT.validate_json(stream.text)["content"])+ return "".join(string_value(block["text"]) for block in blocks if block.get("type") == "text")+ deltas: Final = tuple(+ object_value(frame["delta"]) for frame in stream.frames if frame.get("type") == "content_block_delta"+ )+ return "".join(string_value(delta["text"]) for delta in deltas if delta.get("type") == "text_delta")+++def _converted_reply_text(rig: _Rig, endpoint: _ConvertedEndpoint, deployment: _Deployment) -> str:+ if endpoint == "chat":+ stream: Final = _chat(rig, _chat_body(deployment))+ _assert_restreamed(stream, iv.plain(deployment.name), usage=None)+ return stream.content+ messages: Final = _post(+ rig,+ "/v1/messages",+ {+ "model": deployment.model,+ "max_tokens": 64,+ "messages": [{"role": "user", "content": f"Search for {deployment.name}"}],+ "tools": [dict(_MESSAGES_SEARCH_TOOL), dict(_MESSAGES_LOOKUP_TOOL)],+ "stream": True,+ **_NO_CACHE,+ },+ )+ assert messages.status == 200, messages.text+ return _messages_text(messages)++[email protected]("endpoint", ("chat", "messages"))+def test_a_converted_stream_slower_than_the_deployment_timeout_is_answered_within_its_stream_timeout(+ rig: _Rig, scenario: Scenario, endpoint: _ConvertedEndpoint+) -> None:+ with wire_server(_slowly) as slow:+ name: Final = iv.deployment("plain")+ model: Final = scenario.model(+ model=f"azure/{name}",+ api_base=slow.url,+ api_key=iv.AZURE_KEY,+ api_version=iv.API_VERSION,+ timeout=_SHORT_TIMEOUT_SECONDS,+ stream_timeout=_LONG_STREAM_TIMEOUT_SECONDS,+ )+ assert _converted_reply_text(rig, endpoint, _Deployment(model, name)) == iv.plain(name)+ received: Final = iv.received(slow.drain(), name)+ _assert_upstream(received, model_calls=1, searches=0)+ assert not any(call.get("stream") for call in received.model_calls), received.model_calls++def test_anthropic_sdk_messages_stream_with_only_web_search_on_azure_answers_from_the_search(rig: _Rig, scenario: Scenario) -> None:diff --git a/tests/test_litellm_rust/messages/test_dispatch.py b/tests/test_litellm_rust/messages/test_dispatch.pyindex c38104495a2..2a32e31c250 100644--- a/tests/test_litellm_rust/messages/test_dispatch.py+++ b/tests/test_litellm_rust/messages/test_dispatch.py@@ -172,6 +172,28 @@ def test_native_receives_normalized_request_and_original_call_shape() -> None:assert call_kwargs["litellm_metadata"] is metadata[email protected]("stream, expected_timeout", ((True, 0.5), (False, 30.0)))+def test_native_streams_are_bounded_by_stream_timeout(stream: bool, expected_timeout: float) -> None:+ captured: Final[list[NativeCall]] = []++ def python(*call_args: object, **call_kwargs: object) -> AnthropicMessagesResponse: # kwargs-ok: rejected fallback+ pytest.fail("Required Rust dispatch must not call Python")++ def native(request: NativeCall) -> AnthropicMessagesResponse:+ captured.append(request)+ return response()++ _ = _DISPATCH.run(+ (16, MESSAGES, "anthropic/claude-sonnet-4-5"),+ {"stream": stream, "timeout": 30.0, "stream_timeout": 0.5},+ python=python,+ binding=messages_binding(native),+ native=lambda hook, request, call_args, call_kwargs: hook(request),+ rules=RUST_RULES,+ )+ assert captured[0].resolved["timeout"] == expected_timeout++def test_internal_async_marker_bypasses_native() -> None:args: Final[tuple[object, ...]] = (16, MESSAGES, "claude-sonnet-4-5")kwargs: Final[Mapping[str, object]] = {"is_async": True}diff --git a/tests/unit/llms/azure/chat/test_azure_base_model_routing.py b/tests/unit/llms/azure/chat/test_azure_base_model_routing.pyindex 1e8e23c38ca..aae2587085f 100644--- a/tests/unit/llms/azure/chat/test_azure_base_model_routing.py+++ b/tests/unit/llms/azure/chat/test_azure_base_model_routing.py@@ -5,12 +5,51 @@ setting ``base_model`` should drive model-type detection (o-series, gpt-5,etc.) so the correct config, supported params, and param mapping are used."""+from typing import Final++import httpx+import openaiimport pytestimport litellmfrom litellm.llms.azure.chat.gpt_5_transformation import AzureOpenAIGPT5Configfrom litellm.llms.azure.chat.o_series_transformation import AzureOpenAIO1Configfrom litellm.utils import ProviderConfigManager, get_optional_params+from tests.unit.llms.bedrock.slow_upstream import STREAM_TIMEOUT_SECONDS, slow_upstream_transport++_O3_STREAM_ANSWER: Final = (+ b'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","created":0,"model":"o3",'+ b'"choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}\n\n'+ b"data: [DONE]\n\n"+)+++ ("model", "base_model"),+ [("azure/chat", "azure/o3"), ("azure/gpt4o-pro1", "azure/gpt-4o")],+ ids=["o3_base_model_streams_natively", "o_series_looking_deployment_of_a_non_o_series_base_model"],+)+def test_live_stream_on_a_deployment_named_apart_from_its_base_model_keeps_its_stream_timeout(+ model: str, base_model: str+) -> None:+ client: Final = openai.AzureOpenAI(+ api_key="test-key",+ api_version="2024-12-01-preview",+ azure_endpoint="https://example.openai.azure.com",+ max_retries=0,+ http_client=httpx.Client(transport=slow_upstream_transport(_O3_STREAM_ANSWER)),+ )++ with pytest.raises(litellm.Timeout):+ litellm.completion(+ model=model,+ base_model=base_model,+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ timeout=30.0,+ client=client,+ )# ---------------------------------------------------------------------------diff --git a/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py b/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.pyindex dec32b3325e..3c96163a7b8 100644--- a/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py+++ b/tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py@@ -6,6 +6,8 @@ AWS credential resolution is stubbed so nothing reaches STS.from __future__ import annotationsimport asyncio+import json+from collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom datetime import datetime, timedelta, timezonefrom itertools import chainfrom typing import Final@@ -13,18 +15,24 @@ from unittest.mock import MagicMock, patchimport boto3import httpx+import openaiimport pytest+import respxfrom botocore.credentials import Credentialsfrom botocore.exceptions import ClientErrorimport litellm+from litellm.integrations.custom_logger import CustomLoggerfrom litellm.llms.bedrock.chat.converse_handler import BedrockConverseLLMfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerfrom litellm.rust_bridge import configuration-from litellm.types.utils import ModelResponse+from litellm.types.utils import AdapterCompletionStreamWrapper, ModelResponsefrom tests.unit.llms.bedrock.event_loop_probe import EventLoopProbefrom tests.unit.llms.bedrock.slow_upstream import (+ CONVERSE_ANSWER,STREAM_TIMEOUT_SECONDS,+ UPSTREAM_FIRST_BYTE_SECONDS,+ slow_upstream_answer,slow_upstream_async_client,slow_upstream_sync_client,)@@ -305,6 +313,273 @@ def test_sync_converse_streaming_fails_at_the_request_timeout_not_the_upstreams_litellm.completion(client=slow_upstream_sync_client(), **_converse_streaming_kwargs())+async def test_live_stream_with_a_text_stream_timeout_reports_the_stream_timeout_it_was_cut_at() -> None:+ with pytest.raises(litellm.Timeout) as excinfo:+ await litellm.acompletion(+ client=slow_upstream_async_client(),+ **{+ **_converse_streaming_kwargs(),+ "timeout": UPSTREAM_FIRST_BYTE_SECONDS * 2,+ "stream_timeout": str(STREAM_TIMEOUT_SECONDS),+ },+ )+ assert getattr(excinfo.value, "timeout", None) == STREAM_TIMEOUT_SECONDS++++_FAKE_STREAMED_REQUESTS: Final = pytest.mark.parametrize(+ ("model", "request_params"),+ [+ ("bedrock/converse/ai21.jamba-1-5-large-v1:0", {}),+ (+ "bedrock/converse/meta.llama3-3-70b-instruct-v1:0",+ {"tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}]},+ ),+ (+ "bedrock/converse/meta.llama3-3-70b-instruct-v1:0",+ {"response_format": {"type": "json_schema", "json_schema": {"name": "answer", "schema": {"type": "object"}}}},+ ),+ ("bedrock/invoke/ai21.j2-ultra-v1", {}),+ ],+ ids=[+ "model_without_streaming",+ "request_shape_without_streaming",+ "json_schema_without_native_structured_output",+ "invoke_route_without_streaming",+ ],+)+++def _bedrock_router(model: str, *, timeout: float, stream_timeout: float) -> litellm.Router:+ return litellm.Router(+ model_list=[+ {+ "model_name": "bedrock",+ "litellm_params": {+ "model": model,+ "aws_access_key_id": "fake",+ "aws_secret_access_key": "fake",+ "aws_region_name": "us-east-1",+ },+ }+ ],+ timeout=timeout,+ stream_timeout=stream_timeout,+ num_retries=0,+ )+++def _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(model: str) -> litellm.Router:+ return _bedrock_router(model, timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2, stream_timeout=STREAM_TIMEOUT_SECONDS)+++@_FAKE_STREAMED_REQUESTS+def test_sync_fake_stream_is_bounded_by_the_request_timeout_not_the_stream_timeout(+ model: str, request_params: Mapping[str, object]+) -> None:+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(model)+ response: Final = router.completion(+ model="bedrock",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ client=slow_upstream_sync_client(CONVERSE_ANSWER),+ **request_params,+ )++ assert "".join(chunk.choices[0].delta.content or "" for chunk in response) == "hi"+++@_FAKE_STREAMED_REQUESTS+async def test_async_fake_stream_is_bounded_by_the_request_timeout_not_the_stream_timeout(+ model: str, request_params: Mapping[str, object]+) -> None:+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(model)+ response: Final = await router.acompletion(+ model="bedrock",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ client=slow_upstream_async_client(CONVERSE_ANSWER),+ **request_params,+ )++ assert "".join([chunk.choices[0].delta.content or "" async for chunk in response]) == "hi"+++async def test_fake_stream_keeps_a_stream_timeout_longer_than_the_request_timeout() -> None:+ router: Final = _bedrock_router(+ "bedrock/converse/ai21.jamba-1-5-large-v1:0",+ timeout=STREAM_TIMEOUT_SECONDS,+ stream_timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ )+ response: Final = await router.acompletion(+ model="bedrock",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ client=slow_upstream_async_client(CONVERSE_ANSWER),+ )++ assert "".join([chunk.choices[0].delta.content or "" async for chunk in response]) == "hi"+++_BEDROCK_RUNTIME_URL: Final = r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/.*"+++async def _text_completion_text(router: litellm.Router) -> str:+ response: Final = await router.atext_completion(model="bedrock", prompt="hi", stream=True)+ return "".join([chunk.choices[0].text or "" async for chunk in response])+++async def _anthropic_messages_text(router: litellm.Router) -> str:+ response: Final = await router.aanthropic_messages(+ model="bedrock", messages=[{"role": "user", "content": "hi"}], max_tokens=10, stream=True+ )+ sse: Final = b"".join([chunk async for chunk in response]).decode()+ events: Final = [json.loads(line.removeprefix("data: ")) for line in sse.splitlines() if line.startswith("data: ")]+ return "".join(event["delta"]["text"] for event in events if event["type"] == "content_block_delta")+++async def _responses_text(router: litellm.Router) -> str:+ response: Final = await router.aresponses(model="bedrock", input="hi", stream=True)+ return "".join([event.delta async for event in response if event.type == "response.output_text.delta"])+++ "stream_text",+ [_text_completion_text, _anthropic_messages_text, _responses_text],+ ids=["text_completion", "anthropic_messages", "responses"],+)+async def test_fake_stream_on_each_router_surface_is_bounded_by_the_request_timeout(+ stream_text: Callable[[litellm.Router], Awaitable[str]],+ respx_mock: respx.MockRouter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ respx_mock.post(url__regex=_BEDROCK_RUNTIME_URL).mock(side_effect=slow_upstream_answer(CONVERSE_ANSWER))+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(+ "bedrock/converse/ai21.jamba-1-5-large-v1:0"+ )++ assert await stream_text(router) == "hi"+++class _ChatCompletionAdapter(CustomLogger):+ def translate_completion_input_params(self, kwargs: Mapping[str, object]) -> Mapping[str, object]:+ return kwargs++ def translate_completion_output_params_streaming(self, completion_stream: object) -> AdapterCompletionStreamWrapper:+ return AdapterCompletionStreamWrapper(completion_stream=completion_stream)+++async def test_fake_stream_through_a_router_adapter_is_bounded_by_the_request_timeout(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "adapters", [{"id": "chat", "adapter": _ChatCompletionAdapter()}])+ respx_mock.post(url__regex=_BEDROCK_RUNTIME_URL).mock(side_effect=slow_upstream_answer(CONVERSE_ANSWER))+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(+ "bedrock/converse/ai21.jamba-1-5-large-v1:0"+ )++ response: Final = await router.aadapter_completion(+ adapter_id="chat", model="bedrock", messages=[{"role": "user", "content": "hi"}], stream=True+ )++ assert isinstance(response, AsyncIterator)+ contents: Final = [+ chunk.choices[0].delta.content or "" async for chunk in response if isinstance(chunk, litellm.ModelResponseStream)+ ]+ assert "".join(contents) == "hi"+++async def test_live_anthropic_messages_stream_through_the_router_fails_at_the_stream_timeout(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ respx_mock.post(url__regex=_BEDROCK_RUNTIME_URL).mock(side_effect=slow_upstream_answer())+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(+ "bedrock/invoke/anthropic.claude-sonnet-4-5-v1:0"+ )++ with pytest.raises(litellm.Timeout) as excinfo:+ await _anthropic_messages_text(router)+ assert getattr(excinfo.value, "timeout", None) == STREAM_TIMEOUT_SECONDS+++def test_sync_live_stream_through_the_router_fails_at_the_stream_timeout() -> None:+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(+ "bedrock/anthropic.claude-sonnet-4-5-v1:0"+ )+ with pytest.raises(litellm.Timeout):+ router.completion(+ model="bedrock", messages=[{"role": "user", "content": "hi"}], stream=True, client=slow_upstream_sync_client()+ )+++async def test_async_live_stream_through_the_router_fails_at_the_stream_timeout() -> None:+ router: Final = _router_with_a_stream_timeout_shorter_than_the_upstreams_first_byte(+ "bedrock/anthropic.claude-sonnet-4-5-v1:0"+ )+ with pytest.raises(litellm.Timeout) as excinfo:+ await router.acompletion(+ model="bedrock", messages=[{"role": "user", "content": "hi"}], stream=True, client=slow_upstream_async_client()+ )+ assert getattr(excinfo.value, "timeout", None) == STREAM_TIMEOUT_SECONDS+++async def test_failed_fake_stream_reports_the_request_timeout_it_was_bounded_by() -> None:+ request_timeout: Final = UPSTREAM_FIRST_BYTE_SECONDS / 2+ router: Final = _bedrock_router(+ "bedrock/converse/ai21.jamba-1-5-large-v1:0", timeout=request_timeout, stream_timeout=STREAM_TIMEOUT_SECONDS+ )+ with pytest.raises(litellm.Timeout) as excinfo:+ await router.acompletion(+ model="bedrock",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ client=slow_upstream_async_client(CONVERSE_ANSWER),+ )+ assert getattr(excinfo.value, "timeout", None) == request_timeout++++ "stream_text",+ [_text_completion_text, _anthropic_messages_text, _responses_text],+ ids=["text_completion", "anthropic_messages", "responses"],+)+ ("model", "upstream_answer", "bounding_timeout"),+ [+ ("bedrock/converse/ai21.jamba-1-5-large-v1:0", CONVERSE_ANSWER, UPSTREAM_FIRST_BYTE_SECONDS / 2),+ ("bedrock/anthropic.claude-sonnet-4-5-v1:0", b"", STREAM_TIMEOUT_SECONDS),+ ],+ ids=["fake_stream", "live_stream"],+)+async def test_failed_stream_on_each_router_surface_reports_the_timeout_it_was_bounded_by(+ stream_text: Callable[[litellm.Router], Awaitable[str]],+ model: str,+ upstream_answer: bytes,+ bounding_timeout: float,+ respx_mock: respx.MockRouter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ respx_mock.post(url__regex=_BEDROCK_RUNTIME_URL).mock(side_effect=slow_upstream_answer(upstream_answer))+ router: Final = _bedrock_router(model, timeout=UPSTREAM_FIRST_BYTE_SECONDS / 2, stream_timeout=STREAM_TIMEOUT_SECONDS)++ with pytest.raises(openai.APIError) as excinfo:+ await stream_text(router)+ assert getattr(excinfo.value, "timeout", None) == bounding_timeout+RECORDED_REASONING: Final = "Tokyo proper has about 14 million people."RECORDED_THINKING_TOKENS: Final = 309JSON_MODE_THINKING_CONVERSE_RESPONSE: Final = {diff --git a/tests/unit/llms/bedrock/slow_upstream.py b/tests/unit/llms/bedrock/slow_upstream.pyindex ed262d0f3ed..f23a947105c 100644--- a/tests/unit/llms/bedrock/slow_upstream.py+++ b/tests/unit/llms/bedrock/slow_upstream.py@@ -7,6 +7,8 @@ gets the answer.from __future__ import annotations+import json+from collections.abc import Callablefrom typing import Finalimport httpx@@ -16,20 +18,35 @@ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerSTREAM_TIMEOUT_SECONDS: Final = 0.5UPSTREAM_FIRST_BYTE_SECONDS: Final = 2.0+CONVERSE_ANSWER: Final = json.dumps(+ {+ "output": {"message": {"role": "assistant", "content": [{"text": "hi"}]}},+ "stopReason": "end_turn",+ "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},+ "metrics": {"latencyMs": 1},+ }+).encode()_TIMEOUT_EXTENSION: Final = TypeAdapter(dict[str, float | None])-def _answer_once_the_first_byte_is_due(request: httpx.Request) -> httpx.Response:- read_timeout: Final = _TIMEOUT_EXTENSION.validate_python(request.extensions["timeout"])["read"]- if read_timeout is not None and read_timeout < UPSTREAM_FIRST_BYTE_SECONDS:- raise httpx.ReadTimeout(f"no byte arrived within {read_timeout}s", request=request)- return httpx.Response(200, content=b"", request=request)+def slow_upstream_answer(body: bytes = b"") -> Callable[[httpx.Request], httpx.Response]:+ def answer(request: httpx.Request) -> httpx.Response:+ read_timeout: Final = _TIMEOUT_EXTENSION.validate_python(request.extensions["timeout"])["read"]+ if read_timeout is not None and read_timeout < UPSTREAM_FIRST_BYTE_SECONDS:+ raise httpx.ReadTimeout(f"no byte arrived within {read_timeout}s", request=request)+ return httpx.Response(200, content=body, request=request)+ return answer-def slow_upstream_async_client() -> AsyncHTTPHandler:- return AsyncHTTPHandler(transport=httpx.MockTransport(_answer_once_the_first_byte_is_due))+def slow_upstream_transport(body: bytes = b"") -> httpx.MockTransport:+ return httpx.MockTransport(slow_upstream_answer(body))-def slow_upstream_sync_client() -> HTTPHandler:- return HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_answer_once_the_first_byte_is_due)))++def slow_upstream_async_client(body: bytes = b"") -> AsyncHTTPHandler:+ return AsyncHTTPHandler(transport=slow_upstream_transport(body))+++def slow_upstream_sync_client(body: bytes = b"") -> HTTPHandler:+ return HTTPHandler(client=httpx.Client(transport=slow_upstream_transport(body)))diff --git a/tests/unit/llms/microsoft_365_copilot/chat/test_handler.py b/tests/unit/llms/microsoft_365_copilot/chat/test_handler.pyindex 7be5db74af5..6c41a6dcad5 100644--- a/tests/unit/llms/microsoft_365_copilot/chat/test_handler.py+++ b/tests/unit/llms/microsoft_365_copilot/chat/test_handler.py@@ -17,6 +17,11 @@ from litellm.types.llms.openai import AllMessageValuesfrom litellm.types.proxy.litellm_pre_call_utils import SecretFieldsfrom litellm.types.utils import ModelResponsefrom litellm.utils import token_counter+from tests.unit.llms.bedrock.slow_upstream import (+ STREAM_TIMEOUT_SECONDS,+ UPSTREAM_FIRST_BYTE_SECONDS,+ slow_upstream_answer,+)_MODEL: Final = "microsoft_365_copilot/chat"_MESSAGES_ADAPTER: Final = TypeAdapter(list[AllMessageValues])@@ -552,6 +557,28 @@ def test_streaming_wraps_full_reply_as_fake_stream() -> None:assert usage_chunk.usage.total_tokens == (usage_chunk.usage.prompt_tokens + usage_chunk.usage.completion_tokens)+def test_streaming_is_bounded_by_the_request_timeout_not_the_stream_timeout() -> None:+ slow_chat: Final = slow_upstream_answer(json.dumps(_DEFAULT_CHAT_RESPONSE).encode())++ def respond(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/chat"):+ return slow_chat(request)+ return httpx.Response(status_code=201, json={"id": "conversation/42", "state": "active"}, request=request)++ response: Final = litellm.completion(+ model=_MODEL,+ messages=_messages(),+ api_key="delegated-stream-token-9306",+ stream=True,+ timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ client=HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(respond))),+ )++ assert isinstance(response, CustomStreamWrapper)+ assert "".join(chunk.choices[0].delta.content or "" for chunk in response if chunk.choices) == "Copilot response"++@pytest.mark.asyncioasync def test_async_streaming_wraps_full_reply_as_fake_stream() -> None:client, _ = _async_client()diff --git a/tests/unit/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.py b/tests/unit/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.pyindex 1110b53624a..fb1cf4ced2d 100644--- a/tests/unit/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.py+++ b/tests/unit/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.py@@ -6,9 +6,10 @@ Maps to: litellm/llms/vertex_ai/vertex_gemma_models/transformation.pyimport jsonfrom collections.abc import AsyncIterator-from typing import cast+from typing import Final, castfrom unittest.mock import AsyncMock, Mock, patch+import httpximport pytestimport litellm@@ -17,6 +18,11 @@ from litellm.types.llms.openai import (ResponseCompletedEvent,ResponsesAPIStreamingResponse,)+from tests.unit.llms.bedrock.slow_upstream import (+ STREAM_TIMEOUT_SECONDS,+ UPSTREAM_FIRST_BYTE_SECONDS,+ slow_upstream_transport,+)@pytest.fixture(autouse=True)@@ -1354,6 +1360,25 @@ def test_sync_gemma_stream(_gemma_cached_access_token):assert chunks[1].choices[0].finish_reason == "stop"+def test_gemma_stream_is_bounded_by_the_request_timeout_not_the_stream_timeout(_gemma_cached_access_token: None) -> None:+ stream: Final = litellm.completion(+ model="vertex_ai/gemma/test-model",+ messages=[{"role": "user", "content": "Reply exactly READY"}],+ stream=True,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ api_base=_GEMMA_VERTEX_URL,+ vertex_project="test",+ vertex_location="us-central1",+ vertex_credentials=_FAKE_GEMMA_CREDENTIALS,+ client=httpx.Client(+ transport=slow_upstream_transport(json.dumps(_make_gemma_vertex_response(content="READY")).encode())+ ),+ )++ assert "".join(chunk.choices[0].delta.content or "" for chunk in stream) == "READY"++@pytest.mark.asyncioasync def test_async_gemma_responses_stream(_gemma_cached_access_token):import httpxdiff --git a/tests/unit/responses/test_responses_api_request_body.py b/tests/unit/responses/test_responses_api_request_body.pyindex 8c8b347be82..4a2fc0627ab 100644--- a/tests/unit/responses/test_responses_api_request_body.py+++ b/tests/unit/responses/test_responses_api_request_body.py@@ -16,7 +16,12 @@ import pytestimport respximport litellm-from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler+from tests.unit.llms.bedrock.slow_upstream import (+ STREAM_TIMEOUT_SECONDS,+ UPSTREAM_FIRST_BYTE_SECONDS,+ slow_upstream_sync_client,+)def _expected_dir() -> Path:@@ -1035,3 +1040,39 @@ async def test_a_native_responses_provider_places_every_point_itself():assert user_only == [0, 2, 4, 6]assert with_unmatchable_system == user_only+++def test_non_streamed_response_ignores_a_stream_timeout_it_never_uses() -> None:+ answer: Final = json.dumps(_minimal_responses_api_payload("resp_unstreamed", "gpt-5.6")).encode()+ client: Final = HTTPHandler(+ client=httpx.Client(transport=httpx.MockTransport(lambda request: httpx.Response(200, content=answer)))+ )++ response: Final = litellm.responses(+ model="openai/gpt-5.6", input="hi", stream_timeout="unset", api_key="fake-key", client=client+ )++ assert response.output[0].content[0].text == "Done."+++def test_faked_stream_accepts_a_text_timeout(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setitem(+ litellm.model_cost,+ "slow-faked-responses-model",+ {"litellm_provider": "openai", "mode": "responses", "supports_native_streaming": False},+ )+ answer: Final = json.dumps(_minimal_responses_api_payload("resp_faked", "slow-faked-responses-model")).encode()++ response: Final = litellm.responses(+ model="openai/slow-faked-responses-model",+ input="hi",+ stream=True,+ timeout=str(UPSTREAM_FIRST_BYTE_SECONDS * 2),+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ api_key="fake-key",+ client=slow_upstream_sync_client(answer),+ )++ assert [event.response.output[0].content[0].text for event in response if event.type == "response.completed"] == [+ "Done."+ ]diff --git a/tests/unit/test_completion_timeout_resolution.py b/tests/unit/test_completion_timeout_resolution.pyindex 77166d6e947..37b5cceef5a 100644--- a/tests/unit/test_completion_timeout_resolution.py+++ b/tests/unit/test_completion_timeout_resolution.py@@ -10,7 +10,7 @@ from openai import Timeout as SDKTimeoutsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")))-from litellm.litellm_core_utils.completion_timeout import CompletionTimeout+from litellm.litellm_core_utils.completion_timeout import CompletionTimeout, StreamKindfrom litellm.utils import supports_httpx_timeout@@ -22,6 +22,7 @@ def test_explicit_timeout_wins():"openai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 12.5)@@ -35,6 +36,7 @@ def test_kwargs_timeout_when_param_none():"azure_ai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 21.0)@@ -48,6 +50,7 @@ def test_request_timeout_alias_in_kwargs():"bedrock",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 33.0)@@ -61,6 +64,7 @@ def test_global_timeout_from_litellm_settings():"vertex_ai",global_timeout=360.0,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 360.0)@@ -76,6 +80,7 @@ def test_explicit_global_timeout_6000_is_preserved():"openai",global_timeout=6000.0,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 6000.0)@@ -90,6 +95,7 @@ def test_explicit_request_timeout_6000_preserved():"openai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 6000.0)@@ -103,6 +109,7 @@ def test_explicit_model_timeout_6000_preserved():"openai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 6000.0)@@ -116,6 +123,7 @@ def test_fallback_600_when_no_global_timeout():"azure_ai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== 600.0)@@ -129,6 +137,7 @@ def test_httpx_timeout_coerced_for_provider_without_httpx_timeout_support():"azure_ai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)assert out == 50.0assert not isinstance(out, httpx.Timeout)@@ -142,6 +151,7 @@ def test_httpx_timeout_preserved_for_openai():"openai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)assert out is tassert isinstance(out, httpx.Timeout)@@ -158,6 +168,7 @@ def test_sdk_timeout_preserves_components_for_httpx_providers("openai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)assert isinstance(resolved, httpx.Timeout)assert resolved.as_dict() == timeout.as_dict()@@ -174,6 +185,49 @@ def test_sdk_timeout_coerces_read_timeout_for_providers_without_httpx_support("azure_ai",global_timeout=None,supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.NOT_STREAMED,)== expected)+++ "stream_kind, timeout, stream_timeout, expected",+ (+ (StreamKind.NOT_STREAMED, 120.0, 15.0, 120.0),+ (StreamKind.LIVE, 120.0, 15.0, 15.0),+ (StreamKind.LIVE, 1.0, 15.0, 15.0),+ (StreamKind.FAKED, 120.0, 15.0, 120.0),+ (StreamKind.FAKED, 1.0, 15.0, 15.0),+ (StreamKind.FAKED, httpx.Timeout(5.0, read=None), 15.0, httpx.Timeout(15.0, read=None)),+ (StreamKind.FAKED, httpx.Timeout(1.0, read=120.0), 15.0, httpx.Timeout(15.0, read=120.0)),+ ),+)+def test_stream_timeout_bounds_a_live_stream_and_never_shortens_a_fake_one(+ stream_kind: StreamKind, timeout: float | httpx.Timeout, stream_timeout: float, expected: float | httpx.Timeout+) -> None:+ assert (+ CompletionTimeout.resolve(+ timeout,+ {"stream_timeout": stream_timeout},+ "openai",+ global_timeout=None,+ supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=stream_kind,+ )+ == expected+ )+++def test_fake_stream_with_only_a_stream_timeout_keeps_the_global_request_timeout() -> None:+ assert (+ CompletionTimeout.resolve(+ None,+ {"stream_timeout": 15.0},+ "bedrock",+ global_timeout=None,+ supports_httpx_timeout=supports_httpx_timeout,+ stream_kind=StreamKind.FAKED,+ )+ == 600.0+ )diff --git a/tests/unit/test_main.py b/tests/unit/test_main.pyindex 0293af05c84..7c292ea8f08 100644--- a/tests/unit/test_main.py+++ b/tests/unit/test_main.py@@ -48,6 +48,11 @@ from litellm.types.litellm_params import ControlOptionsfrom litellm.types.llms.openai import AllMessageValues, HttpxBinaryResponseContentfrom litellm.types.prompts.init_prompts import PromptSpecfrom litellm.types.utils import Delta, ModelResponseStream, StandardCallbackDynamicParams, StreamingChoices, Usage+from tests.unit.llms.bedrock.slow_upstream import (+ STREAM_TIMEOUT_SECONDS,+ UPSTREAM_FIRST_BYTE_SECONDS,+ slow_upstream_sync_client,+)@pytest.fixture(autouse=True)@@ -1937,6 +1942,60 @@ def test_responses_bridge_preserves_reasoning_effort_with_drop_params(assert request_body["reasoning"] == {"effort": "high"}+_BRIDGED_RESPONSE_ANSWER: Final = json.dumps(+ {+ "id": "resp_slow",+ "object": "response",+ "created_at": 1734366691,+ "status": "completed",+ "model": "slow-responses-model",+ "output": [+ {+ "type": "message",+ "id": "msg_1",+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "hi", "annotations": []}],+ }+ ],+ "parallel_tool_calls": True,+ "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},+ "tool_choice": "auto",+ "tools": [],+ }+).encode()+++def test_responses_bridge_fake_stream_is_bounded_by_the_request_timeout_not_the_stream_timeout(+ restore_model_registry: None,+) -> None:+ model: Final = "openai/slow-responses-model"+ litellm.register_model(+ {+ model: {+ "litellm_provider": "openai",+ "mode": "responses",+ "supports_native_streaming": False,+ "input_cost_per_token": 0.0,+ "output_cost_per_token": 0.0,+ }+ },+ persist_across_reloads=False,+ )++ response: Final = litellm.completion(+ model=model,+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ api_key="fake-key",+ client=slow_upstream_sync_client(_BRIDGED_RESPONSE_ANSWER),+ )++ assert "".join(chunk.choices[0].delta.content or "" for chunk in response) == "hi"++_FOUNDRY_RESPONSES_FUNCTION_CALL_BODY: Final = {"id": "resp_foundry","object": "response",@@ -6978,6 +7037,23 @@ def test_mock_request_with_mock_timeout_raises_litellm_timeout():assert error.value.model == "gpt-5.6"+async def test_async_mock_timeout_on_a_stream_waits_only_for_the_stream_timeout() -> None:+ with pytest.raises(litellm.Timeout):+ await asyncio.wait_for(+ litellm.acompletion(+ model="gpt-5.6",+ messages=[{"role": "user", "content": "hello"}],+ stream=True,+ timeout=30.0,+ stream_timeout=0.01,+ mock_timeout=True,+ num_retries=0,+ ),+ timeout=5,+ )++def test_router_mock_request_with_mock_timeout_raises_litellm_timeout():router: Final = litellm.Router(model_list=[diff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.pyindex bd3cf738af8..1dec4de45f4 100644--- a/tests/unit/test_router/test_router.py+++ b/tests/unit/test_router/test_router.py@@ -2023,7 +2023,9 @@ async def test_ageneric_api_call_deployment_model_overrides_alias():])- def inject_alias_into_kwargs(deployment, kwargs, function_name=None):+ def inject_alias_into_kwargs(+ deployment: dict, kwargs: dict, function_name: str | None = None, splits_stream_timeout: bool = False+ ) -> None:# Simulate the alias leaking into kwargs (as happens when# _ageneric_api_call_with_fallbacks sets kwargs["model"] = alias before# calling the helper through async_function_with_fallbacks).diff --git a/tests/unit/test_router/test_router_timeout.py b/tests/unit/test_router/test_router_timeout.pyindex 3c3f0692043..3265179a513 100644--- a/tests/unit/test_router/test_router_timeout.py+++ b/tests/unit/test_router/test_router_timeout.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport asyncioimport jsonimport os+from datetime import datetime, timedelta+from collections.abc import Awaitable, Callable, Mappingfrom typing import Finalfrom unittest.mock import AsyncMock, Mock@@ -13,9 +15,22 @@ import respximport litellmfrom litellm import Router+from litellm.integrations.custom_logger import CustomLogger+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging+from litellm.router_utils.cooldown_handlers import is_caller_timeout_408+from litellm.types.integrations.custom_logger import WEBSEARCH_INTERCEPTION_PREFIX, as_converted_stream+from litellm.types.llms.openai import AllMessageValuesimport timefrom unittest.mock import patch, MagicMock+from tests.unit.llms.bedrock.slow_upstream import (+ CONVERSE_ANSWER,+ STREAM_TIMEOUT_SECONDS,+ UPSTREAM_FIRST_BYTE_SECONDS,+ slow_upstream_answer,+ slow_upstream_async_client,+)+@pytest.fixturedef restore_request_timeout(monkeypatch: pytest.MonkeyPatch) -> None:@@ -138,6 +153,276 @@ def test_unit_test_streaming_timeout(stream):assert stream_timeout_val == normal_timeout+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]+++async def test_live_responses_stream_through_the_router_fails_at_the_stream_timeout(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ respx_mock.post("https://api.openai.com/v1/responses").mock(side_effect=slow_upstream_answer())+ router: Final = Router(+ model_list=[{"model_name": "gpt", "litellm_params": {"model": "openai/gpt-4.1", "api_key": "fake"}}],+ timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ num_retries=0,+ )++ with pytest.raises(litellm.Timeout):+ await _drain_responses_stream(router)+++async def test_prompt_managed_stream_keeps_the_target_deployments_own_stream_timeout() -> None:+ router: Final = Router(+ model_list=[+ {+ "model_name": "claude-agent",+ "litellm_params": {"model": "litellm_agent/claude-target"},+ },+ {+ "model_name": "claude-target",+ "litellm_params": {+ "model": "bedrock/anthropic.claude-sonnet-4-5-v1:0",+ "aws_access_key_id": "fake",+ "aws_secret_access_key": "fake",+ "aws_region_name": "us-east-1",+ "stream_timeout": STREAM_TIMEOUT_SECONDS,+ },+ },+ ],+ timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ stream_timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ num_retries=0,+ )+ messages: Final[list[AllMessageValues]] = [{"role": "user", "content": "hi"}]++ with pytest.raises(litellm.Timeout):+ await router.acompletion(+ model="claude-agent",+ messages=messages,+ stream=True,+ client=slow_upstream_async_client(),+ litellm_logging_obj=LiteLLMLogging(+ model="claude-agent",+ messages=messages,+ stream=True,+ call_type="acompletion",+ start_time=datetime.now(),+ litellm_call_id="prompt-managed-stream",+ function_id="f",+ ),+ )++++ ("agent_params", "target_params", "request_params"),+ [+ ({}, {"timeout": UPSTREAM_FIRST_BYTE_SECONDS * 2}, {}),+ ({"timeout": STREAM_TIMEOUT_SECONDS}, {}, {"request_timeout": UPSTREAM_FIRST_BYTE_SECONDS * 2}),+ ],+ ids=["target_deployment_timeout", "caller_request_timeout"],+)+async def test_prompt_managed_fake_stream_keeps_the_timeout_its_caller_or_target_set(+ agent_params: Mapping[str, float], target_params: Mapping[str, float], request_params: Mapping[str, float]+) -> None:+ router: Final = Router(+ model_list=[+ {+ "model_name": "jamba-agent",+ "litellm_params": {"model": "litellm_agent/jamba-target", **agent_params},+ },+ {+ "model_name": "jamba-target",+ "litellm_params": {+ "model": "bedrock/converse/ai21.jamba-1-5-large-v1:0",+ "aws_access_key_id": "fake",+ "aws_secret_access_key": "fake",+ "aws_region_name": "us-east-1",+ **target_params,+ },+ },+ ],+ timeout=STREAM_TIMEOUT_SECONDS,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ num_retries=0,+ )+ messages: Final[list[AllMessageValues]] = [{"role": "user", "content": "hi"}]++ response: Final = await router.acompletion(+ model="jamba-agent",+ messages=messages,+ stream=True,+ client=slow_upstream_async_client(CONVERSE_ANSWER),+ **request_params,+ litellm_logging_obj=LiteLLMLogging(+ model="jamba-agent",+ messages=messages,+ stream=True,+ call_type="acompletion",+ start_time=datetime.now(),+ litellm_call_id="prompt-managed-fake-stream",+ function_id="f",+ ),+ )++ assert isinstance(response, litellm.CustomStreamWrapper)+ assert "".join([chunk.choices[0].delta.content or "" async for chunk in response]) == "hi"+++class _AnswersStreamsInOnePiece(CustomLogger):+ async def async_pre_call_deployment_hook(self, kwargs: dict, call_type: object) -> dict:+ return as_converted_stream(kwargs, WEBSEARCH_INTERCEPTION_PREFIX) if kwargs.get("stream") else kwargs+++_INVOKE_ANSWER: Final = json.dumps(+ {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": "claude",+ "content": [{"type": "text", "text": "hi"}],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 1, "output_tokens": 1},+ }+).encode()+++async def _streamed_chat_text(router: Router) -> str:+ response: Final = await router.acompletion(model="claude", messages=[{"role": "user", "content": "hi"}], stream=True)+ return "".join([chunk.choices[0].delta.content or "" async for chunk in response])+++async def _streamed_messages_text(router: Router) -> str:+ response: Final = await router.aanthropic_messages(+ model="claude", messages=[{"role": "user", "content": "hi"}], max_tokens=10, stream=True+ )+ events: Final = [+ json.loads(line.removeprefix(b"data: "))+ for line in b"".join([chunk async for chunk in response]).splitlines()+ if line.startswith(b"data: ")+ ]+ return "".join(event["delta"]["text"] for event in events if event["type"] == "content_block_delta")+++ ("model", "answer", "streamed_text"),+ [+ ("bedrock/converse/anthropic.claude-sonnet-4-5-v1:0", CONVERSE_ANSWER, _streamed_chat_text),+ ("bedrock/invoke/anthropic.claude-sonnet-4-5-v1:0", _INVOKE_ANSWER, _streamed_messages_text),+ ],+ ids=["chat_completions", "anthropic_messages"],+)+async def test_stream_a_deployment_hook_answers_in_one_piece_gets_the_longer_limit(+ model: str,+ answer: bytes,+ streamed_text: Callable[[Router], Awaitable[str]],+ respx_mock: respx.MockRouter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "callbacks", [_AnswersStreamsInOnePiece()])+ respx_mock.post(url__regex=r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/.*").mock(+ side_effect=slow_upstream_answer(answer)+ )+ router: Final = Router(+ model_list=[+ {+ "model_name": "claude",+ "litellm_params": {+ "model": model,+ "aws_access_key_id": "fake",+ "aws_secret_access_key": "fake",+ "aws_region_name": "us-east-1",+ "timeout": STREAM_TIMEOUT_SECONDS,+ "stream_timeout": UPSTREAM_FIRST_BYTE_SECONDS * 2,+ },+ }+ ],+ num_retries=0,+ )++ assert await streamed_text(router) == "hi"+++class _FailureDetails(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.logged: Final = asyncio.Event()+ self.details: Mapping[str, object] = {}++ async def async_log_failure_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: object, end_time: object+ ) -> None:+ self.details = kwargs+ self.logged.set()+++async def _drain_messages_stream(router: Router) -> None:+ response: Final = await router.aanthropic_messages(+ model="native", messages=[{"role": "user", "content": "hi"}], max_tokens=10, stream=True, client_side_timeout=True+ )+ _ = [chunk async for chunk in response]+++async def _drain_native_responses_stream(router: Router) -> None:+ response: Final = await router.aresponses(model="native", input="hi", stream=True, client_side_timeout=True)+ _ = [event async for event in response]+++ ("model", "drain"),+ [+ ("bedrock/invoke/anthropic.claude-sonnet-4-5-v1:0", _drain_messages_stream),+ ("openai/gpt-4.1", _drain_native_responses_stream),+ ],+ ids=["anthropic_messages", "responses"],+)+async def test_native_live_stream_cut_at_the_stream_timeout_is_not_blamed_on_the_deployment(+ model: str,+ drain: Callable[[Router], Awaitable[None]],+ respx_mock: respx.MockRouter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ failure_details: Final = _FailureDetails()+ monkeypatch.setattr(litellm, "callbacks", [failure_details])+ respx_mock.post(url__regex=r"https://(bedrock-runtime\.us-east-1\.amazonaws\.com|api\.openai\.com)/.*").mock(+ side_effect=slow_upstream_answer()+ )+ router: Final = Router(+ model_list=[+ {+ "model_name": "native",+ "litellm_params": {+ "model": model,+ "api_key": "fake",+ "aws_access_key_id": "fake",+ "aws_secret_access_key": "fake",+ "aws_region_name": "us-east-1",+ },+ }+ ],+ timeout=UPSTREAM_FIRST_BYTE_SECONDS * 2,+ stream_timeout=STREAM_TIMEOUT_SECONDS,+ num_retries=0,+ )++ with pytest.raises(litellm.Timeout):+ await drain(router)+ await asyncio.wait_for(failure_details.logged.wait(), timeout=10)++ started: Final = failure_details.details.get("api_call_start_time")+ assert isinstance(started, datetime)+ assert is_caller_timeout_408(failure_details.details, 408, ended=started + timedelta(seconds=STREAM_TIMEOUT_SECONDS))+@pytest.mark.asyncioasync def test_bedrock_timeout_preserves_the_provider_timeout_error(respx_mock: respx.MockRouter,