Skip to content

Commit 4185c8a

Browse files
authored
Merge pull request BerriAI#38320 from BerriAI/litellm_passthrough_object_ownership
fix(passthrough): record ownership of streamed responses under managed ids
2 parents 5640e7c + 6a9662a commit 4185c8a

7 files changed

Lines changed: 411 additions & 34 deletions

File tree

‎litellm/proxy/common_utils/sse_keepalive.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,17 @@ def is_sse_content_type(content_type: str | None) -> bool:
9191
return content_type is not None and content_type.split(";", 1)[0].strip().lower() == _SSE_MEDIA_TYPE
9292

9393

94+
def split_complete_sse_frames(pending: bytes) -> tuple[bytes, bytes]:
95+
"""Split buffered SSE bytes into ``(complete_frames, unterminated_tail)``."""
96+
boundary_end: Final = max(
97+
(pending.rfind(delimiter) + len(delimiter) for delimiter in _SSE_FRAME_DELIMITERS if delimiter in pending),
98+
default=0,
99+
)
100+
if boundary_end == 0:
101+
return b"", pending
102+
return pending[:boundary_end], pending[boundary_end:]
103+
104+
94105
def wrap_passthrough_sse_bytes_with_keepalive_pings(
95106
stream: AsyncGenerator[bytes, None],
96107
ping_interval_seconds: float | str | None,

‎litellm/proxy/pass_through_endpoints/managed_id_rewriter.py‎

Lines changed: 118 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
import json
3434
import re
35-
from collections.abc import Callable, Mapping, Sequence
35+
from collections.abc import AsyncGenerator, Callable, Mapping, Sequence
3636
from typing import (
3737
TYPE_CHECKING,
3838
Final,
@@ -43,7 +43,7 @@
4343
from urllib.parse import quote, unquote
4444

4545
from fastapi import HTTPException
46-
from pydantic import JsonValue
46+
from pydantic import JsonValue, TypeAdapter, ValidationError
4747

4848
from litellm._logging import verbose_proxy_logger
4949
from litellm.llms.base_llm.managed_resources.isolation import (
@@ -52,6 +52,7 @@
5252
)
5353
from litellm.proxy._types import UserAPIKeyAuth
5454
from litellm.proxy.batches_endpoints.common_utils import validate_batch_list_limit
55+
from litellm.proxy.common_utils.sse_keepalive import split_complete_sse_frames
5556
from litellm.repositories.table_repositories import (
5657
ManagedFileRepository,
5758
ManagedObjectRepository,
@@ -820,6 +821,121 @@ def _record(field_name: str, raw_value: str, managed_id: str) -> None:
820821
return mutated if changed else body
821822

822823

824+
_RESPONSE_ID_PREFIX: Final = "resp_"
825+
_STREAMED_RESPONSE_ID_SPEC: Final[_FieldSpec] = ("id", _RESPONSE_ID_PREFIX)
826+
_SSE_DATA_PREFIX: Final = "data:"
827+
_SSE_EVENT_ADAPTER: Final = TypeAdapter(Mapping[str, JsonValue])
828+
829+
830+
def _first_streamed_response(frames: bytes) -> tuple[str, Mapping[str, JsonValue]] | None:
831+
for line in frames.decode("utf-8", errors="replace").splitlines():
832+
if not line.startswith(_SSE_DATA_PREFIX):
833+
continue
834+
try:
835+
event = _SSE_EVENT_ADAPTER.validate_json(line[len(_SSE_DATA_PREFIX) :])
836+
except ValidationError:
837+
continue
838+
response = event.get("response")
839+
if not isinstance(response, dict):
840+
continue
841+
raw_id = response.get("id")
842+
if isinstance(raw_id, str) and raw_id.startswith(_RESPONSE_ID_PREFIX):
843+
return raw_id, response
844+
return None
845+
846+
847+
class _StreamedResponseIdRewriter:
848+
__slots__ = ("_is_create_route", "_pending", "_prisma_client", "_provider", "_replacement", "_user_api_key_dict")
849+
850+
def __init__(
851+
self,
852+
provider: str,
853+
user_api_key_dict: UserAPIKeyAuth,
854+
prisma_client: PrismaClient,
855+
is_create_route: bool,
856+
) -> None:
857+
self._provider: Final = provider
858+
self._user_api_key_dict: Final = user_api_key_dict
859+
self._prisma_client: Final = prisma_client
860+
self._is_create_route: Final = is_create_route
861+
self._pending = b""
862+
self._replacement: tuple[bytes, bytes] | None = None
863+
864+
async def feed(self, chunk: bytes) -> bytes:
865+
complete_frames, self._pending = split_complete_sse_frames(self._pending + chunk)
866+
if not complete_frames:
867+
return b""
868+
if self._replacement is None:
869+
self._replacement = await self._mint(complete_frames)
870+
return self._rewrite(complete_frames)
871+
872+
def flush(self) -> bytes:
873+
tail: Final = self._pending
874+
self._pending = b""
875+
return self._rewrite(tail)
876+
877+
async def _mint(self, frames: bytes) -> tuple[bytes, bytes] | None:
878+
first: Final = _first_streamed_response(frames)
879+
if first is None:
880+
return None
881+
raw_id, snapshot = first
882+
managed_id: Final = await _mint_or_reuse_object(
883+
raw_id,
884+
self._provider,
885+
"response",
886+
snapshot,
887+
self._user_api_key_dict,
888+
self._prisma_client,
889+
self._is_create_route,
890+
)
891+
return raw_id.encode(), managed_id.encode()
892+
893+
def _rewrite(self, frames: bytes) -> bytes:
894+
if self._replacement is None:
895+
return frames
896+
raw_id, managed_id = self._replacement
897+
return frames.replace(raw_id, managed_id)
898+
899+
900+
async def rewrite_streamed_response_ids(
901+
stream: AsyncGenerator[bytes, None],
902+
provider: str,
903+
method: str,
904+
route: str,
905+
user_api_key_dict: UserAPIKeyAuth,
906+
prisma_client: PrismaClient,
907+
) -> AsyncGenerator[bytes, None]:
908+
"""
909+
Record ownership of the response object streamed back by a Responses API
910+
passthrough and swap its managed id into every SSE frame, so a streamed
911+
response is owned and resolved exactly like a non-streamed one.
912+
913+
Streams for any other ``(provider, method, route)`` are relayed untouched.
914+
"""
915+
from litellm.proxy.auth.auth_utils import normalize_request_route
916+
917+
canonical: Final = normalize_request_route(_canonical_path(route))
918+
field_specs: Final = BUILTIN_OUTPUT_ID_FIELD_MAP.get((provider, method, canonical), ())
919+
if _STREAMED_RESPONSE_ID_SPEC not in field_specs:
920+
async for chunk in stream:
921+
yield chunk
922+
return
923+
924+
rewriter: Final = _StreamedResponseIdRewriter(
925+
provider=provider,
926+
user_api_key_dict=user_api_key_dict,
927+
prisma_client=prisma_client,
928+
is_create_route="{" not in canonical,
929+
)
930+
async for chunk in stream:
931+
rewritten_frames = await rewriter.feed(chunk)
932+
if rewritten_frames:
933+
yield rewritten_frames
934+
tail: Final = rewriter.flush()
935+
if tail:
936+
yield tail
937+
938+
823939
# ---------------------------------------------------------------------------
824940
# List-route interception — serve listing entirely from DB
825941
# ---------------------------------------------------------------------------

‎litellm/proxy/pass_through_endpoints/pass_through_endpoints.py‎

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,14 +1209,19 @@ async def pass_through_request(
12091209

12101210
return StreamingResponse(
12111211
wrap_passthrough_sse_bytes_with_keepalive_pings(
1212-
stream=PassThroughStreamingHandler.chunk_processor(
1213-
response=response,
1214-
request_body=_parsed_body,
1215-
litellm_logging_obj=logging_obj,
1216-
endpoint_type=endpoint_type,
1217-
start_time=start_time,
1218-
passthrough_success_handler_obj=pass_through_endpoint_logging,
1219-
url_route=str(url),
1212+
stream=_own_streamed_managed_ids(
1213+
stream=PassThroughStreamingHandler.chunk_processor(
1214+
response=response,
1215+
request_body=_parsed_body,
1216+
litellm_logging_obj=logging_obj,
1217+
endpoint_type=endpoint_type,
1218+
start_time=start_time,
1219+
passthrough_success_handler_obj=pass_through_endpoint_logging,
1220+
url_route=str(url),
1221+
),
1222+
managed_id_provider=_managed_id_provider,
1223+
request=request,
1224+
user_api_key_dict=user_api_key_dict,
12201225
),
12211226
ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,
12221227
upstream_headers=response.headers,
@@ -1285,14 +1290,19 @@ async def pass_through_request(
12851290

12861291
return StreamingResponse(
12871292
wrap_passthrough_sse_bytes_with_keepalive_pings(
1288-
stream=PassThroughStreamingHandler.chunk_processor(
1289-
response=response,
1290-
request_body=_parsed_body,
1291-
litellm_logging_obj=logging_obj,
1292-
endpoint_type=endpoint_type,
1293-
start_time=start_time,
1294-
passthrough_success_handler_obj=pass_through_endpoint_logging,
1295-
url_route=str(url),
1293+
stream=_own_streamed_managed_ids(
1294+
stream=PassThroughStreamingHandler.chunk_processor(
1295+
response=response,
1296+
request_body=_parsed_body,
1297+
litellm_logging_obj=logging_obj,
1298+
endpoint_type=endpoint_type,
1299+
start_time=start_time,
1300+
passthrough_success_handler_obj=pass_through_endpoint_logging,
1301+
url_route=str(url),
1302+
),
1303+
managed_id_provider=_managed_id_provider,
1304+
request=request,
1305+
user_api_key_dict=user_api_key_dict,
12961306
),
12971307
ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,
12981308
upstream_headers=response.headers,
@@ -2441,6 +2451,36 @@ def _is_streaming_response(response: httpx.Response) -> bool:
24412451
return False
24422452

24432453

2454+
def _own_streamed_managed_ids(
2455+
stream: AsyncGenerator[bytes, None],
2456+
managed_id_provider: str | None,
2457+
request: Request,
2458+
user_api_key_dict: UserAPIKeyAuth,
2459+
) -> AsyncGenerator[bytes, None]:
2460+
from litellm.proxy.proxy_server import general_settings, prisma_client, proxy_logging_obj
2461+
2462+
if (
2463+
managed_id_provider is None
2464+
or not general_settings.get("passthrough_managed_object_ids", False)
2465+
or prisma_client is None
2466+
or proxy_logging_obj.get_proxy_hook("managed_files") is None
2467+
):
2468+
return stream
2469+
from litellm.proxy.auth.auth_utils import get_request_route
2470+
from litellm.proxy.pass_through_endpoints.managed_id_rewriter import (
2471+
rewrite_streamed_response_ids,
2472+
)
2473+
2474+
return rewrite_streamed_response_ids(
2475+
stream=stream,
2476+
provider=managed_id_provider,
2477+
method=request.method,
2478+
route=get_request_route(request),
2479+
user_api_key_dict=user_api_key_dict,
2480+
prisma_client=prisma_client,
2481+
)
2482+
2483+
24442484
def _should_buffer_passthrough_response(response: httpx.Response) -> bool:
24452485
"""
24462486
Decide from the response headers whether the body must be read into memory.

‎litellm/proxy/pass_through_endpoints/streaming_handler.py‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
1111
from litellm.proxy._types import PassThroughEndpointLoggingResultValues
1212
from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing
13+
from litellm.proxy.common_utils.sse_keepalive import split_complete_sse_frames
1314
from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType
1415
from litellm.types.utils import StandardPassThroughResponseObject
1516

@@ -101,7 +102,7 @@ async def chunk_processor(
101102
async for chunk in response.aiter_bytes():
102103
raw_bytes.append(chunk)
103104
PassThroughStreamingHandler._stamp_first_chunk_if_needed(litellm_logging_obj)
104-
complete_frames, pending = PassThroughStreamingHandler._split_complete_sse_frames(
105+
complete_frames, pending = split_complete_sse_frames(
105106
pending + chunk
106107
) # rebind-ok: SSE frame reassembly buffer across transport chunks
107108
if complete_frames:
@@ -139,17 +140,6 @@ async def chunk_processor(
139140
except Exception as e:
140141
verbose_proxy_logger.error("Error scheduling chunk_processor logging: %s", e)
141142

142-
@staticmethod
143-
def _split_complete_sse_frames(pending: bytes) -> tuple[bytes, bytes]:
144-
lf_boundary_end: Final = pending.rfind(b"\n\n") + 2
145-
crlf_boundary_end: Final = pending.rfind(b"\r\n\r\n") + 4
146-
boundary_end: Final = max(
147-
lf_boundary_end if lf_boundary_end >= 2 else 0, crlf_boundary_end if crlf_boundary_end >= 4 else 0
148-
)
149-
if boundary_end == 0:
150-
return b"", pending
151-
return pending[:boundary_end], pending[boundary_end:]
152-
153143
@staticmethod
154144
async def _route_streaming_logging_to_handler(
155145
litellm_logging_obj: LiteLLMLoggingObj,

‎tests/test_litellm/proxy/common_utils/test_sse_keepalive.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
ANTHROPIC_PING_SSE_CHUNK,
1111
SSE_COMMENT_PING_BYTES,
1212
resolve_ttft_keepalive_interval,
13+
split_complete_sse_frames,
1314
wrap_passthrough_sse_bytes_with_keepalive_pings,
1415
wrap_sse_stream_with_keepalive_pings,
1516
)
@@ -18,6 +19,19 @@
1819
TEXT_DELTA_CHUNK: Final = 'data: {"type": "content_block_delta"}\n\n'
1920

2021

22+
@pytest.mark.parametrize("delimiter", [b"\n\n", b"\r\n\r\n", b"\r\r"])
23+
def test_split_complete_sse_frames_recognizes_every_sse_frame_delimiter(delimiter: bytes):
24+
newline: Final = delimiter[: len(delimiter) // 2]
25+
frame: Final = b"event: response.created" + newline + b"data: {}" + delimiter
26+
tail: Final = b"data: partial"
27+
28+
assert split_complete_sse_frames(frame + tail) == (frame, tail)
29+
30+
31+
def test_split_complete_sse_frames_holds_bytes_with_no_complete_frame():
32+
assert split_complete_sse_frames(b"data: unterminated") == (b"", b"data: unterminated")
33+
34+
2135
@pytest.mark.asyncio
2236
async def test_pings_fill_mid_stream_silence_and_preserve_chunk_order():
2337
async def gappy_stream() -> AsyncGenerator[str, None]:

0 commit comments

Comments
 (0)