Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(llm-gateway): send team trace id to the Go gateway (#74249)

Brandon42486787535d
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index 96d4a9f35e93..6544a2e0f7fe 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -1,6 +1,7 @@
import json
from typing import Literal
from urllib.parse import urlparse
+from uuid import UUID, uuid5
from django.conf import settings
@@ -218,6 +219,28 @@ def ai_product_headers(ai_product: str | None) -> dict[str, str] | None:
return _ai_property_headers(ai_product=ai_product)
+# Mirrors the namespace in services/llm-gateway/src/llm_gateway/callbacks/posthog.py. Both must
+# stay equal or a team's trace id changes with whichever gateway serves it.
+_TEAM_TRACE_ID_NAMESPACE = UUID("8d4f6b7e-6a3e-4f3a-9f3b-3b6f4d2e8a1a")
+
+
+def team_trace_id(team_id: int | None) -> str | None:
+ """Deterministic ``$ai_trace_id`` for a team, or None when unattributed.
+
+ Absent an ``X-PostHog-Trace-Id`` header the Go gateway stamps a fresh id per request, leaving
+ every generation in its own trace. Grouping is per team, not per pipeline run.
+ """
+ if team_id is None:
+ return 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``
@@ -285,18 +308,28 @@ def build_async_anthropic_client(
``use_bedrock_fallback`` only affects the Python-gateway fallback path; the Go gateway fails
over to Bedrock on its own via the host breaker and reads no opt-in header. trust_env=False
keeps the in-cluster call off the egress proxy.
+
+ An attributed call also carries ``X-PostHog-Trace-Id`` (see :func:`team_trace_id`); the
+ Python-gateway fallback derives the same id internally and needs no header.
"""
gateway = resolve_ai_gateway_config()
if gateway:
url, api_key = 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),
+ }
return AsyncAnthropic(
api_key=api_key,
base_url=_anthropic_gateway_base_url(url),
- default_headers=_ai_property_headers(
- ai_product=ai_product,
- ai_stage=ai_stage,
- team_id=str(team_id) if team_id is not None else None,
- ),
+ default_headers=default_headers or None,
http_client=httpx.AsyncClient(trust_env=False),
)
return get_async_anthropic_gateway_client(product, team_id=team_id, use_bedrock_fallback=use_bedrock_fallback)
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 95587d784247..5088efea71f3 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -15,10 +15,12 @@ from posthog.llm.gateway_client import (
get_async_llm_client,
get_llm_client,
resolve_ai_gateway_config,
+ team_trace_id,
)
AI_GATEWAY_URL = "https://ai-gateway.example/v1"
AI_GATEWAY_KEY = "phs_project_secret"
+TEAM_42_TRACE_ID = "30a04c7a-98b4-5119-8597-8c696e44a270"
class TestGetLlmClient:
@@ -262,6 +264,28 @@ class TestBuildAsyncOpenAIClient:
assert result is mock_get_async.return_value
+class TestTeamTraceId:
+ # Expected ids are $ai_trace_id values observed on captured events, not recomputed from the
+ # helper: recomputing would make the test agree with itself and miss a namespace change.
+ @pytest.mark.parametrize(
+ "team_id,expected",
+ [
+ (2, "aba5a277-3ba6-5682-a2da-f455d39e8aff"),
+ (1589, "2e803550-d2e1-5dd7-9124-0fdd7e8c9518"),
+ (169318, "92733d55-3d1e-5062-905b-0afa3b2e2a92"),
+ (487950, "78c3f90a-d69e-5fe6-b2b2-3f22a4d7ebb1"),
+ ],
+ )
+ def test_matches_python_gateway_derivation(self, team_id: int, expected: str):
+ assert team_trace_id(team_id) == expected
+
+ def test_unattributed_call_has_no_trace_id(self):
+ assert team_trace_id(None) is None
+
+ def test_distinct_teams_do_not_share_a_trace(self):
+ assert team_trace_id(2) != team_trace_id(3)
+
+
class TestBuildAsyncAnthropicClient:
@override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
@patch("posthog.llm.gateway_client.httpx.AsyncClient")
@@ -281,12 +305,36 @@ class TestBuildAsyncAnthropicClient:
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,
)
assert result is mock_anthropic.return_value
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
+ @patch("posthog.llm.gateway_client.httpx.AsyncClient")
+ @patch("posthog.llm.gateway_client.AsyncAnthropic")
+ def test_gateway_mode_omits_trace_header_when_team_id_unset(self, mock_anthropic, mock_httpx):
+ build_async_anthropic_client("signals", ai_product="signals_grouping", ai_stage="match")
+
+ _, kwargs = mock_anthropic.call_args
+ assert "X-PostHog-Trace-Id" not in kwargs["default_headers"]
+
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
+ @patch("posthog.llm.gateway_client.httpx.AsyncClient")
+ @patch("posthog.llm.gateway_client.AsyncAnthropic")
+ def test_gateway_mode_sends_trace_header_alongside_properties(self, mock_anthropic, mock_httpx):
+ # The emission path replaces the properties blob per call and the gateway strips
+ # $-prefixed keys, so the trace has to ride its own header.
+ build_async_anthropic_client("signals", team_id=42)
+
+ _, kwargs = mock_anthropic.call_args
+ assert kwargs["default_headers"] == {
+ "X-PostHog-Properties": json.dumps({"team_id": "42"}),
+ "X-PostHog-Trace-Id": TEAM_42_TRACE_ID,
+ }
+
@override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
@patch("posthog.llm.gateway_client.httpx.AsyncClient")
@patch("posthog.llm.gateway_client.AsyncAnthropic")