:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): send typed gateway product attribution (#88387)
Richard Solomouc49f28e26d0e
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.pyindex 640e3a432f36..319d78eacaf6 100644--- a/posthog/llm/gateway_client.py+++ b/posthog/llm/gateway_client.py@@ -259,6 +259,8 @@ def ai_gateway_headers(labels["ai_product"] = ai_productheaders = _ai_property_headers(**labels) or {}+ if ai_product:+ headers["X-PostHog-Product"] = ai_productif trace_id:headers["X-PostHog-Trace-Id"] = trace_idif session_id:@@ -302,12 +304,6 @@ def team_trace_id(team_id: int | None) -> str | None:return str(uuid5(_TEAM_TRACE_ID_NAMESPACE, f"team-{team_id}"))-def _ai_trace_headers(team_id: int | None) -> dict[str, str]:- """``X-PostHog-Trace-Id`` header for a team; empty (not None) so callers can splat it."""- trace_id = team_trace_id(team_id)- return {"X-PostHog-Trace-Id": trace_id} if trace_id else {}--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``@@ -332,7 +328,8 @@ def build_openai_client(``product`` names the Python-gateway route used in the fallback; the slugless Go gatewayderives the team from its ``phs_`` bearer and ignores it. ``ai_product`` tags the captured- generation in gateway mode (the Python-gateway fallback derives the tag from ``product``).+ generation through both the typed product header and the legacy property in gateway mode+ (the Python-gateway fallback derives the tag from ``product``).``distinct_id`` is a Go-gateway header only. Callers must also pass the same value as ``user``on every completion request so the Python-gateway fallback preserves end-user attribution.trust_env=False keeps the in-cluster call off the egress proxy.@@ -392,9 +389,10 @@ def build_async_anthropic_client("""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.+ In gateway mode ``ai_product`` rides on both ``X-PostHog-Product`` and the legacy+ ``X-PostHog-Properties`` JSON blob. The ``ai_stage`` and ``team_id`` labels use only the+ blob because the Go gateway ignores the ``x-posthog-property-<key>`` per-header form that+ the Python gateway reads.``team_id`` is the customer team the generation is attributed to (the usage report reads it asa 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@@ -409,21 +407,22 @@ def build_async_anthropic_client("""gateway = resolve_ai_gateway_config()if gateway:- 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,- )- or {}- ),- **_ai_trace_headers(team_id),+ properties = {+ key: value+ for key, value in {+ "ai_stage": ai_stage,+ "team_id": str(team_id) if team_id is not None else None,+ }.items()+ if value}return AsyncAnthropic(api_key=gateway.api_key,base_url=_anthropic_gateway_base_url(gateway.url),- default_headers=default_headers or None,+ default_headers=ai_gateway_headers(+ ai_product=ai_product,+ trace_id=team_trace_id(team_id),+ properties=properties,+ ),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 f6df21db9a40..a3b5ebacf3bc 100644--- a/posthog/llm/test_gateway_client.py+++ b/posthog/llm/test_gateway_client.py@@ -226,7 +226,10 @@ class TestBuildOpenAIClient:mock_openai.assert_called_once_with(api_key=AI_GATEWAY_KEY,base_url=AI_GATEWAY_URL,- default_headers={"X-PostHog-Properties": json.dumps({"ai_product": "aio_summarization"})},+ default_headers={+ "X-PostHog-Properties": json.dumps({"ai_product": "aio_summarization"}),+ "X-PostHog-Product": "aio_summarization",+ },http_client=mock_httpx.return_value,)assert result is mock_openai.return_value@@ -251,7 +254,10 @@ class TestBuildAsyncOpenAIClient:mock_async_openai.assert_called_once_with(api_key=AI_GATEWAY_KEY,base_url=AI_GATEWAY_URL,- default_headers={"X-PostHog-Properties": json.dumps({"ai_product": "aio_eval_summary"})},+ default_headers={+ "X-PostHog-Properties": json.dumps({"ai_product": "aio_eval_summary"}),+ "X-PostHog-Product": "aio_eval_summary",+ },http_client=mock_httpx.return_value,)assert result is mock_async_openai.return_value@@ -336,20 +342,19 @@ class TestBuildAsyncAnthropicClient:)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"}- ),- "X-PostHog-Trace-Id": TEAM_42_TRACE_ID,- },- http_client=mock_httpx.return_value,- )+ mock_anthropic.assert_called_once()+ kwargs = mock_anthropic.call_args.kwargs+ assert kwargs["api_key"] == AI_GATEWAY_KEY+ assert kwargs["base_url"] == "https://ai-gateway.example"+ assert kwargs["http_client"] is mock_httpx.return_value+ headers = kwargs["default_headers"]+ assert json.loads(headers["X-PostHog-Properties"]) == {+ "ai_product": "signals_grouping",+ "ai_stage": "match",+ "team_id": "42",+ }+ assert headers["X-PostHog-Product"] == "signals_grouping"+ assert headers["X-PostHog-Trace-Id"] == TEAM_42_TRACE_IDassert result is mock_anthropic.return_value@override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)@@ -382,7 +387,10 @@ class TestBuildAsyncAnthropicClient: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"})}+ assert kwargs["default_headers"] == {+ "X-PostHog-Properties": json.dumps({"ai_product": "signals"}),+ "X-PostHog-Product": "signals",+ }@override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")@patch("posthog.llm.gateway_client.get_async_anthropic_gateway_client")diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.pyindex d62cf7423065..41ce5bfeb307 100644--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py@@ -82,6 +82,7 @@ class TestBuildOpenAIChatClient:headers = mock_chat.call_args.kwargs["default_headers"]assert headers == {+ "X-PostHog-Product": "aio_clustering","X-PostHog-Properties": json.dumps({"team_id": "42",diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex fb9431d069a7..62a78d7aeb08 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -28,22 +28,23 @@ When a gap closes, new work uses the Go gateway and affected callers should migr| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Customer LLM traffic | The caller uses a project secret or OAuth credential, the team wallet should pay, and standard OpenAI or Anthropic APIs are enough. || Server-to-server PostHog call | A `phs_` credential, team wallet billing, and informational event properties provide enough policy and attribution. Internal spend can use a PostHog-owned team wallet. |+| Capped delegated run | A standard credential can mint a short-lived `phe_` token with pinned attribution and a per-token spend cap. || Stock SDK proxy | The caller needs OpenAI Chat Completions or Responses, Anthropic Messages or token counting, streaming, idempotency, or the model catalog. || Gateway-managed routing | The caller accepts operator-managed provider plans and health-aware selection across OpenAI, Anthropic, Azure OpenAI, Bedrock, or configured Modal, Fireworks, and Baseten hosts. |-Existing Django callers should use `build_openai_client`, `build_async_openai_client`, or `build_async_anthropic_client` from [`posthog/llm/gateway_client.py`](../../posthog/llm/gateway_client.py). The OpenAI builders forward caller-selected distinct IDs, traces, sessions, and metadata while keeping a temporary Python fallback during rollout.+Existing Django callers should use `build_openai_client`, `build_async_openai_client`, or `build_async_anthropic_client` from [`posthog/llm/gateway_client.py`](../../posthog/llm/gateway_client.py). The builders forward product attribution and caller-selected metadata while keeping a temporary Python fallback during rollout.### ⛔ Stay on the Python gateway for now-| Use case | Blocking contract |-| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Trusted product identity, OAuth application allowlists, OAuth user attribution, server-minted credential requirements, per-product model policy, free-tier model allowlists, and product billing or unbilled policy are not available together in Go. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control, followed by a Django policy decision for Startup programs and prepaid credits. An `ai_product` event property is not an authorization or billing boundary. |-| Product or user budget enforcement | Python supports product and user cost limits, plan checks, quota buckets, and requests that debit no wallet. Go currently admits against the credential owner's team wallet and does not branch settlement on credential billing mode. |-| Agent runs a customer can start on demand | Python bounds one run's total spend against the task its credential was minted for, and picks the budget from the token's provenance rather than from the product the caller declares. Go has neither, so both the per-run ceiling and the pipeline-versus-user-started split would be lost on migration. |-| OpenRouter or Cloudflare Workers AI | These provider paths are not available in Go. |-| OpenAI audio transcription | Go has no transcription endpoint. |-| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |-| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |+| Use case | Blocking contract |+| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| PostHog Desktop, PostHog Code, cloud agents, onboarding, Wizard, and similar first-party products | Go can pin product and user attribution in a scoped token, but it does not apply Django's OAuth application allowlists, project access checks, plans, or billing policy. Desktop also requires a request-selected project validated against OAuth scope, live organization membership, and project-level access control. An asserted product remains caller-controlled and is not an authorization boundary. |+| Django plan or quota enforcement | Go supports rolling attribution budgets, a hard team cap, and per-token caps. Python still owns plan checks, quota buckets, free-model policy, and requests that debit no wallet. |+| Agent runs a customer can start on demand | Go can cap one run with a scoped token, but the Django integration only mints tokens for server-authorized internal products. User-started runs still need Python's provenance-based policy. |+| OpenRouter or Cloudflare Workers AI | These provider paths are not available in Go. |+| OpenAI audio transcription | Go has no transcription endpoint. |+| OpenAI models through Anthropic Messages | Go does not provide this reverse translation. |+| Python product usage status | The Python product usage and quota API is different from Go request usage and wallet APIs. |For PostHog Desktop, the Python gateway maps Django credential rejections to generic access denials. Transport, server, and malformed-response failures remain retryable service errors.@@ -52,9 +53,9 @@ For PostHog Desktop, the Python gateway maps Django credential rejections to genThese are compatibility checks, not automatic blockers:- **Model:** it appears in `GET /v1/models` and supports the requested API shape and capabilities.-- **Credential:** Go accepts the credential type and projects the correct team, scope, and revocation state.+- **Credential:** Go accepts `phs_`, `pha_`, and gateway-minted `phe_` credentials. Confirm the resolved team, scope, revocation state, attribution, and cap.- **Billing:** identify which team owns the Go credential and should pay, then confirm its wallet is funded for the expected usage. Internal workloads can debit a PostHog-owned team wallet so spend stays attributable without charging a customer.-- **Attribution:** `X-PostHog-Distinct-Id`, `X-PostHog-Trace-Id`, and `X-PostHog-Properties` provide enough event context. Go does not derive the event distinct ID from OpenAI `user`, Anthropic `metadata.user_id`, or the OAuth user. Caller-supplied properties are not trusted policy.+- **Attribution:** `X-PostHog-Product`, `X-PostHog-Distinct-Id`, `X-PostHog-Trace-Id`, and `X-PostHog-Properties` provide enough event context. Go does not derive the event distinct ID from OpenAI `user`, Anthropic `metadata.user_id`, or the OAuth user. Caller-supplied attribution is not trusted policy.- **Session attribution:** `X-PostHog-Session-Id` provides the required gateway-owned `$ai_session_id`.- **Provider deployment:** Fireworks and Baseten host support exists in Go, but the target environment must declare the required host and credentials. Baseten also requires approved-subprocessor status before deployment.- **Provider behavior:** operator routing policy, health-aware provider ordering, or strict `X-PostHog-Provider` pinning matches the caller's fallback requirements.@@ -63,19 +64,19 @@ These are compatibility checks, not automatic blockers:## Parity map-| Contract | Go gateway today | Python-only behavior that can block migration |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Authentication | `phs_` project secrets and `pha_` OAuth credentials with the literal `llm_gateway:read` scope; credential resolves a fixed team and revocation state. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |-| Trusted first-party identity | No trusted product identity or product-scoped authorization boundary. | Product route selects allowlisted OAuth apps, server credential requirements, model policy, and the project-scoped PostHog Desktop policy on `posthog_code`. Django applies the access override before Startup-program and prepaid-credit restrictions; server-minted `internal_run:read` credentials bypass the human gate. |-| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to team ID. Supports trace ID, custom JSON properties, team project token, provider, usage, and cost. | OAuth user identity, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived end-user identity, gateway-owned `$ai_product` and `$ai_billable`, per-key properties, and feature flag headers. |-| Billing and limits | Wallet reservation and settlement, idempotency, balance read, request usage read, and front-line rate limiting. | Product and user cost windows, per-sandbox-run ceilings keyed on the credential's task binding, budget keys derived from token scopes rather than the declared product, plans, quota buckets, product-specific free-tier model allowlists, unbilled products, and product usage status. |-| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |-| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |-| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and configured Modal, Fireworks, and Baseten hosts. | OpenRouter and Cloudflare Workers AI. |-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. |-| Routing and failure behavior | Operator-managed provider plans, health-aware ordering, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |-| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |-| Session attribution | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |+| Contract | Go gateway today | Python-only behavior that can block migration |+| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Authentication | `phs_` project secrets and `pha_` OAuth credentials require `llm_gateway:read`. Standard credentials can mint capped and revocable `phe_` tokens. | `phx_` personal keys, wildcard OAuth scope handling, product-specific API key or OAuth application rules, and Desktop's request-selected project validated against OAuth scope and live organization membership. |+| Trusted first-party identity | Scoped tokens pin product, user, and obo attribution at mint. Standard credential headers remain caller-controlled and do not authorize a product. | Product routes select allowlisted OAuth apps, server credential requirements, model policy, and Django product policy. Django also decides which callers may receive a product-scoped credential. |+| Attribution | Distinct ID comes from `X-PostHog-Distinct-Id` or falls back to a namespaced team identity. Product, user, and obo attribution land on events and ledger entries with provenance. | OAuth user identity, ACL-resolved OAuth team attribution, staff-owned personal-key customer-team overrides, body-derived end-user identity, gateway-owned `$ai_billable`, per-key properties, and feature flag headers. |+| Billing and limits | Wallet reservation and settlement, soft attribution budgets, a hard team cap, per-token caps, idempotency, balance and usage reads, and front-line rate limits. | Plans, quota buckets, product-specific free-model policy, unbilled products, product usage status, and Django provenance rules that decide which cap applies. |+| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. |+| Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. |+| Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and configured Modal, Fireworks, and Baseten hosts. | OpenRouter and Cloudflare Workers AI. |+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. |+| Routing and failure behavior | Operator-managed provider plans, health-aware ordering, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. |+| Event metadata | One `X-PostHog-Properties` JSON object plus dedicated product, user, obo, distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. |+| Session attribution | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |## Migration checklist@@ -91,10 +92,10 @@ Run `/migrating-llm-gateway-callers` to inventory and convert a caller.Run `/auditing-llm-gateway-parity` after either gateway changes auth, attribution, billing, endpoints, providers, models, routing, or event metadata. The skill audits implementation sources in both repositories and updates this file without migrating callers.-Last verified on 2026-08-24 against:+Last verified on 2026-08-25 against:-- `PostHog/posthog` working tree compared with master at `e579a630700a93bc6a325758015c5e1227f05267`-- `PostHog/ai-gateway` main at `9a9826ea448b3f5fcddeb8bc09ef187963a93902`+- `PostHog/posthog` working tree compared with master at `c22b95e0009c54388fd1b199d3248f48aba019e2`+- `PostHog/ai-gateway` main at `d7545e0979ff38d7df1ce73779253897c99c3c46`## References