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): record ownership of streamed responses under managed ids
mateo-berrie0c101b4da83
diff --git a/litellm/proxy/common_utils/sse_keepalive.py b/litellm/proxy/common_utils/sse_keepalive.pyindex 429fff99ae6..e3cebf9f6c6 100644--- a/litellm/proxy/common_utils/sse_keepalive.py+++ b/litellm/proxy/common_utils/sse_keepalive.py@@ -91,6 +91,18 @@ def is_sse_content_type(content_type: str | None) -> bool:return content_type is not None and content_type.split(";", 1)[0].strip().lower() == _SSE_MEDIA_TYPE+def split_complete_sse_frames(pending: bytes) -> tuple[bytes, bytes]:+ """Split buffered SSE bytes into ``(complete_frames, unterminated_tail)``."""+ lf_boundary_end: Final = pending.rfind(b"\n\n") + 2+ crlf_boundary_end: Final = pending.rfind(b"\r\n\r\n") + 4+ boundary_end: Final = max(+ lf_boundary_end if lf_boundary_end >= 2 else 0, crlf_boundary_end if crlf_boundary_end >= 4 else 0+ )+ if boundary_end == 0:+ return b"", pending+ return pending[:boundary_end], pending[boundary_end:]++def wrap_passthrough_sse_bytes_with_keepalive_pings(stream: AsyncGenerator[bytes, None],ping_interval_seconds: float | str | None,diff --git a/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py b/litellm/proxy/pass_through_endpoints/managed_id_rewriter.pyindex 4de6ef04d76..bdc4c515803 100644--- a/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py+++ b/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py@@ -32,7 +32,7 @@ from __future__ import annotationsimport jsonimport re-from collections.abc import Callable, Mapping, Sequence+from collections.abc import AsyncGenerator, Callable, Mapping, Sequencefrom typing import (TYPE_CHECKING,Final,@@ -43,7 +43,7 @@ from typing import (from urllib.parse import quote, unquotefrom fastapi import HTTPException-from pydantic import JsonValue+from pydantic import JsonValue, TypeAdapter, ValidationErrorfrom litellm._logging import verbose_proxy_loggerfrom litellm.llms.base_llm.managed_resources.isolation import (@@ -52,6 +52,7 @@ from litellm.llms.base_llm.managed_resources.isolation import ()from litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.batches_endpoints.common_utils import validate_batch_list_limit+from litellm.proxy.common_utils.sse_keepalive import split_complete_sse_framesfrom litellm.repositories.table_repositories import (ManagedFileRepository,ManagedObjectRepository,@@ -820,6 +821,125 @@ async def rewrite_response_ids(return mutated if changed else body+# ---------------------------------------------------------------------------+# OUTPUT path — streamed Responses API bodies+# ---------------------------------------------------------------------------++_RESPONSE_ID_PREFIX: Final = "resp_"+_STREAMED_RESPONSE_ID_SPEC: Final[_FieldSpec] = ("id", _RESPONSE_ID_PREFIX)+_SSE_DATA_PREFIX: Final = "data:"+_SSE_EVENT_ADAPTER: Final = TypeAdapter(Mapping[str, JsonValue])+++def _first_streamed_response(frames: bytes) -> tuple[str, Mapping[str, JsonValue]] | None:+ for line in frames.decode("utf-8", errors="replace").splitlines():+ if not line.startswith(_SSE_DATA_PREFIX):+ continue+ try:+ event = _SSE_EVENT_ADAPTER.validate_json(line[len(_SSE_DATA_PREFIX) :])+ except ValidationError:+ continue+ response = event.get("response")+ if not isinstance(response, dict):+ continue+ raw_id = response.get("id")+ if isinstance(raw_id, str) and raw_id.startswith(_RESPONSE_ID_PREFIX):+ return raw_id, response+ return None+++class _StreamedResponseIdRewriter:+ __slots__ = ("_is_create_route", "_pending", "_prisma_client", "_provider", "_replacement", "_user_api_key_dict")++ def __init__(+ self,+ provider: str,+ user_api_key_dict: UserAPIKeyAuth,+ prisma_client: PrismaClient,+ is_create_route: bool,+ ) -> None:+ self._provider: Final = provider+ self._user_api_key_dict: Final = user_api_key_dict+ self._prisma_client: Final = prisma_client+ self._is_create_route: Final = is_create_route+ self._pending = b""+ self._replacement: tuple[bytes, bytes] | None = None++ async def feed(self, chunk: bytes) -> bytes:+ complete_frames, self._pending = split_complete_sse_frames(self._pending + chunk)+ if not complete_frames:+ return b""+ if self._replacement is None:+ self._replacement = await self._mint(complete_frames)+ return self._rewrite(complete_frames)++ def flush(self) -> bytes:+ tail: Final = self._pending+ self._pending = b""+ return self._rewrite(tail)++ async def _mint(self, frames: bytes) -> tuple[bytes, bytes] | None:+ first: Final = _first_streamed_response(frames)+ if first is None:+ return None+ raw_id, snapshot = first+ managed_id: Final = await _mint_or_reuse_object(+ raw_id,+ self._provider,+ "response",+ snapshot,+ self._user_api_key_dict,+ self._prisma_client,+ self._is_create_route,+ )+ return raw_id.encode(), managed_id.encode()++ def _rewrite(self, frames: bytes) -> bytes:+ if self._replacement is None:+ return frames+ raw_id, managed_id = self._replacement+ return frames.replace(raw_id, managed_id)+++async def rewrite_streamed_response_ids(+ stream: AsyncGenerator[bytes, None],+ provider: str,+ method: str,+ route: str,+ user_api_key_dict: UserAPIKeyAuth,+ prisma_client: PrismaClient,+) -> AsyncGenerator[bytes, None]:+ """+ Record ownership of the response object streamed back by a Responses API+ passthrough and swap its managed id into every SSE frame, so a streamed+ response is owned and resolved exactly like a non-streamed one.++ Streams for any other ``(provider, method, route)`` are relayed untouched.+ """+ from litellm.proxy.auth.auth_utils import normalize_request_route++ canonical: Final = normalize_request_route(_canonical_path(route))+ field_specs: Final = BUILTIN_OUTPUT_ID_FIELD_MAP.get((provider, method, canonical), ())+ if _STREAMED_RESPONSE_ID_SPEC not in field_specs:+ async for chunk in stream:+ yield chunk+ return++ rewriter: Final = _StreamedResponseIdRewriter(+ provider=provider,+ user_api_key_dict=user_api_key_dict,+ prisma_client=prisma_client,+ is_create_route="{" not in canonical,+ )+ async for chunk in stream:+ rewritten_frames = await rewriter.feed(chunk)+ if rewritten_frames:+ yield rewritten_frames+ tail: Final = rewriter.flush()+ if tail:+ yield tail++# ---------------------------------------------------------------------------# List-route interception — serve listing entirely from DB# ---------------------------------------------------------------------------diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.pyindex 60b85cb42d0..3d60f4f5f3a 100644--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py@@ -1209,14 +1209,19 @@ async def pass_through_request(return StreamingResponse(wrap_passthrough_sse_bytes_with_keepalive_pings(- stream=PassThroughStreamingHandler.chunk_processor(- response=response,- request_body=_parsed_body,- litellm_logging_obj=logging_obj,- endpoint_type=endpoint_type,- start_time=start_time,- passthrough_success_handler_obj=pass_through_endpoint_logging,- url_route=str(url),+ stream=_own_streamed_managed_ids(+ stream=PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body=_parsed_body,+ litellm_logging_obj=logging_obj,+ endpoint_type=endpoint_type,+ start_time=start_time,+ passthrough_success_handler_obj=pass_through_endpoint_logging,+ url_route=str(url),+ ),+ managed_id_provider=_managed_id_provider,+ request=request,+ user_api_key_dict=user_api_key_dict,),ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,upstream_headers=response.headers,@@ -1285,14 +1290,19 @@ async def pass_through_request(return StreamingResponse(wrap_passthrough_sse_bytes_with_keepalive_pings(- stream=PassThroughStreamingHandler.chunk_processor(- response=response,- request_body=_parsed_body,- litellm_logging_obj=logging_obj,- endpoint_type=endpoint_type,- start_time=start_time,- passthrough_success_handler_obj=pass_through_endpoint_logging,- url_route=str(url),+ stream=_own_streamed_managed_ids(+ stream=PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body=_parsed_body,+ litellm_logging_obj=logging_obj,+ endpoint_type=endpoint_type,+ start_time=start_time,+ passthrough_success_handler_obj=pass_through_endpoint_logging,+ url_route=str(url),+ ),+ managed_id_provider=_managed_id_provider,+ request=request,+ user_api_key_dict=user_api_key_dict,),ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,upstream_headers=response.headers,@@ -2441,6 +2451,36 @@ def _is_streaming_response(response: httpx.Response) -> bool:return False+def _own_streamed_managed_ids(+ stream: AsyncGenerator[bytes, None],+ managed_id_provider: str | None,+ request: Request,+ user_api_key_dict: UserAPIKeyAuth,+) -> AsyncGenerator[bytes, None]:+ from litellm.proxy.proxy_server import general_settings, prisma_client, proxy_logging_obj++ if (+ managed_id_provider is None+ or not general_settings.get("passthrough_managed_object_ids", False)+ or prisma_client is None+ or proxy_logging_obj.get_proxy_hook("managed_files") is None+ ):+ return stream+ from litellm.proxy.auth.auth_utils import get_request_route+ from litellm.proxy.pass_through_endpoints.managed_id_rewriter import (+ rewrite_streamed_response_ids,+ )++ return rewrite_streamed_response_ids(+ stream=stream,+ provider=managed_id_provider,+ method=request.method,+ route=get_request_route(request),+ user_api_key_dict=user_api_key_dict,+ prisma_client=prisma_client,+ )++def _should_buffer_passthrough_response(response: httpx.Response) -> bool:"""Decide from the response headers whether the body must be read into memory.diff --git a/litellm/proxy/pass_through_endpoints/streaming_handler.py b/litellm/proxy/pass_through_endpoints/streaming_handler.pyindex b71622fc33d..eea1b19dea3 100644--- a/litellm/proxy/pass_through_endpoints/streaming_handler.py+++ b/litellm/proxy/pass_through_endpoints/streaming_handler.py@@ -10,6 +10,7 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingfrom litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKERfrom litellm.proxy._types import PassThroughEndpointLoggingResultValuesfrom litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing+from litellm.proxy.common_utils.sse_keepalive import split_complete_sse_framesfrom litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointTypefrom litellm.types.utils import StandardPassThroughResponseObject@@ -101,7 +102,7 @@ class PassThroughStreamingHandler:async for chunk in response.aiter_bytes():raw_bytes.append(chunk)PassThroughStreamingHandler._stamp_first_chunk_if_needed(litellm_logging_obj)- complete_frames, pending = PassThroughStreamingHandler._split_complete_sse_frames(+ complete_frames, pending = split_complete_sse_frames(pending + chunk) # rebind-ok: SSE frame reassembly buffer across transport chunksif complete_frames:@@ -139,17 +140,6 @@ class PassThroughStreamingHandler:except Exception as e:verbose_proxy_logger.error("Error scheduling chunk_processor logging: %s", e)- @staticmethod- def _split_complete_sse_frames(pending: bytes) -> tuple[bytes, bytes]:- lf_boundary_end: Final = pending.rfind(b"\n\n") + 2- crlf_boundary_end: Final = pending.rfind(b"\r\n\r\n") + 4- boundary_end: Final = max(- lf_boundary_end if lf_boundary_end >= 2 else 0, crlf_boundary_end if crlf_boundary_end >= 4 else 0- )- if boundary_end == 0:- return b"", pending- return pending[:boundary_end], pending[boundary_end:]-@staticmethodasync def _route_streaming_logging_to_handler(litellm_logging_obj: LiteLLMLoggingObj,diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_managed_id_rewriter.py b/tests/test_litellm/proxy/pass_through_endpoints/test_managed_id_rewriter.pyindex f5bec4a2585..da4ccff7008 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_managed_id_rewriter.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_managed_id_rewriter.py@@ -1,12 +1,15 @@import datetime+import json+from collections.abc import AsyncIterator, Iterablefrom unittest.mock import AsyncMock, MagicMockimport pytestfrom litellm.proxy._types import ProxyException, UserAPIKeyAuth-from litellm.proxy.pass_through_endpoints.managed_id_codec import new_managed_id+from litellm.proxy.pass_through_endpoints.managed_id_codec import decode, new_managed_idfrom litellm.proxy.pass_through_endpoints.managed_id_rewriter import (list_passthrough_ids_from_db,+ rewrite_streamed_response_ids,)@@ -27,9 +30,39 @@ def _prisma_client(file_rows=None, batch_rows=None) -> MagicMock:pc.db.litellm_managedobjecttable.find_many = AsyncMock(side_effect=lambda *args, take=None, **kwargs: list(batch_rows or [])[:take])+ pc.db.litellm_managedobjecttable.upsert = AsyncMock(return_value=None)return pc+RAW_RESPONSE_ID = "resp_0123456789abcdef"+++def _response_stream_bytes(raw_id: str = RAW_RESPONSE_ID) -> bytes:+ events = (+ ("response.created", {"type": "response.created", "response": {"id": raw_id, "status": "in_progress"}}),+ ("response.output_text.delta", {"type": "response.output_text.delta", "delta": "mango"}),+ ("response.completed", {"type": "response.completed", "response": {"id": raw_id, "status": "completed"}}),+ )+ return b"".join(f"event: {name}\ndata: {json.dumps(payload)}\n\n".encode() for name, payload in events)+++async def _chunks(payload: bytes, size: int) -> AsyncIterator[bytes]:+ for start in range(0, len(payload), size):+ yield payload[start : start + size]+++async def _collect(stream: AsyncIterator[bytes]) -> bytes:+ return b"".join([chunk async for chunk in stream])+++def _response_ids(sse: bytes) -> Iterable[str]:+ for line in sse.decode().splitlines():+ if line.startswith("data:"):+ event = json.loads(line[len("data:") :])+ if "response" in event:+ yield event["response"]["id"]++def _file_row(unified_id: str) -> MagicMock:row = MagicMock()row.unified_file_id = unified_id@@ -67,9 +100,7 @@ def _batch_row(unified_id: str) -> MagicMock:),],)-async def test_list_batches_out_of_range_limit_raises_400(- limit, expected_message, expected_openai_code-):+async def test_list_batches_out_of_range_limit_raises_400(limit, expected_message, expected_openai_code):pc = _prisma_client(batch_rows=[_batch_row(new_managed_id("openai", "batch_abc"))])with pytest.raises(ProxyException) as exc:@@ -147,3 +178,75 @@ async def test_list_files_drops_batch_guardrail_key_persisted_by_an_older_proxy(assert result is not Noneassert "litellm_batch_guardrail" not in result["data"][0]assert result["data"][0]["filename"] == "test.jsonl"++[email protected]("chunk_size", [1, 7, 4096])+async def test_streamed_response_is_owned_and_rewritten_across_chunk_boundaries(chunk_size: int):+ """A streamed POST /v1/responses records the caller as owner once and returns+ the minted id in every event, no matter how the transport splits the SSE bytes."""+ pc = _prisma_client()++ output = await _collect(+ rewrite_streamed_response_ids(+ stream=_chunks(_response_stream_bytes(), chunk_size),+ provider="openai",+ method="POST",+ route="/openai_passthrough/v1/responses",+ user_api_key_dict=_user(),+ prisma_client=pc,+ )+ )++ pc.db.litellm_managedobjecttable.upsert.assert_awaited_once()+ created = pc.db.litellm_managedobjecttable.upsert.await_args.kwargs["data"]["create"]+ assert created["created_by"] == "user-1"+ assert created["team_id"] == "team-1"+ assert created["file_purpose"] == "response"+ assert created["model_object_id"] == f"passthrough:openai:{RAW_RESPONSE_ID}"+ managed_id = created["unified_object_id"]+ assert decode(managed_id).raw_provider_id == RAW_RESPONSE_ID+ assert list(_response_ids(output)) == [managed_id, managed_id]+ assert RAW_RESPONSE_ID.encode() not in output+ assert output == _response_stream_bytes(managed_id)+++async def test_streamed_bytes_untouched_on_routes_without_a_response_id():+ pc = _prisma_client()+ payload = _response_stream_bytes()++ output = await _collect(+ rewrite_streamed_response_ids(+ stream=_chunks(payload, 5),+ provider="openai",+ method="POST",+ route="/openai_passthrough/v1/chat/completions",+ user_api_key_dict=_user(),+ prisma_client=pc,+ )+ )++ assert output == payload+ pc.db.litellm_managedobjecttable.upsert.assert_not_awaited()+++async def test_streamed_response_stays_raw_and_intact_when_the_row_cannot_be_persisted():+ pc = _prisma_client()+ pc.db.litellm_managedobjecttable.upsert = AsyncMock(side_effect=RuntimeError("db down"))+ payload = _response_stream_bytes()++ output = await _collect(+ rewrite_streamed_response_ids(+ stream=_chunks(payload, 3),+ provider="openai",+ method="POST",+ route="/openai_passthrough/v1/responses",+ user_api_key_dict=_user(),+ prisma_client=pc,+ )+ )++ assert output == payload+ pc.db.litellm_managedobjecttable.upsert.assert_awaited_once()diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.pyindex 99a84d43c9b..a3f56adb86f 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py@@ -1493,6 +1493,86 @@ async def test_pass_through_request_sse_response_marks_logging_obj_as_stream():assert logging_obj.model_call_details["stream"] is True+async def test_pass_through_request_streamed_response_is_owned_by_the_caller():+ """+ Regression: with passthrough_managed_object_ids on, a streamed+ POST /openai_passthrough/v1/responses left the raw resp_ id in the stream and+ recorded no owner, so any other key could read, continue, and delete it.+ """+ import litellm+ from litellm.llms.custom_httpx.http_handler import get_async_httpx_client+ from litellm.types.llms.custom_http import httpxSpecialProvider++ raw_id = "resp_0123456789abcdef"+ upstream_body = (+ b'event: response.created\ndata: {"type": "response.created", "response": {"id": "%s"}}\n\n'+ b'event: response.completed\ndata: {"type": "response.completed", "response": {"id": "%s"}}\n\n'+ ) % (raw_id.encode(), raw_id.encode())+ prisma_client = MagicMock()+ prisma_client.db.litellm_managedobjecttable.find_first = AsyncMock(return_value=None)+ prisma_client.db.litellm_managedobjecttable.upsert = AsyncMock(return_value=None)+ prisma_client.db.litellm_managedfiletable.find_first = AsyncMock(return_value=None)++ def transport_handler(upstream_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, content=upstream_body, headers={"content-type": "text/event-stream"})++ real_handler = get_async_httpx_client(+ llm_provider=httpxSpecialProvider.PassThroughEndpoint,+ params={"timeout": resolve_pass_through_request_timeout(None)},+ )+ cache_dict = litellm.in_memory_llm_clients_cache.cache_dict+ cache_key = next(key for key, cached in cache_dict.items() if cached is real_handler)+ cache_dict[cache_key] = SimpleNamespace(client=httpx.AsyncClient(transport=httpx.MockTransport(transport_handler)))++ mock_proxy_logging = MagicMock()+ mock_proxy_logging.pre_call_hook = AsyncMock(side_effect=lambda user_api_key_dict, data, call_type: data)+ mock_proxy_logging.post_call_failure_hook = AsyncMock()+ mock_proxy_logging.post_call_response_headers_hook = AsyncMock(return_value={})+ mock_proxy_logging.get_proxy_hook = MagicMock(return_value=MagicMock())++ mock_request = MagicMock(spec=Request)+ mock_request.method = "POST"+ mock_request.scope = {"path": "/openai_passthrough/v1/responses"}+ mock_request.url = MagicMock()+ mock_request.url.path = "/openai_passthrough/v1/responses"+ mock_request.body = AsyncMock(return_value=b'{"model": "gpt-5.1", "input": "hi", "stream": true}')+ mock_request.headers = Headers({"content-type": "application/json"})+ mock_request.query_params = QueryParams({})++ flag_on = {"passthrough_managed_object_ids": True}+ proxy_server_globals = (+ patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging), # test-quality-ok: read at call time+ patch("litellm.proxy.proxy_server.general_settings", flag_on), # test-quality-ok: read at call time+ patch("litellm.proxy.proxy_server.prisma_client", prisma_client), # test-quality-ok: read at call time+ )++ try:+ with ExitStack() as stack:+ for patched_global in proxy_server_globals:+ stack.enter_context(patched_global)+ response = await pass_through_request(+ request=mock_request,+ target="https://api.openai.com/v1/responses",+ custom_headers={},+ user_api_key_dict=UserAPIKeyAuth(user_id="user-a", team_id="team-a"),+ custom_llm_provider="openai",+ )+ streamed = b"".join([chunk async for chunk in response.body_iterator])+ finally:+ cache_dict[cache_key] = real_handler++ assert response.status_code == 200+ prisma_client.db.litellm_managedobjecttable.upsert.assert_awaited_once()+ created = prisma_client.db.litellm_managedobjecttable.upsert.await_args.kwargs["data"]["create"]+ assert created["created_by"] == "user-a"+ assert created["team_id"] == "team-a"+ assert created["model_object_id"] == f"passthrough:openai:{raw_id}"+ managed_id = created["unified_object_id"]+ assert raw_id.encode() not in streamed+ assert streamed == upstream_body.replace(raw_id.encode(), managed_id.encode())++@pytest.mark.asyncioasync def test_create_pass_through_endpoint():"""