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.

chore(signals): move pipeline to use llm gateway (#60745)

Joshua Snyder068e10d78035
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 6c81968e964c..ea64d136d1ea 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -9,17 +9,17 @@ GitHub repositories, and code execution.
Use them when your feature needs an autonomous agent that reads PostHog data, writes code, and produces artifacts like PRs or reports.
For simpler LLM calls (summarization, translation, classification),
-skip this page and use the LLM gateway (`get_llm_client()`) directly —
+skip this page and use the LLM gateway (`get_llm_client(product=..., team_id=...)`) directly —
it's simpler and doesn't need a sandbox.
## When to use what
-| Example | Solution |
-| ----------------------------------------------------------------------------------------------- | ---------------------------------- |
-| Signals team building an enrichment pipeline that generates reports from PostHog analytics data | Sandboxed agent (this page) |
-| Conversations team building a support agent that queries PostHog and customer documentation | Sandboxed agent (this page) |
-| AI observability summarizing a funnel, generating a natural-language insight title | LLM gateway via `get_llm_client()` |
-| Not sure | Ask in `#team-posthog-ai` |
+| Example | Solution |
+| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
+| Signals team building an enrichment pipeline that generates reports from PostHog analytics data | Sandboxed agent (this page) |
+| Conversations team building a support agent that queries PostHog and customer documentation | Sandboxed agent (this page) |
+| AI observability summarizing a funnel, generating a natural-language insight title | LLM gateway via `get_llm_client(product=..., team_id=...)` |
+| Not sure | Ask in `#team-posthog-ai` |
**Rule of thumb**: if the LLM needs to _do things_ (query data, read files, create branches, open PRs), use a sandboxed agent.
If it just needs to _answer a question_ given some context you already have, use the LLM gateway.
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index c4727016bda8..ea8686c9204e 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -3,6 +3,7 @@ from typing import Literal
from django.conf import settings
import httpx
+from anthropic import AsyncAnthropic
from openai import AsyncOpenAI, OpenAI
Product = Literal[
@@ -21,46 +22,119 @@ Product = Literal[
"slack-posthog-code",
"product_analytics",
"subscriptions",
+ "signals",
] # If you add a product here, make sure it's also in services/llm-gateway/src/llm_gateway/products/config.py
-def get_llm_client(product: Product = "django") -> OpenAI:
+def _team_id_header(team_id: int) -> dict[str, str]:
+ return {"x-posthog-property-team_id": str(team_id)}
+
+
+def get_llm_client(product: Product = "django", team_id: int | None = None) -> OpenAI:
"""
- Get an OpenAI-compatible client for the LLM gateway.
+ Get an OpenAI-compatible client for the internal LLM gateway.
- The gateway supports all OpenAI, Anthropic, Gemini, OpenRouter, and Fireworks AI chat models through a unified interface.
+ The gateway exposes an OpenAI Chat Completions API but routes to any backend —
+ Anthropic, OpenAI, OpenRouter, Fireworks AI — so callers can pass Claude, GPT,
+ or other model IDs through the same interface.
- If you want the user to be tracked by LLM A and rate limited correctly, you should supply the distinct_id as a `user` argument when making the LLM call. For example:
+ ## Per-team attribution (`team_id`)
- client = get_llm_client()
- response = client.chat.completions.create(
- model="claude-opus-4-5", # or any supported OpenAI, Anthropic, Gemini, OpenRouter, or Fireworks AI model
- messages=[...],
- user=request.user.distinct_id, # user for analytics and rate limiting
- )
+ The gateway authenticates with a single shared personal API key (`LLM_GATEWAY_API_KEY`),
+ so by default every captured `$ai_generation` event is attributed to the key owner's team.
+ Pass `team_id` to attribute spend to a specific customer team instead: it is sent as a
+ default `x-posthog-property-team_id` header on every request, and the usage reporter
+ aggregates per-team LLM spend by reading `JSONExtractInt(properties, 'team_id')` (see
+ `posthog/tasks/usage_report.py`). Omit it to keep the key owner's team (the prior behavior).
+
+ ## Per-call extras
+
+ `ai_product` and `$ai_billable` are owned by the gateway product config (the route
+ sets `ai_product` from `product`, and `$ai_billable` from that product's `billable`
+ flag). Do NOT override them via headers — a typo would silently mis-bill or
+ misattribute the generation.
+
+ For genuinely per-call tags (source-specific metadata, etc.), pass
+ `extra_headers={"x-posthog-property-<key>": "<value>"}` on the individual
+ `chat.completions.create(...)` call. Pass the user's distinct_id as `user=` for
+ rate limiting and per-user analytics breakdown.
+
+ Example:
+ client = get_llm_client(product="signals", team_id=team.id)
+ response = client.chat.completions.create(
+ model="claude-haiku-4-5",
+ messages=[...],
+ user=f"team-{team.id}",
+ extra_headers={
+ "x-posthog-property-source_product": "zendesk",
+ },
+ )
Args:
- product: The product to use when making requests to the LLM gateway, should be one of the defined products in the gateway. You can use this to filter traces by the `ai_product` propertly, and also to define custom rate limits / model restrictions in the gateway. If not passed, it will default to the "django" product.
+ product: Product tag for the gateway route — used for filtering traces by `ai_product`
+ and for per-product rate-limit / model-restriction policies on the gateway.
+ Must be one of the values in the `Product` literal above and registered in
+ `services/llm-gateway/src/llm_gateway/products/config.py`.
+ team_id: Optional PostHog team to attribute the captured `$ai_generation` event to.
+ When provided, sent on every request as the `x-posthog-property-team_id` header;
+ when omitted, the event is attributed to the gateway key owner's team.
"""
if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:
raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"
- # Bypass HTTP_PROXY/HTTPS_PROXY — the LLM gateway is an internal service
- return OpenAI(base_url=base_url, api_key=settings.LLM_GATEWAY_API_KEY, http_client=httpx.Client(trust_env=False))
+ return OpenAI(
+ base_url=base_url,
+ api_key=settings.LLM_GATEWAY_API_KEY,
+ default_headers=_team_id_header(team_id) if team_id is not None else None,
+ http_client=httpx.Client(trust_env=False),
+ )
-def get_async_llm_client(product: Product = "django") -> AsyncOpenAI:
+def get_async_llm_client(product: Product = "django", team_id: int | None = None) -> AsyncOpenAI:
"""
- Get an async OpenAI-compatible client for the LLM gateway.
-
- Same as get_llm_client but returns an AsyncOpenAI client for use in async contexts.
+ Async variant of `get_llm_client`. See `get_llm_client` for the rationale on `team_id`
+ attribution and how to attach extra per-call event properties.
"""
if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:
raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"
- # Bypass HTTP_PROXY/HTTPS_PROXY — the LLM gateway is an internal service
return AsyncOpenAI(
- base_url=base_url, api_key=settings.LLM_GATEWAY_API_KEY, http_client=httpx.AsyncClient(trust_env=False)
+ base_url=base_url,
+ api_key=settings.LLM_GATEWAY_API_KEY,
+ default_headers=_team_id_header(team_id) if team_id is not None else None,
+ http_client=httpx.AsyncClient(trust_env=False),
+ )
+
+
+def get_async_anthropic_gateway_client(product: Product = "django", team_id: int | None = None) -> AsyncAnthropic:
+ """
+ Get an Anthropic-native async client pointed at the internal LLM gateway.
+
+ Prefer this over `get_async_llm_client` when you're calling an Anthropic model and want
+ Anthropic-native request features — assistant prefilling, extended thinking, a top-level
+ `system` prompt. The gateway exposes a native Messages endpoint (`/{product}/v1/messages`)
+ that honours the same per-team attribution headers as the OpenAI Chat Completions route, so
+ you get all of that without forcing the request through the OpenAI shape.
+
+ Returns a plain `anthropic.AsyncAnthropic`, NOT `posthoganalytics.ai.anthropic.AsyncAnthropic`:
+ the gateway captures the `$ai_generation` event itself, so wrapping the client would
+ double-capture (and, for billable products, double-bill) every generation.
+
+ The Anthropic SDK posts to `{base_url}/v1/messages` and authenticates via the `x-api-key`
+ header, both of which the gateway accepts. See `get_llm_client` for the `team_id` attribution
+ rationale — it is sent identically as a default `x-posthog-property-team_id` header. For
+ per-call tags, pass `extra_headers={"x-posthog-property-<key>": "<value>"}` on the individual
+ `messages.create(...)` call, and the user identifier as `metadata={"user_id": ...}`.
+ """
+ if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:
+ raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
+
+ base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}"
+ return AsyncAnthropic(
+ base_url=base_url,
+ api_key=settings.LLM_GATEWAY_API_KEY,
+ default_headers=_team_id_header(team_id) if team_id is not None else None,
+ http_client=httpx.AsyncClient(trust_env=False),
)
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 4463eb3af6d0..4edd1a7d9f46 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -3,7 +3,7 @@ from typing import get_args
import pytest
from unittest.mock import patch
-from posthog.llm.gateway_client import Product, get_llm_client
+from posthog.llm.gateway_client import Product, get_async_anthropic_gateway_client, get_async_llm_client, get_llm_client
class TestGetLlmClient:
@@ -17,7 +17,7 @@ class TestGetLlmClient:
mock_settings.LLM_GATEWAY_API_KEY = "test-key"
with pytest.raises(ValueError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"):
- get_llm_client()
+ get_llm_client(product="django", team_id=1)
@patch("posthog.llm.gateway_client.settings")
def test_raises_when_gateway_api_key_missing(self, mock_settings):
@@ -25,14 +25,14 @@ class TestGetLlmClient:
mock_settings.LLM_GATEWAY_API_KEY = ""
with pytest.raises(ValueError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"):
- get_llm_client()
+ get_llm_client(product="django", team_id=1)
@patch("posthog.llm.gateway_client.settings")
def test_returns_client_with_correct_base_url(self, mock_settings):
mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
mock_settings.LLM_GATEWAY_API_KEY = "test-key"
- client = get_llm_client()
+ client = get_llm_client(product="django", team_id=1)
assert str(client.base_url) == "http://gateway:8080/django/v1/"
assert client.api_key == "test-key"
@@ -44,6 +44,7 @@ class TestGetLlmClient:
("llm_gateway", "/llm_gateway/v1/"),
("posthog_code", "/posthog_code/v1/"),
("wizard", "/wizard/v1/"),
+ ("signals", "/signals/v1/"),
],
)
@patch("posthog.llm.gateway_client.settings")
@@ -51,7 +52,7 @@ class TestGetLlmClient:
mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
mock_settings.LLM_GATEWAY_API_KEY = "test-key"
- client = get_llm_client(product=product)
+ client = get_llm_client(product=product, team_id=1)
assert expected_path in str(client.base_url)
@@ -60,6 +61,81 @@ class TestGetLlmClient:
mock_settings.LLM_GATEWAY_URL = "http://gateway:8080/"
mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+ client = get_llm_client(product="django", team_id=1)
+
+ assert str(client.base_url) == "http://gateway:8080/django/v1/"
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_attaches_team_id_default_header(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ client = get_llm_client(product="signals", team_id=42)
+
+ assert client.default_headers.get("x-posthog-property-team_id") == "42"
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_async_client_attaches_team_id_default_header(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ client = get_async_llm_client(product="signals", team_id=42)
+
+ assert client.default_headers.get("x-posthog-property-team_id") == "42"
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_no_team_id_header_when_team_id_omitted(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ client = get_llm_client(product="django")
+
+ assert client.default_headers.get("x-posthog-property-team_id") is None
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_product_defaults_to_django(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
client = get_llm_client()
assert str(client.base_url) == "http://gateway:8080/django/v1/"
+
+
+class TestGetAsyncAnthropicGatewayClient:
+ @patch("posthog.llm.gateway_client.settings")
+ def test_raises_when_gateway_unconfigured(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = ""
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ with pytest.raises(ValueError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"):
+ get_async_anthropic_gateway_client(product="signals", team_id=1)
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_base_url_omits_v1_suffix(self, mock_settings):
+ # The Anthropic SDK appends /v1/messages itself, so the base_url stops at the product.
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080/"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ client = get_async_anthropic_gateway_client(product="signals", team_id=1)
+
+ assert str(client.base_url) == "http://gateway:8080/signals/"
+ assert client.api_key == "test-key"
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_attaches_team_id_default_header(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ client = get_async_anthropic_gateway_client(product="signals", team_id=42)
+
+ assert client.default_headers.get("x-posthog-property-team_id") == "42"
+
+ @patch("posthog.llm.gateway_client.settings")
+ def test_no_team_id_header_when_team_id_omitted(self, mock_settings):
+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"
+ mock_settings.LLM_GATEWAY_API_KEY = "test-key"
+
+ client = get_async_anthropic_gateway_client(product="signals")
+
+ assert client.default_headers.get("x-posthog-property-team_id") is None
diff --git a/posthog/temporal/ai_observability/eval_reports/emit_signal.py b/posthog/temporal/ai_observability/eval_reports/emit_signal.py
index d642e389584c..9f70be35288a 100644
--- a/posthog/temporal/ai_observability/eval_reports/emit_signal.py
+++ b/posthog/temporal/ai_observability/eval_reports/emit_signal.py
@@ -138,10 +138,12 @@ async def summarize_report_for_signal(
return EvalReportSignalSummary.model_validate(data)
return await call_llm(
+ team_id=inputs.team_id,
system_prompt=SUMMARIZE_REPORT_SYSTEM_PROMPT,
user_prompt=user_prompt,
validate=validate,
thinking=True,
+ stage="eval_report_signal_summary",
)
diff --git a/posthog/temporal/data_imports/signals/pipeline.py b/posthog/temporal/data_imports/signals/pipeline.py
index e9883e6cbe7b..b6a32a52028f 100644
--- a/posthog/temporal/data_imports/signals/pipeline.py
+++ b/posthog/temporal/data_imports/signals/pipeline.py
@@ -4,16 +4,15 @@ import dataclasses
from datetime import datetime
from typing import Any
-from django.conf import settings
-
import structlog
import posthoganalytics
-from google.genai import types
-from posthoganalytics.ai.gemini import AsyncClient, genai
+from anthropic import AsyncAnthropic
+from anthropic.types import MessageParam
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.models import Organization, Team
from posthog.sync import database_sync_to_async
from posthog.temporal.data_imports.signals.registry import SignalEmitter, SignalEmitterOutput, SignalSourceTableConfig
@@ -22,8 +21,7 @@ from products.signals.backend.facade.api import emit_signal
logger = structlog.get_logger(__name__)
-# Default model to use for LLM calls
-GEMINI_MODEL = "models/gemini-3-flash-preview"
+LLM_MODEL = "claude-sonnet-4-5"
# Concurrent LLM calls limit for actionability/summarization checks
LLM_CONCURRENCY_LIMIT = 20
# Concurrent workflow spawns for signal emission
@@ -34,11 +32,36 @@ TEMPORAL_PAYLOAD_MAX_BYTES = 2 * 1024 * 1024
LLM_MAX_ATTEMPTS = 3
# Per-call timeout for LLM requests (seconds)
LLM_CALL_TIMEOUT_SECONDS = 120
-# Thinking budget for LLM calls (summarization & actionability are judgment tasks)
-LLM_THINKING_BUDGET_TOKENS = 1024
# Backoff between LLM retry attempts (delay = initial * coefficient ^ (attempt - 1))
LLM_RETRY_INITIAL_DELAY_SECONDS = 5
LLM_RETRY_BACKOFF_COEFFICIENT = 2.0
+# Anthropic's Messages API requires max_tokens, so this is a deliberately high safety ceiling
+# rather than a tuned budget. The risk we care about is a response being cut off mid-output, not
+# runaway generation — the actual outputs here are tiny (a short summary or a one-word verdict).
+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.
+
+ 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.
+
+ `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.
+ """
+ return {
+ "x-posthog-property-ai_stage": stage,
+ "x-posthog-property-source_product": output.source_product,
+ "x-posthog-property-source_type": output.source_type,
+ }
+
+
+def _extract_text(response: Any) -> str:
+ """Concatenate the text blocks of an Anthropic Messages response (ignores non-text blocks)."""
+ return "".join(block.text for block in response.content if getattr(block, "type", None) == "text")
def _capture_pipeline_stage(
@@ -108,33 +131,34 @@ def build_emitter_outputs(
async def _summarize_description(
- client: AsyncClient,
+ client: AsyncAnthropic,
+ team_id: int,
output: SignalEmitterOutput,
summarization_prompt: str,
threshold: int,
) -> SignalEmitterOutput:
- prompt_parts = [types.Part(text=summarization_prompt.format(description=output.description, max_length=threshold))]
+ messages: list[MessageParam] = [
+ {"role": "user", "content": summarization_prompt.format(description=output.description, max_length=threshold)}
+ ]
+ extra_headers = _signals_extra_headers(output, stage="summarization")
for attempt in range(LLM_MAX_ATTEMPTS):
if attempt > 0:
await asyncio.sleep(LLM_RETRY_INITIAL_DELAY_SECONDS * (LLM_RETRY_BACKOFF_COEFFICIENT ** (attempt - 1)))
+ summary = ""
try:
response = await asyncio.wait_for(
- client.models.generate_content(
- model=GEMINI_MODEL,
- contents=prompt_parts,
- config=types.GenerateContentConfig(
- max_output_tokens=LLM_THINKING_BUDGET_TOKENS + max(threshold // 4, 256),
- thinking_config=types.ThinkingConfig(
- thinking_budget=LLM_THINKING_BUDGET_TOKENS,
- include_thoughts=False,
- ),
- ),
+ client.messages.create(
+ model=LLM_MODEL,
+ messages=messages,
+ max_tokens=LLM_MAX_OUTPUT_TOKENS,
+ metadata={"user_id": f"team-{team_id}"},
+ extra_headers=extra_headers,
),
timeout=LLM_CALL_TIMEOUT_SECONDS,
)
- if response.candidates and response.candidates[0].finish_reason == types.FinishReason.MAX_TOKENS:
+ summary = _extract_text(response).strip()
+ if response.stop_reason == "max_tokens":
raise ValueError("LLM summary response was truncated due to token limit")
- summary = (response.text or "").strip()
if not summary:
raise ValueError("Empty response from LLM when summarizing description")
if len(summary) > threshold:
@@ -152,16 +176,23 @@ async def _summarize_description(
"attempt": attempt + 1,
},
)
- prompt_parts.append(
- types.Part(
- text=f"\n\nAttempt {attempt + 1} of {LLM_MAX_ATTEMPTS} to summarize description failed with error: {e!r}\nPlease fix your output."
+ # Anthropic requires user/assistant turns to alternate, so only feed the correction
+ # back when we actually got assistant text to pair it with; otherwise just retry the
+ # existing prompt.
+ if summary:
+ messages.append({"role": "assistant", "content": summary})
+ messages.append(
+ {
+ "role": "user",
+ "content": f"Attempt {attempt + 1} of {LLM_MAX_ATTEMPTS} to summarize description failed with error: {e!r}\nPlease fix your output.",
+ }
)
- )
# Hard-truncate the description to the threshold if all attempts failed
return dataclasses.replace(output, description=output.description[:threshold])
async def summarize_long_descriptions(
+ team: Team,
outputs: list[SignalEmitterOutput],
summarization_prompt: str,
threshold: int,
@@ -170,7 +201,7 @@ 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 = genai.AsyncClient(api_key=settings.GEMINI_API_KEY)
+ client = get_async_anthropic_gateway_client(product="signals", team_id=team.id)
semaphore = asyncio.Semaphore(LLM_CONCURRENCY_LIMIT)
_safe_heartbeat()
completed_count = 0
@@ -179,7 +210,7 @@ async def summarize_long_descriptions(
nonlocal completed_count
async with semaphore:
try:
- result = await _summarize_description(client, output, summarization_prompt, threshold)
+ result = await _summarize_description(client, team.id, output, summarization_prompt, threshold)
except Exception:
logger.exception(
"Summarization failed, skipping signal",
@@ -214,46 +245,30 @@ async def summarize_long_descriptions(
return result
-def _extract_thoughts(response: types.GenerateContentResponse) -> str | None:
- if not response.candidates:
- return None
- content = response.candidates[0].content
- if content is None or content.parts is None:
- return None
- thoughts = []
- for part in content.parts:
- if part.text and part.thought:
- thoughts.append(part.text)
- return "\n".join(thoughts) if thoughts else None
-
-
async def _check_actionability(
- client: AsyncClient,
+ client: AsyncAnthropic,
+ team_id: int,
output: SignalEmitterOutput,
actionability_prompt: str,
-) -> tuple[bool, str | None]:
+) -> bool:
prompt = actionability_prompt.format(description=output.description)
+ extra_headers = _signals_extra_headers(output, stage="actionability")
for attempt in range(LLM_MAX_ATTEMPTS):
if attempt > 0:
await asyncio.sleep(LLM_RETRY_INITIAL_DELAY_SECONDS * (LLM_RETRY_BACKOFF_COEFFICIENT ** (attempt - 1)))
try:
response = await asyncio.wait_for(
- client.models.generate_content(
- model=GEMINI_MODEL,
- contents=[prompt],
- config=types.GenerateContentConfig(
- max_output_tokens=LLM_THINKING_BUDGET_TOKENS + 128,
- thinking_config=types.ThinkingConfig(
- thinking_budget=LLM_THINKING_BUDGET_TOKENS,
- include_thoughts=True,
- ),
- ),
+ client.messages.create(
+ model=LLM_MODEL,
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=LLM_MAX_OUTPUT_TOKENS,
+ metadata={"user_id": f"team-{team_id}"},
+ extra_headers=extra_headers,
),
timeout=LLM_CALL_TIMEOUT_SECONDS,
)
- thoughts = _extract_thoughts(response)
- response_text = (response.text or "").strip().upper()
- return "NOT_ACTION" not in response_text, thoughts
+ response_text = _extract_text(response).strip().upper()
+ return "NOT_ACTION" not in response_text
except Exception as e:
posthoganalytics.capture_exception(
e,
@@ -267,46 +282,46 @@ async def _check_actionability(
},
)
# Assume actionable if all retries exhausted
- return True, None
+ return True
async def filter_actionable(
+ team: Team,
outputs: list[SignalEmitterOutput],
actionability_prompt: str,
extra: dict[str, Any],
) -> list[SignalEmitterOutput]:
- client = genai.AsyncClient(api_key=settings.GEMINI_API_KEY)
+ client = get_async_anthropic_gateway_client(product="signals", team_id=team.id)
semaphore = asyncio.Semaphore(LLM_CONCURRENCY_LIMIT)
_safe_heartbeat()
checked_count = 0
- async def _bounded_check(output: SignalEmitterOutput) -> tuple[bool, str | None]:
+ async def _bounded_check(output: SignalEmitterOutput) -> bool:
nonlocal checked_count
async with semaphore:
try:
- result = await _check_actionability(client, output, actionability_prompt)
+ result = await _check_actionability(client, team.id, output, actionability_prompt)
except Exception:
logger.exception(
"Actionability check failed, assuming actionable",
signal_source_id=output.source_id,
**extra,
)
- return True, None
+ return True
finally:
checked_count += 1
if checked_count % LLM_CONCURRENCY_LIMIT == 0:
_safe_heartbeat()
return result
- tasks: dict[int, asyncio.Task[tuple[bool, str | None]]] = {}
+ tasks: dict[int, asyncio.Task[bool]] = {}
async with asyncio.TaskGroup() as tg:
for i, output in enumerate(outputs):
tasks[i] = tg.create_task(_bounded_check(output))
actionable = []
filtered_count = 0
for i, output in enumerate(outputs):
- is_actionable, thoughts = tasks[i].result()
- if is_actionable:
+ if tasks[i].result():
actionable.append(output)
else:
filtered_count += 1
@@ -314,7 +329,6 @@ async def filter_actionable(
"Filtered non-actionable signal",
signal_source_type=output.source_type,
signal_source_id=output.source_id,
- thoughts=thoughts,
**extra,
)
if filtered_count > 0:
@@ -434,6 +448,7 @@ async def run_signal_pipeline(
threshold = config.description_summarization_threshold_chars
pre_summary_by_id = {o.source_id: o for o in outputs}
outputs = await summarize_long_descriptions(
+ team=team,
outputs=outputs,
summarization_prompt=config.summarization_prompt,
threshold=threshold,
@@ -447,6 +462,7 @@ async def run_signal_pipeline(
if config.actionability_prompt:
pre_filter_by_id = {o.source_id: o for o in outputs}
outputs = await filter_actionable(
+ team=team,
outputs=outputs,
actionability_prompt=config.actionability_prompt,
extra=extra,
diff --git a/posthog/temporal/data_imports/signals/tests/test_emit_signals.py b/posthog/temporal/data_imports/signals/tests/test_emit_signals.py
index 621be6b28ff3..0faec381f2e0 100644
--- a/posthog/temporal/data_imports/signals/tests/test_emit_signals.py
+++ b/posthog/temporal/data_imports/signals/tests/test_emit_signals.py
@@ -57,24 +57,17 @@ def _make_config(**overrides: Any) -> SignalSourceTableConfig:
return SignalSourceTableConfig(**(defaults | overrides))
-def _make_llm_response(text: str | None, thought: str | None = None) -> MagicMock:
- """Build a mock Gemini response with optional thought parts."""
+def _make_llm_response(content: str | None, stop_reason: str = "end_turn") -> MagicMock:
+ """Build a mock Anthropic Messages response (None content => no text blocks)."""
response = MagicMock()
- response.text = text
- parts = []
- if thought is not None:
- thought_part = MagicMock()
- thought_part.text = thought
- thought_part.thought = True
- parts.append(thought_part)
- if text is not None:
- answer_part = MagicMock()
- answer_part.text = text
- answer_part.thought = False
- parts.append(answer_part)
- candidate = MagicMock()
- candidate.content.parts = parts
- response.candidates = [candidate]
+ if content is None:
+ response.content = []
+ else:
+ block = MagicMock()
+ block.type = "text"
+ block.text = content
+ response.content = [block]
+ response.stop_reason = stop_reason
return response
@@ -272,74 +265,79 @@ class TestCheckActionability:
)
async def test_classifies_based_on_llm_response(self, llm_response, expected):
mock_client = MagicMock()
- mock_client.models.generate_content = AsyncMock(return_value=_make_llm_response(llm_response))
+ mock_client.messages.create = AsyncMock(return_value=_make_llm_response(llm_response))
output = _make_output(description="test ticket")
- is_actionable, _thoughts = await _check_actionability(mock_client, output, "Is this actionable? {description}")
+ is_actionable = await _check_actionability(mock_client, 1, output, "Is this actionable? {description}")
assert is_actionable is expected
@pytest.mark.asyncio
- async def test_returns_thoughts_from_response(self):
+ async def test_assumes_actionable_after_retries_exhausted(self):
mock_client = MagicMock()
- mock_client.models.generate_content = AsyncMock(
- return_value=_make_llm_response("NOT_ACTIONABLE", thought="Just a billing question, not a bug.")
- )
+ mock_client.messages.create = AsyncMock(side_effect=Exception("API error"))
- _is_actionable, thoughts = await _check_actionability(
- mock_client, _make_output(), "Is this actionable? {description}"
- )
+ with patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics"):
+ is_actionable = await _check_actionability(mock_client, 1, _make_output(), "prompt {description}")
- assert thoughts == "Just a billing question, not a bug."
+ assert is_actionable is True
+ assert mock_client.messages.create.call_count == LLM_MAX_ATTEMPTS
@pytest.mark.asyncio
- async def test_assumes_actionable_after_retries_exhausted(self):
+ async def test_returns_true_on_none_response_content(self):
mock_client = MagicMock()
- mock_client.models.generate_content = AsyncMock(side_effect=Exception("API error"))
+ mock_client.messages.create = AsyncMock(return_value=_make_llm_response(None))
- is_actionable, thoughts = await _check_actionability(mock_client, _make_output(), "prompt {description}")
+ is_actionable = await _check_actionability(mock_client, 1, _make_output(), "prompt {description}")
assert is_actionable is True
- assert thoughts is None
- assert mock_client.models.generate_content.call_count == LLM_MAX_ATTEMPTS
@pytest.mark.asyncio
- async def test_returns_true_on_none_response_text(self):
+ async def test_passes_team_attribution_headers(self):
mock_client = MagicMock()
- mock_client.models.generate_content = AsyncMock(return_value=_make_llm_response(None))
+ mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
- is_actionable, _thoughts = await _check_actionability(mock_client, _make_output(), "prompt {description}")
+ output = _make_output(source_id="42")
+ await _check_actionability(mock_client, 7, output, "Is this actionable? {description}")
- assert is_actionable is True
+ call_kwargs = mock_client.messages.create.call_args.kwargs
+ assert call_kwargs["metadata"]["user_id"] == "team-7"
+ headers = call_kwargs["extra_headers"]
+ assert headers["x-posthog-property-ai_stage"] == "actionability"
+ assert headers["x-posthog-property-source_product"] == output.source_product
+ assert headers["x-posthog-property-source_type"] == output.source_type
+ # ai_product and $ai_billable are owned by the gateway product config, not headers
+ assert "x-posthog-property-ai_product" not in headers
+ assert "x-posthog-property-$ai_billable" not in headers
class TestFilterActionable:
@pytest.mark.asyncio
async def test_filters_non_actionable_outputs(self):
outputs = [_make_output(source_id="1"), _make_output(source_id="2"), _make_output(source_id="3")]
+ team = MagicMock(id=1)
mock_client = MagicMock()
responses = [
_make_llm_response("ACTIONABLE"),
- _make_llm_response("NOT_ACTIONABLE", thought="This is just a billing question."),
+ _make_llm_response("NOT_ACTIONABLE"),
_make_llm_response("ACTIONABLE"),
]
call_count = 0
- async def mock_generate(*args, **kwargs):
+ async def mock_create(*args, **kwargs):
nonlocal call_count
resp = responses[call_count]
call_count += 1
return resp
- mock_client.models.generate_content = mock_generate
+ mock_client.messages.create = mock_create
with (
- patch(f"{PIPELINE_MODULE_PATH}.genai") as mock_genai,
+ patch(f"{PIPELINE_MODULE_PATH}.get_async_anthropic_gateway_client", return_value=mock_client),
patch(f"{PIPELINE_MODULE_PATH}.activity"),
):
- mock_genai.AsyncClient.return_value = mock_client
- result = await filter_actionable(outputs, "prompt {description}", extra={})
+ result = await filter_actionable(team, outputs, "prompt {description}", extra={})
assert [o.source_id for o in result] == ["1", "3"]
@@ -350,16 +348,7 @@ class TestSummarizeDescription:
def _mock_client(self, responses: Sequence[str | None]) -> MagicMock:
client = MagicMock()
- call_idx = 0
-
- async def generate(*args, **kwargs):
- nonlocal call_idx
- resp = MagicMock()
- resp.text = responses[call_idx]
- call_idx += 1
- return resp
-
- client.models.generate_content = generate
+ client.messages.create = AsyncMock(side_effect=[_make_llm_response(r) for r in responses])
return client
@pytest.mark.asyncio
@@ -367,7 +356,7 @@ class TestSummarizeDescription:
client = self._mock_client(["Short summary."])
output = _make_output(description="x" * 500)
- result = await _summarize_description(client, output, self.PROMPT, self.THRESHOLD)
+ result = await _summarize_description(client, 1, output, self.PROMPT, self.THRESHOLD)
assert result.description == "Short summary."
@@ -376,7 +365,8 @@ class TestSummarizeDescription:
client = self._mock_client(["a" * 300, "Concise."])
output = _make_output(description="x" * 500)
- result = await _summarize_description(client, output, self.PROMPT, self.THRESHOLD)
+ with patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics"):
+ result = await _summarize_description(client, 1, output, self.PROMPT, self.THRESHOLD)
assert result.description == "Concise."
@@ -387,7 +377,7 @@ class TestSummarizeDescription:
output = _make_output(description=original)
with patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics"):
- result = await _summarize_description(client, output, self.PROMPT, self.THRESHOLD)
+ result = await _summarize_description(client, 1, output, self.PROMPT, self.THRESHOLD)
assert result.description == original[: self.THRESHOLD]
@@ -403,7 +393,7 @@ class TestSummarizeDescription:
extra={"html_url": "https://example.com"},
)
- result = await _summarize_description(client, output, self.PROMPT, self.THRESHOLD)
+ result = await _summarize_description(client, 1, output, self.PROMPT, self.THRESHOLD)
assert result.source_product == "github"
assert result.source_type == "issue"
@@ -411,6 +401,21 @@ class TestSummarizeDescription:
assert result.weight == 0.8
assert result.extra == {"html_url": "https://example.com"}
+ @pytest.mark.asyncio
+ async def test_passes_team_attribution_headers(self):
+ client = self._mock_client(["Short summary."])
+ output = _make_output(description="x" * 500)
+
+ await _summarize_description(client, 42, output, self.PROMPT, self.THRESHOLD)
+
+ call_kwargs = client.messages.create.call_args.kwargs
+ assert call_kwargs["metadata"]["user_id"] == "team-42"
+ headers = call_kwargs["extra_headers"]
+ assert headers["x-posthog-property-ai_stage"] == "summarization"
+ # ai_product and $ai_billable are owned by the gateway product config, not headers
+ assert "x-posthog-property-ai_product" not in headers
+ assert "x-posthog-property-$ai_billable" not in headers
+
class TestSummarizeLongDescriptions:
PROMPT = "Summarize: {description}"
@@ -420,18 +425,16 @@ class TestSummarizeLongDescriptions:
async def test_only_summarizes_descriptions_above_threshold(self):
short = _make_output(source_id="1", description="short")
long = _make_output(source_id="2", description="x" * 200)
+ team = MagicMock(id=1)
mock_client = MagicMock()
- mock_response = MagicMock()
- mock_response.text = "Summarized."
- mock_client.models.generate_content = AsyncMock(return_value=mock_response)
+ mock_client.messages.create = AsyncMock(return_value=_make_llm_response("Summarized."))
with (
- patch(f"{PIPELINE_MODULE_PATH}.genai") as mock_genai,
+ patch(f"{PIPELINE_MODULE_PATH}.get_async_anthropic_gateway_client", return_value=mock_client),
patch(f"{PIPELINE_MODULE_PATH}.activity"),
):
- mock_genai.AsyncClient.return_value = mock_client
- result = await summarize_long_descriptions([short, long], self.PROMPT, self.THRESHOLD, extra={})
+ result = await summarize_long_descriptions(team, [short, long], self.PROMPT, self.THRESHOLD, extra={})
assert result[0].description == "short"
assert result[1].description == "Summarized."
@@ -439,8 +442,9 @@ class TestSummarizeLongDescriptions:
@pytest.mark.asyncio
async def test_returns_unchanged_when_all_under_threshold(self):
outputs = [_make_output(source_id="1", description="short"), _make_output(source_id="2", description="also")]
+ team = MagicMock(id=1)
- result = await summarize_long_descriptions(outputs, self.PROMPT, self.THRESHOLD, extra={})
+ result = await summarize_long_descriptions(team, outputs, self.PROMPT, self.THRESHOLD, extra={})
assert result == outputs
@@ -573,27 +577,23 @@ class TestPipelineStageTelemetry:
mock_llm_client = MagicMock()
- async def generate_content(*args, **kwargs):
- contents = kwargs.get("contents") or (args[1] if len(args) > 1 else None)
- prompt_text = ""
- if contents:
- first = contents[0]
- prompt_text = first.text if hasattr(first, "text") else first
+ async def create(*args, **kwargs):
+ messages = kwargs.get("messages") or []
+ prompt_text = messages[0]["content"] if messages else ""
if "Summarize" in prompt_text:
return _make_llm_response("Summarized ticket body.")
if "not actionable" in prompt_text:
return _make_llm_response("NOT_ACTIONABLE")
return _make_llm_response("ACTIONABLE")
- mock_llm_client.models.generate_content = generate_content
+ mock_llm_client.messages.create = create
with (
- patch(f"{PIPELINE_MODULE_PATH}.genai") as mock_genai,
+ patch(f"{PIPELINE_MODULE_PATH}.get_async_anthropic_gateway_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,
):
- mock_genai.AsyncClient.return_value = mock_llm_client
await run_signal_pipeline(team=team, config=config, records=records, extra={})
events_by_source_id: dict[str, list[str]] = {}
diff --git a/products/signals/backend/management/commands/emit_signals_from_llm.py b/products/signals/backend/management/commands/emit_signals_from_llm.py
index da33896b9117..a5fafb367003 100644
--- a/products/signals/backend/management/commands/emit_signals_from_llm.py
+++ b/products/signals/backend/management/commands/emit_signals_from_llm.py
@@ -170,6 +170,7 @@ class Command(BaseCommand):
)
cluster_signals = asyncio.run(
generate_canonical_signals(
+ team_id=team.id,
system_prompt=SYSTEM_PROMPT,
user_prompt=user_prompt,
temperature=options["temperature"],
diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.py
index 82d70b7c25ef..1a5d6974b2a5 100644
--- a/products/signals/backend/temporal/buffer.py
+++ b/products/signals/backend/temporal/buffer.py
@@ -186,7 +186,7 @@ class BufferSignalsWorkflow:
*[
workflow.execute_activity(
safety_filter_activity,
- SafetyFilterInput(description=s.description),
+ SafetyFilterInput(team_id=s.team_id, description=s.description),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
diff --git a/products/signals/backend/temporal/emit_eval_signal.py b/products/signals/backend/temporal/emit_eval_signal.py
index e769e81d6c0d..96e837597c20 100644
--- a/products/signals/backend/temporal/emit_eval_signal.py
+++ b/products/signals/backend/temporal/emit_eval_signal.py
@@ -104,10 +104,12 @@ async def summarize_eval_for_signal(inputs: EmitEvalSignalInputs) -> EvalSignalS
return EvalSignalSummary.model_validate(data)
return await call_llm(
+ team_id=inputs.team_id,
system_prompt=SUMMARIZE_EVAL_SYSTEM_PROMPT,
user_prompt=user_prompt,
validate=validate,
thinking=True,
+ stage="eval_signal_summary",
)
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.py
index 19f4913450f2..3718994c3809 100644
--- a/products/signals/backend/temporal/grouping.py
+++ b/products/signals/backend/temporal/grouping.py
@@ -144,6 +144,7 @@ def _build_query_generation_system_prompt(signal_type_examples: list[SignalTypeE
async def generate_search_queries(
+ team_id: int | None,
description: str,
source_product: str,
source_type: str,
@@ -166,10 +167,12 @@ async def generate_search_queries(
return [truncate_query_to_token_limit(q) for q in result.queries]
return await call_llm(
+ team_id=team_id,
system_prompt=system_prompt,
user_prompt=user_prompt,
validate=validate,
temperature=0.7,
+ stage="query_generation",
)
@@ -179,6 +182,9 @@ class GenerateSearchQueriesInput:
source_product: str
source_type: str
signal_type_examples: list[SignalTypeExample]
+ # Optional with a default so workflows mid-flight across a deploy (whose activity input was
+ # serialized before this field existed) still deserialize; missing => gateway key owner's team.
+ team_id: int | None = None
@dataclass
@@ -192,6 +198,7 @@ async def generate_search_queries_activity(input: GenerateSearchQueriesInput) ->
"""Use LLM to generate 1-3 search queries for finding related signals."""
try:
queries = await generate_search_queries(
+ team_id=input.team_id,
description=input.description,
source_product=input.source_product,
source_type=input.source_type,
@@ -405,6 +412,7 @@ Write a PR title covering ALL the above signals (existing + new), then judge if
async def match_signal_to_report(
+ team_id: int | None,
description: str,
source_product: str,
source_type: str,
@@ -456,10 +464,12 @@ async def match_signal_to_report(
)
return await call_llm(
+ team_id=team_id,
system_prompt=MATCHING_SYSTEM_PROMPT,
user_prompt=user_prompt,
validate=validate,
temperature=0.2,
+ stage="match",
)
@@ -471,6 +481,8 @@ class MatchSignalToReportInput:
queries: list[str]
query_results: list[list[SignalCandidate]]
report_contexts: dict[str, ReportContext]
+ # Optional with a default for deploy-time backward compatibility — see GenerateSearchQueriesInput.
+ team_id: int | None = None
@temporalio.activity.defn
@@ -479,6 +491,7 @@ async def match_signal_to_report_activity(input: MatchSignalToReportInput) -> Ma
"""Determine if a new signal matches an existing report or needs a new one."""
try:
result = await match_signal_to_report(
+ team_id=input.team_id,
description=input.description,
source_product=input.source_product,
source_type=input.source_type,
@@ -562,6 +575,7 @@ class VerifyMatchSpecificityOutput:
async def verify_match_specificity(
+ team_id: int,
new_signal_description: str,
new_signal_source_product: str,
new_signal_source_type: str,
@@ -578,10 +592,12 @@ async def verify_match_specificity(
)
specificity = await call_llm(
+ team_id=team_id,
system_prompt=SPECIFICITY_CHECK_SYSTEM_PROMPT,
user_prompt=specificity_prompt,
validate=lambda text: SpecificityResult.model_validate_json(text),
temperature=0.2,
+ stage="specificity",
)
return VerifyMatchSpecificityOutput(
@@ -597,6 +613,7 @@ async def verify_match_specificity_activity(input: VerifyMatchSpecificityInput)
"""Verify that adding a signal to a group produces a specific-enough PR title."""
try:
result = await verify_match_specificity(
+ team_id=input.team_id,
new_signal_description=input.new_signal_description,
new_signal_source_product=input.new_signal_source_product,
new_signal_source_type=input.new_signal_source_type,
@@ -940,6 +957,7 @@ async def _process_signal_batch(
workflow.execute_activity(
generate_search_queries_activity,
GenerateSearchQueriesInput(
+ team_id=team_id,
description=s.description,
source_product=s.source_product,
source_type=s.source_type,
@@ -1056,6 +1074,7 @@ async def _process_signal_batch(
match_result = await workflow.execute_activity(
match_signal_to_report_activity,
MatchSignalToReportInput(
+ team_id=team_id,
description=signal.description,
source_product=signal.source_product,
source_type=signal.source_type,
diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.py
index f8c6bcd39c80..d8ae9f21075f 100644
--- a/products/signals/backend/temporal/llm.py
+++ b/products/signals/backend/temporal/llm.py
@@ -5,11 +5,10 @@ from typing import Optional, TypeVar
from django.conf import settings
import structlog
-import posthoganalytics
from anthropic.types import MessageParam
-from posthoganalytics.ai.anthropic import AsyncAnthropic
from 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
logger = structlog.get_logger(__name__)
@@ -31,23 +30,6 @@ MAX_QUERY_TOKENS = 2048
TIMEOUT = 100.0
-def get_async_anthropic_client() -> AsyncAnthropic:
- """Get configured AsyncAnthropic client with PostHog analytics."""
- posthog_client = posthoganalytics.default_client
- if not posthog_client:
- raise ValueError("PostHog analytics client not configured")
-
- api_key = settings.ANTHROPIC_API_KEY
- if not api_key:
- raise ValueError("ANTHROPIC_API_KEY is not configured")
-
- return AsyncAnthropic(
- api_key=api_key,
- posthog_client=posthog_client,
- timeout=TIMEOUT,
- )
-
-
def truncate_query_to_token_limit(query: str, max_tokens: int = MAX_QUERY_TOKENS) -> str:
"""Truncate a query string to fit within token limit for embedding."""
try:
@@ -94,17 +76,18 @@ T = TypeVar("T")
# I reached doing ~the same thing in 3 or 4 places and decided to abstract it.
async def call_llm(
*,
+ team_id: int | None,
system_prompt: str,
user_prompt: str,
validate: Callable[[str], T],
thinking: bool = False,
temperature: Optional[float] = 0.2,
retries: int = MAX_RETRIES,
+ stage: Optional[str] = None,
) -> T:
- # Worth noting a lot of this code only really works for the Anthropic API, I think (prefilling and thinking in particular). Haven't
- # looked into the OpenAI SDK yet - that'll be for the switch to the LLM gateway.
+ # 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_client()
+ client = get_async_anthropic_gateway_client(product="signals", team_id=team_id)
messages: list[MessageParam] = [
{"role": "user", "content": user_prompt},
@@ -121,7 +104,12 @@ async def call_llm(
"messages": messages,
"max_tokens": MAX_RESPONSE_TOKENS,
"temperature": temperature,
+ "timeout": TIMEOUT,
}
+ if team_id is not None:
+ create_kwargs["metadata"] = {"user_id": f"team-{team_id}"}
+ if stage:
+ 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.
if thinking:
diff --git a/products/signals/backend/temporal/parallel_grouping.py b/products/signals/backend/temporal/parallel_grouping.py
index e7cbd5a566ca..7f8d338727de 100644
--- a/products/signals/backend/temporal/parallel_grouping.py
+++ b/products/signals/backend/temporal/parallel_grouping.py
@@ -165,6 +165,7 @@ async def _process_signal(
match_result = await workflow.execute_activity(
match_signal_to_report_activity,
MatchSignalToReportInput(
+ team_id=team_id,
description=signal.description,
source_product=signal.source_product,
source_type=signal.source_type,
diff --git a/products/signals/backend/temporal/report_safety_judge.py b/products/signals/backend/temporal/report_safety_judge.py
index 75572cc2d5b5..385cc1782226 100644
--- a/products/signals/backend/temporal/report_safety_judge.py
+++ b/products/signals/backend/temporal/report_safety_judge.py
@@ -74,6 +74,7 @@ def _build_report_safety_judge_prompt(
# to the average embedding for all signals of the same type - if it's some enormous outlier, it's probably a warning
# that it's a bit odd (but the mechanics of exactly how that comparison should work are TBD).
async def judge_report_safety(
+ team_id: int,
signals: list[SignalData],
) -> SafetyJudgeResponse:
"""
@@ -89,10 +90,12 @@ async def judge_report_safety(
return SafetyJudgeResponse.model_validate(data)
return await call_llm(
+ team_id=team_id,
system_prompt=REPORT_SAFETY_JUDGE_SYSTEM_PROMPT,
user_prompt=user_prompt,
validate=validate,
thinking=True,
+ stage="report_safety_judge",
)
@@ -115,6 +118,7 @@ async def report_safety_judge_activity(input: SafetyJudgeInput) -> SafetyJudgeOu
"""Assess report for prompt injection attacks and store result as artefact."""
try:
result = await judge_report_safety(
+ team_id=input.team_id,
signals=input.signals,
)
diff --git a/products/signals/backend/temporal/safety_filter.py b/products/signals/backend/temporal/safety_filter.py
index 306e8bc02ca9..06df926cd4da 100644
--- a/products/signals/backend/temporal/safety_filter.py
+++ b/products/signals/backend/temporal/safety_filter.py
@@ -102,6 +102,9 @@ Respond with valid JSON only:
@dataclass
class SafetyFilterInput:
description: str
+ # Optional with a default for deploy-time backward compatibility: a batch scheduled before this
+ # field existed must still deserialize on a new worker; missing => gateway key owner's team.
+ team_id: int | None = None
@dataclass
@@ -111,16 +114,18 @@ class SafetyFilterOutput:
explanation: Optional[str]
-async def safety_filter(description: str) -> SafetyFilterJudgeResponse:
+async def safety_filter(team_id: int | None, description: str) -> SafetyFilterJudgeResponse:
def validate(text: str) -> SafetyFilterJudgeResponse:
data = json.loads(text)
return SafetyFilterJudgeResponse.model_validate(data)
try:
return await call_llm(
+ team_id=team_id,
system_prompt=SAFETY_FILTER_PROMPT,
user_prompt=description,
validate=validate,
+ stage="safety_filter",
)
except EmptyLLMResponseError:
return SafetyFilterJudgeResponse(
@@ -135,7 +140,7 @@ async def safety_filter(description: str) -> SafetyFilterJudgeResponse:
async def safety_filter_activity(input: SafetyFilterInput) -> SafetyFilterOutput:
"""Filter out unsafe signals before passing them through the pipeline."""
try:
- result = await safety_filter(input.description)
+ result = await safety_filter(input.team_id, input.description)
except Exception:
logger.exception("Failed to run safety filter")
raise
diff --git a/products/signals/eval/AGENTS.md b/products/signals/eval/AGENTS.md
index c2599eb66eff..eef9806c3843 100644
--- a/products/signals/eval/AGENTS.md
+++ b/products/signals/eval/AGENTS.md
@@ -17,7 +17,7 @@ interleaved across groups to simulate real-world arrival patterns.
### Pipeline stages per signal
-1. **Pre-emit** — summarize long descriptions, check actionability (Gemini).
+1. **Pre-emit** — summarize long descriptions, check actionability (Claude Haiku via the internal LLM gateway).
Signals that fail actionability are dropped.
2. **Match** — generate search queries (LLM), embed queries (OpenAI),
cosine search against stored signals, LLM match to existing report or create new,
@@ -46,13 +46,14 @@ pytest products/signals/eval/eval_grouping_e2e.py -xvs --online
Set in `.env` at the repo root (loaded automatically):
-| Variable | Purpose |
-| ------------------------- | ------------------------------------------------------ |
-| `ANTHROPIC_API_KEY` | LLM calls (matching, specificity, summarization) |
-| `OPENAI_API_KEY` | Embeddings (text-embedding-3-small) |
-| `GEMINI_API_KEY` | Actionability check |
-| `POSTHOG_PROJECT_API_KEY` | Capturing eval results (skip with `--no-capture`) |
-| `POSTHOG_HOST` | PostHog instance (defaults to `http://localhost:8010`) |
+| Variable | Purpose |
+| ------------------------------ | ---------------------------------------------------------------------------------------------------------- |
+| `OPENAI_API_KEY` | Embeddings (text-embedding-3-small) |
+| `LLM_GATEWAY_URL` | Internal LLM gateway base URL (all LLM calls: matching, specificity, summarization, actionability, safety) |
+| `LLM_GATEWAY_PERSONAL_API_KEY` | Bearer token for the LLM gateway (PostHog personal API key) |
+| `SIGNALS_EVAL_TEAM_ID` | Team id used for LLM cost attribution headers (defaults to `1`) |
+| `POSTHOG_PROJECT_API_KEY` | Capturing eval results (skip with `--no-capture`) |
+| `POSTHOG_HOST` | PostHog instance (defaults to `http://localhost:8010`) |
### CLI options
diff --git a/products/signals/eval/conftest.py b/products/signals/eval/conftest.py
index d2cc5e94f951..d2b9f09d50c2 100644
--- a/products/signals/eval/conftest.py
+++ b/products/signals/eval/conftest.py
@@ -1,5 +1,4 @@
import os
-import logging
from pathlib import Path
import pytest
@@ -10,16 +9,13 @@ from django.conf import settings
import posthoganalytics
from dotenv import load_dotenv
from posthoganalytics import Posthog
-from posthoganalytics.ai.gemini import genai
from posthoganalytics.ai.openai import AsyncOpenAI
+from posthog.llm.gateway_client import get_async_anthropic_gateway_client
from posthog.models import Organization, Team
load_dotenv(Path(__file__).resolve().parents[3] / ".env")
-logging.getLogger("google_genai").setLevel(logging.ERROR)
-logging.getLogger("google.genai").setLevel(logging.ERROR)
-
# Initialize posthoganalytics default_client so the LLM wrapper (which requires it) works
posthoganalytics.default_client = Posthog( # ty: ignore[invalid-assignment]
os.environ.get("POSTHOG_PROJECT_API_KEY", "phx_unused"),
@@ -30,14 +26,17 @@ posthoganalytics.default_client = Posthog( # ty: ignore[invalid-assignment]
# Django settings are loaded before conftest, so .env vars aren't picked up.
# Override settings that need to come from .env.
-if not settings.ANTHROPIC_API_KEY:
- settings.ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
if not getattr(settings, "OPENAI_API_KEY", ""):
settings.OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
+if not getattr(settings, "LLM_GATEWAY_URL", ""):
+ settings.LLM_GATEWAY_URL = os.environ.get("LLM_GATEWAY_URL", "")
+if not getattr(settings, "LLM_GATEWAY_API_KEY", ""):
+ settings.LLM_GATEWAY_API_KEY = os.environ.get("LLM_GATEWAY_PERSONAL_API_KEY", "") or os.environ.get(
+ "LLM_GATEWAY_API_KEY", ""
+ )
-# Gemini client expects GOOGLE_API_KEY; alias from GEMINI_API_KEY if needed
-if not os.environ.get("GOOGLE_API_KEY") and os.environ.get("GEMINI_API_KEY"):
- os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
+# Team id used by the eval harness when attributing LLM cost via the gateway.
+EVAL_TEAM_ID = int(os.environ.get("SIGNALS_EVAL_TEAM_ID", "1"))
def pytest_addoption(parser):
@@ -94,9 +93,13 @@ async def openai_client(posthog_client):
@pytest.fixture
-def gemini_client():
- api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY", "")
- return genai.AsyncClient(api_key=api_key)
+def gateway_client():
+ """Async Anthropic client pointed at the internal LLM gateway's native Messages endpoint.
+
+ Used by eval_grouping_e2e to drive the production signals pre-emit pipeline
+ (`_check_actionability` etc.) through the gateway, attributing cost to EVAL_TEAM_ID.
+ """
+ return get_async_anthropic_gateway_client(product="signals", team_id=EVAL_TEAM_ID)
@pytest.fixture
diff --git a/products/signals/eval/eval_grouping_e2e.py b/products/signals/eval/eval_grouping_e2e.py
index a1f8ea5d3cf2..58b120b6353d 100644
--- a/products/signals/eval/eval_grouping_e2e.py
+++ b/products/signals/eval/eval_grouping_e2e.py
@@ -66,15 +66,22 @@ from products.signals.eval.common import (
MatchFailureMode,
get_signals_stream,
)
+from products.signals.eval.conftest import EVAL_TEAM_ID
from products.signals.eval.fixtures.grouping_data import GROUP_DATA
from products.signals.eval.mock import EmbeddingStore, ReportStore
class EvalGroupingPipeline:
+ def _eval_team(self):
+ """Lightweight Team stand-in for the pipeline helpers — they only read .id."""
+ from unittest.mock import MagicMock
+
+ return MagicMock(id=EVAL_TEAM_ID)
+
@pytest.fixture(autouse=True)
- def _setup(self, posthog_client, openai_client, gemini_client, mock_temporal, limit, no_capture, online):
+ def _setup(self, posthog_client, openai_client, gateway_client, mock_temporal, limit, no_capture, online):
self.posthog_client = posthog_client
- self.gemini_client = gemini_client
+ self.gateway_client = gateway_client
self.openai_client = openai_client
self.store = EmbeddingStore(openai_client)
self.report_store = ReportStore()
@@ -129,7 +136,7 @@ class EvalGroupingPipeline:
self.progress.signal_dropped()
return
- safety_result = await safety_filter(description)
+ safety_result = await safety_filter(EVAL_TEAM_ID, description)
await self._capture_safety_filter(case, safety_result)
if not safety_result.safe:
@@ -160,6 +167,7 @@ class EvalGroupingPipeline:
"""Generate search queries and compute all embeddings. No store mutations."""
queries = await generate_search_queries(
+ team_id=EVAL_TEAM_ID,
description=description,
source_product=case.signal.config.source_product,
source_type=case.signal.config.source_type,
@@ -187,6 +195,7 @@ class EvalGroupingPipeline:
candidates = [self.store.search(emb) for emb in query_embeddings]
match_result = await match_signal_to_report(
+ team_id=EVAL_TEAM_ID,
description=description,
source_product=case.signal.config.source_product,
source_type=case.signal.config.source_type,
@@ -202,6 +211,7 @@ class EvalGroupingPipeline:
group_signals = self.store.get_signals_for_report(specificity_match_result.report_id)
specificity_result = await verify_match_specificity(
+ team_id=EVAL_TEAM_ID,
new_signal_description=description,
new_signal_source_product=case.signal.config.source_product,
new_signal_source_type=case.signal.config.source_type,
@@ -264,6 +274,7 @@ class EvalGroupingPipeline:
if config.summarization_prompt is not None and config.description_summarization_threshold_chars is not None:
outputs = await _summarize_long_descriptions(
+ team=self._eval_team(),
outputs=outputs,
summarization_prompt=config.summarization_prompt,
threshold=config.description_summarization_threshold_chars,
@@ -273,10 +284,10 @@ class EvalGroupingPipeline:
output = outputs[0]
if config.actionability_prompt:
- is_actionable, thoughts = await _check_actionability(
- self.gemini_client, output, config.actionability_prompt
+ is_actionable = await _check_actionability(
+ self.gateway_client, EVAL_TEAM_ID, output, config.actionability_prompt
)
- await self._capture_pre_emit_actionability(case, thoughts, is_actionable)
+ await self._capture_pre_emit_actionability(case, None, is_actionable)
if not is_actionable:
return None
@@ -449,7 +460,7 @@ class EvalGroupingPipeline:
try:
expected_safe = all(GROUP_DATA[g].safe for g in report.true_signal_groups)
- safety_result = await judge_report_safety(signals=signals)
+ safety_result = await judge_report_safety(team_id=EVAL_TEAM_ID, signals=signals)
report.safety_choice = safety_result.choice
passed = safety_result.choice == expected_safe
diff --git a/products/signals/eval/llm_gen/client.py b/products/signals/eval/llm_gen/client.py
index ba25a109d67b..14a2f4832a3f 100644
--- a/products/signals/eval/llm_gen/client.py
+++ b/products/signals/eval/llm_gen/client.py
@@ -33,6 +33,7 @@ def _validator(schema_cls: type[T]) -> Callable[[str], T]:
async def generate_canonical_signals(
*,
+ team_id: int,
system_prompt: str,
user_prompt: str,
temperature: float = 0.7,
@@ -42,12 +43,14 @@ async def generate_canonical_signals(
Reuses `call_llm` from products.signals.backend.temporal.llm so we get the
same retry-on-validation-failure behavior the rest of the pipeline uses.
Model is controlled by the SIGNAL_MATCHING_LLM_MODEL env var (default
- claude-sonnet-4-5).
+ claude-sonnet-4-5). LLM cost is attributed to team_id via the gateway.
"""
batch = await call_llm(
+ team_id=team_id,
system_prompt=system_prompt,
user_prompt=user_prompt,
validate=_validator(CanonicalSignalBatch),
temperature=temperature,
+ stage="eval_signal_generation",
)
return batch.signals
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 8115592d272c..6a8b568ca4e5 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -49,7 +49,7 @@ You can use this key directly to make requests to the gateway locally.
It is also available as `settings.DEV_API_KEY` in Django.
In local dev (`DEBUG=True`), the gateway client defaults to `http://localhost:3308` and this key,
-so `get_llm_client()` works out of the box without setting any environment variables.
+so `get_llm_client(product=..., team_id=...)` works out of the box without setting any environment variables.
You can also provision the key manually:
@@ -302,10 +302,18 @@ For calling from PostHog Django:
```python
from posthog.llm.gateway_client import get_llm_client
-client = get_llm_client()
+# Pass `team_id` to attribute the captured `$ai_generation` event to a specific
+# customer team: it sets the `x-posthog-property-team_id` header on every request so
+# the usage reporter can break cost down per customer (the gateway PAK owns a single
+# internal team). Omit it to attribute to the key owner's team (the default).
+client = get_llm_client(product="my_product", team_id=team.id)
response = client.chat.completions.create(
model="claude-opus-4-5", # or any supported OpenAI, Anthropic, OpenRouter, or Fireworks AI model
messages=[...],
user=request.user.distinct_id, # user for analytics and rate limiting
)
```
+
+`ai_product` and `$ai_billable` are derived from the product config (`products/config.py`):
+the route sets `ai_product` from the `product` arg, and `$ai_billable` from that product's
+`billable` flag. Set `billable=True` on the product config to bill its generations.
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index bbc471bfc289..d29828d8bc08 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -63,6 +63,33 @@ def _is_product_billable(product: str) -> bool:
return bool(config and config.billable)
+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.
+ """
+ properties["ai_product"] = product
+ properties["$ai_billable"] = _is_product_billable(product)
+ 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
+ # property matches the rest of the platform (the usage reporter reads it via JSONExtractInt)
+ # rather than relying on ClickHouse string coercion.
+ raw_team_id = properties.get("team_id")
+ if raw_team_id is not None:
+ try:
+ properties["team_id"] = int(raw_team_id)
+ except (TypeError, ValueError):
+ if team_id is not None:
+ properties["team_id"] = team_id
+ else:
+ properties.pop("team_id", None)
+
+
# Stable namespace for hashing non-UUID trace identifiers (e.g. Claude Code's
# JSON-encoded session blobs sent via Anthropic's metadata.user_id) into a
# deterministic UUID. Generated once and frozen so the same input always maps
@@ -177,8 +204,6 @@ class PostHogCallback(InstrumentedCallback):
"$ai_stream": is_streaming,
"$ai_trace_id": trace_id,
"$ai_span_id": str(uuid4()),
- "ai_product": product,
- "$ai_billable": _is_product_billable(product),
# Stamped explicitly to bypass the SDK's group_type_index lookup.
# The AI usage report hardcodes `$group_1` (posthog/tasks/usage_report.py)
# so the gateway must guarantee that slot regardless of how the
@@ -213,8 +238,7 @@ class PostHogCallback(InstrumentedCallback):
for flag_key, variant in posthog_flags.items():
properties[f"$feature/{flag_key}"] = variant
- if team_id:
- properties["team_id"] = team_id
+ _apply_owned_event_properties(properties, product, team_id)
response_cost = standard_logging_object.get("response_cost")
if response_cost is not None:
@@ -291,8 +315,6 @@ class PostHogCallback(InstrumentedCallback):
"$ai_trace_id": trace_id,
"$ai_is_error": True,
"$ai_error": standard_logging_object.get("error_str", ""),
- "ai_product": product,
- "$ai_billable": _is_product_billable(product),
"$group_1": self._region_url,
}
@@ -306,8 +328,7 @@ class PostHogCallback(InstrumentedCallback):
for flag_key, variant in posthog_flags.items():
properties[f"$feature/{flag_key}"] = variant
- if team_id:
- properties["team_id"] = team_id
+ _apply_owned_event_properties(properties, product, team_id)
capture_kwargs: dict[str, Any] = {
"distinct_id": distinct_id,
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 978fcab45cdc..1f41bae76a62 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -16,9 +16,9 @@ class ProductConfig:
allowed_application_ids: frozenset[str] | None = frozenset()
allowed_models: frozenset[str] | None = None # None = all allowed
allow_api_keys: bool = True
- # Tag emitted $ai_generation events with $ai_billable=true so the PHAI
- # daily aggregator (posthog/tasks/usage_report.py) rolls them into the
- # customer team's AI credits bucket.
+ # Tag emitted $ai_generation events with $ai_billable=true so the usage reporter
+ # (posthog/tasks/usage_report.py) rolls them into the customer team's credit bucket
+ # for this product's ai_product (e.g. PostHog AI credits, or signals credits).
billable: bool = False
@@ -140,8 +140,10 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allow_api_keys=True,
),
"signals": ProductConfig(
- allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID}),
- allow_api_keys=False,
+ allowed_application_ids=None,
+ allowed_models=None, # any model — the signals pipeline picks models per stage (haiku, sonnet, ...)
+ allow_api_keys=True,
+ billable=True,
),
"subscriptions": ProductConfig(
allowed_application_ids=None,
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index 7d1c6b346181..8525f1191f0f 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -109,6 +109,111 @@ class TestPostHogCallback:
assert props["ai_product"] == "wizard"
mock_client.shutdown.assert_called_once()
+ @pytest.mark.asyncio
+ async def test_on_success_header_team_id_overrides_auth_user_team(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ ) -> None:
+ """A caller-supplied x-posthog-property-team_id wins over the key owner's team.
+
+ This is how a shared-key caller (e.g. signals) attributes a generation to the
+ customer team rather than the key owner's team that the usage reporter reads.
+ """
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch("llm_gateway.callbacks.posthog.get_product", return_value="signals"),
+ # headers arrive as strings — this is the realistic x-posthog-property-team_id path
+ patch("llm_gateway.callbacks.posthog.get_posthog_properties", return_value={"team_id": "999"}),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ call_kwargs = mock_client.capture.call_args.kwargs
+ props = call_kwargs["properties"]
+ # header-supplied customer team wins over auth_user.team_id (456), stored as an int
+ assert props["team_id"] == 999
+ assert isinstance(props["team_id"], int)
+ # the analytics project the event lands in still follows the authenticated team
+ assert call_kwargs["groups"] == {"instance": "https://us.posthog.com", "project": 456}
+
+ @pytest.mark.asyncio
+ async def test_on_success_invalid_header_team_id_falls_back_to_auth_team(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ ) -> None:
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch("llm_gateway.callbacks.posthog.get_product", return_value="signals"),
+ patch("llm_gateway.callbacks.posthog.get_posthog_properties", return_value={"team_id": "not-a-number"}),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ assert props["team_id"] == 456
+ assert isinstance(props["team_id"], int)
+
+ @pytest.mark.asyncio
+ async def test_on_success_invalid_header_team_id_dropped_without_auth_team(
+ self,
+ callback: PostHogCallback,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ ) -> None:
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=None),
+ patch("llm_gateway.callbacks.posthog.get_product", return_value="signals"),
+ patch("llm_gateway.callbacks.posthog.get_posthog_properties", return_value={"team_id": "not-a-number"}),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ assert "team_id" not in props
+
+ @pytest.mark.asyncio
+ async def test_on_success_headers_cannot_override_ai_product_or_billable(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ ) -> None:
+ """ai_product and $ai_billable are gateway-owned: caller headers can't override them.
+
+ Otherwise a typo'd header would silently mis-bill or misattribute the generation.
+ """
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+
+ 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_posthog_properties",
+ return_value={"ai_product": "spoofed", "$ai_billable": True},
+ ),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ # route-derived product wins over the header value
+ assert props["ai_product"] == "posthog_code"
+ # config-derived billable flag wins (posthog_code is non-billable)
+ assert props["$ai_billable"] is False
+
@pytest.mark.asyncio
async def test_on_success_uses_uuid_when_no_auth_user(
self,
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 73bcd205e8d6..48fd23527b39 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -58,12 +58,11 @@ class TestCheckProductAccess:
("llma_translation", "personal_api_key", None, "gpt-4.1-mini", True, None),
("llma_translation", "personal_api_key", None, "claude-3-opus", False, "not allowed"),
("llma_translation", "oauth_access_token", "any-app-id", "gpt-4.1-mini", False, "not authorized"),
- # signals requires OAuth with a posthog_code app ID; API keys rejected; no model allowlist
- ("signals", "personal_api_key", None, None, False, "requires OAuth"),
- ("signals", "oauth_access_token", "invalid-app-id", None, False, "not authorized"),
- ("signals", "oauth_access_token", POSTHOG_CODE_US_APP_ID, None, True, None),
- ("signals", "oauth_access_token", POSTHOG_CODE_EU_APP_ID, None, True, None),
- ("signals", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-3-opus", True, None),
+ # signals allows API keys (shared gateway key) with any model; OAuth rejected (no app IDs configured)
+ ("signals", "personal_api_key", None, "claude-haiku-4-5", True, None),
+ ("signals", "personal_api_key", None, "claude-sonnet-4-5", True, None),
+ ("signals", "personal_api_key", None, "claude-3-opus", True, None),
+ ("signals", "oauth_access_token", "any-app-id", "claude-haiku-4-5", False, "not authorized"),
# unknown product
("unknown", "personal_api_key", None, None, False, "Unknown product"),
],