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(signals): route grouping through the ai-gateway (#71948)

Brandon12fbb039d565
diff --git a/products/signals/backend/emission/pipeline.py b/products/signals/backend/emission/pipeline.py
index 6b479706a86a..db7a0fcf9b36 100644
--- a/products/signals/backend/emission/pipeline.py
+++ b/products/signals/backend/emission/pipeline.py
@@ -12,7 +12,7 @@ from temporalio import activity
from temporalio.exceptions import ApplicationError
from posthog.event_usage import groups
-from posthog.llm.gateway_client import get_async_anthropic_gateway_client
+from posthog.llm.gateway_client import build_async_anthropic_client, resolve_ai_gateway_config
from posthog.models import Organization, Team
from posthog.sync import database_sync_to_async
@@ -22,6 +22,8 @@ from products.signals.backend.facade.api import emit_signal
logger = structlog.get_logger(__name__)
LLM_MODEL = "claude-sonnet-4-5"
+# ai_product label for the emission-stage generations (summarization, actionability).
+EMISSION_AI_PRODUCT = "signals_emission"
# Concurrent LLM calls limit for actionability/summarization checks
LLM_CONCURRENCY_LIMIT = 20
# Concurrent workflow spawns for signal emission
@@ -41,22 +43,35 @@ LLM_RETRY_BACKOFF_COEFFICIENT = 2.0
LLM_MAX_OUTPUT_TOKENS = 8192
-def _signals_extra_headers(output: SignalEmitterOutput, stage: str) -> dict[str, str]:
- """Per-call event properties that ride along to the gateway as headers.
+def _signals_extra_headers(
+ output: SignalEmitterOutput, stage: str, gateway_mode: bool | None = None, team_id: int | None = None
+) -> dict[str, str]:
+ """Per-call event properties for the emission-stage generation.
- The `team_id` header is set as a default on the client at construction time,
- so it doesn't need to be repeated here. See posthog/llm/gateway_client.py.
+ In Go-gateway mode the labels ride on the `X-PostHog-Properties` JSON blob and the caller owns
+ `ai_product` (the slugless gateway has no product route) and `team_id` (the customer team the
+ usage report attributes spend to). Because this per-call blob replaces any client default, it
+ carries `team_id` itself rather than relying on the client's default header. The Go gateway
+ drops the `x-posthog-property-<key>` per-header form, so that shape is only used on the
+ Python-gateway fallback, where the route derives `ai_product`/`$ai_billable` and the client's
+ default header carries `team_id`.
- `ai_product` and `$ai_billable` are intentionally NOT set here: the gateway
- derives both from the `signals` product config (the route path sets
- `ai_product=signals` and `billable=True`). Passing them as headers would let a
- typo silently misattribute or mis-bill the generation, so we let the gateway own them.
+ `gateway_mode` is resolved once per batch by the caller and threaded in; left None it
+ self-resolves, which the direct-call tests rely on.
"""
- return {
- "x-posthog-property-ai_stage": stage,
- "x-posthog-property-source_product": output.source_product,
- "x-posthog-property-source_type": output.source_type,
+ if gateway_mode is None:
+ gateway_mode = resolve_ai_gateway_config() is not None
+ labels = {
+ "ai_stage": stage,
+ "source_product": output.source_product,
+ "source_type": output.source_type,
}
+ if gateway_mode:
+ blob = {"ai_product": EMISSION_AI_PRODUCT, **labels}
+ if team_id is not None:
+ blob["team_id"] = str(team_id)
+ return {"X-PostHog-Properties": json.dumps(blob)}
+ return {f"x-posthog-property-{key}": value for key, value in labels.items()}
def _extract_text(response: Any) -> str:
@@ -136,11 +151,12 @@ async def _summarize_description(
output: SignalEmitterOutput,
summarization_prompt: str,
threshold: int,
+ gateway_mode: bool | None = None,
) -> SignalEmitterOutput:
messages: list[MessageParam] = [
{"role": "user", "content": summarization_prompt.format(description=output.description, max_length=threshold)}
]
- extra_headers = _signals_extra_headers(output, stage="summarization")
+ extra_headers = _signals_extra_headers(output, stage="summarization", gateway_mode=gateway_mode, team_id=team_id)
for attempt in range(LLM_MAX_ATTEMPTS):
if attempt > 0:
await asyncio.sleep(LLM_RETRY_INITIAL_DELAY_SECONDS * (LLM_RETRY_BACKOFF_COEFFICIENT ** (attempt - 1)))
@@ -201,7 +217,8 @@ async def summarize_long_descriptions(
needs_summary = [i for i, output in enumerate(outputs) if len(output.description) > threshold]
if not needs_summary:
return outputs
- client = get_async_anthropic_gateway_client(product="signals", team_id=team.id)
+ client = build_async_anthropic_client(product="signals", ai_product=EMISSION_AI_PRODUCT, team_id=team.id)
+ gateway_mode = resolve_ai_gateway_config() is not None
semaphore = asyncio.Semaphore(LLM_CONCURRENCY_LIMIT)
_safe_heartbeat()
completed_count = 0
@@ -210,7 +227,9 @@ async def summarize_long_descriptions(
nonlocal completed_count
async with semaphore:
try:
- result = await _summarize_description(client, team.id, output, summarization_prompt, threshold)
+ result = await _summarize_description(
+ client, team.id, output, summarization_prompt, threshold, gateway_mode=gateway_mode
+ )
except Exception:
logger.exception(
"Summarization failed, skipping signal",
@@ -250,9 +269,10 @@ async def _check_actionability(
team_id: int,
output: SignalEmitterOutput,
actionability_prompt: str,
+ gateway_mode: bool | None = None,
) -> bool:
prompt = actionability_prompt.format(description=output.description)
- extra_headers = _signals_extra_headers(output, stage="actionability")
+ extra_headers = _signals_extra_headers(output, stage="actionability", gateway_mode=gateway_mode, team_id=team_id)
for attempt in range(LLM_MAX_ATTEMPTS):
if attempt > 0:
await asyncio.sleep(LLM_RETRY_INITIAL_DELAY_SECONDS * (LLM_RETRY_BACKOFF_COEFFICIENT ** (attempt - 1)))
@@ -291,7 +311,8 @@ async def filter_actionable(
actionability_prompt: str,
extra: dict[str, Any],
) -> list[SignalEmitterOutput]:
- client = get_async_anthropic_gateway_client(product="signals", team_id=team.id)
+ client = build_async_anthropic_client(product="signals", ai_product=EMISSION_AI_PRODUCT, team_id=team.id)
+ gateway_mode = resolve_ai_gateway_config() is not None
semaphore = asyncio.Semaphore(LLM_CONCURRENCY_LIMIT)
_safe_heartbeat()
checked_count = 0
@@ -300,7 +321,9 @@ async def filter_actionable(
nonlocal checked_count
async with semaphore:
try:
- result = await _check_actionability(client, team.id, output, actionability_prompt)
+ result = await _check_actionability(
+ client, team.id, output, actionability_prompt, gateway_mode=gateway_mode
+ )
except Exception:
logger.exception(
"Actionability check failed, assuming actionable",
diff --git a/products/signals/backend/emission/tests/test_emit_signals.py b/products/signals/backend/emission/tests/test_emit_signals.py
index e38397f0e70b..f855a88f039b 100644
--- a/products/signals/backend/emission/tests/test_emit_signals.py
+++ b/products/signals/backend/emission/tests/test_emit_signals.py
@@ -7,6 +7,8 @@ from typing import Any
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
import temporalio.worker
from temporalio import activity
from temporalio.testing import WorkflowEnvironment
@@ -310,6 +312,28 @@ class TestCheckActionability:
assert "x-posthog-property-ai_product" not in headers
assert "x-posthog-property-$ai_billable" not in headers
+ @pytest.mark.asyncio
+ @override_settings(AI_GATEWAY_URL="https://ai-gateway.example/v1", AI_GATEWAY_API_KEY="phs_test")
+ async def test_gateway_mode_labels_ride_on_properties_blob(self):
+ mock_client = MagicMock()
+ mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
+
+ output = _make_output(source_id="42")
+ await _check_actionability(mock_client, 7, output, "Is this actionable? {description}")
+
+ headers = mock_client.messages.create.call_args.kwargs["extra_headers"]
+ # The Go gateway reads labels only from X-PostHog-Properties; the per-key headers are gone.
+ # The blob owns ai_product (no product route) and team_id (the customer team the usage
+ # report attributes to), since the per-call blob replaces the client default.
+ assert "x-posthog-property-ai_stage" not in headers
+ assert json.loads(headers["X-PostHog-Properties"]) == {
+ "ai_product": "signals_emission",
+ "ai_stage": "actionability",
+ "source_product": output.source_product,
+ "source_type": output.source_type,
+ "team_id": "7",
+ }
+
class TestFilterActionable:
@pytest.mark.asyncio
@@ -334,7 +358,7 @@ class TestFilterActionable:
mock_client.messages.create = mock_create
with (
- patch(f"{PIPELINE_MODULE_PATH}.get_async_anthropic_gateway_client", return_value=mock_client),
+ patch(f"{PIPELINE_MODULE_PATH}.build_async_anthropic_client", return_value=mock_client),
patch(f"{PIPELINE_MODULE_PATH}.activity"),
):
result = await filter_actionable(team, outputs, "prompt {description}", extra={})
@@ -431,7 +455,7 @@ class TestSummarizeLongDescriptions:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response("Summarized."))
with (
- patch(f"{PIPELINE_MODULE_PATH}.get_async_anthropic_gateway_client", return_value=mock_client),
+ patch(f"{PIPELINE_MODULE_PATH}.build_async_anthropic_client", return_value=mock_client),
patch(f"{PIPELINE_MODULE_PATH}.activity"),
):
result = await summarize_long_descriptions(team, [short, long], self.PROMPT, self.THRESHOLD, extra={})
@@ -589,7 +613,7 @@ class TestPipelineStageTelemetry:
mock_llm_client.messages.create = create
with (
- patch(f"{PIPELINE_MODULE_PATH}.get_async_anthropic_gateway_client", return_value=mock_llm_client),
+ patch(f"{PIPELINE_MODULE_PATH}.build_async_anthropic_client", return_value=mock_llm_client),
patch(f"{PIPELINE_MODULE_PATH}.activity"),
patch(f"{PIPELINE_MODULE_PATH}.emit_signal", new_callable=AsyncMock),
patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics.capture") as capture,
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.py
index f32ca7c29429..289c72f7333f 100644
--- a/products/signals/backend/temporal/grouping.py
+++ b/products/signals/backend/temporal/grouping.py
@@ -181,6 +181,7 @@ async def generate_search_queries(
validate=validate,
temperature=0.7,
stage="query_generation",
+ ai_product="signals_grouping",
)
@@ -479,6 +480,7 @@ async def match_signal_to_report(
validate=validate,
temperature=0.2,
stage="match",
+ ai_product="signals_grouping",
)
@@ -609,6 +611,7 @@ async def verify_match_specificity(
validate=lambda text: SpecificityResult.model_validate_json(text),
temperature=0.2,
stage="specificity",
+ ai_product="signals_grouping",
)
return VerifyMatchSpecificityOutput(