: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
feat(signals): add ai-gateway client and per-call opt-in for signals LLM calls (#71947)
Brandon922b6110f606
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.pyindex d67fa71f4f79..868f2aec6988 100644--- a/posthog/llm/gateway_client.py+++ b/posthog/llm/gateway_client.py@@ -191,16 +191,38 @@ def resolve_ai_gateway_config() -> tuple[str, str] | None:return url, api_key+def _ai_property_headers(**labels: str | None) -> dict[str, str] | None:+ """Build the ``X-PostHog-Properties`` header from caller labels, dropping unset ones.++ The slugless Go gateway reads event labels only from this JSON blob, not from the+ ``x-posthog-property-<key>`` per-header form the Python gateway accepts. Don't use a+ ``$ai_`` prefix on a key: the gateway strips those as reserved. Returns None when no+ label is set so the client sends no properties header.+ """+ set_labels = {key: value for key, value in labels.items() if value}+ if not set_labels:+ return None+ return {"X-PostHog-Properties": json.dumps(set_labels)}++def ai_product_headers(ai_product: str | None) -> dict[str, str] | None:"""X-PostHog-Properties header tagging the captured generation with its AIO product.The slugless Go gateway has no product route, so callers pass the product here to keep- per-product attribution on the shared ``phs_`` token. Don't use a ``$ai_`` prefix — the- gateway strips those as reserved.+ per-product attribution on the shared ``phs_`` token."""- if not ai_product:- return None- return {"X-PostHog-Properties": json.dumps({"ai_product": ai_product})}+ return _ai_property_headers(ai_product=ai_product)+++def _anthropic_gateway_base_url(openai_base_url: str) -> str:+ """Drop the OpenAI ``/v1`` suffix so the Anthropic SDK, which appends ``/v1/messages``+ itself, hits the same gateway root the OpenAI route uses. ``resolve_ai_gateway_config``+ guarantees the ``/v1`` suffix, so this is the inverse of that validation.+ """+ trimmed = openai_base_url.rstrip("/")+ if trimmed.endswith("/v1"):+ trimmed = trimmed[: -len("/v1")]+ return trimmeddef build_openai_client(product: Product, ai_product: str | None = None) -> OpenAI:@@ -236,3 +258,41 @@ def build_async_openai_client(product: Product, ai_product: str | None = None) -http_client=httpx.AsyncClient(trust_env=False),)return get_async_llm_client(product)+++def build_async_anthropic_client(+ product: Product,+ ai_product: str | None = None,+ ai_stage: str | None = None,+ team_id: int | None = None,+ use_bedrock_fallback: bool = False,+) -> AsyncAnthropic:+ """Return a raw Anthropic client routed through the internal Go ai-gateway when configured,+ else the Python LLM gateway via :func:`get_async_anthropic_gateway_client`.++ In gateway mode the ``ai_product``, ``ai_stage``, and ``team_id`` labels ride on the+ ``X-PostHog-Properties`` JSON blob: the Go gateway ignores the ``x-posthog-property-<key>``+ per-header form the Python gateway reads, so they would be dropped if passed that way.+ ``team_id`` is the customer team the generation is attributed to (the usage report reads it as+ a property); it does not change the event's owning project, which the gateway derives from the+ ``phs_`` bearer. The Anthropic SDK appends ``/v1/messages``, so the client gets the gateway+ root rather than the ``/v1`` OpenAI base.++ ``use_bedrock_fallback`` only affects the Python-gateway fallback path; the Go gateway fails+ over to Bedrock on its own via the host breaker and reads no opt-in header. trust_env=False+ keeps the in-cluster call off the egress proxy.+ """+ gateway = resolve_ai_gateway_config()+ if gateway:+ url, api_key = gateway+ return AsyncAnthropic(+ api_key=api_key,+ base_url=_anthropic_gateway_base_url(url),+ default_headers=_ai_property_headers(+ ai_product=ai_product,+ ai_stage=ai_stage,+ team_id=str(team_id) if team_id is not None else None,+ ),+ http_client=httpx.AsyncClient(trust_env=False),+ )+ return get_async_anthropic_gateway_client(product, team_id=team_id, use_bedrock_fallback=use_bedrock_fallback)diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.pyindex 13bd3866c643..d50d80200a96 100644--- a/posthog/llm/test_gateway_client.py+++ b/posthog/llm/test_gateway_client.py@@ -8,6 +8,7 @@ from django.test import override_settingsfrom posthog.llm.gateway_client import (Product,+ build_async_anthropic_client,build_async_openai_client,build_openai_client,get_async_anthropic_gateway_client,@@ -250,3 +251,58 @@ class TestBuildAsyncOpenAIClient:mock_get_async.assert_called_once_with("llma_eval_summary")assert result is mock_get_async.return_value+++class TestBuildAsyncAnthropicClient:+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)+ @patch("posthog.llm.gateway_client.httpx.AsyncClient")+ @patch("posthog.llm.gateway_client.AsyncAnthropic")+ def test_gateway_mode_strips_v1_and_labels_product_stage_and_team(self, mock_anthropic, mock_httpx):+ result = build_async_anthropic_client(+ "signals", ai_product="signals_grouping", ai_stage="match", team_id=42, use_bedrock_fallback=True+ )++ mock_httpx.assert_called_once_with(trust_env=False)+ mock_anthropic.assert_called_once_with(+ api_key=AI_GATEWAY_KEY,+ # The Anthropic SDK appends /v1/messages, so the /v1 OpenAI suffix is stripped.+ base_url="https://ai-gateway.example",+ # team_id rides as a property (usage report reads it) since the Go gateway drops the+ # per-key header form.+ default_headers={+ "X-PostHog-Properties": json.dumps(+ {"ai_product": "signals_grouping", "ai_stage": "match", "team_id": "42"}+ )+ },+ http_client=mock_httpx.return_value,+ )+ assert result is mock_anthropic.return_value++ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)+ @patch("posthog.llm.gateway_client.httpx.AsyncClient")+ @patch("posthog.llm.gateway_client.AsyncAnthropic")+ def test_gateway_mode_omits_stage_when_unset(self, mock_anthropic, mock_httpx):+ build_async_anthropic_client("signals", ai_product="signals")++ _, kwargs = mock_anthropic.call_args+ assert kwargs["default_headers"] == {"X-PostHog-Properties": json.dumps({"ai_product": "signals"})}++ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")+ @patch("posthog.llm.gateway_client.get_async_anthropic_gateway_client")+ def test_falls_back_to_python_anthropic_gateway_when_unset(self, mock_get_anthropic):+ result = build_async_anthropic_client(+ "signals", ai_product="signals_grouping", ai_stage="match", team_id=42, use_bedrock_fallback=True+ )++ # Fallback keeps the Python-gateway signature: route-derived product plus the passthrough knobs.+ mock_get_anthropic.assert_called_once_with("signals", team_id=42, use_bedrock_fallback=True)+ assert result is mock_get_anthropic.return_value++ @override_settings(AI_GATEWAY_URL="https://ai-gateway.example", AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)+ @patch("posthog.llm.gateway_client.get_async_anthropic_gateway_client")+ def test_misconfig_falls_back_to_python_anthropic_gateway(self, mock_get_anthropic):+ # URL missing the /v1 base path is a misconfig: resolve returns None and the caller falls back.+ result = build_async_anthropic_client("signals", ai_product="signals_grouping")++ mock_get_anthropic.assert_called_once_with("signals", team_id=None, use_bedrock_fallback=False)+ assert result is mock_get_anthropic.return_valuediff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.pyindex 5ec8e452e6c6..69f779c6b9fc 100644--- a/products/signals/backend/temporal/llm.py+++ b/products/signals/backend/temporal/llm.py@@ -8,7 +8,11 @@ import structlogfrom anthropic.types import MessageParamfrom posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model-from posthog.llm.gateway_client import get_async_anthropic_gateway_client+from posthog.llm.gateway_client import (+ build_async_anthropic_client,+ get_async_anthropic_gateway_client,+ resolve_ai_gateway_config,+)from products.signals.backend.temporal import metrics@@ -86,10 +90,23 @@ async def call_llm(temperature: Optional[float] = 0.2,retries: int = MAX_RETRIES,stage: Optional[str] = None,+ ai_product: Optional[str] = None,) -> T:# Native Anthropic Messages endpoint so prefilling and extended thinking carry over unchanged.thinking = thinking and MATCHING_MODEL in ANTHROPIC_THINKING_MODELS- client = get_async_anthropic_gateway_client(product="signals", team_id=team_id, use_bedrock_fallback=True)+ # A call site opts onto the Go ai-gateway by passing ai_product, which both routes it through+ # the gateway-capable client and tags the generation. Without it the call stays on the Python+ # gateway, so each product is switched (and reverted) independently.+ if ai_product is not None:+ client = build_async_anthropic_client(+ product="signals",+ ai_product=ai_product,+ ai_stage=stage,+ team_id=team_id,+ use_bedrock_fallback=True,+ )+ else:+ client = get_async_anthropic_gateway_client(product="signals", team_id=team_id, use_bedrock_fallback=True)messages: list[MessageParam] = [{"role": "user", "content": user_prompt},@@ -110,7 +127,12 @@ async def call_llm(}if team_id is not None:create_kwargs["metadata"] = {"user_id": f"team-{team_id}"}- if stage:+ # The per-key ai_stage header is what the Python gateway reads. Send it whenever the request+ # lands there: an un-opted call site, or an opted one before the gateway env is set. Skip it+ # only when an opted call site actually reaches the Go gateway, which reads ai_stage from the+ # X-PostHog-Properties blob instead.+ on_go_gateway = ai_product is not None and resolve_ai_gateway_config() is not None+ if stage and not on_go_gateway:create_kwargs["extra_headers"] = {"x-posthog-property-ai_stage": stage}# Later, we'll want to tune how many tokens we give over to thinking vs. producing output. Hard-coded for now.diff --git a/products/signals/backend/test/test_llm.py b/products/signals/backend/test/test_llm.pynew file mode 100644index 000000000000..d45445f96810--- /dev/null+++ b/products/signals/backend/test/test_llm.py@@ -0,0 +1,77 @@+import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from django.test import override_settings++from products.signals.backend.temporal.llm import call_llm++MODULE_PATH = "products.signals.backend.temporal.llm"+++def _text_response(text: str) -> MagicMock:+ block = MagicMock()+ block.type = "text"+ block.text = text+ response = MagicMock()+ response.content = [block]+ return response+++def _mock_anthropic_client() -> MagicMock:+ client = MagicMock()+ client.messages.create = AsyncMock(return_value=_text_response("ok"))+ return client+++@override_settings(AI_GATEWAY_URL="https://ai-gateway.example/v1", AI_GATEWAY_API_KEY="phs_test")+async def test_gateway_mode_omits_legacy_stage_header():+ client = _mock_anthropic_client()+ with patch(f"{MODULE_PATH}.build_async_anthropic_client", return_value=client):+ await call_llm(+ team_id=1,+ system_prompt="s",+ user_prompt="u",+ validate=lambda text: text,+ stage="match",+ ai_product="signals_grouping",+ )++ # In gateway mode the labels ride on the builder's X-PostHog-Properties blob; the per-key+ # ai_stage header (which the Go gateway drops) must not be sent.+ assert "extra_headers" not in client.messages.create.call_args.kwargs+++@override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")+async def test_fallback_mode_sends_legacy_stage_header():+ client = _mock_anthropic_client()+ with patch(f"{MODULE_PATH}.build_async_anthropic_client", return_value=client):+ await call_llm(+ team_id=1,+ system_prompt="s",+ user_prompt="u",+ validate=lambda text: text,+ stage="match",+ ai_product="signals_grouping",+ )++ # On the Python-gateway fallback the stage still rides as a per-key header the route reads.+ assert client.messages.create.call_args.kwargs["extra_headers"] == {"x-posthog-property-ai_stage": "match"}+++@override_settings(AI_GATEWAY_URL="https://ai-gateway.example/v1", AI_GATEWAY_API_KEY="phs_test")+async def test_without_ai_product_stays_on_python_gateway_even_with_env_set():+ client = _mock_anthropic_client()+ with (+ patch(f"{MODULE_PATH}.get_async_anthropic_gateway_client", return_value=client) as legacy,+ patch(f"{MODULE_PATH}.build_async_anthropic_client") as gateway,+ ):+ await call_llm(team_id=1, system_prompt="s", user_prompt="u", validate=lambda text: text, stage="match")++ # A call site that hasn't opted in (no ai_product) never touches the Go-gateway builder, even+ # with the env configured, and keeps the legacy per-key stage header.+ legacy.assert_called_once()+ gateway.assert_not_called()+ assert client.messages.create.call_args.kwargs["extra_headers"] == {"x-posthog-property-ai_stage": "match"}