|
32 | 32 |
|
33 | 33 | import json |
34 | 34 | import re |
35 | | -from collections.abc import Callable, Mapping, Sequence |
| 35 | +from collections.abc import AsyncGenerator, Callable, Mapping, Sequence |
36 | 36 | from typing import ( |
37 | 37 | TYPE_CHECKING, |
38 | 38 | Final, |
|
43 | 43 | from urllib.parse import quote, unquote |
44 | 44 |
|
45 | 45 | from fastapi import HTTPException |
46 | | -from pydantic import JsonValue |
| 46 | +from pydantic import JsonValue, TypeAdapter, ValidationError |
47 | 47 |
|
48 | 48 | from litellm._logging import verbose_proxy_logger |
49 | 49 | from litellm.llms.base_llm.managed_resources.isolation import ( |
|
52 | 52 | ) |
53 | 53 | from litellm.proxy._types import UserAPIKeyAuth |
54 | 54 | 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 |
55 | 56 | from litellm.repositories.table_repositories import ( |
56 | 57 | ManagedFileRepository, |
57 | 58 | ManagedObjectRepository, |
@@ -820,6 +821,121 @@ def _record(field_name: str, raw_value: str, managed_id: str) -> None: |
820 | 821 | return mutated if changed else body |
821 | 822 |
|
822 | 823 |
|
| 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 | + |
823 | 939 | # --------------------------------------------------------------------------- |
824 | 940 | # List-route interception — serve listing entirely from DB |
825 | 941 | # --------------------------------------------------------------------------- |
|
0 commit comments