Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llm-gateway): prevent invalid anthropic streams (#72287)

Alessandro Pogliaghi85d0d52fc901
diff --git a/services/llm-gateway/pyproject.toml b/services/llm-gateway/pyproject.toml
index ac2740444611..01bea7a4f7a9 100644
--- a/services/llm-gateway/pyproject.toml
+++ b/services/llm-gateway/pyproject.toml
@@ -15,7 +15,7 @@ dependencies = [
"pydantic-settings>=2.1.0",
"asyncpg>=0.30.0",
"redis==5.3.1",
- "litellm==1.84.0",
+ "litellm==1.92.0",
"orjson>=3.10.0",
"prometheus-client>=0.21.0",
"prometheus-fastapi-instrumentator>=7.0.0",
diff --git a/services/llm-gateway/src/llm_gateway/anthropic_stream.py b/services/llm-gateway/src/llm_gateway/anthropic_stream.py
new file mode 100644
index 000000000000..cb6a2ccd7312
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/anthropic_stream.py
@@ -0,0 +1,150 @@
+from __future__ import annotations
+
+import codecs
+import json
+import re
+from collections.abc import AsyncIterator
+from typing import Any
+
+from llm_gateway.metrics.prometheus import ANTHROPIC_BRIDGE_INVALID_STREAM
+
+_DELTA_BLOCK_TYPES = {
+ "compaction_delta": "compaction",
+ "input_json_delta": "tool_use",
+ "signature_delta": "thinking",
+ "text_delta": "text",
+ "thinking_delta": "thinking",
+}
+_SSE_FRAME_SEPARATOR = re.compile(r"\r?\n\r?\n")
+
+
+class _SSEPayloadDecoder:
+ def __init__(self) -> None:
+ self._decoder = codecs.getincrementaldecoder("utf-8")()
+ self._buffer = ""
+
+ def feed(self, chunk: bytes) -> list[dict[str, Any]]:
+ try:
+ self._buffer += self._decoder.decode(chunk)
+ except UnicodeDecodeError:
+ self._decoder.reset()
+ self._buffer = ""
+ return []
+
+ frames: list[str] = []
+ while match := _SSE_FRAME_SEPARATOR.search(self._buffer):
+ frames.append(self._buffer[: match.start()])
+ self._buffer = self._buffer[match.end() :]
+ return self._parse_frames(frames)
+
+ def finish(self) -> list[dict[str, Any]]:
+ try:
+ self._buffer += self._decoder.decode(b"", final=True)
+ except UnicodeDecodeError:
+ self._buffer = ""
+ return []
+
+ final_frame = self._buffer
+ self._buffer = ""
+ return self._parse_frames([final_frame]) if final_frame.strip() else []
+
+ @staticmethod
+ def _parse_frames(frames: list[str]) -> list[dict[str, Any]]:
+ payloads: list[dict[str, Any]] = []
+ for frame in frames:
+ data_lines = []
+ for line in frame.splitlines():
+ if not line.startswith("data:"):
+ continue
+ data = line.removeprefix("data:")
+ data_lines.append(data.removeprefix(" "))
+ if not data_lines:
+ continue
+ try:
+ payload = json.loads("\n".join(data_lines))
+ except json.JSONDecodeError:
+ continue
+ if isinstance(payload, dict):
+ payloads.append(payload)
+ return payloads
+
+
+async def observe_anthropic_stream(stream: AsyncIterator[Any], backend: str) -> AsyncIterator[Any]:
+ active_blocks: dict[int, str] = {}
+ recorded_violations: set[tuple[int, str]] = set()
+ sse_decoder = _SSEPayloadDecoder()
+
+ async for chunk in stream:
+ for payload in _payloads_from_chunk(chunk, sse_decoder):
+ _observe_payload(payload, backend, active_blocks, recorded_violations)
+ yield chunk
+
+ for payload in sse_decoder.finish():
+ _observe_payload(payload, backend, active_blocks, recorded_violations)
+ for index in active_blocks:
+ _record_violation(backend, index, "unclosed_block", recorded_violations)
+
+
+def _payloads_from_chunk(chunk: Any, sse_decoder: _SSEPayloadDecoder) -> list[dict[str, Any]]:
+ if isinstance(chunk, dict):
+ return [chunk]
+ if hasattr(chunk, "model_dump"):
+ payload = chunk.model_dump()
+ return [payload] if isinstance(payload, dict) else []
+ if isinstance(chunk, bytes):
+ return sse_decoder.feed(chunk)
+ return []
+
+
+def _observe_payload(
+ payload: dict[str, Any],
+ backend: str,
+ active_blocks: dict[int, str],
+ recorded_violations: set[tuple[int, str]],
+) -> None:
+ event_type = payload.get("type")
+ index = payload.get("index")
+ if not isinstance(index, int):
+ return
+
+ if event_type == "content_block_start":
+ if index in active_blocks:
+ _record_violation(backend, index, "duplicate_start", recorded_violations)
+ return
+ content_block = payload.get("content_block")
+ block_type = content_block.get("type") if isinstance(content_block, dict) else None
+ if isinstance(block_type, str):
+ active_blocks[index] = block_type
+ return
+
+ if event_type == "content_block_stop":
+ if active_blocks.pop(index, None) is None:
+ _record_violation(backend, index, "stop_without_start", recorded_violations)
+ return
+
+ if event_type != "content_block_delta":
+ return
+
+ block_type = active_blocks.get(index)
+ if block_type is None:
+ _record_violation(backend, index, "delta_without_start", recorded_violations)
+ return
+
+ delta = payload.get("delta")
+ delta_type = delta.get("type") if isinstance(delta, dict) else None
+ expected_block_type = _DELTA_BLOCK_TYPES.get(delta_type) if isinstance(delta_type, str) else None
+ if expected_block_type is not None and block_type != expected_block_type:
+ _record_violation(backend, index, "delta_type_mismatch", recorded_violations)
+
+
+def _record_violation(
+ backend: str,
+ index: int,
+ violation: str,
+ recorded_violations: set[tuple[int, str]],
+) -> None:
+ violation_key = (index, violation)
+ if violation_key in recorded_violations:
+ return
+ recorded_violations.add(violation_key)
+ ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend=backend, violation=violation).inc()
diff --git a/services/llm-gateway/src/llm_gateway/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.py
index ba1e4e78e303..993462073751 100644
--- a/services/llm-gateway/src/llm_gateway/cloudflare.py
+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from collections.abc import Awaitable, Callable
+from collections.abc import AsyncIterator, Awaitable, Callable
from typing import Any
import litellm
@@ -11,6 +11,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (
LiteLLMMessagesToCompletionTransformationHandler,
)
+from llm_gateway.anthropic_stream import observe_anthropic_stream
from llm_gateway.config import Settings
from llm_gateway.rate_limiting.cost_refresh import COST_ALIASES
@@ -96,7 +97,10 @@ def make_cloudflare_anthropic_call(api_base: str, api_key: str) -> Callable[...,
async def llm_call(**kwargs: Any) -> Any:
_inject_cloudflare_params(kwargs, api_base, api_key)
- return await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)
+ response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)
+ if isinstance(response, AsyncIterator):
+ return observe_anthropic_stream(response, "cloudflare")
+ return response
return llm_call
diff --git a/services/llm-gateway/src/llm_gateway/metrics/prometheus.py b/services/llm-gateway/src/llm_gateway/metrics/prometheus.py
index 45b1fc5d3ad5..26f16f995858 100644
--- a/services/llm-gateway/src/llm_gateway/metrics/prometheus.py
+++ b/services/llm-gateway/src/llm_gateway/metrics/prometheus.py
@@ -178,6 +178,12 @@ STREAMING_CLIENT_DISCONNECT = Counter(
labelnames=["provider", "model", "product"],
)
+ANTHROPIC_BRIDGE_INVALID_STREAM = Counter(
+ "llm_gateway_anthropic_bridge_invalid_stream_total",
+ "Invalid Anthropic SSE event ordering produced by a compatibility bridge",
+ labelnames=["backend", "violation"],
+)
+
CONCURRENT_REQUESTS = Gauge(
"llm_gateway_concurrent_requests",
"Current in-flight requests",
diff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.py
index 7bf2925588dd..a41a733afe9a 100644
--- a/services/llm-gateway/src/llm_gateway/modal.py
+++ b/services/llm-gateway/src/llm_gateway/modal.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import hashlib
-from collections.abc import Awaitable, Callable
+from collections.abc import AsyncIterator, Awaitable, Callable
from typing import Any, Final
import litellm
@@ -12,6 +12,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (
LiteLLMMessagesToCompletionTransformationHandler,
)
+from llm_gateway.anthropic_stream import observe_anthropic_stream
from llm_gateway.config import Settings, _normalize_cost_key
# Modal endpoints are OpenAI-compatible vLLM servers; no native litellm provider.
@@ -109,7 +110,10 @@ def _inject_modal_params(kwargs: dict[str, Any], api_base: str, modal_key: str,
def make_modal_anthropic_call(api_base: str, modal_key: str, modal_secret: str) -> Callable[..., Awaitable[Any]]:
async def llm_call(**kwargs: Any) -> Any:
_inject_modal_params(kwargs, api_base, modal_key, modal_secret)
- return await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)
+ response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)
+ if isinstance(response, AsyncIterator):
+ return observe_anthropic_stream(response, "modal")
+ return response
return llm_call
diff --git a/services/llm-gateway/tests/test_anthropic_stream.py b/services/llm-gateway/tests/test_anthropic_stream.py
new file mode 100644
index 000000000000..36d5af4b475a
--- /dev/null
+++ b/services/llm-gateway/tests/test_anthropic_stream.py
@@ -0,0 +1,226 @@
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator, Iterator
+from typing import Any
+
+import pytest
+from litellm.llms.anthropic.experimental_pass_through.adapters.streaming_iterator import AnthropicStreamWrapper
+from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+from llm_gateway.anthropic_stream import observe_anthropic_stream
+from llm_gateway.metrics.prometheus import ANTHROPIC_BRIDGE_INVALID_STREAM
+
+
+def _chunk(
+ *,
+ reasoning_content: str | None = None,
+ tool_calls: list[dict[str, Any]] | None = None,
+ finish_reason: str | None = None,
+) -> ModelResponseStream:
+ return ModelResponseStream(
+ choices=[
+ StreamingChoices(
+ index=0,
+ finish_reason=finish_reason,
+ delta=Delta(
+ role="assistant",
+ reasoning_content=reasoning_content,
+ tool_calls=tool_calls,
+ ),
+ )
+ ]
+ )
+
+
+def _glm_stream(label: str) -> Iterator[ModelResponseStream]:
+ return iter(
+ [
+ _chunk(reasoning_content=f"plan-{label}"),
+ _chunk(
+ tool_calls=[
+ {
+ "index": 0,
+ "id": f"call-{label}",
+ "type": "function",
+ "function": {"name": "shell", "arguments": ""},
+ }
+ ]
+ ),
+ _chunk(
+ tool_calls=[
+ {
+ "index": 0,
+ "id": None,
+ "type": "function",
+ "function": {"name": None, "arguments": "{}"},
+ }
+ ]
+ ),
+ _chunk(finish_reason="tool_calls"),
+ ]
+ )
+
+
+def _assert_valid_event_order(events: list[dict[str, Any]]) -> None:
+ active_blocks: dict[int, str] = {}
+ delta_block_types = {
+ "input_json_delta": "tool_use",
+ "signature_delta": "thinking",
+ "text_delta": "text",
+ "thinking_delta": "thinking",
+ }
+
+ for event in events:
+ event_type = event.get("type")
+ index = event.get("index")
+ if event_type == "content_block_start":
+ assert isinstance(index, int)
+ assert index not in active_blocks
+ active_blocks[index] = event["content_block"]["type"]
+ elif event_type == "content_block_delta":
+ assert isinstance(index, int)
+ assert index in active_blocks
+ expected_block_type = delta_block_types.get(event["delta"]["type"])
+ if expected_block_type is not None:
+ assert active_blocks[index] == expected_block_type
+ elif event_type == "content_block_stop":
+ assert isinstance(index, int)
+ assert index in active_blocks
+ active_blocks.pop(index)
+
+
+def test_litellm_anthropic_streams_do_not_share_event_queues() -> None:
+ wrappers = [
+ AnthropicStreamWrapper(_glm_stream("a"), model="glm-a"),
+ AnthropicStreamWrapper(_glm_stream("b"), model="glm-b"),
+ ]
+ outputs: list[list[dict[str, Any]]] = [[], []]
+ completed = [False, False]
+
+ while not all(completed):
+ for index, wrapper in enumerate(wrappers):
+ if completed[index]:
+ continue
+ try:
+ event = next(wrapper)
+ except (StopIteration, StopAsyncIteration):
+ completed[index] = True
+ continue
+ assert isinstance(event, dict)
+ outputs[index].append(event)
+
+ for output in outputs:
+ _assert_valid_event_order(output)
+ assert "call-b" not in json.dumps(outputs[0])
+ assert "call-a" not in json.dumps(outputs[1])
+
+
+def test_litellm_anthropic_stream_uses_matching_thinking_block() -> None:
+ events = list(AnthropicStreamWrapper(_glm_stream("a"), model="glm-a"))
+ dict_events = [event for event in events if isinstance(event, dict)]
+
+ _assert_valid_event_order(dict_events)
+
+
[email protected]("serialize", [False, True], ids=["structured", "sse_bytes"])
+async def test_observer_records_invalid_stream_without_modifying_it(serialize: bool) -> None:
+ event = {"type": "content_block_delta", "index": 2, "delta": {"type": "input_json_delta", "partial_json": "{}"}}
+ chunks = [f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() if serialize else event] * 2
+
+ async def stream() -> AsyncIterator[Any]:
+ for chunk in chunks:
+ yield chunk
+
+ labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="delta_without_start")
+ initial_value = labels._value.get()
+
+ observed = [chunk async for chunk in observe_anthropic_stream(stream(), "test")]
+
+ assert observed == chunks
+ assert labels._value.get() == initial_value + 1
+
+
+async def test_observer_accepts_compaction_delta_for_compaction_block() -> None:
+ events = [
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "compaction", "content": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "compaction_delta", "content": "summary"}},
+ {"type": "content_block_stop", "index": 0},
+ ]
+
+ async def stream() -> AsyncIterator[dict[str, Any]]:
+ for event in events:
+ yield event
+
+ labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="delta_type_mismatch")
+ initial_value = labels._value.get()
+
+ observed = [event async for event in observe_anthropic_stream(stream(), "test")]
+
+ assert observed == events
+ assert labels._value.get() == initial_value
+
+
+async def test_observer_handles_fragmented_and_coalesced_sse_frames() -> None:
+ events = [
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "hello"}},
+ {"type": "content_block_stop", "index": 0},
+ ]
+ encoded = b"".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() for event in events)
+ chunks = [encoded[:23], encoded[23:]]
+
+ async def stream() -> AsyncIterator[bytes]:
+ for chunk in chunks:
+ yield chunk
+
+ delta_labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="delta_without_start")
+ unclosed_labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="unclosed_block")
+ initial_delta_value = delta_labels._value.get()
+ initial_unclosed_value = unclosed_labels._value.get()
+
+ observed = [chunk async for chunk in observe_anthropic_stream(stream(), "test")]
+
+ assert observed == chunks
+ assert delta_labels._value.get() == initial_delta_value
+ assert unclosed_labels._value.get() == initial_unclosed_value
+
+
+async def test_observer_records_unclosed_block_at_normal_eof() -> None:
+ events = [{"type": "content_block_start", "index": 3, "content_block": {"type": "text", "text": ""}}]
+
+ async def stream() -> AsyncIterator[dict[str, Any]]:
+ for event in events:
+ yield event
+
+ labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="unclosed_block")
+ initial_value = labels._value.get()
+
+ observed = [event async for event in observe_anthropic_stream(stream(), "test")]
+
+ assert observed == events
+ assert labels._value.get() == initial_value + 1
+
+
+async def test_duplicate_start_preserves_original_block_type() -> None:
+ events = [
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "name": "shell"}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "hello"}},
+ {"type": "content_block_stop", "index": 0},
+ ]
+
+ async def stream() -> AsyncIterator[dict[str, Any]]:
+ for event in events:
+ yield event
+
+ duplicate_labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="duplicate_start")
+ mismatch_labels = ANTHROPIC_BRIDGE_INVALID_STREAM.labels(backend="test", violation="delta_type_mismatch")
+ initial_duplicate_value = duplicate_labels._value.get()
+ initial_mismatch_value = mismatch_labels._value.get()
+
+ observed = [event async for event in observe_anthropic_stream(stream(), "test")]
+
+ assert observed == events
+ assert duplicate_labels._value.get() == initial_duplicate_value + 1
+ assert mismatch_labels._value.get() == initial_mismatch_value
diff --git a/services/llm-gateway/tests/test_metrics.py b/services/llm-gateway/tests/test_metrics.py
index 638d7a15f5a4..090b9ddf2d58 100644
--- a/services/llm-gateway/tests/test_metrics.py
+++ b/services/llm-gateway/tests/test_metrics.py
@@ -70,6 +70,7 @@ class TestMetricsExport:
pytest.param(b"llm_gateway_active_streams", id="active_streams"),
pytest.param(b"llm_gateway_concurrent_requests", id="concurrent_requests"),
pytest.param(b"llm_gateway_streaming_client_disconnect_total", id="streaming_client_disconnect"),
+ pytest.param(b"llm_gateway_anthropic_bridge_invalid_stream_total", id="anthropic_bridge_invalid_stream"),
pytest.param(b"llm_gateway_db_pool_size", id="db_pool_size"),
pytest.param(b"llm_gateway_llm_response_time_seconds", id="llm_response_time"),
pytest.param(b"llm_gateway_llm_ttft_seconds", id="llm_time_to_first_token"),
diff --git a/services/llm-gateway/uv.lock b/services/llm-gateway/uv.lock
index d76f2a65bc5b..d4e70cb0be0c 100644
--- a/services/llm-gateway/uv.lock
+++ b/services/llm-gateway/uv.lock
@@ -3,7 +3,7 @@ revision = 3
requires-python = ">=3.13"
[options]
-exclude-newer = "2026-06-11T14:02:18.838684Z"
+exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[[package]]
@@ -836,7 +836,7 @@ wheels = [
[[package]]
name = "litellm"
-version = "1.84.0"
+version = "1.92.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -852,9 +852,10 @@ dependencies = [
{ name = "tiktoken" },
{ name = "tokenizers" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/dd/e9/8941b7e72a187000561d932c0f2f2ed2b0fd080dfc33ba6e05961d45ca7d/litellm-1.84.0.tar.gz", hash = "sha256:b8ad0cbea11a5941b18d5af973017a340abd3d3ab41cb86e5401b970626d71a6", size = 15103206, upload-time = "2026-05-14T05:45:53.017Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/46/ea/5522be7e0dbcaa7c3fddfd2834f387c6e8eab47c0cc65f2a74657c815af7/litellm-1.92.0.tar.gz", hash = "sha256:773adf5503ee1793289689c899394a83df8122993760d9acd782e32aa798db9d", size = 15098143, upload-time = "2026-07-12T01:15:59.828Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/01/a6/77fa1bbf5e42eb596b06318b3f7e6af5d0f44028046d1d598c6a595d028f/litellm-1.84.0-py3-none-any.whl", hash = "sha256:2a58d6041e6aa27d1a28dc8d8828ab500fef1a00ef74ca65e60899035010c2f2", size = 16735062, upload-time = "2026-05-14T05:45:49.927Z" },
+ { url = "https://files.pythonhosted.org/packages/10/34/1671376f228443330471416e24ee51bc8364c0ae6155d4ec6217b70a4753/litellm-1.92.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:437a0e403136996430795ead76502103dcf74769b6909e12d3e2511061ea8ff8", size = 19291560, upload-time = "2026-07-12T01:15:54.66Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/4f/141cf1162eeee762fc839c335e3f78fc309a65f2385023479a20b09e680a/litellm-1.92.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:8f03047a73154f33c2733899e4bf9b5ed129e2e345caa305895a318452e4a807", size = 19289770, upload-time = "2026-07-12T01:15:57.136Z" },
]
[[package]]
@@ -905,7 +906,7 @@ requires-dist = [
{ name = "fastapi", specifier = ">=0.115.0" },
{ name = "gunicorn", specifier = ">=23.0.0" },
{ name = "httpx", specifier = ">=0.28.0" },
- { name = "litellm", specifier = "==1.84.0" },
+ { name = "litellm", specifier = "==1.92.0" },
{ name = "orjson", specifier = ">=3.10.0" },
{ name = "posthoganalytics", specifier = ">=3.0.0" },
{ name = "prometheus-client", specifier = ">=0.21.0" },