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.

feat(llm-gateway): capture reasoning effort on $ai_generation events (#69173)

Vasco de Krijgerb880d675ba80
diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.py
index 0e809beaacf5..549db3912b5a 100644
--- a/services/llm-gateway/src/llm_gateway/api/handler.py
+++ b/services/llm-gateway/src/llm_gateway/api/handler.py
@@ -26,6 +26,7 @@ from llm_gateway.request_context import (
get_posthog_properties,
get_request_id,
set_auth_user,
+ set_effort,
set_request_context,
set_time_to_first_token,
)
@@ -34,21 +35,84 @@ from llm_gateway.streaming.sse import format_sse_stream
logger = structlog.get_logger(__name__)
+def _clean_effort(value: Any) -> str | None:
+ if isinstance(value, str) and (stripped := value.strip()):
+ return stripped
+ return None
+
+
+def effort_from_output_config(request_data: dict[str, Any]) -> str | None:
+ """Anthropic Messages: ``output_config: {"effort": "..."}``."""
+ output_config = request_data.get("output_config")
+ return _clean_effort(output_config.get("effort")) if isinstance(output_config, dict) else None
+
+
+def effort_from_reasoning_effort(request_data: dict[str, Any]) -> str | None:
+ """OpenAI chat completions: top-level ``reasoning_effort``."""
+ return _clean_effort(request_data.get("reasoning_effort"))
+
+
+def effort_from_reasoning(request_data: dict[str, Any]) -> str | None:
+ """OpenAI Responses: ``reasoning: {"effort": "..."}``."""
+ reasoning = request_data.get("reasoning")
+ return _clean_effort(reasoning.get("effort")) if isinstance(reasoning, dict) else None
+
+
+def no_effort(request_data: dict[str, Any]) -> str | None:
+ """Endpoints with no reasoning-effort parameter (e.g. transcription)."""
+ return None
+
+
@dataclass
class ProviderConfig:
name: str
endpoint_name: str
+ # Where reasoning effort lives varies per API surface. Required (no default) so a new
+ # provider can't be added without deciding; see the effort_from_* functions above.
+ extract_effort: Callable[[dict[str, Any]], str | None]
-ANTHROPIC_CONFIG = ProviderConfig(name="anthropic", endpoint_name="anthropic_messages")
-BEDROCK_CONFIG = ProviderConfig(name="bedrock", endpoint_name="bedrock_messages")
-OPENAI_CONFIG = ProviderConfig(name="openai", endpoint_name="chat_completions")
-OPENAI_RESPONSES_CONFIG = ProviderConfig(name="openai", endpoint_name="responses")
-OPENAI_TRANSCRIPTION_CONFIG = ProviderConfig(name="openai", endpoint_name="audio_transcriptions")
+ANTHROPIC_CONFIG = ProviderConfig(
+ name="anthropic",
+ endpoint_name="anthropic_messages",
+ extract_effort=effort_from_output_config,
+)
+BEDROCK_CONFIG = ProviderConfig(
+ name="bedrock",
+ endpoint_name="bedrock_messages",
+ extract_effort=effort_from_output_config,
+)
+OPENAI_CONFIG = ProviderConfig(
+ name="openai",
+ endpoint_name="chat_completions",
+ extract_effort=effort_from_reasoning_effort,
+)
+OPENAI_RESPONSES_CONFIG = ProviderConfig(
+ name="openai",
+ endpoint_name="responses",
+ extract_effort=effort_from_reasoning,
+)
+OPENAI_TRANSCRIPTION_CONFIG = ProviderConfig(
+ name="openai",
+ endpoint_name="audio_transcriptions",
+ extract_effort=no_effort,
+)
# Split endpoint labels so an adapter-specific regression is distinguishable in metrics.
-CLOUDFLARE_ANTHROPIC_CONFIG = ProviderConfig(name="cloudflare", endpoint_name="cloudflare_anthropic_messages")
-CLOUDFLARE_OPENAI_CONFIG = ProviderConfig(name="cloudflare", endpoint_name="cloudflare_chat_completions")
-CLOUDFLARE_OPENAI_RESPONSES_CONFIG = ProviderConfig(name="cloudflare", endpoint_name="cloudflare_responses")
+CLOUDFLARE_ANTHROPIC_CONFIG = ProviderConfig(
+ name="cloudflare",
+ endpoint_name="cloudflare_anthropic_messages",
+ extract_effort=effort_from_output_config,
+)
+CLOUDFLARE_OPENAI_CONFIG = ProviderConfig(
+ name="cloudflare",
+ endpoint_name="cloudflare_chat_completions",
+ extract_effort=effort_from_reasoning_effort,
+)
+CLOUDFLARE_OPENAI_RESPONSES_CONFIG = ProviderConfig(
+ name="cloudflare",
+ endpoint_name="cloudflare_responses",
+ extract_effort=effort_from_reasoning,
+)
_KNOWN_LITELLM_PROVIDER_PREFIXES = (
"anthropic/",
@@ -155,6 +219,11 @@ async def handle_llm_request(
)
set_auth_user(user)
+ # Stash effort for the PostHog callback to stamp on the $ai_generation event (mirrors
+ # time_to_first_token). Set unconditionally so a stale value can't leak if the context
+ # is reused.
+ set_effort(provider_config.extract_effort(request_data))
+
structlog.contextvars.bind_contextvars(
user_id=user.user_id,
team_id=user.team_id,
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index 95134e437c7c..e7f16877ab5c 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -14,6 +14,7 @@ from llm_gateway.products.config import get_product_config
from llm_gateway.rate_limiting.cost_refresh import normalize_metric_labels
from llm_gateway.request_context import (
get_auth_user,
+ get_effort,
get_posthog_flags,
get_posthog_properties,
get_product,
@@ -73,14 +74,19 @@ def _is_product_billable(product: str) -> bool:
def _apply_owned_event_properties(properties: dict[str, Any], product: str, team_id: int | None) -> None:
"""Enforce gateway-owned event properties, run after caller `x-posthog-property-*` headers are merged.
- `ai_product` and `$ai_billable` are derived from the product config / route and must NOT be
- overridable by callers — a typo would silently mis-bill or misattribute the generation, so we
- re-assert them on top of whatever the headers set. `team_id`, in contrast, is a deliberate caller
- override (a shared-key caller such as signals sets it to the customer team); we only fall back to
- the authenticated key owner's team when no override was supplied.
+ `ai_product`, `$ai_billable`, and `$ai_effort` are gateway-derived (effort via
+ `ProviderConfig.extract_effort`) and must not be spoofable via headers, so we re-assert them
+ here and drop `$ai_effort` when the gateway found none. `team_id`, in contrast, is a
+ deliberate caller override (e.g. a shared-key caller attributing to a customer team); we only
+ fall back to the key owner's team when no override was supplied.
"""
properties["ai_product"] = product
properties["$ai_billable"] = _is_product_billable(product)
+ effort = get_effort()
+ if effort is not None:
+ properties["$ai_effort"] = effort
+ else:
+ properties.pop("$ai_effort", None)
if team_id is not None:
properties.setdefault("team_id", team_id)
# A header-supplied team_id arrives as a string ("42"); store it as an int so the captured
diff --git a/services/llm-gateway/src/llm_gateway/request_context.py b/services/llm-gateway/src/llm_gateway/request_context.py
index b816d0ff43f8..1c9bdbfd88ad 100644
--- a/services/llm-gateway/src/llm_gateway/request_context.py
+++ b/services/llm-gateway/src/llm_gateway/request_context.py
@@ -36,6 +36,7 @@ throttle_runner_var: ContextVar[ThrottleRunner | None] = ContextVar("throttle_ru
throttle_context_var: ContextVar[ThrottleContext | None] = ContextVar("throttle_context", default=None)
auth_user_var: ContextVar[AuthenticatedUser | None] = ContextVar("auth_user", default=None)
time_to_first_token_var: ContextVar[float | None] = ContextVar("time_to_first_token", default=None)
+effort_var: ContextVar[str | None] = ContextVar("effort", default=None)
def get_request_context() -> RequestContext | None:
@@ -168,6 +169,14 @@ def set_time_to_first_token(ttft: float) -> None:
time_to_first_token_var.set(ttft)
+def get_effort() -> str | None:
+ return effort_var.get()
+
+
+def set_effort(effort: str | None) -> None:
+ effort_var.set(effort)
+
+
async def record_cost(cost: float, end_user_id: str | None = None) -> None:
"""Record cost for rate limiting. Call after response completes."""
runner = throttle_runner_var.get()
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index 1af441df12fb..ebe8e611cb29 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -110,6 +110,51 @@ class TestPostHogCallback:
assert props["ai_product"] == "wizard"
mock_client.shutdown.assert_called_once()
+ @pytest.mark.parametrize(
+ "event_method, effort, caller_effort, expected",
+ [
+ # gateway-resolved effort is stamped, on both success and error events
+ ("_on_success", "medium", None, "medium"),
+ ("_on_failure", "high", None, "high"),
+ # omitted when the gateway found none
+ ("_on_success", None, None, None),
+ # gateway-owned: a caller header can neither override a resolved value...
+ ("_on_success", "medium", "spoofed", "medium"),
+ # ...nor sneak one in when the gateway found none (success and error paths)
+ ("_on_success", None, "spoofed", None),
+ ("_on_failure", None, "spoofed", None),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_effort_is_gateway_owned(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ event_method: str,
+ effort: str | None,
+ caller_effort: str | None,
+ expected: str | None,
+ ) -> None:
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+ caller_props = {"$ai_effort": caller_effort} if caller_effort is not None else {}
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch("llm_gateway.callbacks.posthog.get_product", return_value="posthog_code"),
+ patch("llm_gateway.callbacks.posthog.get_effort", return_value=effort),
+ patch("llm_gateway.callbacks.posthog.get_posthog_properties", return_value=caller_props),
+ ):
+ await getattr(callback, event_method)(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ if expected is None:
+ assert "$ai_effort" not in props
+ else:
+ assert props["$ai_effort"] == expected
+
@pytest.mark.asyncio
async def test_on_success_header_team_id_overrides_auth_user_team(
self,
diff --git a/services/llm-gateway/tests/test_handler.py b/services/llm-gateway/tests/test_handler.py
new file mode 100644
index 000000000000..3aab95953453
--- /dev/null
+++ b/services/llm-gateway/tests/test_handler.py
@@ -0,0 +1,106 @@
+from collections.abc import Iterator
+from typing import Any
+
+import pytest
+
+from llm_gateway.api.handler import (
+ ANTHROPIC_CONFIG,
+ BEDROCK_CONFIG,
+ CLOUDFLARE_ANTHROPIC_CONFIG,
+ CLOUDFLARE_OPENAI_CONFIG,
+ CLOUDFLARE_OPENAI_RESPONSES_CONFIG,
+ OPENAI_CONFIG,
+ OPENAI_RESPONSES_CONFIG,
+ OPENAI_TRANSCRIPTION_CONFIG,
+ ProviderConfig,
+ effort_from_output_config,
+ effort_from_reasoning,
+ effort_from_reasoning_effort,
+ handle_llm_request,
+ no_effort,
+)
+from llm_gateway.auth.models import AuthenticatedUser
+from llm_gateway.request_context import effort_var, get_effort
+
+
+class TestEffortExtractors:
+ @pytest.mark.parametrize(
+ "extractor, request_data, expected",
+ [
+ # Anthropic Messages: output_config.effort
+ (effort_from_output_config, {"output_config": {"effort": "medium"}}, "medium"),
+ (effort_from_output_config, {"output_config": {"effort": " medium "}}, "medium"),
+ # Structured-outputs-only request (format, no effort)
+ (effort_from_output_config, {"output_config": {"format": {"type": "json_schema"}}}, None),
+ (effort_from_output_config, {"output_config": "not-a-dict"}, None),
+ (effort_from_output_config, {"output_config": {"effort": 5}}, None),
+ (effort_from_output_config, {}, None),
+ # OpenAI chat completions: reasoning_effort
+ (effort_from_reasoning_effort, {"reasoning_effort": "high"}, "high"),
+ (effort_from_reasoning_effort, {"reasoning_effort": " "}, None),
+ # Permissive: a newly-introduced level passes through
+ (effort_from_reasoning_effort, {"reasoning_effort": "ultra"}, "ultra"),
+ (effort_from_reasoning_effort, {}, None),
+ # OpenAI Responses: reasoning.effort
+ (effort_from_reasoning, {"reasoning": {"effort": "xhigh"}}, "xhigh"),
+ (effort_from_reasoning, {"reasoning": "not-a-dict"}, None),
+ (effort_from_reasoning, {}, None),
+ # Endpoints without an effort param ignore everything
+ (no_effort, {"reasoning_effort": "high"}, None),
+ ],
+ )
+ def test_extractor(self, extractor: Any, request_data: dict[str, Any], expected: str | None) -> None:
+ assert extractor(request_data) == expected
+
+
+class TestEffortInstrumentation:
+ @pytest.fixture(autouse=True)
+ def reset_effort(self) -> Iterator[None]:
+ token = effort_var.set(None)
+ yield
+ effort_var.reset(token)
+
+ # One case per real config with its surface's natural request shape, so miswiring any
+ # config to the wrong extractor (silently dropping $ai_effort for that surface) fails here.
+ @pytest.mark.parametrize(
+ "provider_config, request_data, expected",
+ [
+ (ANTHROPIC_CONFIG, {"output_config": {"effort": "medium"}}, "medium"),
+ (BEDROCK_CONFIG, {"output_config": {"effort": "low"}}, "low"),
+ (OPENAI_CONFIG, {"reasoning_effort": "high"}, "high"),
+ (OPENAI_RESPONSES_CONFIG, {"reasoning": {"effort": "xhigh"}}, "xhigh"),
+ (OPENAI_TRANSCRIPTION_CONFIG, {"reasoning_effort": "high"}, None),
+ (CLOUDFLARE_ANTHROPIC_CONFIG, {"output_config": {"effort": "medium"}}, "medium"),
+ (CLOUDFLARE_OPENAI_CONFIG, {"reasoning_effort": "high"}, "high"),
+ (CLOUDFLARE_OPENAI_RESPONSES_CONFIG, {"reasoning": {"effort": "xhigh"}}, "xhigh"),
+ # No effort in the request resets any stale context value to None
+ (ANTHROPIC_CONFIG, {}, None),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_effort_from_request_reaches_context(
+ self,
+ authenticated_user: AuthenticatedUser,
+ provider_config: ProviderConfig,
+ request_data: dict[str, Any],
+ expected: str | None,
+ ) -> None:
+ # Pre-seed a stale value: handle_llm_request must set effort unconditionally, so the
+ # no-effort case resets to None rather than leaking the stale value into the callback.
+ effort_var.set("stale")
+ captured: dict[str, Any] = {}
+
+ async def mock_llm_call(**kwargs: Any) -> dict[str, Any]:
+ captured["effort"] = get_effort()
+ return {"ok": True}
+
+ await handle_llm_request(
+ request_data=request_data,
+ user=authenticated_user,
+ model="test-model",
+ is_streaming=False,
+ provider_config=provider_config,
+ llm_call=mock_llm_call,
+ )
+
+ assert captured["effort"] == expected