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: add sync streaming fallback + fix 429 for all streaming paths (#22375)
CSteigstra98974771fdca
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 3b75a56fcc9..569cbdaa2e7 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -13,6 +13,7 @@ from typing import (Dict,Iterator,List,+ NoReturn,Optional,Union,cast,@@ -1899,14 +1900,7 @@ class CustomStreamWrapper:threading.Thread(target=self.logging_obj.failure_handler, args=(e, traceback_exception)).start()- if isinstance(e, OpenAIError):- raise e- else:- raise exception_type(- model=self.model,- original_exception=e,- custom_llm_provider=self.custom_llm_provider,- )+ self._handle_stream_fallback_error(e)def fetch_sync_stream(self):if self.completion_stream is None and self.make_call is not None:@@ -2124,7 +2118,25 @@ class CustomStreamWrapper:asyncio.create_task(self.logging_obj.async_failure_handler(e, traceback_exception) # type: ignore)- ## Map to OpenAI Exception+ self._handle_stream_fallback_error(e)++ def _handle_stream_fallback_error(self, e: Exception) -> "NoReturn":+ """+ Common error handling for both __next__ and __anext__.++ Maps the raw exception to an OpenAI-compatible type, then decides+ whether to raise it directly (non-retriable 4xx) or wrap it in+ MidStreamFallbackError so the Router can trigger a fallback.++ 429 (rate-limit) is explicitly exempted from the 4xx filter because+ it is transient and the Router should switch to another model group.+ """+ from litellm.exceptions import MidStreamFallbackError++ # Map to OpenAI exception format+ if isinstance(e, OpenAIError):+ mapped_exception: Exception = e+ else:try:mapped_exception = exception_type(model=self.model,@@ -2136,46 +2148,44 @@ class CustomStreamWrapper:except Exception as mapping_error:mapped_exception = mapping_error- def _normalize_status_code(exc: Exception) -> Optional[int]:- """- Best-effort status_code extraction.- Uses status_code on the exception, then falls back to the response.- """+ def _normalize_status_code(exc: Exception) -> Optional[int]:+ """Best-effort status_code extraction."""+ try:+ code = getattr(exc, "status_code", None)+ if code is not None:+ return int(code)+ except Exception:+ pass++ response = getattr(exc, "response", None)+ if response is not None:try:- code = getattr(exc, "status_code", None)- if code is not None:- return int(code)+ status_code = getattr(response, "status_code", None)+ if status_code is not None:+ return int(status_code)except Exception:pass+ return None- response = getattr(exc, "response", None)- if response is not None:- try:- status_code = getattr(response, "status_code", None)- if status_code is not None:- return int(status_code)- except Exception:- pass- return None-- mapped_status_code = _normalize_status_code(mapped_exception)- original_status_code = _normalize_status_code(e)-- if mapped_status_code is not None and 400 <= mapped_status_code < 500:- raise mapped_exception- if original_status_code is not None and 400 <= original_status_code < 500:- raise mapped_exception-- from litellm.exceptions import MidStreamFallbackError-- raise MidStreamFallbackError(- message=str(mapped_exception),- model=self.model,- llm_provider=self.custom_llm_provider or "anthropic",- original_exception=mapped_exception,- generated_content=self.response_uptil_now,- is_pre_first_chunk=not self.sent_first_chunk,- )+ mapped_status_code = _normalize_status_code(mapped_exception)+ original_status_code = _normalize_status_code(e)++ # Raise non-retriable client errors directly (skip fallback).+ # Exception: 429 (rate-limit) IS retriable/transient — allow it+ # through so the Router can switch to a different model group.+ if mapped_status_code is not None and 400 <= mapped_status_code < 500 and mapped_status_code != 429:+ raise mapped_exception+ if original_status_code is not None and 400 <= original_status_code < 500 and original_status_code != 429:+ raise mapped_exception++ raise MidStreamFallbackError(+ message=str(mapped_exception),+ model=self.model,+ llm_provider=self.custom_llm_provider or "anthropic",+ original_exception=mapped_exception,+ generated_content=self.response_uptil_now,+ is_pre_first_chunk=not self.sent_first_chunk,+ )@staticmethoddef _strip_sse_data_from_chunk(chunk: Optional[str]) -> Optional[str]:diff --git a/litellm/router.py b/litellm/router.pyindex d89a5099b01..34408e38e40 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -25,6 +25,7 @@ from typing import (AsyncGenerator,Callable,Dict,+ Generator,List,Literal,Optional,@@ -1327,6 +1328,11 @@ class Router:model_name = Nonedeployment = Nonetry:+ # Capture kwargs before deployment selection so the streaming+ # fallback iterator can re-dispatch with the original model group.+ input_kwargs_for_streaming_fallback = kwargs.copy()+ input_kwargs_for_streaming_fallback["model"] = model+# pick the one that is available (lowest TPM/RPM)deployment = self.get_available_deployment(model=model,@@ -1398,6 +1404,15 @@ class Router:llm_provider="",)+ # Wrap streaming responses so MidStreamFallbackError (raised+ # during iteration) triggers the Router's fallback chain.+ if isinstance(response, CustomStreamWrapper):+ return self._completion_streaming_iterator(+ model_response=response,+ messages=messages,+ initial_kwargs=input_kwargs_for_streaming_fallback,+ )+return responseexcept Exception as e:verbose_router_logger.info(@@ -1597,17 +1612,24 @@ class Router:"content_policy_fallbacks", self.content_policy_fallbacks)initial_kwargs["original_function"] = self._acompletion- initial_kwargs["messages"] = messages + [- {- "role": "system",- "content": "You are a helpful assistant. You are given a message and you need to respond to it. You are also given a generated content. You need to respond to the message in continuation of the generated content. Do not repeat the same content. Your response should be in continuation of this text: ",- },- {- "role": "assistant",- "content": e.generated_content,- "prefix": True,- },- ]+ if e.is_pre_first_chunk or not e.generated_content:+ # No content was generated before the error (e.g. a+ # rate-limit 429 on the very first chunk). Retry with+ # the original messages — adding a continuation prompt+ # would waste tokens and confuse the model.+ initial_kwargs["messages"] = messages+ else:+ initial_kwargs["messages"] = messages + [+ {+ "role": "system",+ "content": "You are a helpful assistant. You are given a message and you need to respond to it. You are also given a generated content. You need to respond to the message in continuation of the generated content. Do not repeat the same content. Your response should be in continuation of this text: ",+ },+ {+ "role": "assistant",+ "content": e.generated_content,+ "prefix": True,+ },+ ]self._update_kwargs_before_fallbacks(model=model_group, kwargs=initial_kwargs)@@ -1696,6 +1718,164 @@ class Router:return FallbackStreamWrapper(stream_with_fallbacks())+ def _completion_streaming_iterator(+ self,+ model_response: CustomStreamWrapper,+ messages: List[Dict[str, str]],+ initial_kwargs: dict,+ ) -> CustomStreamWrapper:+ """+ Sync equivalent of _acompletion_streaming_iterator.++ Wraps a sync streaming response so that MidStreamFallbackError+ (raised by CustomStreamWrapper.__next__) triggers the Router's+ fallback chain instead of surfacing directly to the caller.+ """+ from litellm.exceptions import MidStreamFallbackError++ class SyncFallbackStreamWrapper(CustomStreamWrapper):+ def __init__(self, sync_generator: Generator):+ super().__init__(+ completion_stream=sync_generator,+ model=model_response.model,+ custom_llm_provider=model_response.custom_llm_provider,+ logging_obj=model_response.logging_obj,+ )+ self._sync_generator = sync_generator+ if hasattr(model_response, "_hidden_params"):+ self._hidden_params = model_response._hidden_params.copy()++ def __iter__(self):+ return self++ def __next__(self):+ return next(self._sync_generator)++ router_self = self++ def stream_with_fallbacks():+ fallback_response = None+ try:+ for item in model_response:+ yield item+ except MidStreamFallbackError as e:+ from litellm.main import stream_chunk_builder++ complete_response_object = stream_chunk_builder(+ chunks=model_response.chunks+ )+ complete_response_object_usage = cast(+ Optional[Usage],+ getattr(complete_response_object, "usage", None),+ )+ try:+ model_group = cast(str, initial_kwargs.get("model"))+ fallbacks: Optional[List] = initial_kwargs.get(+ "fallbacks", router_self.fallbacks+ )+ context_window_fallbacks: Optional[List] = initial_kwargs.get(+ "context_window_fallbacks",+ router_self.context_window_fallbacks,+ )+ content_policy_fallbacks: Optional[List] = initial_kwargs.get(+ "content_policy_fallbacks",+ router_self.content_policy_fallbacks,+ )+ initial_kwargs["original_function"] = router_self._completion+ if e.is_pre_first_chunk or not e.generated_content:+ initial_kwargs["messages"] = messages+ else:+ initial_kwargs["messages"] = messages + [+ {+ "role": "system",+ "content": "You are a helpful assistant. You are given a message and you need to respond to it. You are also given a generated content. You need to respond to the message in continuation of the generated content. Do not repeat the same content. Your response should be in continuation of this text: ",+ },+ {+ "role": "assistant",+ "content": e.generated_content,+ "prefix": True,+ },+ ]+ router_self._update_kwargs_before_fallbacks(+ model=model_group, kwargs=initial_kwargs+ )+ fallback_response = (+ router_self.function_with_fallbacks(+ **initial_kwargs,+ fallbacks=fallbacks,+ context_window_fallbacks=context_window_fallbacks,+ content_policy_fallbacks=content_policy_fallbacks,+ )+ )++ if hasattr(fallback_response, "__iter__"):+ for fallback_item in fallback_response:+ if (+ fallback_item+ and isinstance(fallback_item, ModelResponseStream)+ and hasattr(fallback_item, "usage")+ ):+ from litellm.cost_calculator import (+ BaseTokenUsageProcessor,+ )++ usage = cast(+ Optional[Usage],+ getattr(fallback_item, "usage", None),+ )+ if usage is not None:+ usage_objects = [usage]+ else:+ usage_objects = []++ if (+ complete_response_object_usage is not None+ and hasattr(+ complete_response_object_usage, "usage"+ )+ and complete_response_object_usage.usage is not None # type: ignore+ ):+ usage_objects.append(+ complete_response_object_usage+ )++ combined_usage = (+ BaseTokenUsageProcessor.combine_usage_objects(+ usage_objects=usage_objects+ )+ )+ setattr(fallback_item, "usage", combined_usage)+ yield fallback_item+ else:+ yield None++ except Exception as fallback_error:+ verbose_router_logger.error(+ f"Fallback also failed: {fallback_error}"+ )+ raise fallback_error+ finally:+ if hasattr(model_response, "close"):+ try:+ model_response.close()+ except BaseException as close_err:+ verbose_router_logger.debug(+ "stream_with_fallbacks: error closing model_response: %s",+ close_err,+ )+ if fallback_response is not None and hasattr(+ fallback_response, "close"+ ):+ try:+ fallback_response.close()+ except BaseException as close_err:+ verbose_router_logger.debug(+ "stream_with_fallbacks: error closing fallback_response: %s",+ close_err,+ )++ return SyncFallbackStreamWrapper(stream_with_fallbacks())+async def _silent_experiment_acompletion(self, silent_model: str, messages: List[Any], **kwargs):diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py b/tests/test_litellm/litellm_core_utils/test_streaming_handler.pyindex 73ecaa20a2d..5a31baf177b 100644--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py@@ -714,6 +714,86 @@ async def test_vertex_streaming_bad_request_not_midstream(logging_obj: Logging):assert "invalid maxOutputTokens" in str(excinfo.value)+async def test_vertex_streaming_rate_limit_triggers_midstream_fallback(logging_obj: Logging):+ """Ensure Vertex 429 rate-limit errors raise MidStreamFallbackError, not RateLimitError.++ Regression test for https://github.com/BerriAI/litellm/issues/20870+ """+ from litellm.exceptions import MidStreamFallbackError+ from litellm.llms.vertex_ai.common_utils import VertexAIError++ async def _raise_rate_limit(**kwargs):+ raise VertexAIError(status_code=429, message="Resource exhausted.", headers=None)++ response = CustomStreamWrapper(+ completion_stream=None,+ model="gemini-3-flash-preview",+ logging_obj=logging_obj,+ custom_llm_provider="vertex_ai_beta",+ make_call=_raise_rate_limit,+ )++ with pytest.raises(MidStreamFallbackError) as excinfo:+ await response.__anext__()++ assert excinfo.value.is_pre_first_chunk is True+ assert excinfo.value.generated_content == ""+++def test_sync_streaming_rate_limit_triggers_midstream_fallback(logging_obj: Logging):+ """Ensure __next__ raises MidStreamFallbackError on 429, not RateLimitError.++ This is the sync-streaming equivalent of the async test above. Before+ this fix, __next__ would raise RateLimitError directly, bypassing the+ Router's fallback chain entirely.+ """+ from litellm.exceptions import MidStreamFallbackError+ from litellm.llms.vertex_ai.common_utils import VertexAIError++ def _raise_rate_limit(**kwargs):+ raise VertexAIError(status_code=429, message="Resource exhausted.", headers=None)++ response = CustomStreamWrapper(+ completion_stream=None,+ model="gemini-3-flash-preview",+ logging_obj=logging_obj,+ custom_llm_provider="vertex_ai_beta",+ make_call=_raise_rate_limit,+ )++ with pytest.raises(MidStreamFallbackError) as excinfo:+ next(response)++ assert excinfo.value.is_pre_first_chunk is True+ assert excinfo.value.generated_content == ""+++def test_sync_streaming_bad_request_not_midstream(logging_obj: Logging):+ """Ensure __next__ raises BadRequestError (400) directly, not MidStreamFallbackError.++ Non-retriable 4xx errors should surface immediately to the caller.+ """+ from litellm.llms.vertex_ai.common_utils import VertexAIError++ def _raise_bad_request(**kwargs):+ raise VertexAIError(status_code=400, message="invalid maxOutputTokens", headers=None)++ response = CustomStreamWrapper(+ completion_stream=None,+ model="gemini-3-pro-preview",+ logging_obj=logging_obj,+ custom_llm_provider="vertex_ai_beta",+ make_call=_raise_bad_request,+ )++ with pytest.raises(litellm.BadRequestError) as excinfo:+ next(response)++ assert getattr(excinfo.value, "status_code", None) == 400+ assert "invalid maxOutputTokens" in str(excinfo.value)++def test_streaming_handler_with_created_time_propagation(initialized_custom_stream_wrapper: CustomStreamWrapper, logging_obj: Logging):diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.pyindex 4bb9685f5e6..99ff7953586 100644--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@ -1357,8 +1357,9 @@ async def test_acompletion_streaming_iterator_edge_cases():fallback_kwargs = mock_fallback_utils.call_args.kwargs["kwargs"]modified_messages = fallback_kwargs["messages"]- # Should have assistant message with empty content- assert modified_messages[2]["content"] == ""+ # Empty content → pre-first-chunk path uses original messages+ # (no continuation prompt added)+ assert modified_messages == messagesprint("✓ Handles empty generated content correctly")print("✓ Edge case tests passed!")@@ -1419,6 +1420,179 @@ async def test_acompletion_streaming_iterator_preserves_hidden_params():assert result._hidden_params.get("_response_ms") == 500.0+def test_completion_streaming_iterator_fallback_on_429():+ """Sync streaming: MidStreamFallbackError (429 pre-first-chunk) triggers fallback.++ This is the sync counterpart of test_acompletion_streaming_iterator.+ Before this fix, __next__ raised RateLimitError directly and the Router+ never got a chance to fall back.+ """+ from unittest.mock import MagicMock++ from litellm.exceptions import MidStreamFallbackError++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4", "api_key": "fake-key"},+ }+ ],+ )++ messages = [{"role": "user", "content": "Test"}]+ initial_kwargs = {"model": "gpt-4", "stream": True}++ rate_limit_error = MidStreamFallbackError(+ message="Resource exhausted",+ model="gpt-4",+ llm_provider="vertex_ai",+ generated_content="",+ is_pre_first_chunk=True,+ )++ class SyncIteratorImmediateError:+ def __init__(self):+ self.model = "gpt-4"+ self.custom_llm_provider = "openai"+ self.logging_obj = MagicMock()+ self.chunks = []++ def __iter__(self):+ return self++ def __next__(self):+ raise rate_limit_error++ mock_response = SyncIteratorImmediateError()++ # Fallback returns a simple non-streaming response (fallback may not stream)+ mock_fallback_response = MagicMock()+ mock_fallback_response.__iter__ = MagicMock(return_value=iter([]))++ with patch.object(+ router,+ "function_with_fallbacks",+ return_value=mock_fallback_response,+ ) as mock_fallback:+ result = router._completion_streaming_iterator(+ model_response=mock_response,+ messages=messages,+ initial_kwargs=initial_kwargs,+ )++ collected_chunks = list(result)++ assert mock_fallback.called+ call_kwargs = mock_fallback.call_args+ # Pre-first-chunk: should use original messages, no continuation prompt+ assert call_kwargs.kwargs.get("messages") == messages+ # Verify original_function is _completion (sync)+ assert call_kwargs.kwargs.get("original_function") == router._completion+++def test_completion_streaming_iterator_preserves_hidden_params():+ """SyncFallbackStreamWrapper must copy _hidden_params from original response."""+ from unittest.mock import MagicMock++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4", "api_key": "fake-key"},+ }+ ],+ )++ mock_response = MagicMock()+ mock_response.model = "gpt-4"+ mock_response.custom_llm_provider = "openai"+ mock_response.logging_obj = MagicMock()+ mock_response._hidden_params = {+ "litellm_overhead_time_ms": 42.0,+ "litellm_call_id": "test-sync-call",+ }+ mock_response.__iter__ = MagicMock(return_value=iter([]))++ result = router._completion_streaming_iterator(+ model_response=mock_response,+ messages=[{"role": "user", "content": "hi"}],+ initial_kwargs={"model": "gpt-4", "stream": True},+ )++ assert hasattr(result, "_hidden_params")+ assert result._hidden_params.get("litellm_overhead_time_ms") == 42.0+ assert result._hidden_params.get("litellm_call_id") == "test-sync-call"+++async def test_acompletion_streaming_iterator_pre_first_chunk_skips_continuation():+ """When MidStreamFallbackError has is_pre_first_chunk=True, use original messages."""+ from unittest.mock import MagicMock++ from litellm.exceptions import MidStreamFallbackError++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4",+ "litellm_params": {"model": "gpt-4", "api_key": "fake-key"},+ }+ ],+ )++ messages = [{"role": "user", "content": "Hello"}]+ initial_kwargs = {"model": "gpt-4", "stream": True}++ pre_first_chunk_error = MidStreamFallbackError(+ message="429 Resource exhausted",+ model="gpt-4",+ llm_provider="vertex_ai",+ generated_content="",+ is_pre_first_chunk=True,+ )++ class AsyncIteratorPreFirstChunkError:+ def __init__(self):+ self.model = "gpt-4"+ self.custom_llm_provider = "openai"+ self.logging_obj = MagicMock()+ self.chunks = []++ def __aiter__(self):+ return self++ async def __anext__(self):+ raise pre_first_chunk_error++ mock_response = AsyncIteratorPreFirstChunkError()++ class EmptyAsyncIterator:+ def __aiter__(self):+ return self++ async def __anext__(self):+ raise StopAsyncIteration++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ return_value=EmptyAsyncIterator(),+ ) as mock_fallback_utils:+ iterator = await router._acompletion_streaming_iterator(+ model_response=mock_response,+ messages=messages,+ initial_kwargs=initial_kwargs,+ )+ async for _ in iterator:+ pass++ assert mock_fallback_utils.called+ fallback_kwargs = mock_fallback_utils.call_args.kwargs["kwargs"]+ # Pre-first-chunk: should use original messages, no continuation prompt+ assert fallback_kwargs["messages"] == messages++@pytest.mark.asyncioasync def test_async_function_with_fallbacks_common_utils():"""Test the async_function_with_fallbacks_common_utils method"""