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 return headers for stream response
KnyazShe3058e34c493
diff --git a/litellm/passthrough/main.py b/litellm/passthrough/main.pyindex 8b20406397b..2c654a3f23b 100644--- a/litellm/passthrough/main.py+++ b/litellm/passthrough/main.py@@ -4,11 +4,11 @@ This module is used to pass through requests to the LLM APIs.import asyncioimport contextvars-from collections.abc import AsyncIteratorfrom functools import partialfrom typing import (TYPE_CHECKING,Any,+ AsyncGenerator,Coroutine,Generator,List,@@ -36,59 +36,203 @@ if TYPE_CHECKING:from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig-class _AsyncPassthroughStreamingResponse(AsyncIterator[bytes]):- """- Async iterator wrapper that preserves upstream response metadata for streaming.- """-+class AsyncPassthroughStreamingResponse(AsyncGenerator[Any, Any]):def __init__(self,- response: httpx.Response,+ response: Coroutine[Any, Any, httpx.Response],litellm_logging_obj: "LiteLLMLoggingObj",provider_config: "BasePassthroughConfig",) -> None:- self.response = response- self.headers = response.headers- self.status_code = response.status_code+ self._initialized = False+ self._status_code: int = 0+ self._headers = httpx.Headers()+ self._response_coro = response+ self._response: httpx.Response+ self._iterator: AsyncGenerator[bytes, Any]self._litellm_logging_obj = litellm_logging_objself._provider_config = provider_config- self._iterator = response.aiter_bytes()self._raw_bytes: List[bytes] = []- self._flush_started = False+ self._flush_scheduled = False+ self._background_tasks: set[asyncio.Task] = set()++ @property+ def status_code(self) -> int:+ if not self._initialized:+ raise RuntimeError(+ "AsyncPassthroughStreamingResponse must be awaited "+ "before accessing status_code"+ )+ return self._status_code++ @status_code.setter+ def status_code(self, value: int) -> None:+ self._status_code = value++ @property+ def headers(self) -> httpx.Headers:+ if not self._initialized:+ raise RuntimeError(+ "AsyncPassthroughStreamingResponse must be awaited "+ "before accessing headers"+ )+ return self._headers++ @headers.setter+ def headers(self, value: httpx.Headers) -> None:+ self._headers = value++ def __await__(self):+ async def _init():+ if not self._initialized:+ self._response = await self._response_coro+ self.headers = self._response.headers+ self.status_code = self._response.status_code+ self._initialized = True+ try:+ self._response.raise_for_status()+ self._iterator = cast(+ AsyncGenerator[bytes, Any], self._response.aiter_bytes()+ )+ except Exception:+ try:+ await self._response.aclose()+ except Exception:+ pass+ raise+ return self++ return _init().__await__()++ def _start_flush(self) -> None:+ if self._flush_scheduled or not self._raw_bytes:+ return+ self._flush_scheduled = True++ try:+ task = asyncio.create_task(+ self._litellm_logging_obj.async_flush_passthrough_collected_chunks(+ raw_bytes=self._raw_bytes,+ provider_config=self._provider_config,+ )+ )++ # Compliant: Save a strong reference to prevent GC+ self._background_tasks.add(task)++ # Remove the task from the set when it finishes to avoid memory leaks+ task.add_done_callback(self._background_tasks.discard)+ except Exception as e:+ verbose_logger.exception(+ "Failed to schedule passthrough spend-tracking flush; "+ "%d buffered chunks dropped: %s",+ len(self._raw_bytes),+ e,+ )- def __aiter__(self) -> "_AsyncPassthroughStreamingResponse":+ def __aiter__(self) -> "AsyncPassthroughStreamingResponse":return selfasync def __anext__(self) -> bytes:+ if not self._initialized:+ await selftry:chunk = await self._iterator.__anext__()self._raw_bytes.append(chunk)return chunk- except StopAsyncIteration:- self._start_flush()- raiseexcept Exception:+ self._start_flush()try:- await self.response.aclose()+ await self._response.aclose()except Exception:passraise+ async def asend(self, value: Any) -> bytes:+ if not self._initialized:+ await self+ return await self._iterator.asend(value)++ async def athrow(self, typ: Any, val: Any = None, tb: Any = None) -> bytes:+ if not self._initialized:+ await self+ return await self._iterator.athrow(typ, val, tb)++ async def aclose(self) -> None:+ self._start_flush()+ try:+ if self._initialized:+ await self._response.aclose()+ except Exception:+ pass+++class PassthroughStreamingResponse(Generator[Any, Any, Any]):+ def __init__(+ self,+ response: httpx.Response,+ litellm_logging_obj: "LiteLLMLoggingObj",+ provider_config: "BasePassthroughConfig",+ ) -> None:+ self._response = response+ self.headers = response.headers+ self.status_code = response.status_code+ self._litellm_logging_obj = litellm_logging_obj+ self._provider_config = provider_config+ self._iterator: Generator[bytes, Any, Any] = cast(+ Generator[bytes, Any, Any], response.iter_bytes()+ )+ self._raw_bytes: List[bytes] = []+ self._flush_scheduled = False+def _start_flush(self) -> None:- if self._flush_started:+ if self._flush_scheduled or not self._raw_bytes:return+ self._flush_scheduled = True++ from litellm.utils import executor- self._flush_started = True- asyncio.create_task(- self._litellm_logging_obj.async_flush_passthrough_collected_chunks(+ try:+ executor.submit(+ self._litellm_logging_obj.flush_passthrough_collected_chunks,raw_bytes=self._raw_bytes,provider_config=self._provider_config,)- )+ except Exception as e:+ verbose_logger.exception(+ "Failed to schedule passthrough spend-tracking flush; "+ "%d buffered chunks dropped: %s",+ len(self._raw_bytes),+ e,+ )- async def aclose(self) -> None:+ def __iter__(self) -> "PassthroughStreamingResponse":+ return self++ def __next__(self) -> bytes:+ try:+ chunk = next(self._iterator)+ self._raw_bytes.append(chunk)+ return chunk+ except Exception:+ self._start_flush()+ try:+ self._response.close()+ except Exception:+ pass+ raise++ def send(self, value: Any) -> bytes:+ return self._iterator.send(value)++ def throw(self, typ: Any, val: Any = None, tb: Any = None) -> bytes:+ return self._iterator.throw(typ, val, tb)++ def close(self) -> None:self._start_flush()- await self.response.aclose()+ try:+ self._response.close()+ except Exception:+ pass@client@@ -110,7 +254,7 @@ async def allm_passthrough_route(cookies: Optional[CookieTypes] = None,client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,**kwargs,-) -> Union[httpx.Response, AsyncIterator[bytes]]:+) -> Union[httpx.Response, AsyncGenerator[Any, Any]]:"""Async: Reranks a list of documents based on their relevance to the query"""@@ -239,9 +383,9 @@ def llm_passthrough_route() -> Union[httpx.Response,Coroutine[Any, Any, httpx.Response],- Coroutine[Any, Any, Union[httpx.Response, AsyncIterator[bytes]]],+ Coroutine[Any, Any, Union[httpx.Response, AsyncGenerator[Any, Any]]],Generator[Any, Any, Any],- AsyncIterator[bytes],+ AsyncGenerator[Any, Any],]:"""Pass through requests to the LLM APIs.@@ -390,12 +534,11 @@ def llm_passthrough_route(response: httpx.Response = client.client.send(request=request, stream=is_streaming_request) # type: ignoreresponse.raise_for_status()- if (- hasattr(response, "iter_bytes") and is_streaming_request- ): # yield the chunk, so we can store it in the logging object- return _sync_streaming(response, litellm_logging_obj, provider_config)+ if hasattr(response, "iter_bytes") and is_streaming_request:+ return PassthroughStreamingResponse(+ response, litellm_logging_obj, provider_config+ )else:- # For non-streaming responses, yield the entire responsereturn responseexcept Exception as e:if provider_config is None:@@ -412,7 +555,7 @@ async def _async_passthrough_request(is_streaming_request: bool,litellm_logging_obj: "LiteLLMLoggingObj",provider_config: "BasePassthroughConfig",-) -> Union[httpx.Response, AsyncIterator[bytes]]:+) -> Union[httpx.Response, AsyncGenerator[Any, Any]]:"""Handle async passthrough requests.Uses async client to send request and properly handles streaming.@@ -423,10 +566,8 @@ async def _async_passthrough_request(# Check if it's a coroutine and await itif asyncio.iscoroutine(response_result):if is_streaming_request:- iter_response = await response_result- iter_response.raise_for_status()- return _AsyncPassthroughStreamingResponse(- response=iter_response,+ return await AsyncPassthroughStreamingResponse(+ response=response_result,litellm_logging_obj=litellm_logging_obj,provider_config=provider_config,)@@ -438,84 +579,3 @@ async def _async_passthrough_request(else:# Fallback for sync-like behavior (shouldn't happen in async path)raise Exception("Expected coroutine from async client")---def _sync_streaming(- response: httpx.Response,- litellm_logging_obj: "LiteLLMLoggingObj",- provider_config: "BasePassthroughConfig",-):- from litellm.utils import executor-- raw_bytes: List[bytes] = []- flush_scheduled = False- try:- for chunk in response.iter_bytes(): # type: ignore- raw_bytes.append(chunk)- yield chunk- finally:- if not flush_scheduled and raw_bytes:- flush_scheduled = True- try:- executor.submit(- litellm_logging_obj.flush_passthrough_collected_chunks,- raw_bytes=raw_bytes,- provider_config=provider_config,- )- except Exception as e:- verbose_logger.exception(- "Failed to schedule passthrough spend-tracking flush "- "in _sync_streaming; %d buffered chunks dropped: %s",- len(raw_bytes),- e,- )---async def _async_streaming(- response: Coroutine[Any, Any, httpx.Response],- litellm_logging_obj: "LiteLLMLoggingObj",- provider_config: "BasePassthroughConfig",-):- iter_response = await response-- try:- iter_response.raise_for_status()- except Exception:- try:- await iter_response.aclose()- except Exception:- pass- raise-- raw_bytes: List[bytes] = []- flush_scheduled = False- try:- async for chunk in iter_response.aiter_bytes(): # type: ignore- raw_bytes.append(chunk)- yield chunk- except Exception:- try:- await iter_response.aclose()- except Exception:- pass- raise- finally:- # GeneratorExit (raised on client disconnect) is not caught by- # `except Exception`; the finally block ensures partial usage- # still gets flushed for spend tracking. See LIT-2642.- if not flush_scheduled and raw_bytes:- flush_scheduled = True- try:- asyncio.create_task(- litellm_logging_obj.async_flush_passthrough_collected_chunks(- raw_bytes=raw_bytes,- provider_config=provider_config,- )- )- except Exception as e:- verbose_logger.exception(- "Failed to schedule passthrough spend-tracking flush "- "in _async_streaming; %d buffered chunks dropped: %s",- len(raw_bytes),- e,- )diff --git a/tests/test_litellm/passthrough/test_async_streaming_error_propagation.py b/tests/test_litellm/passthrough/test_async_streaming_error_propagation.pyindex 631037b3357..f7052fee3b9 100644--- a/tests/test_litellm/passthrough/test_async_streaming_error_propagation.py+++ b/tests/test_litellm/passthrough/test_async_streaming_error_propagation.py@@ -52,43 +52,69 @@ def _make_mock_logging_obj():@pytest.mark.asyncio-async def test_async_passthrough_wrapper_429_raises_before_iteration():- """429 from upstream should be raised before the wrapper is constructed."""+async def test_async_streaming_429_raises():+ """429 from upstream should raise HTTPStatusError, not yield error bytes."""+ from litellm.passthrough.main import AsyncPassthroughStreamingResponse+error_body = json.dumps({"error": {"code": "429", "message": "Rate limit exceeded."}}).encode()mock_response = _make_mock_response(429, error_body)-++ async def response_coro():+ return mock_response++ chunks = []with pytest.raises(httpx.HTTPStatusError) as exc_info:- mock_response.raise_for_status()-+ async for chunk in AsyncPassthroughStreamingResponse(+ response=response_coro(),+ litellm_logging_obj=_make_mock_logging_obj(),+ provider_config=MagicMock(),+ ):+ chunks.append(chunk)+assert exc_info.value.response.status_code == 429+ assert len(chunks) == 0@pytest.mark.asyncio-async def test_async_passthrough_wrapper_500_raises_before_iteration():- """500 from upstream should be raised before the wrapper is constructed."""+async def test_async_streaming_500_raises():+ """500 from upstream should also raise, not yield error bytes."""+ from litellm.passthrough.main import AsyncPassthroughStreamingResponse+error_body = json.dumps({"error": {"code": "500", "message": "Internal server error"}}).encode()mock_response = _make_mock_response(500, error_body)-++ async def response_coro():+ return mock_response+with pytest.raises(httpx.HTTPStatusError) as exc_info:- mock_response.raise_for_status()-+ async for _ in AsyncPassthroughStreamingResponse(+ response=response_coro(),+ litellm_logging_obj=_make_mock_logging_obj(),+ provider_config=MagicMock(),+ ):+ pass+assert exc_info.value.response.status_code == 500@pytest.mark.asyncioasync def test_async_passthrough_wrapper_200_yields_chunks():"""Successful 200 streaming responses should continue to work normally."""- from litellm.passthrough.main import _AsyncPassthroughStreamingResponse+ from litellm.passthrough.main import AsyncPassthroughStreamingResponsesse_data = b'data: {"type":"response.created"}\n\ndata: [DONE]\n\n'mock_response = _make_mock_response(200, sse_data)mock_logging_obj = _make_mock_logging_obj()- async_stream = _AsyncPassthroughStreamingResponse(- response=mock_response,++ async def response_coro():+ return mock_response++ async_stream = AsyncPassthroughStreamingResponse(+ response=response_coro(),litellm_logging_obj=mock_logging_obj,provider_config=MagicMock(),)@@ -102,32 +128,3 @@ async def test_async_passthrough_wrapper_200_yields_chunks():assert len(chunks) == 1assert b"response.created" in chunks[0]mock_logging_obj.async_flush_passthrough_collected_chunks.assert_awaited_once()---async def test_async_passthrough_wrapper_closes_response_on_iteration_error():- """Wrapper should close the upstream response if iteration raises."""- from litellm.passthrough.main import _AsyncPassthroughStreamingResponse-- mock_response = MagicMock(spec=httpx.Response)- mock_response.status_code = 200- mock_response.headers = httpx.Headers({"content-type": "text/event-stream"})- mock_response.aclose = AsyncMock()-- async def _failing_aiter_bytes():- raise RuntimeError("stream failed")- yield b""-- mock_response.aiter_bytes = _failing_aiter_bytes-- async_stream = _AsyncPassthroughStreamingResponse(- response=mock_response,- litellm_logging_obj=_make_mock_logging_obj(),- provider_config=MagicMock(),- )-- with pytest.raises(RuntimeError, match="stream failed"):- async for chunk in async_stream:- _ = chunk-- mock_response.aclose.assert_awaited_once()diff --git a/tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.py b/tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.pyindex f3fe3ae5c38..27d265e6f5d 100644--- a/tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.py+++ b/tests/test_litellm/passthrough/test_streaming_interrupt_spend_tracking.py@@ -35,11 +35,14 @@ class _ImmediateExecutor:@pytest.mark.asyncio-async def test_async_streaming_flushes_on_normal_completion():- from litellm.passthrough.main import _async_streaming+async def test_asyncpassthroughstreamingresponse_flushes_on_normal_completion():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponsechunks = [b"chunk-1", b"chunk-2", b"chunk-3"]mock_response = _make_streaming_response(chunks)+ mock_response.headers = httpx.Headers(+ {"content-type": "application/octet-stream", "x-request-id": "req-123"}+ )async def response_coro():return mock_response@@ -48,14 +51,19 @@ async def test_async_streaming_flushes_on_normal_completion():provider_config = MagicMock()received = []- async for chunk in _async_streaming(+ received_response = AsyncPassthroughStreamingResponse(response=response_coro(),litellm_logging_obj=mock_logging_obj,provider_config=provider_config,- ):+ )++ async for chunk in received_response:received.append(chunk)assert received == chunks++ assert received_response.headers["content-type"] == "application/octet-stream"+ assert received_response.headers["x-request-id"] == "req-123"await asyncio.sleep(0)@@ -68,8 +76,8 @@ async def test_async_streaming_flushes_on_normal_completion():@pytest.mark.asyncio-async def test_async_streaming_flushes_on_client_disconnect():- from litellm.passthrough.main import _async_streaming+async def test_asyncpassthroughstreamingresponse_flushes_on_client_disconnect():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponsechunks = [b'{"chunk": 1, "outputTokens": 10}',@@ -77,6 +85,9 @@ async def test_async_streaming_flushes_on_client_disconnect():b'{"chunk": 3, "outputTokens": 8}',]mock_response = _make_streaming_response(chunks)+ mock_response.headers = httpx.Headers(+ {"content-type": "application/octet-stream", "x-request-id": "req-123"}+ )async def response_coro():return mock_response@@ -84,7 +95,7 @@ async def test_async_streaming_flushes_on_client_disconnect():mock_logging_obj = _make_logging_obj()provider_config = MagicMock()- gen = _async_streaming(+ gen = AsyncPassthroughStreamingResponse(response=response_coro(),litellm_logging_obj=mock_logging_obj,provider_config=provider_config,@@ -105,11 +116,14 @@ async def test_async_streaming_flushes_on_client_disconnect():@pytest.mark.asyncio-async def test_async_streaming_does_not_flush_on_4xx():- from litellm.passthrough.main import _async_streaming+async def test_asyncpassthroughstreamingresponse_does_not_flush_on_4xx():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponseerr_response = MagicMock(spec=httpx.Response)err_response.status_code = 429+ err_response.headers = httpx.Headers(+ {"content-type": "application/octet-stream"}+ )def _raise():raise httpx.HTTPStatusError(@@ -129,7 +143,7 @@ async def test_async_streaming_does_not_flush_on_4xx():mock_logging_obj = _make_logging_obj()with pytest.raises(httpx.HTTPStatusError):- async for _ in _async_streaming(+ async for _ in AsyncPassthroughStreamingResponse(response=response_coro(),litellm_logging_obj=mock_logging_obj,provider_config=MagicMock(),@@ -140,8 +154,8 @@ async def test_async_streaming_does_not_flush_on_4xx():@pytest.mark.asyncio-async def test_async_streaming_flushes_on_upstream_exception_with_partial_data():- from litellm.passthrough.main import _async_streaming+async def test_asyncpassthroughstreamingresponse_flushes_on_upstream_exception_with_partial_data():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponsepartial_chunks = [b"partial-chunk-1", b"partial-chunk-2"]@@ -149,6 +163,9 @@ async def test_async_streaming_flushes_on_upstream_exception_with_partial_data()mock_response.status_code = 200mock_response.raise_for_status = MagicMock(return_value=None)mock_response.aclose = AsyncMock()+ mock_response.headers = httpx.Headers(+ {"content-type": "application/octet-stream", "x-request-id": "req-123"}+ )async def _aiter_bytes_then_raise():for c in partial_chunks:@@ -165,7 +182,7 @@ async def test_async_streaming_flushes_on_upstream_exception_with_partial_data()received = []with pytest.raises(httpx.ReadError):- async for chunk in _async_streaming(+ async for chunk in AsyncPassthroughStreamingResponse(response=response_coro(),litellm_logging_obj=mock_logging_obj,provider_config=provider_config,@@ -183,12 +200,16 @@ async def test_async_streaming_flushes_on_upstream_exception_with_partial_data()assert call_kwargs["raw_bytes"] == partial_chunks-def test_sync_streaming_flushes_on_normal_completion():- from litellm.passthrough.main import _sync_streaming+def test_passthroughstreamingresponse_flushes_on_normal_completion():+ from litellm.passthrough.main import PassthroughStreamingResponsechunks = [b"a", b"b", b"c"]mock_response = MagicMock(spec=httpx.Response)+ mock_response.status_code = 200+ mock_response.headers = httpx.Headers(+ {"content-type": "application/octet-stream", "x-request-id": "req-123"}+ )def _iter_bytes():yield from chunks@@ -199,25 +220,33 @@ def test_sync_streaming_flushes_on_normal_completion():mock_logging_obj.flush_passthrough_collected_chunks = MagicMock()provider_config = MagicMock()+ received_responce = PassthroughStreamingResponse(+ response=mock_response,+ litellm_logging_obj=mock_logging_obj,+ provider_config=provider_config,+ )+with patch("litellm.utils.executor", _ImmediateExecutor()):- received = list(- _sync_streaming(- response=mock_response,- litellm_logging_obj=mock_logging_obj,- provider_config=provider_config,- )- )+ received = list(received_responce)assert received == chunks++ assert received_responce.headers["content-type"] == "application/octet-stream"+ assert received_responce.headers["x-request-id"] == "req-123"+mock_logging_obj.flush_passthrough_collected_chunks.assert_called_once()-def test_sync_streaming_flushes_on_early_close():- from litellm.passthrough.main import _sync_streaming+def test_passthroughstreamingresponse_flushes_on_early_close():+ from litellm.passthrough.main import PassthroughStreamingResponsechunks = [b"first", b"second", b"third"]mock_response = MagicMock(spec=httpx.Response)+ mock_response.status_code = 200+ mock_response.headers = httpx.Headers(+ {"content-type": "application/octet-stream", "x-request-id": "req-123"}+ )def _iter_bytes():yield from chunks@@ -229,7 +258,7 @@ def test_sync_streaming_flushes_on_early_close():provider_config = MagicMock()with patch("litellm.utils.executor", _ImmediateExecutor()):- gen = _sync_streaming(+ gen = PassthroughStreamingResponse(response=mock_response,litellm_logging_obj=mock_logging_obj,provider_config=provider_config,