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(passthrough): flush interrupted streams on client disconnect and reuse cached gigachat http clients
mateo-berride1f38820a2f
diff --git a/litellm/llms/gigachat/authenticator.py b/litellm/llms/gigachat/authenticator.pyindex 293176d8931..d6b217d5746 100644--- a/litellm/llms/gigachat/authenticator.py+++ b/litellm/llms/gigachat/authenticator.py@@ -17,6 +17,7 @@ from litellm.caching.caching import InMemoryCachefrom litellm.llms.base_llm.chat.transformation import BaseLLMExceptionfrom litellm.llms.custom_httpx.http_handler import (HTTPHandler,+ _get_httpx_client, # pyright: ignore[reportPrivateUsage] # house cached-client factory has no public aliasget_async_httpx_client,)from litellm.secret_managers.main import get_secret_str@@ -56,7 +57,7 @@ def _get_scope() -> str:def _get_http_client() -> HTTPHandler:"""Get cached httpx client with SSL verification disabled."""- return HTTPHandler(ssl_verify=False)+ return _get_httpx_client(params={"ssl_verify": False})def get_access_token(diff --git a/litellm/llms/gigachat/file_handler.py b/litellm/llms/gigachat/file_handler.pyindex 900aa72f34c..163e944f124 100644--- a/litellm/llms/gigachat/file_handler.py+++ b/litellm/llms/gigachat/file_handler.py@@ -14,7 +14,7 @@ from typing import Finalfrom litellm._logging import verbose_loggerfrom litellm.llms.custom_httpx.http_handler import (- HTTPHandler,+ _get_httpx_client,get_async_httpx_client,)from litellm.llms.gigachat.utils import get_api_base@@ -52,7 +52,7 @@ def _parse_data_url(data_url: str) -> tuple[bytes, str, str] | None:def _download_image_sync(url: str) -> tuple[bytes, str, str]:"""Download image from URL synchronously."""- client: Final = HTTPHandler(ssl_verify=False)+ client: Final = _get_httpx_client(params={"ssl_verify": False})response: Final = client.get(url)response.raise_for_status()@@ -120,7 +120,7 @@ def upload_file_sync(base_url: Final = get_api_base(api_base)upload_url: Final = f"{base_url}/files"- client: Final = HTTPHandler(ssl_verify=False)+ client: Final = _get_httpx_client(params={"ssl_verify": False})response: Final = client.post(upload_url,headers={"Authorization": f"Bearer {access_token}"},diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 8ffb259473c..67306ea7d46 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -2496,7 +2496,7 @@ class ProxyBaseLLMRequestProcessing:# For passthrough routes, stream directly without error parsing# since we're dealing with raw binary data (e.g., AWS event streams)- return StreamingResponse(+ return _UpstreamClosingStreamingResponse(content=generator, # pyright: ignore[reportArgumentType] # generator-configured StreamingResponsestatus_code=getattr(response, "status_code", status.HTTP_200_OK),media_type=self._passthrough_event_stream_media_type(),diff --git a/tests/test_litellm/llms/gigachat/test_authenticator.py b/tests/test_litellm/llms/gigachat/test_authenticator.pyindex 30b3dec52cb..0a2695dc21e 100644--- a/tests/test_litellm/llms/gigachat/test_authenticator.py+++ b/tests/test_litellm/llms/gigachat/test_authenticator.py@@ -485,3 +485,10 @@ class TestParseTokenResponse:_parse_token_response(self._make_response({"exp": 1700000000000}))assert exc_info.value.status_code == 500assert "Invalid token response" in exc_info.value.message+++class TestGetHttpClient:+ def test_reuses_cached_client_across_calls(self):+ """Regression: the sync OAuth path must use the shared cached httpx client,+ not construct a fresh HTTPHandler per token request."""+ assert authenticator._get_http_client() is authenticator._get_http_client()diff --git a/tests/test_litellm/llms/gigachat/test_file_handler.py b/tests/test_litellm/llms/gigachat/test_file_handler.pyindex ced7c30ed9d..ce9505f11f2 100644--- a/tests/test_litellm/llms/gigachat/test_file_handler.py+++ b/tests/test_litellm/llms/gigachat/test_file_handler.py@@ -128,7 +128,7 @@ class TestParseDataUrl:class TestDownloadImageSync:- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_downloads_image_successfully(self, mock_http_handler_cls):mock_client = MagicMock()mock_response = MagicMock()@@ -144,7 +144,7 @@ class TestDownloadImageSync:assert ext == "jpeg"mock_client.get.assert_called_once_with("https://example.com/img.jpg")- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_raises_on_http_error(self, mock_http_handler_cls):mock_client = MagicMock()mock_client.get.side_effect = httpx.HTTPStatusError(@@ -157,7 +157,7 @@ class TestDownloadImageSync:with pytest.raises(httpx.HTTPStatusError):file_handler._download_image_sync("https://example.com/404")- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_parse_content_type_fallback(self, mock_http_handler_cls):mock_client = MagicMock()mock_response = MagicMock()@@ -171,7 +171,7 @@ class TestDownloadImageSync:assert content_type == "image/jpeg"assert ext == "jpeg"- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_extracts_extension_from_parametrized_type(self, mock_http_handler_cls):mock_client = MagicMock()mock_response = MagicMock()@@ -235,7 +235,7 @@ class TestDownloadImageAsync:class TestUploadFileSync:@patch(f"{FILE_MODULE}.get_api_base", return_value="https://api.example.com")@patch(f"{FILE_MODULE}.get_access_token", return_value="test-token")- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_uploads_base64_image_and_caches(self, mock_http_handler_cls, mock_get_token, mock_get_api_base):@@ -268,7 +268,7 @@ class TestUploadFileSync:@patch(f"{FILE_MODULE}.get_api_base", return_value="https://api.example.com")@patch(f"{FILE_MODULE}.get_access_token", return_value="test-token")- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_returns_cached_file_id(self, mock_http_handler_cls, mock_get_token, mock_get_api_base):@@ -282,7 +282,7 @@ class TestUploadFileSync:# No upload call was mademock_http_handler_cls.return_value.post.assert_not_called()- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")@patch(f"{FILE_MODULE}.get_access_token", return_value="test-token")@patch(f"{FILE_MODULE}.get_api_base", return_value="https://api.example.com")@patch(f"{FILE_MODULE}._download_image_sync")@@ -304,7 +304,7 @@ class TestUploadFileSync:assert result == "file-remote"mock_download.assert_called_once_with("https://example.com/remote.png")- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")@patch(f"{FILE_MODULE}.get_access_token", return_value="test-token")@patch(f"{FILE_MODULE}.get_api_base", return_value="https://api.example.com")def test_returns_none_on_upload_failure(@@ -325,7 +325,7 @@ class TestUploadFileSync:assert result is None- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")@patch(f"{FILE_MODULE}.get_access_token", return_value="test-token")@patch(f"{FILE_MODULE}.get_api_base", return_value="https://api.example.com")def test_returns_none_when_response_missing_id(@@ -346,7 +346,7 @@ class TestUploadFileSync:@patch(f"{FILE_MODULE}.get_api_base", return_value="https://api.example.com")@patch(f"{FILE_MODULE}.get_access_token", return_value="test-token")- @patch(f"{FILE_MODULE}.HTTPHandler")+ @patch(f"{FILE_MODULE}._get_httpx_client")def test_uploads_without_optional_args(self, mock_http_handler_cls, mock_get_token, mock_get_api_base):diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.pyindex 833c3754022..45e079c8595 100644--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@ -4694,7 +4694,7 @@ class TestAllmPassthroughStreamingProviderGate:}return ProxyBaseLLMRequestProcessing(data=data)- async def _run(self, processing_obj, monkeypatch, chunks):+ async def _run(self, processing_obj, monkeypatch, chunks, stream=None):import litellm.proxy.common_request_processing as crpfrom litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth@@ -4702,9 +4702,11 @@ class TestAllmPassthroughStreamingProviderGate:for chunk in chunks:yield chunk+ upstream_stream = stream if stream is not None else streaming_response()+async def fake_route_request(**kwargs):async def _llm_call():- return streaming_response()+ return upstream_streamreturn _llm_call()@@ -4729,6 +4731,40 @@ class TestAllmPassthroughStreamingProviderGate:skip_pre_call_logic=True,)+ @pytest.mark.asyncio+ async def test_client_disconnect_closes_unbuffered_passthrough_stream(self, monkeypatch):+ """Starlette abandons the body iterator when the client disconnects, so the+ unbuffered passthrough branch must return _UpstreamClosingStreamingResponse,+ whose shielded cleanup closes the upstream stream; that close is what flushes+ buffered passthrough usage into spend logs."""+ processing_obj = self._build_processing_obj("gigachat")+ monkeypatch.setattr(litellm, "callbacks", [])+ upstream_closed = asyncio.Event()++ async def hanging_stream():+ try:+ yield b"chunk-1"+ await asyncio.Event().wait()+ finally:+ upstream_closed.set()++ result = await self._run(processing_obj, monkeypatch, [], stream=hanging_stream())++ assert isinstance(result, _UpstreamClosingStreamingResponse)++ first_chunk_sent = asyncio.Event()++ async def receive():+ await first_chunk_sent.wait()+ return {"type": "http.disconnect"}++ async def send(message):+ if message["type"] == "http.response.body" and message.get("body"):+ first_chunk_sent.set()++ await result({"type": "http"}, receive, send)+ await asyncio.wait_for(upstream_closed.wait(), timeout=5)+@pytest.mark.asyncioasync def test_non_bedrock_stream_is_not_buffered(self, monkeypatch):processing_obj = self._build_processing_obj("anthropic")