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(caching): tolerate SSE chunk splits in anthropic stream cache writer
mateo-berri9a1e63c9f0b6
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/response_cache.py b/litellm/llms/anthropic/experimental_pass_through/messages/response_cache.pyindex 1bbb1317fd9..9ac5187681b 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/response_cache.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/response_cache.py@@ -1,3 +1,4 @@+import refrom collections.abc import AsyncIterator, Mapping, Sequencefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Final@@ -20,11 +21,17 @@ CACHED_STREAM_EVENTS_KEY: Final = "litellm_cached_anthropic_sse_events"_EMPTY_MAPPING: Final[Mapping[str, object]] = MappingProxyType({})+_SSE_EVENT_BOUNDARY: Final = re.compile(r"(?<=\n\n)")+def _decode(chunk: bytes | str) -> str:return chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk+def _split_sse_events(stream_text: str) -> tuple[str, ...]:+ return tuple(event for event in _SSE_EVENT_BOUNDARY.split(stream_text) if event)++class AnthropicMessagesStreamCacheWriter:def __init__(self,@@ -33,9 +40,7 @@ class AnthropicMessagesStreamCacheWriter:) -> None:self.stream = streamself.caching_handler = caching_handler- self.collected_events: list[str] = [] # mutable-ok: rebuilding a tuple per SSE chunk is quadratic- self.saw_message_stop = False- self.saw_provider_error = False+ self.collected_chunks: list[bytes] = [] # mutable-ok: rebuilding a tuple per SSE chunk is quadraticself.persisted = Falseself._hidden_params: dict[str, object] = dict( # mutable-ok: callers stamp cache_key in herestream._hidden_params if isinstance(stream, AnthropicMessagesStreamingResponse) else _EMPTY_MAPPING@@ -50,10 +55,7 @@ class AnthropicMessagesStreamCacheWriter:except StopAsyncIteration:await self._persist()raise- chunk_bytes: Final = chunk.encode("utf-8") if isinstance(chunk, str) else chunk- self.saw_message_stop = self.saw_message_stop or _is_message_stop_chunk(chunk_bytes)- self.saw_provider_error = self.saw_provider_error or _is_provider_error_chunk(chunk_bytes)- self.collected_events.append(_decode(chunk))+ self.collected_chunks.append(chunk.encode("utf-8") if isinstance(chunk, str) else chunk)return chunkasync def aclose(self) -> None:@@ -62,7 +64,8 @@ class AnthropicMessagesStreamCacheWriter:async def _persist(self) -> None:if self.persisted or litellm.cache is None:return- if not self.saw_message_stop or self.saw_provider_error:+ collected_stream: Final = b"".join(self.collected_chunks)+ if not _is_message_stop_chunk(collected_stream) or _is_provider_error_chunk(collected_stream):returnself.persisted = True@@ -78,10 +81,12 @@ class AnthropicMessagesStreamCacheWriter:request_kwargs: Final[Mapping[str, object]] = MappingProxyType({**self.caching_handler.request_kwargs, **cache_key_override})- events: Final = tuple(self.collected_events)- cached_payload: Final = {CACHED_STREAM_EVENTS_KEY: events} # mutable-ok: cache backends serialize plain dictstry:+ events: Final = _split_sse_events(collected_stream.decode("utf-8"))+ cached_payload: Final = {+ CACHED_STREAM_EVENTS_KEY: events+ } # mutable-ok: cache backends serialize plain dictsawait litellm.cache.async_add_cache(cached_payload,dynamic_cache_object=self.caching_handler.dual_cache,diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_response_cache.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_response_cache.pyindex 071580347a6..3fe1b6b0e38 100644--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_response_cache.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_response_cache.py@@ -164,6 +164,61 @@ async def test_failed_stream_is_not_cached(local_cache, request_kwargs, monkeypaassert replayed == STREAM_EVENTS+async def test_multibyte_utf8_split_across_chunks_streams_and_caches(local_cache, request_kwargs, monkeypatch):+ """aiter_bytes() can split a multi-byte character across chunks; per-chunk+ strict decoding raised UnicodeDecodeError mid-stream and broke the client."""+ multibyte_delta = (+ 'event: content_block_delta\ndata: {"type": "content_block_delta", "index": 0, '+ '"delta": {"type": "text_delta", "text": "ALPHA €"}}\n\n'+ ).encode("utf-8")+ split_at = multibyte_delta.index("€".encode("utf-8")) + 1+ chunks = STREAM_EVENTS[:2] + [multibyte_delta[:split_at], multibyte_delta[split_at:]] + STREAM_EVENTS[3:]+ fake_handler = _CountingHandler([_byte_stream(chunks), _byte_stream([b"event: never_used\n\n"])])+ monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)++ first = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))+ second = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))++ assert len(fake_handler.calls) == 1+ assert first == chunks+ assert b"".join(second) == b"".join(chunks)+++async def test_message_stop_split_across_chunks_still_caches(local_cache, request_kwargs, monkeypatch):+ """The terminal `event: message_stop` line can arrive split across two+ chunks; per-chunk line matching missed it, so the stream was never stored."""+ stop_event = STREAM_EVENTS[-1]+ chunks = STREAM_EVENTS[:-1] + [stop_event[:10], stop_event[10:]]+ fake_handler = _CountingHandler([_byte_stream(chunks), _byte_stream([b"event: never_used\n\n"])])+ monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)++ first = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))+ second = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))++ assert len(fake_handler.calls) == 1+ assert first == chunks+ assert b"".join(second) == b"".join(chunks)+++async def test_error_event_split_across_chunks_is_not_cached(local_cache, request_kwargs, monkeypatch):+ error_event = (+ b'event: error\ndata: {"type": "error", "error": {"type": "overloaded_error", "message": "overloaded"}}\n\n'+ )+ chunks = STREAM_EVENTS[:4] + [error_event[:8], error_event[8:]] + STREAM_EVENTS[4:]+ fake_handler = _CountingHandler([_byte_stream(chunks), _byte_stream(STREAM_EVENTS)])+ monkeypatch.setattr(handler, "anthropic_messages_handler", fake_handler)++ failed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))+ replayed = await _collect(await litellm.anthropic_messages(**request_kwargs, stream=True))++ assert failed == chunks+ assert len(fake_handler.calls) == 2+ assert replayed == STREAM_EVENTS++@pytest.mark.asyncioasync def test_abandoned_stream_is_not_cached(local_cache, request_kwargs, monkeypatch):fake_handler = _CountingHandler([_byte_stream(STREAM_EVENTS), _byte_stream(STREAM_EVENTS)])@@ -178,6 +233,7 @@ async def test_abandoned_stream_is_not_cached(local_cache, request_kwargs, monkeassert len(fake_handler.calls) == 2assert replayed == STREAM_EVENTS+@pytest.mark.asyncioasync def test_cached_stream_replay_logs_once_when_polled_after_exhaustion():from unittest.mock import AsyncMock, MagicMock, patch