: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): drop orphaned clear-thinking edits on the Anthropic route (#73838)
Alessandro Pogliaghi7c350c49e914
diff --git a/services/llm-gateway/src/llm_gateway/anthropic_request.py b/services/llm-gateway/src/llm_gateway/anthropic_request.pynew file mode 100644index 000000000000..e1eb514102aa--- /dev/null+++ b/services/llm-gateway/src/llm_gateway/anthropic_request.py@@ -0,0 +1,39 @@+"""Request-shape fixes shared by every backend that speaks the Anthropic Messages format."""++from __future__ import annotations++from typing import Any, Final++from llm_gateway.metrics.prometheus import CLEAR_THINKING_EDIT_DROPPED++CLEAR_THINKING_EDIT: Final[str] = "clear_thinking_20251015"+++def drop_orphaned_clear_thinking(request_data: dict[str, Any], *, product: str) -> dict[str, Any]:+ """Strip a `clear_thinking_20251015` edit the request can't legally carry.++ Anthropic 400s the pair ("strategy requires `thinking` to be enabled or adaptive"), so dropping+ the edit costs a context-management optimization while keeping it costs the whole turn.+ """+ thinking = request_data.get("thinking")+ if isinstance(thinking, dict) and thinking.get("type") in {"enabled", "adaptive"}:+ return request_data++ context_management = request_data.get("context_management")+ if not isinstance(context_management, dict):+ return request_data+ edits = context_management.get("edits")+ if not isinstance(edits, list):+ return request_data++ kept = [edit for edit in edits if not (isinstance(edit, dict) and edit.get("type") == CLEAR_THINKING_EDIT)]+ if len(kept) == len(edits):+ return request_data++ CLEAR_THINKING_EDIT_DROPPED.labels(product=product).inc()+ normalized = dict(request_data)+ if kept:+ normalized["context_management"] = {**context_management, "edits": kept}+ else:+ normalized.pop("context_management", None)+ return normalizeddiff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.pyindex 68cd51f6f575..d5285250409a 100644--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py@@ -11,6 +11,7 @@ from botocore.exceptions import ClientErrorfrom fastapi import APIRouter, HTTPException, Requestfrom fastapi.responses import StreamingResponse+from llm_gateway.anthropic_request import drop_orphaned_clear_thinkingfrom llm_gateway.api.handler import (ANTHROPIC_CONFIG,BEDROCK_CONFIG,@@ -539,6 +540,11 @@ async def _handle_anthropic_messages(if await _maybe_bypass_anthropic(breaker, body.model, product, use_bedrock_fallback=use_bedrock_fallback):return await _send_bedrock_messages(data, user, request, body.stream or False, product)+ # A body assembled for a non-thinking model reaches Anthropic when a runtime retries under its+ # fallback model. Only this leg needs the fix: GLM normalizes its own traffic and Bedrock drops+ # context_management wholesale.+ data = drop_orphaned_clear_thinking(data, product=product)+litellm_data = {**data, "model": normalize_litellm_model_name(body.model, ANTHROPIC_CONFIG.name)}try:diff --git a/services/llm-gateway/src/llm_gateway/glm_routing.py b/services/llm-gateway/src/llm_gateway/glm_routing.pyindex 355dfd668a9c..e62428a99304 100644--- a/services/llm-gateway/src/llm_gateway/glm_routing.py+++ b/services/llm-gateway/src/llm_gateway/glm_routing.py@@ -13,6 +13,7 @@ from typing import Anyfrom fastapi.responses import StreamingResponse+from llm_gateway.anthropic_request import drop_orphaned_clear_thinkingfrom llm_gateway.api.handler import (CLOUDFLARE_ANTHROPIC_CONFIG,CLOUDFLARE_OPENAI_CONFIG,@@ -50,7 +51,7 @@ LlmCall = Callable[..., Awaitable[Any]]GLM_REASONING_EFFORTS: frozenset[str] = frozenset({"high", "max"})-def normalize_glm_anthropic_request(request_data: dict[str, Any]) -> dict[str, Any]:+def normalize_glm_anthropic_request(request_data: dict[str, Any], *, product: str) -> dict[str, Any]:"""Make Claude runtime reasoning settings valid for GLM's Anthropic surface."""normalized = dict(request_data)output_config = normalized.get("output_config")@@ -59,22 +60,7 @@ def normalize_glm_anthropic_request(request_data: dict[str, Any]) -> dict[str, Aif effort in GLM_REASONING_EFFORTS:normalized["thinking"] = {"type": "adaptive"}- thinking = normalized.get("thinking")- thinking_type = thinking.get("type") if isinstance(thinking, dict) else None- if thinking_type not in {"enabled", "adaptive"}:- context_management = normalized.get("context_management")- if isinstance(context_management, dict) and isinstance(context_management.get("edits"), list):- edits = [- edit- for edit in context_management["edits"]- if not isinstance(edit, dict) or edit.get("type") != "clear_thinking_20251015"- ]- if edits:- normalized["context_management"] = {**context_management, "edits": edits}- else:- normalized.pop("context_management", None)-- return normalized+ return drop_orphaned_clear_thinking(normalized, product=product)async def _route_to_modal(model: str, user: AuthenticatedUser, product: str, settings: Settings) -> bool:@@ -169,7 +155,7 @@ async def send_glm_anthropic_messages(product: str,) -> dict[str, Any] | StreamingResponse:return await _send_glm_request(- normalize_glm_anthropic_request(request_data),+ normalize_glm_anthropic_request(request_data, product=product),user,is_streaming,product,diff --git a/services/llm-gateway/src/llm_gateway/metrics/prometheus.py b/services/llm-gateway/src/llm_gateway/metrics/prometheus.pyindex 26f16f995858..e9e423dff731 100644--- a/services/llm-gateway/src/llm_gateway/metrics/prometheus.py+++ b/services/llm-gateway/src/llm_gateway/metrics/prometheus.py@@ -257,6 +257,14 @@ BEDROCK_PARAM_STRIPPED = Counter(labelnames=["param", "product"],)+CLEAR_THINKING_EDIT_DROPPED = Counter(+ "llm_gateway_clear_thinking_edit_dropped_total",+ "Requests where a clear_thinking_20251015 context-management edit was stripped because the "+ "request didn't enable thinking. No model label: this fires before the model is validated, so "+ "a caller-supplied id would be unbounded cardinality.",+ labelnames=["product"],+)+BEDROCK_COUNT_TOKENS_ERRORS = Counter("llm_gateway_bedrock_count_tokens_errors_total","Bedrock CountTokens provider-call failures before fallback handling",diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.pyindex 2b7d24429d6b..662f85aedb4b 100644--- a/services/llm-gateway/tests/test_anthropic.py+++ b/services/llm-gateway/tests/test_anthropic.py@@ -260,6 +260,32 @@ class TestAnthropicMessagesEndpoint:assert response.status_code == 200assert mock_anthropic.call_args.kwargs["model"] == "anthropic/claude-opus-4-8"+ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_orphaned_clear_thinking_edit_not_forwarded_to_anthropic(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ provider_mock_response: dict,+ ) -> None:+ # Anthropic 400s `clear_thinking_20251015` when thinking isn't enabled; the drop rules+ # themselves live in test_anthropic_request.py.+ mock_response = MagicMock()+ mock_response.model_dump = MagicMock(return_value=provider_mock_response)+ mock_anthropic.return_value = mock_response++ response = authenticated_client.post(+ "/v1/messages",+ json={+ "model": "claude-opus-4-8",+ "messages": [{"role": "user", "content": "Hello"}],+ "context_management": {"edits": [{"type": "clear_thinking_20251015", "keep": "all"}]},+ },+ headers={"Authorization": "Bearer phx_test_key"},+ )++ assert response.status_code == 200+ assert "context_management" not in mock_anthropic.call_args.kwargs+@pytest.mark.parametrize("error_status,error_message,error_type",[diff --git a/services/llm-gateway/tests/test_anthropic_request.py b/services/llm-gateway/tests/test_anthropic_request.pynew file mode 100644index 000000000000..d44886b2f2a9--- /dev/null+++ b/services/llm-gateway/tests/test_anthropic_request.py@@ -0,0 +1,85 @@+from typing import Any++import pytest++from llm_gateway.anthropic_request import drop_orphaned_clear_thinking+from llm_gateway.metrics.prometheus import CLEAR_THINKING_EDIT_DROPPED++PRODUCT = "posthog_code"+OTHER_PRODUCT = "llm_gateway"+CLEAR_THINKING = {"type": "clear_thinking_20251015", "keep": "all"}+CLEAR_TOOL_USES = {"type": "clear_tool_uses_20250919"}+++def _dropped_count(product: str) -> float:+ return CLEAR_THINKING_EDIT_DROPPED.labels(product=product)._value.get()+++ ("thinking", "edits", "expected_context_management", "expected_increment"),+ [+ pytest.param(None, [CLEAR_THINKING], None, 1, id="no_thinking_drops_context_management"),+ pytest.param({"type": "disabled"}, [CLEAR_THINKING], None, 1, id="disabled_thinking_drops_context_management"),+ pytest.param(+ {"type": "disabled"},+ [CLEAR_THINKING, CLEAR_TOOL_USES],+ {"edits": [CLEAR_TOOL_USES]},+ 1,+ id="other_edits_survive",+ ),+ pytest.param(+ {"type": "adaptive"},+ [CLEAR_THINKING],+ {"edits": [CLEAR_THINKING]},+ 0,+ id="adaptive_thinking_keeps_the_edit",+ ),+ pytest.param(+ {"type": "enabled", "budget_tokens": 1024},+ [CLEAR_THINKING],+ {"edits": [CLEAR_THINKING]},+ 0,+ id="enabled_thinking_keeps_the_edit",+ ),+ pytest.param(None, [CLEAR_TOOL_USES], {"edits": [CLEAR_TOOL_USES]}, 0, id="unrelated_edits_untouched"),+ ],+)+def test_clear_thinking_edit_is_dropped_only_without_thinking(+ thinking: dict[str, Any] | None,+ edits: list[dict[str, Any]],+ expected_context_management: dict[str, Any] | None,+ expected_increment: int,+) -> None:+ request = {+ "model": "claude-opus-4-8",+ "messages": [{"role": "user", "content": "hi"}],+ "context_management": {"edits": edits},+ **({"thinking": thinking} if thinking else {}),+ }+ before = _dropped_count(PRODUCT)+ before_other = _dropped_count(OTHER_PRODUCT)++ normalized = drop_orphaned_clear_thinking(request, product=PRODUCT)++ assert normalized.get("context_management") == expected_context_management+ assert request["context_management"] == {"edits": edits}+ # The counter is the only signal that this fired, so pin both that it ticks on a drop and that+ # it stays put otherwise — and that it lands on the caller's product, not some other series.+ assert _dropped_count(PRODUCT) == before + expected_increment+ assert _dropped_count(OTHER_PRODUCT) == before_other+++ "context_management",+ [+ pytest.param(None, id="absent"),+ pytest.param({}, id="no_edits_key"),+ pytest.param({"edits": "not-a-list"}, id="malformed_edits"),+ ],+)+def test_request_without_edits_is_returned_untouched(context_management: Any) -> None:+ request: dict[str, Any] = {"model": "claude-opus-4-8", "messages": []}+ if context_management is not None:+ request["context_management"] = context_management++ assert drop_orphaned_clear_thinking(request, product=PRODUCT) is requestdiff --git a/services/llm-gateway/tests/test_glm_routing.py b/services/llm-gateway/tests/test_glm_routing.pyindex 2bc6d7748993..62f3f86d5068 100644--- a/services/llm-gateway/tests/test_glm_routing.py+++ b/services/llm-gateway/tests/test_glm_routing.py@@ -96,29 +96,16 @@ async def test_normalizes_supported_reasoning_effort_for_anthropic_requests(effo}- ("edits", "expected_context_management"),- [- ([{"type": "clear_thinking_20251015", "keep": "all"}], None),- (- [- {"type": "clear_thinking_20251015", "keep": "all"},- {"type": "clear_tool_uses_20250919"},- ],- {"edits": [{"type": "clear_tool_uses_20250919"}]},- ),- ],-)-def test_drops_clear_thinking_when_thinking_is_not_enabled(- edits: list[dict[str, str]], expected_context_management: dict[str, Any] | None-) -> None:+def test_drops_clear_thinking_when_no_effort_enables_thinking() -> None:+ # Edit-level rules live in test_anthropic_request.py; this pins that GLM still applies them+ # once its effort upgrade has had a chance to enable thinking.request = {"model": GLM_MODEL,"messages": [{"role": "user", "content": "hi"}],- "context_management": {"edits": edits},+ "context_management": {"edits": [{"type": "clear_thinking_20251015", "keep": "all"}]},}- assert normalize_glm_anthropic_request(request).get("context_management") == expected_context_management+ assert "context_management" not in normalize_glm_anthropic_request(request, product=PRODUCT)async def test_routes_to_modal_when_fraction_one_without_flag_roundtrip() -> None: