: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llm-gateway): keep GLM reasoning out of the visible transcript (#96271)
posthog[bot]6bffe14d99f2
diff --git a/services/llm-gateway/src/llm_gateway/anthropic_stream.py b/services/llm-gateway/src/llm_gateway/anthropic_stream.pyindex cb6a2ccd7312..a305a8c8d918 100644--- a/services/llm-gateway/src/llm_gateway/anthropic_stream.py+++ b/services/llm-gateway/src/llm_gateway/anthropic_stream.py@@ -69,14 +69,26 @@ class _SSEPayloadDecoder:return payloads-async def observe_anthropic_stream(stream: AsyncIterator[Any], backend: str) -> AsyncIterator[Any]:+async def repair_anthropic_stream(stream: AsyncIterator[Any], backend: str) -> AsyncIterator[Any]:+ """Record invalid bridge output, and drop reasoning deltas aimed at a text block.++ A bridge that reads the block type from the OpenAI `content` field but the delta type+ from `reasoning_content` puts a `thinking_delta` inside a block it opened as `text`.+ Clients that trust the block type then show the reasoning as assistant prose. Dropping+ the delta keeps reasoning out of the visible transcript and keeps the block consistent,+ so a client that diffs streamed chunks against the assembled message stays in step.+ """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):+ payloads = _payloads_from_chunk(chunk, sse_decoder)+ drop_chunk = any(_leaks_reasoning_into_text_block(payload, active_blocks) for payload in payloads)+ for payload in payloads:_observe_payload(payload, backend, active_blocks, recorded_violations)+ if drop_chunk:+ continueyield chunkfor payload in sse_decoder.finish():@@ -85,6 +97,17 @@ async def observe_anthropic_stream(stream: AsyncIterator[Any], backend: str) ->_record_violation(backend, index, "unclosed_block", recorded_violations)+def _leaks_reasoning_into_text_block(payload: dict[str, Any], active_blocks: dict[int, str]) -> bool:+ if payload.get("type") != "content_block_delta":+ return False+ delta = payload.get("delta")+ delta_type = delta.get("type") if isinstance(delta, dict) else None+ if not isinstance(delta_type, str) or _DELTA_BLOCK_TYPES.get(delta_type) != "thinking":+ return False+ index = payload.get("index")+ return isinstance(index, int) and active_blocks.get(index) == "text"++def _payloads_from_chunk(chunk: Any, sse_decoder: _SSEPayloadDecoder) -> list[dict[str, Any]]:if isinstance(chunk, dict):return [chunk]diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.pyindex ad2865176056..7d4278da492e 100644--- a/services/llm-gateway/src/llm_gateway/baseten.py+++ b/services/llm-gateway/src/llm_gateway/baseten.py@@ -10,7 +10,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import ()from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive, force_stream_usage-from llm_gateway.anthropic_stream import observe_anthropic_stream+from llm_gateway.anthropic_stream import repair_anthropic_streamfrom llm_gateway.config import SettingsBASETEN_PUBLIC_MODEL = "@cf/zai-org/glm-5.2"@@ -71,7 +71,7 @@ def make_baseten_anthropic_call(api_base: str, api_key: str) -> Callable[..., Aw_inject_baseten_params(kwargs, api_base, api_key)response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)if isinstance(response, AsyncIterator):- return observe_anthropic_stream(response, "baseten")+ return repair_anthropic_stream(response, "baseten")return responsereturn llm_calldiff --git a/services/llm-gateway/src/llm_gateway/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.pyindex c1ef58d1f0bd..b0a7fcb4787e 100644--- a/services/llm-gateway/src/llm_gateway/cloudflare.py+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py@@ -12,7 +12,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import ()from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive, force_stream_usage-from llm_gateway.anthropic_stream import observe_anthropic_stream+from llm_gateway.anthropic_stream import repair_anthropic_streamfrom llm_gateway.config import Settingsfrom llm_gateway.rate_limiting.cost_refresh import COST_ALIASES@@ -102,7 +102,7 @@ def make_cloudflare_anthropic_call(api_base: str, api_key: str) -> Callable[...,_inject_cloudflare_params(kwargs, api_base, api_key)response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)if isinstance(response, AsyncIterator):- return observe_anthropic_stream(response, "cloudflare")+ return repair_anthropic_stream(response, "cloudflare")return responsereturn llm_calldiff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.pyindex a1fdd45c66c1..29233bd5b566 100644--- a/services/llm-gateway/src/llm_gateway/modal.py+++ b/services/llm-gateway/src/llm_gateway/modal.py@@ -14,7 +14,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import ()from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive, force_stream_usage-from llm_gateway.anthropic_stream import observe_anthropic_stream+from llm_gateway.anthropic_stream import repair_anthropic_streamfrom llm_gateway.config import Settings, _normalize_cost_key# Modal endpoints are OpenAI-compatible vLLM servers; no native litellm provider.@@ -150,7 +150,7 @@ def make_modal_anthropic_call(api_base: str, modal_key: str, modal_secret: str)_inject_modal_params(kwargs, api_base, modal_key, modal_secret)response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)if isinstance(response, AsyncIterator):- return observe_anthropic_stream(response, "modal")+ return repair_anthropic_stream(response, "modal")return responsereturn llm_calldiff --git a/services/llm-gateway/tests/test_anthropic_stream.py b/services/llm-gateway/tests/test_anthropic_stream.pyindex 36d5af4b475a..bb8c492606de 100644--- a/services/llm-gateway/tests/test_anthropic_stream.py+++ b/services/llm-gateway/tests/test_anthropic_stream.py@@ -3,17 +3,20 @@ from __future__ import annotationsimport jsonfrom collections.abc import AsyncIterator, Iteratorfrom typing import Any+from unittest.mock import AsyncMock, patchimport pytestfrom litellm.llms.anthropic.experimental_pass_through.adapters.streaming_iterator import AnthropicStreamWrapperfrom litellm.types.utils import Delta, ModelResponseStream, StreamingChoices-from llm_gateway.anthropic_stream import observe_anthropic_stream+from llm_gateway.anthropic_stream import repair_anthropic_stream+from llm_gateway.baseten import BASETEN_GLM53_FLASH_PUBLIC_MODEL, make_baseten_anthropic_callfrom llm_gateway.metrics.prometheus import ANTHROPIC_BRIDGE_INVALID_STREAMdef _chunk(*,+ content: str | None = None,reasoning_content: str | None = None,tool_calls: list[dict[str, Any]] | None = None,finish_reason: str | None = None,@@ -25,6 +28,7 @@ def _chunk(finish_reason=finish_reason,delta=Delta(role="assistant",+ content=content,reasoning_content=reasoning_content,tool_calls=tool_calls,),@@ -124,7 +128,7 @@ def test_litellm_anthropic_stream_uses_matching_thinking_block() -> None:@pytest.mark.parametrize("serialize", [False, True], ids=["structured", "sse_bytes"])-async def test_observer_records_invalid_stream_without_modifying_it(serialize: bool) -> None:+async def test_repairer_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@@ -135,13 +139,13 @@ async def test_observer_records_invalid_stream_without_modifying_it(serialize: blabels = 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")]+ observed = [chunk async for chunk in repair_anthropic_stream(stream(), "test")]assert observed == chunksassert labels._value.get() == initial_value + 1-async def test_observer_accepts_compaction_delta_for_compaction_block() -> None:+async def test_repairer_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"}},@@ -155,13 +159,13 @@ async def test_observer_accepts_compaction_delta_for_compaction_block() -> None: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")]+ observed = [event async for event in repair_anthropic_stream(stream(), "test")]assert observed == eventsassert labels._value.get() == initial_value-async def test_observer_handles_fragmented_and_coalesced_sse_frames() -> None:+async def test_repairer_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"}},@@ -179,14 +183,14 @@ async def test_observer_handles_fragmented_and_coalesced_sse_frames() -> None: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")]+ observed = [chunk async for chunk in repair_anthropic_stream(stream(), "test")]assert observed == chunksassert delta_labels._value.get() == initial_delta_valueassert unclosed_labels._value.get() == initial_unclosed_value-async def test_observer_records_unclosed_block_at_normal_eof() -> None:+async def test_repairer_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]]:@@ -196,7 +200,7 @@ async def test_observer_records_unclosed_block_at_normal_eof() -> None: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")]+ observed = [event async for event in repair_anthropic_stream(stream(), "test")]assert observed == eventsassert labels._value.get() == initial_value + 1@@ -219,8 +223,66 @@ async def test_duplicate_start_preserves_original_block_type() -> None: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")]+ observed = [event async for event in repair_anthropic_stream(stream(), "test")]assert observed == eventsassert duplicate_labels._value.get() == initial_duplicate_value + 1assert mismatch_labels._value.get() == initial_mismatch_value+++async def test_glm_reasoning_never_reaches_visible_anthropic_sse() -> None:+ chunks = [+ _chunk(reasoning_content="weigh the options"),+ _chunk(content="Here is the answer"),+ # GLM can carry the next reasoning token alongside visible text.+ _chunk(content=" and more", reasoning_content="second thought"),+ _chunk(content=" done"),+ _chunk(finish_reason="stop"),+ ]++ async def source() -> AsyncIterator[ModelResponseStream]:+ for chunk in chunks:+ yield chunk++ with patch("litellm.acompletion", new=AsyncMock(return_value=source())):+ stream = await make_baseten_anthropic_call("https://baseten.test/v1", "bt-key")(+ model=BASETEN_GLM53_FLASH_PUBLIC_MODEL,+ messages=[{"role": "user", "content": "hi"}],+ max_tokens=64,+ stream=True,+ )++ response = b"".join([chunk async for chunk in stream])++ events = [+ json.loads(line.removeprefix("data: ")) for line in response.decode().splitlines() if line.startswith("data: ")+ ]+ _assert_valid_event_order(events)+ visible = "".join(+ event["delta"]["text"]+ for event in events+ if event.get("type") == "content_block_delta" and event["delta"]["type"] == "text_delta"+ )+ assert visible == "Here is the answer done"+++ ("block_type", "dropped"),+ [("text", True), ("thinking", False)],+ ids=["text_block", "thinking_block"],+)+async def test_repairer_drops_reasoning_delta_only_when_the_block_is_text(block_type: str, dropped: bool) -> None:+ reasoning_delta = {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "hm"}}+ events = [+ {"type": "content_block_start", "index": 0, "content_block": {"type": block_type}},+ reasoning_delta,+ {"type": "content_block_stop", "index": 0},+ ]++ async def stream() -> AsyncIterator[dict[str, Any]]:+ for event in events:+ yield event++ observed = [event async for event in repair_anthropic_stream(stream(), "test")]++ assert (reasoning_delta not in observed) is dropped