Skip to content

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]

refactor(anthropic): move raw SSE stream assembly helpers out of proxy guardrails (#45749)

nate-berri3981228d7038
diff --git a/litellm/integrations/otel/model/request_io.py b/litellm/integrations/otel/model/request_io.py
index 4131f3de6da..287d28a0d17 100644
--- a/litellm/integrations/otel/model/request_io.py
+++ b/litellm/integrations/otel/model/request_io.py
@@ -6,7 +6,7 @@ from typing_extensions import ReadOnly, TypedDict
import litellm
from litellm.integrations.otel.mappers.utils import json_or_none
-from litellm.proxy.guardrails.anthropic_sse import assemble_anthropic_sse_stream, is_raw_sse_stream
+from litellm.llms.anthropic.pass_through.stream_assembly import assemble_anthropic_sse_stream, is_raw_sse_stream
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.llms.openai import ResponseCompletedEvent, ResponsesAPIResponse
from litellm.types.utils import ModelResponse, ModelResponseStream
diff --git a/litellm/litellm_core_utils/served_output_texts.py b/litellm/litellm_core_utils/served_output_texts.py
index 2788720448b..ce9a568ea72 100644
--- a/litellm/litellm_core_utils/served_output_texts.py
+++ b/litellm/litellm_core_utils/served_output_texts.py
@@ -110,7 +110,10 @@ def served_output_texts(response: object) -> ServedTexts | None:
def served_stream_output_texts(chunks: Sequence[object]) -> ServedTexts | None:
if chunks and all(isinstance(chunk, ModelResponseStream) for chunk in chunks):
return _chat_stream_texts(tuple(chunk for chunk in chunks if isinstance(chunk, ModelResponseStream)))
- from litellm.proxy.guardrails.anthropic_sse import assemble_anthropic_sse_stream, is_anthropic_sse_stream
+ from litellm.llms.anthropic.pass_through.stream_assembly import (
+ assemble_anthropic_sse_stream,
+ is_anthropic_sse_stream,
+ )
if not is_anthropic_sse_stream(chunks):
return None
diff --git a/litellm/llms/anthropic/pass_through/stream_assembly.py b/litellm/llms/anthropic/pass_through/stream_assembly.py
index 76d1896ac32..89961bbe255 100644
--- a/litellm/llms/anthropic/pass_through/stream_assembly.py
+++ b/litellm/llms/anthropic/pass_through/stream_assembly.py
@@ -1,5 +1,6 @@
+import codecs
import json
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from typing import Final
import litellm
@@ -395,3 +396,124 @@ def build_usage_only_response_from_chunks(
],
usage=usage_obj,
)
+
+
+_ANTHROPIC_EVENT_TYPES: Final = frozenset(
+ {
+ "message_start",
+ "message_delta",
+ "message_stop",
+ "content_block_start",
+ "content_block_delta",
+ "content_block_stop",
+ "ping",
+ "error",
+ }
+)
+
+
+def is_raw_sse_stream(all_chunks: Sequence[object]) -> bool:
+ return any(isinstance(chunk, (str, bytes)) for chunk in all_chunks)
+
+
+def _joined_sse_stream(all_chunks: Sequence[object]) -> str | None:
+ raw: Final = b"".join(
+ chunk if isinstance(chunk, bytes) else chunk.encode("utf-8")
+ for chunk in all_chunks
+ if isinstance(chunk, (str, bytes))
+ )
+ try:
+ return codecs.getincrementaldecoder("utf-8")().decode(raw, final=False)
+ except UnicodeDecodeError:
+ return None
+
+
+def _parsed_sse_events(sse_stream: str) -> tuple[Mapping[str, object], ...]:
+ return tuple(
+ event_data
+ for event in split_sse_chunk_into_events(sse_stream)
+ if (event_data := extract_sse_data(event)) is not None
+ )
+
+
+def _anthropic_message_start(sse_stream: str) -> Mapping[str, object] | None:
+ return next(
+ (
+ message
+ for event_data in _parsed_sse_events(sse_stream)
+ if event_data.get("type") == "message_start" and isinstance(message := event_data.get("message"), dict)
+ ),
+ None,
+ )
+
+
+def is_anthropic_sse_stream(all_chunks: Sequence[object]) -> bool:
+ """Whether raw SSE frames are Anthropic Messages events.
+
+ ``is_raw_sse_stream`` only says the chunks are unparsed bytes, and ``/v1/messages`` is not the
+ only endpoint that streams those: the Google ``:streamGenerateContent`` route marks its own
+ stream raw too. Reading its frames as Anthropic ones would refuse the response in a wire format
+ its client cannot parse, so the surface is decided on the event types actually present.
+ """
+ sse_stream: Final = _joined_sse_stream(all_chunks)
+ if sse_stream is None:
+ return False
+ return any(event.get("type") in _ANTHROPIC_EVENT_TYPES for event in _parsed_sse_events(sse_stream))
+
+
+def assemble_anthropic_sse_stream(
+ all_chunks: Sequence[object], *, restore_identity: bool = False
+) -> ModelResponse | None:
+ """Assemble raw Anthropic SSE frames into a ModelResponse.
+
+ ``restore_identity`` stamps the upstream message id and model onto the result, which the
+ assembler does not carry through. It is off by default so callers that re-emit the assembled
+ response keep the wire shape they had before this helper was shared. The writes land on a
+ freshly built object that is unreachable from caller state until returned.
+ """
+ sse_stream: Final = _joined_sse_stream(all_chunks)
+ if sse_stream is None:
+ return None
+ message_start: Final = _anthropic_message_start(sse_stream)
+ if message_start is None:
+ return None
+ model: Final = message_start.get("model") if restore_identity else None
+ try:
+ assembled: Final = build_complete_streaming_response(
+ all_chunks=(sse_stream,),
+ litellm_logging_obj=None, # pyright: ignore[reportArgumentType] # only forwarded to stream_chunk_builder, which accepts None
+ model=model if isinstance(model, str) else "",
+ )
+ except Exception: # noqa: BLE001 # stream_chunk_builder re-raises every assembly failure as litellm.APIError
+ return None
+ if not isinstance(assembled, ModelResponse):
+ return None
+ if not restore_identity:
+ return assembled
+ message_id: Final = message_start.get("id")
+ if isinstance(message_id, str):
+ assembled.id = message_id
+ if isinstance(model, str) and model:
+ assembled.model = model
+ return assembled
+
+
+def is_sse_error_stream(all_chunks: Sequence[object]) -> bool:
+ """Whether the buffered stream carries nothing but error frames.
+
+ post_call guardrails run in a chain, so a hook can be handed the terminal error frames an
+ earlier guardrail emitted when it blocked. Those carry no message to assemble, and replacing
+ them would hide the refusal the client is owed. Covers both wire forms a guardrail emits: the
+ Anthropic ``error`` event and the chat-completions ``{"error": ...}`` payload.
+ """
+ if not all(isinstance(chunk, (str, bytes)) for chunk in all_chunks):
+ # A stream mixing typed chunks with an error frame still carries content to scan, and the
+ # frames-only join below would drop exactly the part that has to be scanned
+ return False
+ sse_stream: Final = _joined_sse_stream(all_chunks)
+ if sse_stream is None:
+ return False
+ events: Final = _parsed_sse_events(sse_stream)
+ return len(events) > 0 and all(
+ event.get("type") == "error" or isinstance(event.get("error"), Mapping) for event in events
+ )
diff --git a/litellm/proxy/guardrails/anthropic_sse.py b/litellm/proxy/guardrails/anthropic_sse.py
index 07a5d511117..c3a6f259f95 100644
--- a/litellm/proxy/guardrails/anthropic_sse.py
+++ b/litellm/proxy/guardrails/anthropic_sse.py
@@ -7,115 +7,19 @@ hook scan such a stream, and re-emit it when the guardrail rewrote the response.
from __future__ import annotations
-import codecs
import json
-from collections.abc import Mapping, Sequence
from typing import Final
-from litellm.types.utils import Choices, ModelResponse
-
-_ANTHROPIC_EVENT_TYPES: Final = frozenset(
- {
- "message_start",
- "message_delta",
- "message_stop",
- "content_block_start",
- "content_block_delta",
- "content_block_stop",
- "ping",
- "error",
- }
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ assemble_anthropic_sse_stream as assemble_anthropic_sse_stream, # noqa: PLC0414 # public re-export
)
-
-
-def is_raw_sse_stream(all_chunks: Sequence[object]) -> bool:
- return any(isinstance(chunk, (str, bytes)) for chunk in all_chunks)
-
-
-def _joined_sse_stream(all_chunks: Sequence[object]) -> str | None:
- raw: Final = b"".join(
- chunk if isinstance(chunk, bytes) else chunk.encode("utf-8")
- for chunk in all_chunks
- if isinstance(chunk, (str, bytes))
- )
- try:
- return codecs.getincrementaldecoder("utf-8")().decode(raw, final=False)
- except UnicodeDecodeError:
- return None
-
-
-def _parsed_sse_events(sse_stream: str) -> tuple[Mapping[str, object], ...]:
- from litellm.llms.anthropic.pass_through.stream_assembly import extract_sse_data, split_sse_chunk_into_events
-
- return tuple(
- event_data
- for event in split_sse_chunk_into_events(sse_stream)
- if (event_data := extract_sse_data(event)) is not None
- )
-
-
-def _anthropic_message_start(sse_stream: str) -> Mapping[str, object] | None:
- return next(
- (
- message
- for event_data in _parsed_sse_events(sse_stream)
- if event_data.get("type") == "message_start" and isinstance(message := event_data.get("message"), dict)
- ),
- None,
- )
-
-
-def is_anthropic_sse_stream(all_chunks: Sequence[object]) -> bool:
- """Whether raw SSE frames are Anthropic Messages events.
-
- ``is_raw_sse_stream`` only says the chunks are unparsed bytes, and ``/v1/messages`` is not the
- only endpoint that streams those: the Google ``:streamGenerateContent`` route marks its own
- stream raw too. Reading its frames as Anthropic ones would refuse the response in a wire format
- its client cannot parse, so the surface is decided on the event types actually present.
- """
- sse_stream: Final = _joined_sse_stream(all_chunks)
- if sse_stream is None:
- return False
- return any(event.get("type") in _ANTHROPIC_EVENT_TYPES for event in _parsed_sse_events(sse_stream))
-
-
-def assemble_anthropic_sse_stream(
- all_chunks: Sequence[object], *, restore_identity: bool = False
-) -> ModelResponse | None:
- """Assemble raw Anthropic SSE frames into a ModelResponse.
-
- ``restore_identity`` stamps the upstream message id and model onto the result, which the
- assembler does not carry through. It is off by default so callers that re-emit the assembled
- response keep the wire shape they had before this helper was shared. The writes land on a
- freshly built object that is unreachable from caller state until returned.
- """
- from litellm.llms.anthropic.pass_through.stream_assembly import build_complete_streaming_response
-
- sse_stream: Final = _joined_sse_stream(all_chunks)
- if sse_stream is None:
- return None
- message_start: Final = _anthropic_message_start(sse_stream)
- if message_start is None:
- return None
- model: Final = message_start.get("model") if restore_identity else None
- try:
- assembled: Final = build_complete_streaming_response(
- all_chunks=(sse_stream,),
- litellm_logging_obj=None, # pyright: ignore[reportArgumentType] # only forwarded to stream_chunk_builder, which accepts None
- model=model if isinstance(model, str) else "",
- )
- except Exception: # noqa: BLE001 # stream_chunk_builder re-raises every assembly failure as litellm.APIError
- return None
- if not isinstance(assembled, ModelResponse):
- return None
- if not restore_identity:
- return assembled
- message_id: Final = message_start.get("id")
- if isinstance(message_id, str):
- assembled.id = message_id
- if isinstance(model, str) and model:
- assembled.model = model
- return assembled
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ is_anthropic_sse_stream as is_anthropic_sse_stream, # noqa: PLC0414 # public re-export
+)
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ is_raw_sse_stream as is_raw_sse_stream, # noqa: PLC0414 # public re-export
+)
+from litellm.types.utils import Choices, ModelResponse
def model_response_text(response: ModelResponse) -> str:
@@ -141,25 +45,9 @@ def anthropic_sse_error_frames(message: str) -> tuple[bytes, ...]:
)
-def is_sse_error_stream(all_chunks: Sequence[object]) -> bool:
- """Whether the buffered stream carries nothing but error frames.
-
- post_call guardrails run in a chain, so a hook can be handed the terminal error frames an
- earlier guardrail emitted when it blocked. Those carry no message to assemble, and replacing
- them would hide the refusal the client is owed. Covers both wire forms a guardrail emits: the
- Anthropic ``error`` event and the chat-completions ``{"error": ...}`` payload.
- """
- if not all(isinstance(chunk, (str, bytes)) for chunk in all_chunks):
- # A stream mixing typed chunks with an error frame still carries content to scan, and the
- # frames-only join below would drop exactly the part that has to be scanned
- return False
- sse_stream: Final = _joined_sse_stream(all_chunks)
- if sse_stream is None:
- return False
- events: Final = _parsed_sse_events(sse_stream)
- return len(events) > 0 and all(
- event.get("type") == "error" or isinstance(event.get("error"), Mapping) for event in events
- )
+from litellm.llms.anthropic.pass_through.stream_assembly import ( # noqa: E402 # re-export after the definitions above
+ is_sse_error_stream as is_sse_error_stream, # noqa: PLC0414 # public re-export
+)
def anthropic_sse_chunks_from_response(assembled: ModelResponse) -> tuple[bytes, ...]:
diff --git a/tests/unit/llms/anthropic/pass_through/test_stream_assembly.py b/tests/unit/llms/anthropic/pass_through/test_stream_assembly.py
new file mode 100644
index 00000000000..33f95ccc9ff
--- /dev/null
+++ b/tests/unit/llms/anthropic/pass_through/test_stream_assembly.py
@@ -0,0 +1,144 @@
+import json
+from typing import Final
+
+import pytest
+
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ assemble_anthropic_sse_stream,
+ is_anthropic_sse_stream,
+ is_raw_sse_stream,
+ is_sse_error_stream,
+)
+from litellm.types.utils import Choices
+
+
+def _frame(event: str, data: dict[str, object]) -> bytes:
+ return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()
+
+
+MESSAGE_ID: Final = "msg_upstream_1"
+MODEL: Final = "claude-upstream"
+
+ANTHROPIC_STREAM: Final = (
+ _frame(
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "id": MESSAGE_ID,
+ "type": "message",
+ "role": "assistant",
+ "model": MODEL,
+ "content": [],
+ "stop_reason": None,
+ "usage": {"input_tokens": 3, "output_tokens": 1},
+ },
+ },
+ ),
+ _frame(
+ "content_block_start",
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ ),
+ _frame(
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}},
+ ),
+ _frame(
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": " there"}},
+ ),
+ _frame("content_block_stop", {"type": "content_block_stop", "index": 0}),
+ _frame(
+ "message_delta",
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 2}},
+ ),
+ _frame("message_stop", {"type": "message_stop"}),
+)
+
+GOOGLE_STREAM: Final = (b'data: {"candidates": [{"content": {"parts": [{"text": "Hello"}]}}]}\n\n',)
+ANTHROPIC_ERROR: Final = _frame("error", {"type": "error", "error": {"type": "overloaded_error", "message": "busy"}})
+CHAT_ERROR: Final = b'data: {"error": {"message": "blocked by guardrail"}}\n\n'
+INVALID_UTF8: Final = (b"\xff\xfe data",)
+
+
+ ("chunks", "expected"),
+ [
+ ((b"data: {}\n\n",), True),
+ (("data: {}\n\n",), True),
+ ((object(), b"data: {}\n\n"), True),
+ ((object(),), False),
+ ((), False),
+ ],
+)
+def test_is_raw_sse_stream_is_true_only_when_a_chunk_is_str_or_bytes(chunks: tuple[object, ...], expected: bool):
+ assert is_raw_sse_stream(chunks) is expected
+
+
+ ("chunks", "expected"),
+ [
+ (ANTHROPIC_STREAM, True),
+ ((ANTHROPIC_ERROR,), True),
+ (tuple(chunk.decode() for chunk in ANTHROPIC_STREAM), True),
+ (GOOGLE_STREAM, False),
+ (INVALID_UTF8, False),
+ ((), False),
+ ],
+)
+def test_is_anthropic_sse_stream_decides_on_the_event_types_present(chunks: tuple[object, ...], expected: bool):
+ assert is_anthropic_sse_stream(chunks) is expected
+
+
+def test_assemble_anthropic_sse_stream_joins_the_text_deltas():
+ assembled = assemble_anthropic_sse_stream(ANTHROPIC_STREAM)
+
+ assert assembled is not None
+ choice = assembled.choices[0]
+ assert isinstance(choice, Choices)
+ assert choice.message.content == "Hello there"
+
+
+def test_assemble_anthropic_sse_stream_restores_upstream_identity_only_when_asked():
+ plain = assemble_anthropic_sse_stream(ANTHROPIC_STREAM)
+ restored = assemble_anthropic_sse_stream(ANTHROPIC_STREAM, restore_identity=True)
+
+ assert plain is not None and restored is not None
+ assert plain.id != MESSAGE_ID
+ assert (restored.id, restored.model) == (MESSAGE_ID, MODEL)
+
+
+ "chunks",
+ [GOOGLE_STREAM, INVALID_UTF8, (ANTHROPIC_ERROR,), ()],
+ ids=["no-message-start", "undecodable", "error-only", "empty"],
+)
+def test_assemble_anthropic_sse_stream_returns_none_without_a_message_to_build(chunks: tuple[object, ...]):
+ assert assemble_anthropic_sse_stream(chunks) is None
+
+
+ ("chunks", "expected"),
+ [
+ ((ANTHROPIC_ERROR,), True),
+ ((CHAT_ERROR,), True),
+ ((ANTHROPIC_ERROR, CHAT_ERROR), True),
+ ((ANTHROPIC_ERROR, ANTHROPIC_STREAM[0]), False),
+ ((object(), ANTHROPIC_ERROR), False),
+ (ANTHROPIC_STREAM, False),
+ (INVALID_UTF8, False),
+ ((b"\n\n",), False),
+ ],
+ ids=[
+ "anthropic-error",
+ "chat-error",
+ "both-error-forms",
+ "error-then-message",
+ "typed-chunk-mixed-in",
+ "normal-stream",
+ "undecodable",
+ "no-events",
+ ],
+)
+def test_is_sse_error_stream_is_true_only_for_frames_that_are_all_errors(chunks: tuple[object, ...], expected: bool):
+ assert is_sse_error_stream(chunks) is expected