: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): fix thinking-enabled 400s on open source models (#78165)
Peter Kirkhama695e371acb8
diff --git a/services/llm-gateway/src/llm_gateway/anthropic_request.py b/services/llm-gateway/src/llm_gateway/anthropic_request.pyindex a8b22119e353..96593fff0673 100644--- a/services/llm-gateway/src/llm_gateway/anthropic_request.py+++ b/services/llm-gateway/src/llm_gateway/anthropic_request.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom typing import Any, Final+from litellm.litellm_core_utils.reasoning_effort_utils import reasoning_effort_from_thinking_budget+from llm_gateway.metrics.prometheus import CLEAR_THINKING_EDIT_DROPPEDCLEAR_THINKING_EDIT: Final[str] = "clear_thinking_20251015"@@ -26,6 +28,31 @@ def enable_required_opus_5_thinking(request_data: dict[str, Any]) -> dict[str, Areturn {**request_data, "thinking": {"type": "adaptive"}}+def convert_enabled_thinking_to_adaptive(request_data: dict[str, Any]) -> dict[str, Any]:+ """Swap enabled thinking for adaptive so litellm keeps the request on chat/completions.++ litellm's Anthropic->chat/completions adapter reroutes provider="openai" requests carrying+ `thinking: {"type": "enabled"}` through OpenAI's native Responses API by prefixing the model+ with "responses/". Our OpenAI-compatible backends (Cloudflare, Modal, Baseten) only serve+ chat/completions, and the prefixed model id fails litellm's provider lookup with a 400+ ("LLM Provider NOT provided"). Adaptive thinking translates to `reasoning_effort` without the+ reroute; the budget maps to `output_config.effort` with litellm's own thresholds, so the+ request carries the same effort the enabled-thinking translation would have produced.+ """+ thinking = request_data.get("thinking")+ if not isinstance(thinking, dict) or thinking.get("type") != "enabled":+ return request_data++ normalized = {**request_data, "thinking": {"type": "adaptive"}}+ output_config = normalized.get("output_config")+ output_config = dict(output_config) if isinstance(output_config, dict) else {}+ if not output_config.get("effort"):+ budget = thinking.get("budget_tokens")+ output_config["effort"] = reasoning_effort_from_thinking_budget(budget if isinstance(budget, int) else 0)+ normalized["output_config"] = output_config+ return normalized++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.diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.pyindex 76ada99bc85d..5d1bf2296432 100644--- a/services/llm-gateway/src/llm_gateway/baseten.py+++ b/services/llm-gateway/src/llm_gateway/baseten.py@@ -9,6 +9,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (LiteLLMMessagesToCompletionTransformationHandler,)+from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptivefrom llm_gateway.anthropic_stream import observe_anthropic_streamfrom llm_gateway.config import Settings@@ -56,6 +57,7 @@ def _inject_baseten_params(kwargs: dict[str, Any], api_base: str, api_key: str)def make_baseten_anthropic_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:async def llm_call(**kwargs: Any) -> Any:+ kwargs = convert_enabled_thinking_to_adaptive(kwargs)_inject_baseten_params(kwargs, api_base, api_key)response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)if isinstance(response, AsyncIterator):diff --git a/services/llm-gateway/src/llm_gateway/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.pyindex 993462073751..f30ade2d1345 100644--- a/services/llm-gateway/src/llm_gateway/cloudflare.py+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py@@ -11,6 +11,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (LiteLLMMessagesToCompletionTransformationHandler,)+from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptivefrom llm_gateway.anthropic_stream import observe_anthropic_streamfrom llm_gateway.config import Settingsfrom llm_gateway.rate_limiting.cost_refresh import COST_ALIASES@@ -96,6 +97,7 @@ def make_cloudflare_anthropic_call(api_base: str, api_key: str) -> Callable[...,"""async def llm_call(**kwargs: Any) -> Any:+ kwargs = convert_enabled_thinking_to_adaptive(kwargs)_inject_cloudflare_params(kwargs, api_base, api_key)response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)if isinstance(response, AsyncIterator):diff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.pyindex e9afaface43c..21c39d82cda1 100644--- a/services/llm-gateway/src/llm_gateway/modal.py+++ b/services/llm-gateway/src/llm_gateway/modal.py@@ -13,6 +13,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (LiteLLMMessagesToCompletionTransformationHandler,)+from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptivefrom llm_gateway.anthropic_stream import observe_anthropic_streamfrom llm_gateway.config import Settings, _normalize_cost_key@@ -144,6 +145,7 @@ 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:+ kwargs = convert_enabled_thinking_to_adaptive(kwargs)_inject_modal_params(kwargs, api_base, modal_key, modal_secret)response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)if isinstance(response, AsyncIterator):diff --git a/services/llm-gateway/tests/test_anthropic_request.py b/services/llm-gateway/tests/test_anthropic_request.pyindex ad8e3f9d0d38..1bc72bdfd118 100644--- a/services/llm-gateway/tests/test_anthropic_request.py+++ b/services/llm-gateway/tests/test_anthropic_request.py@@ -2,7 +2,11 @@ from typing import Anyimport pytest-from llm_gateway.anthropic_request import drop_orphaned_clear_thinking, enable_required_opus_5_thinking+from llm_gateway.anthropic_request import (+ convert_enabled_thinking_to_adaptive,+ drop_orphaned_clear_thinking,+ enable_required_opus_5_thinking,+)from llm_gateway.metrics.prometheus import CLEAR_THINKING_EDIT_DROPPEDPRODUCT = "posthog_code"@@ -39,6 +43,53 @@ def test_other_thinking_configurations_are_untouched(model: str, effort: str, thassert enable_required_opus_5_thinking(request) is request+ ("thinking", "output_config", "expected_output_config"),+ [+ pytest.param({"type": "enabled", "budget_tokens": 31999}, None, {"effort": "high"}, id="large_budget_high"),+ pytest.param({"type": "enabled", "budget_tokens": 2048}, None, {"effort": "medium"}, id="medium_budget"),+ pytest.param({"type": "enabled", "budget_tokens": 1024}, None, {"effort": "low"}, id="small_budget_low"),+ pytest.param({"type": "enabled"}, None, {"effort": "minimal"}, id="missing_budget_minimal"),+ pytest.param(+ {"type": "enabled", "budget_tokens": 1024}, {"effort": "max"}, {"effort": "max"}, id="explicit_effort_wins"+ ),+ ],+)+def test_enabled_thinking_becomes_adaptive_with_budget_derived_effort(+ thinking: dict[str, Any],+ output_config: dict[str, Any] | None,+ expected_output_config: dict[str, Any],+) -> None:+ request = {+ "model": "deepseek-ai/deepseek-v4-flash-0731",+ "messages": [{"role": "user", "content": "hi"}],+ "thinking": thinking,+ **({"output_config": output_config} if output_config else {}),+ }++ normalized = convert_enabled_thinking_to_adaptive(request)++ assert normalized["thinking"] == {"type": "adaptive"}+ assert normalized["output_config"] == expected_output_config+ assert request["thinking"] == thinking+++ "thinking",+ [+ pytest.param(None, id="absent"),+ pytest.param({"type": "disabled"}, id="disabled"),+ pytest.param({"type": "adaptive"}, id="already_adaptive"),+ ],+)+def test_non_enabled_thinking_is_untouched(thinking: dict[str, Any] | None) -> None:+ request: dict[str, Any] = {"model": "moonshotai/kimi-k3", "messages": []}+ if thinking is not None:+ request["thinking"] = thinking++ assert convert_enabled_thinking_to_adaptive(request) is request++def _dropped_count(product: str) -> float:return CLEAR_THINKING_EDIT_DROPPED.labels(product=product)._value.get()diff --git a/services/llm-gateway/tests/test_inference_routing.py b/services/llm-gateway/tests/test_inference_routing.pyindex 2b5c076ae95b..7a60b7f236a3 100644--- a/services/llm-gateway/tests/test_inference_routing.py+++ b/services/llm-gateway/tests/test_inference_routing.py@@ -3,9 +3,14 @@ from unittest.mock import AsyncMock, patchimport pytestfrom fastapi import HTTPException+from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (+ LiteLLMMessagesToCompletionTransformationHandler,+)from llm_gateway.api.handler import ProviderErrorfrom llm_gateway.auth.models import AuthenticatedUser+from llm_gateway.baseten import make_baseten_anthropic_call+from llm_gateway.cloudflare import make_cloudflare_anthropic_callfrom llm_gateway.config import Settingsfrom llm_gateway.inference_routing import (normalize_glm_anthropic_request,@@ -13,6 +18,7 @@ from llm_gateway.inference_routing import (send_inference_chat_completions,send_inference_responses,)+from llm_gateway.modal import make_modal_anthropic_callfrom llm_gateway.request_context import RequestContext, set_request_contextGLM_MODEL = "@cf/zai-org/glm-5.2"@@ -263,3 +269,33 @@ async def test_provider_failure_propagates_without_cross_backend_retry(await _send(settings, handle, flag=flag)assert exc_info.value.status_code == 502assert _called_providers(handle) == [expected_provider]+++ ("make_call", "model"),+ [+ pytest.param(+ lambda: make_cloudflare_anthropic_call("https://cf.test/v1", "cf-key"), GLM_MODEL, id="cloudflare"+ ),+ pytest.param(+ lambda: make_modal_anthropic_call("https://modal.test/v1", "wk", "ws"), "moonshotai/kimi-k3", id="modal"+ ),+ pytest.param(+ lambda: make_baseten_anthropic_call("https://baseten.test/v1", "bt-key"), DEEPSEEK_MODEL, id="baseten"+ ),+ ],+)+async def test_anthropic_calls_convert_enabled_thinking_to_adaptive(make_call: Any, model: str) -> None:+ # litellm reroutes provider="openai" requests with enabled thinking through OpenAI's Responses+ # API ("responses/" model prefix), which 400s on these chat/completions-only backends.+ handler = AsyncMock(return_value={"ok": True})+ with patch.object(LiteLLMMessagesToCompletionTransformationHandler, "async_anthropic_messages_handler", handler):+ await make_call()(+ model=model,+ messages=[{"role": "user", "content": "hi"}],+ max_tokens=64,+ thinking={"type": "enabled", "budget_tokens": 31999},+ )++ assert handler.call_args.kwargs["thinking"] == {"type": "adaptive"}+ assert handler.call_args.kwargs["output_config"] == {"effort": "high"}