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): pass through claude code classifier fields (#107305)

Brandon57ca35773084
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index e31b35c54a3f..146ea70b241e 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -36,6 +36,12 @@ from llm_gateway.cloudflare import (
from llm_gateway.config import get_settings
from llm_gateway.dependencies import AnthropicCircuitBreakerDep, RateLimitedUser
from llm_gateway.inference_routing import is_inference_routed_model, send_inference_anthropic_messages
+from llm_gateway.litellm_passthrough import (
+ caller_anthropic_beta,
+ install,
+ with_caller_anthropic_beta,
+ without_passthrough_fields,
+)
from llm_gateway.metrics.prometheus import (
ANTHROPIC_CIRCUIT_BREAKER_BYPASSED,
BEDROCK_COUNT_TOKENS_ERRORS,
@@ -58,6 +64,8 @@ from llm_gateway.request_context import (
logger = structlog.get_logger(__name__)
+install()
+
anthropic_router = APIRouter()
ANTHROPIC_COUNT_TOKENS_URL = "https://api.anthropic.com/v1/messages/count_tokens"
@@ -374,9 +382,9 @@ async def _send_bedrock_messages(
# ids like "us.anthropic.claude-opus-4-7", so prefix explicitly.
data["model"] = f"bedrock/{bedrock_model}"
- anthropic_beta = request.headers.get("anthropic-beta")
+ anthropic_beta = caller_anthropic_beta(request.headers)
if anthropic_beta:
- data["anthropic_beta"] = [h.strip() for h in anthropic_beta.split(",") if h.strip()]
+ data["anthropic_beta"] = anthropic_beta.split(",")
data = sanitize_for_bedrock(data, model=bedrock_model, product=product)
@@ -534,10 +542,14 @@ async def _handle_anthropic_messages(
# serves tools fine: litellm's Anthropic->chat/completions adapter translates Anthropic tools
# into OpenAI function tools that both backends' OpenAI-compatible endpoints accept.
if provider == "cloudflare" or is_inference_routed_model(body.model):
- return await send_inference_anthropic_messages(data, user, body.stream or False, product)
+ return await send_inference_anthropic_messages(
+ without_passthrough_fields(data), user, body.stream or False, product
+ )
if is_modal_served_model(body.model):
- return await send_modal_anthropic_messages(data, user, body.stream or False, product)
+ return await send_modal_anthropic_messages(
+ without_passthrough_fields(data), user, body.stream or False, product
+ )
if provider == "bedrock":
return await _send_bedrock_messages(data, user, request, body.stream or False, product)
@@ -550,7 +562,9 @@ async def _handle_anthropic_messages(
# context_management wholesale.
data = drop_orphaned_clear_thinking(data, product=product)
- litellm_data = {**data, "model": normalize_litellm_model_name(body.model, ANTHROPIC_CONFIG.name)}
+ litellm_data = with_caller_anthropic_beta(
+ {**data, "model": normalize_litellm_model_name(body.model, ANTHROPIC_CONFIG.name)}, request.headers
+ )
try:
result = await handle_llm_request(
@@ -643,7 +657,9 @@ async def _handle_count_tokens(
return await _bedrock_count_tokens_impl(data, body.model, user, product)
try:
- result = await _anthropic_count_tokens_impl(data, body.model, user, product)
+ result = await _anthropic_count_tokens_impl(
+ data, body.model, user, product, anthropic_beta=caller_anthropic_beta(request.headers)
+ )
except HTTPException as exc:
await _record_anthropic_outcome(breaker, success=_is_breaker_success(exc.status_code))
if not use_bedrock_fallback or _is_breaker_success(exc.status_code):
@@ -684,6 +700,8 @@ async def _anthropic_count_tokens_impl(
model: str,
user: RateLimitedUser,
product: str,
+ *,
+ anthropic_beta: str | None = None,
) -> dict[str, Any]:
settings = get_settings()
start_time = time.monotonic()
@@ -701,6 +719,8 @@ async def _anthropic_count_tokens_impl(
"anthropic-version": ANTHROPIC_API_VERSION,
"content-type": "application/json",
}
+ if anthropic_beta:
+ headers["anthropic-beta"] = anthropic_beta
try:
async with httpx.AsyncClient(timeout=settings.request_timeout) as client:
diff --git a/services/llm-gateway/src/llm_gateway/litellm_passthrough.py b/services/llm-gateway/src/llm_gateway/litellm_passthrough.py
new file mode 100644
index 000000000000..534f34bb1031
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/litellm_passthrough.py
@@ -0,0 +1,55 @@
+"""litellm drops unknown Messages body keys and `anthropic-beta` values outside its allowlist.
+Claude Code's server-side classifier needs `safeguards` and its beta to reach Anthropic.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+import litellm
+from litellm.llms.anthropic.experimental_pass_through.messages.transformation import AnthropicMessagesConfig
+from litellm.llms.anthropic.experimental_pass_through.messages.utils import _anthropic_messages_optional_param_keys
+from litellm.types.llms.anthropic import AnthropicMessagesRequestOptionalParams
+from litellm.utils import ProviderConfigManager
+
+if TYPE_CHECKING:
+ from starlette.datastructures import Headers
+
+PASSTHROUGH_BODY_FIELDS: tuple[str, ...] = ("safeguards",)
+
+
+class VerbatimBetaAnthropicMessagesConfig(AnthropicMessagesConfig):
+ """Send caller betas to Anthropic unfiltered, as a direct connection does."""
+
+ def should_filter_anthropic_beta_headers(self) -> bool:
+ return False
+
+
+def install() -> None:
+ for field in PASSTHROUGH_BODY_FIELDS:
+ AnthropicMessagesRequestOptionalParams.__annotations__.setdefault(field, Any)
+ _anthropic_messages_optional_param_keys.cache_clear()
+
+ litellm.AnthropicMessagesConfig = VerbatimBetaAnthropicMessagesConfig # type: ignore[misc, unused-ignore]
+ ProviderConfigManager._get_provider_anthropic_messages_config_cached.cache_clear()
+
+
+def caller_anthropic_beta(headers: Headers) -> str | None:
+ values = [value.strip() for line in headers.getlist("anthropic-beta") for value in line.split(",")]
+ joined = ",".join(value for value in values if value)
+ return joined or None
+
+
+def with_caller_anthropic_beta(data: dict[str, Any], headers: Headers) -> dict[str, Any]:
+ beta = caller_anthropic_beta(headers)
+ if beta is None:
+ return data
+ extra_headers = data.get("extra_headers")
+ merged = dict(extra_headers) if isinstance(extra_headers, dict) else {}
+ merged["anthropic-beta"] = beta
+ return {**data, "extra_headers": merged}
+
+
+def without_passthrough_fields(data: dict[str, Any]) -> dict[str, Any]:
+ """Non-Anthropic backends cannot run the classifier and can reject these fields."""
+ return {key: value for key, value in data.items() if key not in PASSTHROUGH_BODY_FIELDS}
diff --git a/services/llm-gateway/tests/test_litellm_passthrough.py b/services/llm-gateway/tests/test_litellm_passthrough.py
new file mode 100644
index 000000000000..cf85c638fc82
--- /dev/null
+++ b/services/llm-gateway/tests/test_litellm_passthrough.py
@@ -0,0 +1,203 @@
+import json
+from collections.abc import Iterator
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import litellm
+import pytest
+import respx
+from fastapi.testclient import TestClient
+from starlette.datastructures import Headers
+
+from llm_gateway.litellm_passthrough import caller_anthropic_beta, install
+from llm_gateway.streaming.sse import format_sse_stream
+
+UNKNOWN_BETA = "future-feature-2099-01-01"
+SAFEGUARDS = [{"type": "tool_use_review", "classifier_context": "ctx"}]
+SAFEGUARD_RESULTS = [{"type": "tool_use_review", "verdict": "allow"}]
+MESSAGE = {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-opus-4-8",
+ "content": [{"type": "text", "text": "hi"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+}
+SSE = (
+ b'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","type":"message",'
+ b'"role":"assistant","model":"claude-opus-4-8","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn",'
+ b'"safeguard_results":[{"type":"tool_use_review","verdict":"allow"}]},"usage":{"output_tokens":1}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+)
+
+
+class TestCallerAnthropicBeta:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ pytest.param([], None, id="absent"),
+ pytest.param([("anthropic-beta", " , ")], None, id="blank"),
+ pytest.param([("anthropic-beta", "a, b")], "a,b", id="single_line"),
+ pytest.param([("anthropic-beta", "a"), ("anthropic-beta", "b,c")], "a,b,c", id="repeated_lines"),
+ ],
+ )
+ def test_joins_values(self, raw: list[tuple[str, str]], expected: str | None) -> None:
+ headers = Headers(raw=[(k.encode(), v.encode()) for k, v in raw])
+ assert caller_anthropic_beta(headers) == expected
+
+
+class TestLitellmWire:
+ @pytest.fixture
+ def upstream(self, monkeypatch: pytest.MonkeyPatch) -> Iterator[respx.MockRouter]:
+ install()
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ litellm.in_memory_llm_clients_cache.flush_cache()
+ with respx.mock(assert_all_called=False) as router:
+ router.get(url__startswith="https://raw.githubusercontent.com").mock(return_value=httpx.Response(404))
+ yield router
+ litellm.in_memory_llm_clients_cache.flush_cache()
+
+ async def test_unknown_beta_and_safeguards_reach_anthropic(self, upstream: respx.MockRouter) -> None:
+ route = upstream.post("https://api.anthropic.com/v1/messages").mock(
+ return_value=httpx.Response(200, json={**MESSAGE, "safeguard_results": SAFEGUARD_RESULTS})
+ )
+
+ response = await litellm.anthropic_messages(
+ model="anthropic/claude-opus-4-8",
+ messages=[{"role": "user", "content": "hi"}],
+ max_tokens=10,
+ api_key="test-key",
+ safeguards=SAFEGUARDS,
+ extra_headers={"anthropic-beta": UNKNOWN_BETA},
+ )
+
+ sent = route.calls.last.request
+ assert UNKNOWN_BETA in sent.headers["anthropic-beta"].split(",")
+ assert json.loads(sent.content)["safeguards"] == SAFEGUARDS
+ assert dict(response)["safeguard_results"] == SAFEGUARD_RESULTS
+
+ async def test_stream_returns_upstream_bytes_unchanged(self, upstream: respx.MockRouter) -> None:
+ upstream.post("https://api.anthropic.com/v1/messages").mock(
+ return_value=httpx.Response(200, content=SSE, headers={"content-type": "text/event-stream"})
+ )
+
+ stream = await litellm.anthropic_messages(
+ model="anthropic/claude-opus-4-8",
+ messages=[{"role": "user", "content": "hi"}],
+ max_tokens=10,
+ api_key="test-key",
+ stream=True,
+ )
+
+ assert b"".join([chunk async for chunk in format_sse_stream(stream)]) == SSE
+
+
+class TestEndpointForwarding:
+ @pytest.fixture
+ def body(self) -> dict[str, Any]:
+ return {
+ "model": "claude-opus-4-8",
+ "messages": [{"role": "user", "content": "hi"}],
+ "safeguards": SAFEGUARDS,
+ }
+
+ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")
+ def test_direct_leg_forwards_beta_and_safeguards(
+ self, mock_anthropic: MagicMock, authenticated_client: TestClient, body: dict[str, Any]
+ ) -> None:
+ mock_response = MagicMock()
+ mock_response.model_dump = MagicMock(return_value=MESSAGE)
+ mock_anthropic.return_value = mock_response
+
+ response = authenticated_client.post(
+ "/v1/messages",
+ json=body,
+ headers=[
+ ("Authorization", "Bearer phx_test_key"),
+ ("anthropic-beta", "context-management-2025-06-27"),
+ ("anthropic-beta", UNKNOWN_BETA),
+ ],
+ )
+
+ assert response.status_code == 200
+ kwargs = mock_anthropic.call_args.kwargs
+ assert kwargs["extra_headers"] == {"anthropic-beta": f"context-management-2025-06-27,{UNKNOWN_BETA}"}
+ assert kwargs["safeguards"] == SAFEGUARDS
+
+ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")
+ def test_direct_leg_without_beta_sets_no_extra_headers(
+ self, mock_anthropic: MagicMock, authenticated_client: TestClient, body: dict[str, Any]
+ ) -> None:
+ mock_response = MagicMock()
+ mock_response.model_dump = MagicMock(return_value=MESSAGE)
+ mock_anthropic.return_value = mock_response
+
+ response = authenticated_client.post(
+ "/v1/messages", json=body, headers={"Authorization": "Bearer phx_test_key"}
+ )
+
+ assert response.status_code == 200
+ assert "extra_headers" not in mock_anthropic.call_args.kwargs
+
+ @pytest.mark.parametrize(
+ "route_patch,sender_patch",
+ [
+ pytest.param(
+ "llm_gateway.api.anthropic.is_inference_routed_model",
+ "llm_gateway.api.anthropic.send_inference_anthropic_messages",
+ id="inference",
+ ),
+ pytest.param(
+ "llm_gateway.api.anthropic.is_modal_served_model",
+ "llm_gateway.api.anthropic.send_modal_anthropic_messages",
+ id="modal",
+ ),
+ ],
+ )
+ def test_non_anthropic_legs_drop_safeguards(
+ self, route_patch: str, sender_patch: str, authenticated_client: TestClient, body: dict[str, Any]
+ ) -> None:
+ with (
+ patch(route_patch, return_value=True),
+ patch(sender_patch, new_callable=AsyncMock, return_value=MESSAGE) as sender,
+ ):
+ response = authenticated_client.post(
+ "/v1/messages",
+ json=body,
+ headers={"Authorization": "Bearer phx_test_key", "anthropic-beta": UNKNOWN_BETA},
+ )
+
+ assert response.status_code == 200
+ sent = sender.call_args.args[0]
+ assert "safeguards" not in sent
+ assert sent["messages"] == body["messages"]
+
+ @patch("llm_gateway.api.anthropic.get_settings")
+ @patch("llm_gateway.api.anthropic.httpx.AsyncClient")
+ def test_count_tokens_forwards_beta(
+ self,
+ mock_httpx_client_cls: MagicMock,
+ mock_get_settings: MagicMock,
+ authenticated_client: TestClient,
+ body: dict[str, Any],
+ ) -> None:
+ mock_get_settings.return_value = MagicMock(anthropic_api_key="test-anthropic-key", request_timeout=300.0)
+ mock_client = MagicMock()
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=None)
+ mock_client.post = AsyncMock(return_value=httpx.Response(200, json={"input_tokens": 3}))
+ mock_httpx_client_cls.return_value = mock_client
+
+ response = authenticated_client.post(
+ "/v1/messages/count_tokens",
+ json=body,
+ headers={"Authorization": "Bearer phx_test_key", "anthropic-beta": UNKNOWN_BETA},
+ )
+
+ assert response.status_code == 200
+ call = mock_client.post.call_args
+ assert call.kwargs["headers"]["anthropic-beta"] == UNKNOWN_BETA
+ assert call.kwargs["json"]["safeguards"] == SAFEGUARDS