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(aio): group background agent calls into sessions (#78980)

Radu Raicea799f85226087
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index a2509d5393c4..c96ada6a63ce 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -1,4 +1,5 @@
import json
+from collections.abc import Mapping
from typing import Literal
from urllib.parse import urlparse
from uuid import UUID, uuid5
@@ -44,7 +45,17 @@ 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, api_key: str | None = None) -> OpenAI:
+def team_distinct_id(team_id: int) -> str:
+ """Namespace team-owned work away from bare numeric user distinct IDs."""
+ return f"team-{team_id}"
+
+
+def get_llm_client(
+ product: Product = "django",
+ team_id: int | None = None,
+ api_key: str | None = None,
+ default_headers: Mapping[str, str] | None = None,
+) -> OpenAI:
"""
Get an OpenAI-compatible client for the internal LLM gateway.
@@ -94,21 +105,31 @@ def get_llm_client(product: Product = "django", team_id: int | None = None, api_
when omitted, the event is attributed to the gateway key owner's team.
api_key: Optional short-lived credential to use instead of `LLM_GATEWAY_API_KEY`.
Server-only products use this to avoid exposing the shared personal API key.
+ default_headers: Optional headers sent with every request. Product-owned headers such as
+ team attribution override values supplied here.
"""
resolved_api_key = api_key or settings.LLM_GATEWAY_API_KEY
if not settings.LLM_GATEWAY_URL or not resolved_api_key:
raise ValueError("LLM_GATEWAY_URL and an API key must be configured")
base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"
+ headers = dict(default_headers or {})
+ if team_id is not None:
+ headers.update(_team_id_header(team_id))
+
return OpenAI(
base_url=base_url,
api_key=resolved_api_key,
- default_headers=_team_id_header(team_id) if team_id is not None else None,
+ default_headers=headers or None,
http_client=httpx.Client(trust_env=False),
)
-def get_async_llm_client(product: Product = "django", team_id: int | None = None) -> AsyncOpenAI:
+def get_async_llm_client(
+ product: Product = "django",
+ team_id: int | None = None,
+ default_headers: Mapping[str, str] | None = None,
+) -> AsyncOpenAI:
"""
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.
@@ -117,10 +138,14 @@ def get_async_llm_client(product: Product = "django", team_id: int | None = None
raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")
base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"
+ headers = dict(default_headers or {})
+ if team_id is not None:
+ headers.update(_team_id_header(team_id))
+
return AsyncOpenAI(
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,
+ default_headers=headers or None,
http_client=httpx.AsyncClient(trust_env=False),
)
@@ -211,13 +236,27 @@ def _ai_property_headers(**labels: str | None) -> dict[str, str] | None:
return {"X-PostHog-Properties": json.dumps(set_labels)}
-def ai_product_headers(ai_product: str | None) -> dict[str, str] | None:
- """X-PostHog-Properties header tagging the captured generation with its AIO product.
-
- The slugless Go gateway has no product route, so callers pass the product here to keep
- per-product attribution on the shared ``phs_`` token.
- """
- return _ai_property_headers(ai_product=ai_product)
+def ai_gateway_headers(
+ *,
+ ai_product: str | None = None,
+ trace_id: str | None = None,
+ session_id: str | None = None,
+ properties: Mapping[str, str] | None = None,
+ distinct_id: str | None = None,
+) -> dict[str, str] | None:
+ """Build the Go ai-gateway headers that correlate a multi-call AI operation."""
+ labels = dict(properties or {})
+ if ai_product:
+ labels["ai_product"] = ai_product
+
+ headers = _ai_property_headers(**labels) or {}
+ if trace_id:
+ headers["X-PostHog-Trace-Id"] = trace_id
+ if session_id:
+ headers["X-PostHog-Session-Id"] = session_id
+ if distinct_id:
+ headers["X-PostHog-Distinct-Id"] = distinct_id
+ return headers or None
# Mirrors the namespace in services/llm-gateway/src/llm_gateway/callbacks/posthog.py. Both must
@@ -225,6 +264,24 @@ def ai_product_headers(ai_product: str | None) -> dict[str, str] | None:
_TEAM_TRACE_ID_NAMESPACE = UUID("8d4f6b7e-6a3e-4f3a-9f3b-3b6f4d2e8a1a")
+def _python_gateway_observability_headers(
+ trace_id: str | None,
+ session_id: str | None,
+ properties: Mapping[str, str] | None,
+) -> dict[str, str] | None:
+ headers = {f"x-posthog-property-{key}": value for key, value in (properties or {}).items()}
+ if session_id:
+ headers["x-posthog-property-$ai_session_id"] = session_id
+ if trace_id:
+ try:
+ normalized_trace_id = UUID(trace_id)
+ except ValueError:
+ normalized_trace_id = uuid5(_TEAM_TRACE_ID_NAMESPACE, trace_id)
+ span_id = uuid5(_TEAM_TRACE_ID_NAMESPACE, f"span-{trace_id}").hex[:16]
+ headers["traceparent"] = f"00-{normalized_trace_id.hex}-{span_id}-01"
+ return headers or None
+
+
def team_trace_id(team_id: int | None) -> str | None:
"""Deterministic ``$ai_trace_id`` for a team, or None when unattributed.
@@ -253,13 +310,22 @@ def _anthropic_gateway_base_url(openai_base_url: str) -> str:
return trimmed
-def build_openai_client(product: Product, ai_product: str | None = None) -> OpenAI:
+def build_openai_client(
+ product: Product,
+ ai_product: str | None = None,
+ trace_id: str | None = None,
+ session_id: str | None = None,
+ properties: Mapping[str, str] | None = None,
+ distinct_id: str | None = None,
+) -> OpenAI:
"""Return a raw OpenAI client routed through the internal Go ai-gateway when configured,
else the Python LLM gateway via :func:`get_llm_client`.
``product`` names the Python-gateway route used in the fallback; the slugless Go gateway
derives 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``).
+ ``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.
"""
gateway = resolve_ai_gateway_config()
@@ -268,13 +334,27 @@ def build_openai_client(product: Product, ai_product: str | None = None) -> Open
return OpenAI(
api_key=api_key,
base_url=url,
- default_headers=ai_product_headers(ai_product),
+ default_headers=ai_gateway_headers(
+ ai_product=ai_product,
+ trace_id=trace_id,
+ session_id=session_id,
+ properties=properties,
+ distinct_id=distinct_id,
+ ),
http_client=httpx.Client(trust_env=False),
)
- return get_llm_client(product)
+ fallback_headers = _python_gateway_observability_headers(trace_id, session_id, properties)
+ return get_llm_client(product, default_headers=fallback_headers)
-def build_async_openai_client(product: Product, ai_product: str | None = None) -> AsyncOpenAI:
+def build_async_openai_client(
+ product: Product,
+ ai_product: str | None = None,
+ trace_id: str | None = None,
+ session_id: str | None = None,
+ properties: Mapping[str, str] | None = None,
+ distinct_id: str | None = None,
+) -> AsyncOpenAI:
"""Async variant of :func:`build_openai_client`."""
gateway = resolve_ai_gateway_config()
if gateway:
@@ -282,10 +362,17 @@ def build_async_openai_client(product: Product, ai_product: str | None = None) -
return AsyncOpenAI(
api_key=api_key,
base_url=url,
- default_headers=ai_product_headers(ai_product),
+ default_headers=ai_gateway_headers(
+ ai_product=ai_product,
+ trace_id=trace_id,
+ session_id=session_id,
+ properties=properties,
+ distinct_id=distinct_id,
+ ),
http_client=httpx.AsyncClient(trust_env=False),
)
- return get_async_llm_client(product)
+ fallback_headers = _python_gateway_observability_headers(trace_id, session_id, properties)
+ return get_async_llm_client(product, default_headers=fallback_headers)
def build_async_anthropic_client(
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 5088efea71f3..f14cea725ca9 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -235,7 +235,7 @@ class TestBuildOpenAIClient:
def test_falls_back_to_python_gateway_when_unset(self, mock_get_llm_client):
result = build_openai_client("llma_summarization", ai_product="aio_summarization")
- mock_get_llm_client.assert_called_once_with("llma_summarization")
+ mock_get_llm_client.assert_called_once_with("llma_summarization", default_headers=None)
assert result is mock_get_llm_client.return_value
@@ -255,14 +255,53 @@ class TestBuildAsyncOpenAIClient:
)
assert result is mock_async_openai.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.AsyncOpenAI")
+ def test_gateway_mode_correlates_all_calls_in_a_trace_and_session(self, mock_async_openai, mock_httpx):
+ result = build_async_openai_client(
+ "llma_eval_summary",
+ ai_product="aio_eval_summary",
+ trace_id="a9f9e1dd-8332-4ad0-959b-36ea0a45734e",
+ session_id="summary-session-1",
+ properties={"team_id": "42", "evaluation_id": "evaluation-123"},
+ distinct_id="user-123",
+ )
+
+ headers = mock_async_openai.call_args.kwargs["default_headers"]
+ assert headers["X-PostHog-Trace-Id"] == "a9f9e1dd-8332-4ad0-959b-36ea0a45734e"
+ assert headers["X-PostHog-Session-Id"] == "summary-session-1"
+ assert headers["X-PostHog-Distinct-Id"] == "user-123"
+ assert json.loads(headers["X-PostHog-Properties"]) == {
+ "team_id": "42",
+ "evaluation_id": "evaluation-123",
+ "ai_product": "aio_eval_summary",
+ }
+ assert result is mock_async_openai.return_value
+
@override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
@patch("posthog.llm.gateway_client.get_async_llm_client")
def test_falls_back_to_python_async_gateway_when_unset(self, mock_get_async):
result = build_async_openai_client("llma_eval_summary", ai_product="aio_eval_summary")
- mock_get_async.assert_called_once_with("llma_eval_summary")
+ mock_get_async.assert_called_once_with("llma_eval_summary", default_headers=None)
assert result is mock_get_async.return_value
+ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
+ @patch("posthog.llm.gateway_client.get_async_llm_client")
+ def test_python_gateway_fallback_preserves_trace_and_native_session(self, mock_get_async):
+ build_async_openai_client(
+ "llma_eval_summary",
+ trace_id="a9f9e1dd-8332-4ad0-959b-36ea0a45734e",
+ session_id="summary-session-1",
+ properties={"evaluation_id": "evaluation-123"},
+ )
+
+ headers = mock_get_async.call_args.kwargs["default_headers"]
+ assert headers["traceparent"].startswith("00-a9f9e1dd83324ad0959b36ea0a45734e-")
+ assert headers["x-posthog-property-$ai_session_id"] == "summary-session-1"
+ assert headers["x-posthog-property-evaluation_id"] == "evaluation-123"
+
class TestTeamTraceId:
# Expected ids are $ai_trace_id values observed on captured events, not recomputed from the
diff --git a/posthog/temporal/ai_observability/clustering_agent/__init__.py b/posthog/temporal/ai_observability/clustering_agent/__init__.py
index c92f2e5dd89d..f0e7aaea514e 100644
--- a/posthog/temporal/ai_observability/clustering_agent/__init__.py
+++ b/posthog/temporal/ai_observability/clustering_agent/__init__.py
@@ -8,6 +8,8 @@ duplicate; the level-specific prompts, tools, and state TypedDicts live with
each individual agent so per-level prompt iteration stays local.
"""
+from collections.abc import Mapping
+
from langchain_openai import ChatOpenAI
from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
@@ -15,7 +17,15 @@ from posthog.temporal.ai_observability.trace_clustering.constants import NOISE_C
from posthog.temporal.ai_observability.trace_clustering.models import ClusterLabel
-def get_labeling_llm(model: str, timeout: float) -> ChatOpenAI:
+def get_labeling_llm(
+ model: str,
+ timeout: float,
+ *,
+ trace_id: str,
+ session_id: str,
+ properties: Mapping[str, str],
+ distinct_id: str,
+) -> ChatOpenAI:
"""Return a ChatOpenAI client for cluster labeling.
Shared by the trace and evaluation labeling agents. Routes through the
@@ -23,7 +33,15 @@ def get_labeling_llm(model: str, timeout: float) -> ChatOpenAI:
``posthog.temporal.ai_observability.llm_endpoint``. Enforces the same
guardrail as before: AI features only run in Cloud or local DEBUG builds.
"""
- return build_langchain_chat_client(model, timeout, ai_product="aio_clustering")
+ return build_langchain_chat_client(
+ model,
+ timeout,
+ ai_product="aio_clustering",
+ trace_id=trace_id,
+ session_id=session_id,
+ properties=properties,
+ distinct_id=distinct_id,
+ )
def fill_missing_labels(
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 14781ed1e546..69a4544a1f08 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -590,6 +590,9 @@ async def run_eval_report_agent_activity(
return (
run_eval_report_agent(
team_id=inputs.team_id,
+ report_id=inputs.report_id,
+ trace_id=inputs.trace_id,
+ session_id=inputs.session_id,
evaluation_id=inputs.evaluation_id,
evaluation_name=inputs.evaluation_name,
evaluation_description=inputs.evaluation_description,
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
index 56ccc4e57742..2a9b92c42d8e 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -4,14 +4,11 @@ import uuid
from typing import Any
import structlog
-import posthoganalytics
-from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import HumanMessage
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt import create_react_agent
-from posthoganalytics.ai.langchain.callbacks import CallbackHandler
-from posthog.llm.gateway_client import resolve_ai_gateway_config
+from posthog.llm.gateway_client import team_distinct_id
from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import build_eval_report_system_prompt
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
@@ -35,7 +32,7 @@ from posthog.temporal.ai_observability.eval_reports.targets import (
TRACE_ID_ALLOWLIST_KEY,
get_target_descriptor,
)
-from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
+from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks, build_langchain_chat_client
logger = structlog.get_logger(__name__)
@@ -220,6 +217,9 @@ def run_eval_report_agent(
report_prompt_guidance: str = "",
output_type: str = "boolean",
evaluation_target: str = "generation",
+ report_id: str = "",
+ trace_id: str = "",
+ session_id: str = "",
) -> EvalReportContent:
"""Run the evaluation report agent and return the generated content.
@@ -259,7 +259,23 @@ def run_eval_report_agent(
)
return _metrics_unavailable_content(evaluation_target)
- llm = build_langchain_chat_client(EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports")
+ resolved_trace_id = trace_id or str(uuid.uuid4())
+ resolved_session_id = session_id or resolved_trace_id
+ resolved_distinct_id = team_distinct_id(team_id)
+ observability_properties = {
+ "team_id": str(team_id),
+ "evaluation_id": evaluation_id,
+ **({"report_id": report_id} if report_id else {}),
+ }
+ llm = build_langchain_chat_client(
+ EVAL_REPORT_AGENT_MODEL,
+ EVAL_REPORT_AGENT_TIMEOUT,
+ ai_product="aio_eval_reports",
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
+ properties=observability_properties,
+ distinct_id=resolved_distinct_id,
+ )
system_prompt = build_eval_report_system_prompt(
evaluation_name=evaluation_name,
@@ -302,21 +318,13 @@ def run_eval_report_agent(
SESSION_ID_ALLOWLIST_KEY: [],
}
- # Skip in gateway mode: the Go gateway captures $ai_generation itself, so the
- # SDK callback would double-count. Same gate the model routing above reads.
- callbacks: list[BaseCallbackHandler] = []
- if posthoganalytics.default_client and resolve_ai_gateway_config() is None:
- callbacks.append(
- CallbackHandler(
- posthoganalytics.default_client,
- distinct_id=str(team_id),
- trace_id=f"llma-eval-report-{evaluation_id}-{uuid.uuid4()}",
- properties={
- "ai_product": "llma_eval_reports",
- "evaluation_id": evaluation_id,
- },
- )
- )
+ callbacks = build_langchain_callbacks(
+ distinct_id=resolved_distinct_id,
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
+ ai_product="aio_eval_reports",
+ properties=observability_properties,
+ )
config: RunnableConfig = {
"recursion_limit": EVAL_REPORT_AGENT_RECURSION_LIMIT,
@@ -345,6 +353,8 @@ def run_eval_report_agent(
reason=validation_error,
title=content.title,
section_count=len(content.sections),
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
)
return _fallback_content(evaluation_name, metrics, validation_error, evaluation_target)
@@ -360,6 +370,8 @@ def run_eval_report_agent(
section_count=len(content.sections),
citation_count=len(content.citations),
metrics=metrics.to_dict(),
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
)
return content
@@ -373,6 +385,8 @@ def run_eval_report_agent(
error_type=type(e).__name__,
team_id=team_id,
evaluation_id=evaluation_id,
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
)
return _fallback_content(
evaluation_name,
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
index 117cd00baf22..9ea8a608546e 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
@@ -352,17 +352,18 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
fails this test even though the agent run itself is mocked out.
"""
- @patch.object(graph, "posthoganalytics")
+ @patch.object(graph, "build_langchain_callbacks", return_value=[])
@patch.object(graph, "create_react_agent")
@patch.object(graph, "build_langchain_chat_client")
@patch.object(graph, "_compute_metrics")
- def test_routes_llm_through_gateway_helper(self, mock_metrics, mock_build_llm, mock_create_agent, mock_pha):
+ def test_routes_llm_through_gateway_helper(
+ self, mock_metrics, mock_build_llm, mock_create_agent, _mock_build_callbacks
+ ):
from posthog.temporal.ai_observability.eval_reports.constants import (
EVAL_REPORT_AGENT_MODEL,
EVAL_REPORT_AGENT_TIMEOUT,
)
- mock_pha.default_client = None # skip the analytics callback
mock_metrics.return_value = EvalReportMetrics()
mock_agent = MagicMock()
mock_agent.invoke.return_value = {
@@ -376,6 +377,9 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
graph.run_eval_report_agent(
team_id=1,
+ report_id="report-1",
+ trace_id="report-run-1",
+ session_id="report-session-1",
evaluation_id="eval-1",
evaluation_name="Relevance",
evaluation_description="",
@@ -387,21 +391,25 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
)
mock_build_llm.assert_called_once_with(
- EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports"
+ EVAL_REPORT_AGENT_MODEL,
+ EVAL_REPORT_AGENT_TIMEOUT,
+ ai_product="aio_eval_reports",
+ trace_id="report-run-1",
+ session_id="report-session-1",
+ properties={"team_id": "1", "evaluation_id": "eval-1", "report_id": "report-1"},
+ distinct_id="team-1",
)
# the agent is built with the gateway-helper client, not a directly-constructed one
self.assertIs(mock_create_agent.call_args.kwargs["model"], mock_build_llm.return_value)
class TestRunEvalReportAgentMetricsUnavailable(SimpleTestCase):
- @patch.object(graph, "posthoganalytics")
@patch.object(graph, "build_langchain_chat_client")
@patch.object(graph, "create_react_agent")
@patch.object(graph, "_compute_metrics")
def test_metrics_unavailable_skips_agent_and_returns_fallback(
- self, mock_metrics, mock_create_agent, mock_build_llm, mock_pha
+ self, mock_metrics, mock_create_agent, mock_build_llm
):
- mock_pha.default_client = None
mock_metrics.return_value = None
with (
@@ -432,16 +440,18 @@ class TestRunEvalReportAgentMetricsUnavailable(SimpleTestCase):
self.assertEqual(content.sections, [])
-class TestRunEvalReportAgentCallbackGating(SimpleTestCase):
- """The SDK CallbackHandler fires only when NOT routing through the gateway.
-
- In gateway mode the Go gateway captures $ai_generation itself, so attaching the
- SDK callback too would double-count every eval-report LLM call. The gate is the
- same resolve_ai_gateway_config() the model routing reads. Reverting the guard
- (dropping `and resolve_ai_gateway_config() is None`) fails the gateway-on case.
- """
-
- def _run_and_get_callbacks(self, mock_create_agent):
+class TestRunEvalReportAgentInstrumentation(SimpleTestCase):
+ @patch.object(graph.logger, "info")
+ @patch.object(graph, "build_langchain_callbacks")
+ @patch.object(graph, "create_react_agent")
+ @patch.object(graph, "build_langchain_chat_client")
+ @patch.object(graph, "_compute_metrics")
+ def test_uses_one_trace_and_session_for_the_report_run(
+ self, mock_metrics, mock_build_llm, mock_create_agent, mock_build_callbacks, mock_logger_info
+ ):
+ mock_metrics.return_value = EvalReportMetrics()
+ callbacks = [MagicMock()]
+ mock_build_callbacks.return_value = callbacks
mock_agent = MagicMock()
mock_agent.invoke.return_value = {
"report": EvalReportContent(
@@ -453,6 +463,9 @@ class TestRunEvalReportAgentCallbackGating(SimpleTestCase):
mock_create_agent.return_value = mock_agent
graph.run_eval_report_agent(
team_id=1,
+ report_id="report-1",
+ trace_id="report-run-1",
+ session_id="report-session-1",
evaluation_id="eval-1",
evaluation_name="Relevance",
evaluation_description="",
@@ -462,40 +475,60 @@ class TestRunEvalReportAgentCallbackGating(SimpleTestCase):
period_end="2026-04-08T15:00:00+00:00",
previous_period_start="2026-04-08T13:00:00+00:00",
)
- return mock_agent.invoke.call_args.args[1]["callbacks"]
- @patch.object(graph, "resolve_ai_gateway_config")
- @patch.object(graph, "CallbackHandler")
- @patch.object(graph, "posthoganalytics")
- @patch.object(graph, "create_react_agent")
- @patch.object(graph, "build_langchain_chat_client")
- @patch.object(graph, "_compute_metrics")
- def test_gateway_mode_attaches_no_callback(
- self, mock_metrics, mock_build_llm, mock_create_agent, mock_pha, mock_cb, mock_resolve
- ):
- mock_metrics.return_value = EvalReportMetrics()
- mock_pha.default_client = MagicMock() # analytics client available...
- mock_resolve.return_value = ("https://gateway.example/v1", "key") # ...but gateway is live
-
- callbacks = self._run_and_get_callbacks(mock_create_agent)
-
- self.assertEqual(callbacks, [], "gateway mode must attach no SDK callback (the gateway captures the event)")
- mock_cb.assert_not_called()
+ expected_properties = {"team_id": "1", "evaluation_id": "eval-1", "report_id": "report-1"}
+ mock_build_callbacks.assert_called_once_with(
+ distinct_id="team-1",
+ trace_id="report-run-1",
+ session_id="report-session-1",
+ ai_product="aio_eval_reports",
+ properties=expected_properties,
+ )
+ self.assertEqual(mock_agent.invoke.call_args.args[1]["callbacks"], callbacks)
+ mock_logger_info.assert_called_once_with(
+ "llma_eval_reports_agent_completed",
+ team_id=1,
+ evaluation_id="eval-1",
+ title="A report",
+ section_count=1,
+ citation_count=0,
+ metrics=EvalReportMetrics().to_dict(),
+ trace_id="report-run-1",
+ session_id="report-session-1",
+ )
- @patch.object(graph, "resolve_ai_gateway_config")
- @patch.object(graph, "CallbackHandler")
- @patch.object(graph, "posthoganalytics")
+ @patch.object(graph.logger, "exception")
+ @patch.object(graph, "build_langchain_callbacks", return_value=[])
@patch.object(graph, "create_react_agent")
@patch.object(graph, "build_langchain_chat_client")
@patch.object(graph, "_compute_metrics")
- def test_direct_mode_attaches_tagged_callback(
- self, mock_metrics, mock_build_llm, mock_create_agent, mock_pha, mock_cb, mock_resolve
- ):
+ def test_error_log_includes_report_trace_and_session(
+ self, mock_metrics, _mock_build_llm, mock_create_agent, _mock_build_callbacks, mock_logger_exception
+ ) -> None:
mock_metrics.return_value = EvalReportMetrics()
- mock_pha.default_client = MagicMock()
- mock_resolve.return_value = None # no gateway -> direct OpenAI, SDK must capture the event
+ mock_create_agent.return_value.invoke.side_effect = RuntimeError("agent failed")
- callbacks = self._run_and_get_callbacks(mock_create_agent)
+ graph.run_eval_report_agent(
+ team_id=1,
+ report_id="report-1",
+ trace_id="report-run-1",
+ session_id="report-session-1",
+ evaluation_id="eval-1",
+ evaluation_name="Relevance",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ previous_period_start="2026-04-08T13:00:00+00:00",
+ )
- self.assertEqual(len(callbacks), 1, "direct mode must attach the SDK callback so the run is captured")
- self.assertEqual(mock_cb.call_args.kwargs["properties"]["ai_product"], "llma_eval_reports")
+ mock_logger_exception.assert_called_once_with(
+ "llma_eval_reports_agent_error",
+ error="agent failed",
+ error_type="RuntimeError",
+ team_id=1,
+ evaluation_id="eval-1",
+ trace_id="report-run-1",
+ session_id="report-session-1",
+ )
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
index e0ff64a39be8..c9b858e0749f 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -156,6 +156,8 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
period_start="2026-07-01T00:00:00+00:00",
period_end="2026-07-02T00:00:00+00:00",
previous_period_start="2026-06-30T00:00:00+00:00",
+ trace_id="report-run-id",
+ session_id="report-session-id",
)
with (
@@ -179,6 +181,9 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
assert result.generation_status == "completed"
assert run_agent.call_args.kwargs["output_type"] == output_type
assert run_agent.call_args.kwargs["evaluation_target"] == evaluation_target
+ assert run_agent.call_args.kwargs["report_id"] == "report-id"
+ assert run_agent.call_args.kwargs["trace_id"] == "report-run-id"
+ assert run_agent.call_args.kwargs["session_id"] == "report-session-id"
load_target.assert_called_once_with(inputs.team_id, inputs.evaluation_id)
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
index 20938adb9995..157a04147231 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
@@ -1,4 +1,5 @@
import asyncio
+from uuid import UUID
import pytest
from unittest.mock import patch
@@ -26,6 +27,8 @@ from posthog.temporal.ai_observability.eval_reports.workflow import (
@pytest.mark.asyncio
async def test_generate_workflow_forwards_sentiment_output_type() -> None:
+ trace_uuid = UUID("11111111-1111-4111-8111-111111111111")
+ session_uuid = UUID("22222222-2222-4222-8222-222222222222")
activity_inputs: list[object] = []
responses = iter(
[
@@ -66,6 +69,10 @@ async def test_generate_workflow_forwards_sentiment_output_type() -> None:
"posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.patched",
return_value=False,
),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.uuid4",
+ side_effect=[trace_uuid, session_uuid],
+ ),
):
await GenerateAndDeliverEvalReportWorkflow().run(
GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id", manual=True)
@@ -74,6 +81,8 @@ async def test_generate_workflow_forwards_sentiment_output_type() -> None:
agent_input = activity_inputs[1]
assert isinstance(agent_input, RunEvalReportAgentInput)
assert agent_input.output_type == "sentiment"
+ assert agent_input.trace_id == str(trace_uuid)
+ assert agent_input.session_id == str(session_uuid)
@pytest.mark.parametrize(
@@ -152,6 +161,10 @@ async def test_generate_workflow_forwards_generation_status_to_schedule(
"posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.patched",
side_effect=is_patch_enabled,
),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.uuid4",
+ return_value=UUID(int=0),
+ ),
):
await GenerateAndDeliverEvalReportWorkflow().run(
GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id")
@@ -233,6 +246,10 @@ async def test_automatic_run_records_attempt_before_delivery_failure(generation_
}
),
),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.uuid4",
+ return_value=UUID(int=0),
+ ),
pytest.raises(RuntimeError, match="delivery unavailable"),
):
await GenerateAndDeliverEvalReportWorkflow().run(
@@ -292,6 +309,10 @@ async def test_generate_workflow_does_not_emit_signal_without_metrics() -> None:
patch(
"posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.start_child_workflow"
) as start_child_workflow,
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.uuid4",
+ return_value=UUID(int=0),
+ ),
):
await GenerateAndDeliverEvalReportWorkflow().run(
GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id", manual=True)
diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.py
index f0a9a77e1bb9..b5c181ecd45c 100644
--- a/posthog/temporal/ai_observability/eval_reports/types.py
+++ b/posthog/temporal/ai_observability/eval_reports/types.py
@@ -81,6 +81,8 @@ class RunEvalReportAgentInput:
previous_period_start: str
report_prompt_guidance: str = ""
output_type: str = "boolean"
+ trace_id: str = ""
+ session_id: str = ""
@dataclasses.dataclass
diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.py
index 804679390550..d20789f9835f 100644
--- a/posthog/temporal/ai_observability/eval_reports/workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py
@@ -316,6 +316,8 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
start_to_close_timeout=PREPARE_ACTIVITY_TIMEOUT,
retry_policy=FETCH_RETRY_POLICY,
)
+ trace_id = str(temporalio.workflow.uuid4())
+ session_id = str(temporalio.workflow.uuid4())
# 2. Run agent
agent_result = await temporalio.workflow.execute_activity(
@@ -333,6 +335,8 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
period_end=context.period_end,
previous_period_start=context.previous_period_start,
report_prompt_guidance=context.report_prompt_guidance,
+ trace_id=trace_id,
+ session_id=session_id,
),
start_to_close_timeout=AGENT_ACTIVITY_TIMEOUT,
heartbeat_timeout=AGENT_HEARTBEAT_TIMEOUT,
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/activities.py b/posthog/temporal/ai_observability/evaluation_clustering/activities.py
index 558bff28b26d..418d280d9129 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/activities.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/activities.py
@@ -127,6 +127,20 @@ class GenerateEvaluationLabelsInputs:
# ClickHouse for partition pruning.
window_start: str
window_end: str
+ trace_id: str = ""
+ session_id: str = ""
+ clustering_run_id: str = ""
+ clustering_job_id: str = ""
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "team_id": self.team_id,
+ "trace_id": self.trace_id,
+ "session_id": self.session_id,
+ "clustering_run_id": self.clustering_run_id,
+ "clustering_job_id": self.clustering_job_id,
+ }
@dataclass
@@ -350,6 +364,10 @@ def _label_sync(inputs: GenerateEvaluationLabelsInputs) -> GenerateEvaluationLab
eval_metadata=inputs.eval_metadata,
window_start=inputs.window_start,
window_end=inputs.window_end,
+ trace_id=inputs.trace_id,
+ session_id=inputs.session_id,
+ clustering_run_id=inputs.clustering_run_id,
+ clustering_job_id=inputs.clustering_job_id,
)
return GenerateEvaluationLabelsOutputs(cluster_labels=labels)
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/labeling.py b/posthog/temporal/ai_observability/evaluation_clustering/labeling.py
index 02039ce43954..57eb3d0f27fa 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/labeling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/labeling.py
@@ -27,6 +27,10 @@ def generate_evaluation_cluster_labels(
eval_metadata: dict[str, EvaluationMetadata],
window_start: str,
window_end: str,
+ trace_id: str = "",
+ session_id: str = "",
+ clustering_run_id: str = "",
+ clustering_job_id: str = "",
) -> dict[int, ClusterLabel]:
"""Build eval-agent inputs from compute outputs and run the labeling agent."""
labels_array = np.array(labels)
@@ -49,6 +53,10 @@ def generate_evaluation_cluster_labels(
all_eval_contents=all_eval_contents,
window_start=window_start,
window_end=window_end,
+ trace_id=trace_id,
+ session_id=session_id,
+ clustering_run_id=clustering_run_id,
+ clustering_job_id=clustering_job_id,
)
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/graph.py b/posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/graph.py
index ba5d4c1ea96a..f4acdd3e5a3f 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/graph.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/labeling_agent/graph.py
@@ -1,11 +1,13 @@
"""LangGraph agent entry point for evaluation cluster labeling."""
+import uuid
from typing import Any
import structlog
from langchain_core.messages import HumanMessage
from langgraph.prebuilt import create_react_agent
+from posthog.llm.gateway_client import team_distinct_id
from posthog.temporal.ai_observability.clustering_agent import fill_missing_labels, get_labeling_llm
from posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.prompts import (
EVAL_CLUSTER_LABELING_SYSTEM_PROMPT,
@@ -16,6 +18,7 @@ from posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.stat
EvalLabelingState,
)
from posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.tools import EVAL_LABELING_TOOLS
+from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks
from posthog.temporal.ai_observability.trace_clustering.models import ClusterLabel
logger = structlog.get_logger(__name__)
@@ -27,6 +30,10 @@ def run_eval_labeling_agent(
all_eval_contents: dict[str, EvalContent],
window_start: str,
window_end: str,
+ trace_id: str = "",
+ session_id: str = "",
+ clustering_run_id: str = "",
+ clustering_job_id: str = "",
) -> dict[int, ClusterLabel]:
"""Run the evaluation cluster labeling agent and return generated labels.
@@ -44,7 +51,23 @@ def run_eval_labeling_agent(
LABELING_AGENT_TIMEOUT,
)
- llm = get_labeling_llm(LABELING_AGENT_MODEL, LABELING_AGENT_TIMEOUT)
+ resolved_trace_id = trace_id or str(uuid.uuid4())
+ resolved_session_id = session_id or resolved_trace_id
+ resolved_distinct_id = team_distinct_id(team_id)
+ observability_properties = {
+ "team_id": str(team_id),
+ "analysis_level": "evaluation",
+ **({"clustering_run_id": clustering_run_id} if clustering_run_id else {}),
+ **({"clustering_job_id": clustering_job_id} if clustering_job_id else {}),
+ }
+ llm = get_labeling_llm(
+ LABELING_AGENT_MODEL,
+ LABELING_AGENT_TIMEOUT,
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
+ properties=observability_properties,
+ distinct_id=resolved_distinct_id,
+ )
agent = create_react_agent(
model=llm,
@@ -63,10 +86,18 @@ def run_eval_labeling_agent(
"current_labels": {},
}
+ callbacks = build_langchain_callbacks(
+ distinct_id=resolved_distinct_id,
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
+ ai_product="aio_clustering",
+ properties=observability_properties,
+ )
+
try:
result = agent.invoke(
initial_state,
- {"recursion_limit": LABELING_AGENT_RECURSION_LIMIT},
+ {"recursion_limit": LABELING_AGENT_RECURSION_LIMIT, "callbacks": callbacks},
)
logger.info(
"eval_cluster_labeling_agent_completed",
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_labeling_agent.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_labeling_agent.py
index 1b97e65e6ad9..e873a9ec70a0 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_labeling_agent.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_labeling_agent.py
@@ -2,7 +2,7 @@
import json
-from unittest.mock import MagicMock, patch
+from unittest.mock import ANY, MagicMock, patch
from langchain_core.messages import HumanMessage
@@ -208,10 +208,13 @@ class TestApplyFallbacks:
class TestRunEvalLabelingAgent:
+ @patch("posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.graph.build_langchain_callbacks")
@patch("posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.graph.get_labeling_llm")
@patch("posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.graph.create_react_agent")
- def test_runs_agent_and_returns_labels(self, mock_create_agent, mock_get_labeling_llm):
+ def test_runs_agent_and_returns_labels(self, mock_create_agent, mock_get_labeling_llm, mock_build_callbacks):
mock_get_labeling_llm.return_value = MagicMock()
+ callbacks = [MagicMock()]
+ mock_build_callbacks.return_value = callbacks
mock_agent = MagicMock()
mock_create_agent.return_value = mock_agent
mock_agent.invoke.return_value = {
@@ -230,11 +233,29 @@ class TestRunEvalLabelingAgent:
all_eval_contents={},
window_start="2026-04-15T00:00:00Z",
window_end="2026-04-16T00:00:00Z",
+ trace_id="evaluation-clustering-run-1",
+ session_id="evaluation-clustering-run-1:session",
+ clustering_run_id="evaluation-clustering-run-1",
+ clustering_job_id="clustering-job-1",
)
assert result[0].title == "Agent-produced"
assert result[1].title == "Cluster 1" # filled by fallback
mock_create_agent.assert_called_once()
+ mock_get_labeling_llm.assert_called_once_with(
+ ANY,
+ ANY,
+ trace_id="evaluation-clustering-run-1",
+ session_id="evaluation-clustering-run-1:session",
+ properties={
+ "team_id": "1",
+ "analysis_level": "evaluation",
+ "clustering_run_id": "evaluation-clustering-run-1",
+ "clustering_job_id": "clustering-job-1",
+ },
+ distinct_id="team-1",
+ )
+ assert mock_agent.invoke.call_args.args[1]["callbacks"] == callbacks
@patch("posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.graph.get_labeling_llm")
@patch("posthog.temporal.ai_observability.evaluation_clustering.labeling_agent.graph.create_react_agent")
@@ -255,3 +276,6 @@ class TestRunEvalLabelingAgent:
)
# Fallback kicks in; test must not raise
assert result[0].title == "Cluster 0"
+ observability_kwargs = mock_get_labeling_llm.call_args.kwargs
+ assert observability_kwargs["session_id"] == observability_kwargs["trace_id"]
+ assert observability_kwargs["distinct_id"] == "team-1"
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
index ec98eeffdecf..c82889265c86 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
@@ -4,11 +4,18 @@ import uuid
from datetime import UTC, datetime, timedelta
import pytest
+from unittest.mock import patch
from temporalio import activity
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from posthog.temporal.ai_observability.evaluation_clustering.activities import (
+ EvaluationClusteringComputeResult,
+ FetchEvaluationMetadataResult,
+ GenerateEvaluationLabelsInputs,
+ GenerateEvaluationLabelsOutputs,
+)
from posthog.temporal.ai_observability.evaluation_clustering.constants import (
SAMPLER_MAX_SAMPLES_PER_JOB,
SAMPLER_WINDOW_MINUTES,
@@ -20,8 +27,12 @@ from posthog.temporal.ai_observability.evaluation_clustering.models import (
SamplerActivityResult,
SamplerWorkflowInputs,
)
-from posthog.temporal.ai_observability.evaluation_clustering.workflow import AIObservabilityEvaluationSamplerWorkflow
+from posthog.temporal.ai_observability.evaluation_clustering.workflow import (
+ AIObservabilityEvaluationClusteringWorkflow,
+ AIObservabilityEvaluationSamplerWorkflow,
+)
from posthog.temporal.ai_observability.shared_activities import JobConfig
+from posthog.temporal.ai_observability.trace_clustering.models import ClusteringMetrics, ClusteringResult, ClusterLabel
class TestEvaluationJobsForTeam:
@@ -173,3 +184,78 @@ class TestSamplerWorkflowWindowMath:
assert activity_inputs.job_id == "j-forward"
assert activity_inputs.job_name == "forward test"
assert activity_inputs.event_filters == filters
+
+
+class TestClusteringWorkflowWiring:
+ @pytest.mark.asyncio
+ async def test_forwards_workflow_run_identity_to_labeling(self) -> None:
+ trace_uuid = uuid.UUID("11111111-1111-4111-8111-111111111111")
+ compute_result = EvaluationClusteringComputeResult(
+ clustering_run_id="1_evaluation_20250108_000000_job-1",
+ eval_ids=["evaluation-1"],
+ labels=[0],
+ centroids=[[0.0, 0.0]],
+ distances=[[0.0]],
+ coords_2d=[[0.0, 0.0]],
+ centroid_coords_2d=[[0.0, 0.0]],
+ )
+ emitted_result = ClusteringResult(
+ clustering_run_id=compute_result.clustering_run_id,
+ team_id=1,
+ timestamp="2025-01-08T00:00:00+00:00",
+ window_start="2025-01-01T00:00:00+00:00",
+ window_end="2025-01-08T00:00:00+00:00",
+ metrics=ClusteringMetrics(total_items_analyzed=1, num_clusters=1, duration_seconds=1.0),
+ clusters=[],
+ )
+ activity_inputs: list[object] = []
+ responses = iter(
+ [
+ compute_result,
+ FetchEvaluationMetadataResult(metadata={}),
+ GenerateEvaluationLabelsOutputs(
+ cluster_labels={0: ClusterLabel(title="Cluster", description="Description")}
+ ),
+ {},
+ emitted_result,
+ ]
+ )
+
+ async def fake_execute_activity(_activity: object, inputs: object, **_kwargs: object) -> object:
+ activity_inputs.append(inputs)
+ return next(responses)
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.evaluation_clustering.workflow.workflow.execute_activity",
+ new=fake_execute_activity,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.evaluation_clustering.workflow.workflow.now",
+ return_value=datetime(2025, 1, 8, tzinfo=UTC),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.evaluation_clustering.workflow.workflow.uuid4",
+ return_value=trace_uuid,
+ ),
+ patch("posthog.temporal.ai_observability.evaluation_clustering.workflow.record_items_analyzed"),
+ patch("posthog.temporal.ai_observability.evaluation_clustering.workflow.record_noise_points"),
+ patch("posthog.temporal.ai_observability.evaluation_clustering.workflow.record_clusters_generated"),
+ ):
+ await AIObservabilityEvaluationClusteringWorkflow().run(
+ SamplerWorkflowInputs(team_id=1, job_id="job-1", job_name="Job 1")
+ )
+
+ label_inputs = activity_inputs[2]
+ assert isinstance(label_inputs, GenerateEvaluationLabelsInputs)
+ assert label_inputs.trace_id == str(trace_uuid)
+ assert label_inputs.session_id == f"{trace_uuid}:session"
+ assert label_inputs.clustering_run_id == compute_result.clustering_run_id
+ assert label_inputs.clustering_job_id == "job-1"
+ assert label_inputs.properties_to_log == {
+ "team_id": 1,
+ "trace_id": str(trace_uuid),
+ "session_id": f"{trace_uuid}:session",
+ "clustering_run_id": compute_result.clustering_run_id,
+ "clustering_job_id": "job-1",
+ }
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/workflow.py b/posthog/temporal/ai_observability/evaluation_clustering/workflow.py
index 7d24dea88762..aec300a764d3 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/workflow.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/workflow.py
@@ -214,6 +214,7 @@ class AIObservabilityEvaluationClusteringWorkflow(PostHogWorkflow):
)
item_metadata = compute_item_labeling_metadata(compute_result)
+ trace_id = str(workflow.uuid4())
# 3. Labels (LangGraph agent)
labels_result = await workflow.execute_activity(
@@ -227,6 +228,10 @@ class AIObservabilityEvaluationClusteringWorkflow(PostHogWorkflow):
eval_metadata=metadata_result.metadata,
window_start=window_start,
window_end=window_end,
+ trace_id=trace_id,
+ session_id=f"{trace_id}:session",
+ clustering_run_id=compute_result.clustering_run_id,
+ clustering_job_id=inputs.job_id,
),
start_to_close_timeout=LLM_ACTIVITY_TIMEOUT,
schedule_to_close_timeout=LLM_SCHEDULE_TO_CLOSE_TIMEOUT,
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.py
index 8a70ccb0e33b..a4257fe21de3 100644
--- a/posthog/temporal/ai_observability/llm_endpoint.py
+++ b/posthog/temporal/ai_observability/llm_endpoint.py
@@ -3,27 +3,40 @@ Go ai-gateway when AI_GATEWAY_URL + AI_GATEWAY_API_KEY are set, else direct to O
The raw-SDK builders for summarization live in ``posthog.llm.gateway_client`` (importing
from this package would pull in the temporal workflow graph and cycle); this module shares
-its ``resolve_ai_gateway_config`` validator and ``ai_product_headers`` helper.
+its ``resolve_ai_gateway_config`` validator and ``ai_gateway_headers`` helper.
"""
import os
+from collections.abc import Mapping
from django.conf import settings
import httpx
+import posthoganalytics
+from langchain_core.callbacks import BaseCallbackHandler
from langchain_openai import ChatOpenAI
+from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from posthog.cloud_utils import is_cloud
-from posthog.llm.gateway_client import ai_product_headers, resolve_ai_gateway_config
+from posthog.llm.gateway_client import ai_gateway_headers, resolve_ai_gateway_config
-def build_langchain_chat_client(model: str, timeout: float, ai_product: str | None = None) -> ChatOpenAI:
+def build_langchain_chat_client(
+ model: str,
+ timeout: float,
+ ai_product: str | None = None,
+ trace_id: str | None = None,
+ session_id: str | None = None,
+ properties: Mapping[str, str] | None = None,
+ distinct_id: str | None = None,
+) -> ChatOpenAI:
"""Return a ChatOpenAI client for the labeling/report agents. Cloud/DEBUG only.
Routes through the internal Go ai-gateway when configured; on a misconfiguration the shared
resolver logs and returns None, so this falls back to direct OpenAI rather than failing the
- call. In gateway mode the ``phs_`` bearer is team-scoped, so no per-team header is needed;
- ``ai_product`` (when given) tags the captured ``$ai_generation`` via X-PostHog-Properties.
+ call. In gateway mode the bearer selects the capture project, while ``distinct_id`` attributes
+ the generation to the customer user or team. The other observability arguments correlate every
+ model call in one agent invocation.
"""
if not settings.DEBUG and not is_cloud():
raise Exception("AI features are only available in PostHog Cloud")
@@ -37,7 +50,13 @@ def build_langchain_chat_client(model: str, timeout: float, ai_product: str | No
base_url=url,
timeout=timeout,
max_retries=2,
- default_headers=ai_product_headers(ai_product),
+ default_headers=ai_gateway_headers(
+ ai_product=ai_product,
+ trace_id=trace_id,
+ session_id=session_id,
+ properties=properties,
+ distinct_id=distinct_id,
+ ),
# trust_env=False keeps the in-cluster gateway call off the egress proxy.
http_client=httpx.Client(trust_env=False),
http_async_client=httpx.AsyncClient(trust_env=False),
@@ -47,3 +66,29 @@ def build_langchain_chat_client(model: str, timeout: float, ai_product: str | No
if not direct_key:
raise Exception("OPENAI_API_KEY is not configured")
return ChatOpenAI(model=model, api_key=direct_key, timeout=timeout, max_retries=2)
+
+
+def build_langchain_callbacks(
+ *,
+ distinct_id: str,
+ trace_id: str,
+ session_id: str,
+ ai_product: str,
+ properties: Mapping[str, str] | None = None,
+) -> list[BaseCallbackHandler]:
+ # The Go gateway captures $ai_generation itself, so attaching the SDK callback in gateway
+ # mode would double-count every model call.
+ if not posthoganalytics.default_client or resolve_ai_gateway_config() is not None:
+ return []
+
+ callback_properties = dict(properties or {})
+ callback_properties["ai_product"] = ai_product
+ callback_properties["$ai_session_id"] = session_id
+ return [
+ CallbackHandler(
+ posthoganalytics.default_client,
+ distinct_id=distinct_id,
+ trace_id=trace_id,
+ properties=callback_properties,
+ )
+ ]
diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
index d1e4e76bd0b2..d62cf7423065 100644
--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
@@ -7,7 +7,7 @@ from unittest.mock import patch
from django.test import override_settings
-from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
+from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks, build_langchain_chat_client
GATEWAY_URL = "https://gateway.example/v1"
GATEWAY_KEY = "phs_project_secret"
@@ -70,10 +70,29 @@ class TestBuildOpenAIChatClient:
@override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY)
def test_gateway_mode_tags_ai_product_via_posthog_properties_header(self):
with patch("posthog.temporal.ai_observability.llm_endpoint.ChatOpenAI") as mock_chat:
- build_langchain_chat_client("gpt-5.4", 600.0, ai_product="aio_clustering")
+ build_langchain_chat_client(
+ "gpt-5.4",
+ 600.0,
+ ai_product="aio_clustering",
+ trace_id="clustering-run-1",
+ session_id="clustering-run-1:session",
+ properties={"team_id": "42", "analysis_level": "trace", "clustering_job_id": "job-1"},
+ distinct_id="42",
+ )
- assert mock_chat.call_args.kwargs["default_headers"] == {
- "X-PostHog-Properties": json.dumps({"ai_product": "aio_clustering"})
+ headers = mock_chat.call_args.kwargs["default_headers"]
+ assert headers == {
+ "X-PostHog-Properties": json.dumps(
+ {
+ "team_id": "42",
+ "analysis_level": "trace",
+ "clustering_job_id": "job-1",
+ "ai_product": "aio_clustering",
+ }
+ ),
+ "X-PostHog-Trace-Id": "clustering-run-1",
+ "X-PostHog-Session-Id": "clustering-run-1:session",
+ "X-PostHog-Distinct-Id": "42",
}
@override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY)
@@ -82,3 +101,45 @@ class TestBuildOpenAIChatClient:
build_langchain_chat_client("gpt-5.4", 600.0)
assert mock_chat.call_args.kwargs["default_headers"] is None
+
+ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
+ @patch("posthog.temporal.ai_observability.llm_endpoint.CallbackHandler")
+ @patch("posthog.temporal.ai_observability.llm_endpoint.posthoganalytics")
+ def test_direct_mode_callback_preserves_trace_and_session(self, mock_posthoganalytics, mock_callback):
+ mock_posthoganalytics.default_client = object()
+
+ callbacks = build_langchain_callbacks(
+ distinct_id="42",
+ trace_id="clustering-run-1",
+ session_id="clustering-run-1:session",
+ ai_product="aio_clustering",
+ properties={"analysis_level": "trace"},
+ )
+
+ assert callbacks == [mock_callback.return_value]
+ mock_callback.assert_called_once_with(
+ mock_posthoganalytics.default_client,
+ distinct_id="42",
+ trace_id="clustering-run-1",
+ properties={
+ "analysis_level": "trace",
+ "ai_product": "aio_clustering",
+ "$ai_session_id": "clustering-run-1:session",
+ },
+ )
+
+ @override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY)
+ @patch("posthog.temporal.ai_observability.llm_endpoint.CallbackHandler")
+ @patch("posthog.temporal.ai_observability.llm_endpoint.posthoganalytics")
+ def test_gateway_mode_omits_callback_to_avoid_duplicate_generations(self, mock_posthoganalytics, mock_callback):
+ mock_posthoganalytics.default_client = object()
+
+ callbacks = build_langchain_callbacks(
+ distinct_id="42",
+ trace_id="clustering-run-1",
+ session_id="clustering-run-1:session",
+ ai_product="aio_clustering",
+ )
+
+ assert callbacks == []
+ mock_callback.assert_not_called()
diff --git a/posthog/temporal/ai_observability/trace_clustering/activities.py b/posthog/temporal/ai_observability/trace_clustering/activities.py
index 1ae0fce2c8fb..fbf4c5e2b7a9 100644
--- a/posthog/temporal/ai_observability/trace_clustering/activities.py
+++ b/posthog/temporal/ai_observability/trace_clustering/activities.py
@@ -335,6 +335,10 @@ def _generate_cluster_labels(inputs: GenerateLabelsActivityInputs) -> GenerateLa
window_end=window_end,
batch_run_ids=inputs.batch_run_ids,
analysis_level=inputs.analysis_level,
+ trace_id=inputs.trace_id,
+ session_id=inputs.session_id,
+ clustering_run_id=inputs.clustering_run_id,
+ clustering_job_id=inputs.clustering_job_id,
)
return GenerateLabelsActivityOutputs(cluster_labels=cluster_labels)
diff --git a/posthog/temporal/ai_observability/trace_clustering/labeling.py b/posthog/temporal/ai_observability/trace_clustering/labeling.py
index 9f755ca491f6..8cbdb92e9fd8 100644
--- a/posthog/temporal/ai_observability/trace_clustering/labeling.py
+++ b/posthog/temporal/ai_observability/trace_clustering/labeling.py
@@ -31,6 +31,10 @@ def generate_cluster_labels(
window_end: datetime,
batch_run_ids: dict[str, str] | None = None,
analysis_level: AnalysisLevel = "trace",
+ trace_id: str = "",
+ session_id: str = "",
+ clustering_run_id: str = "",
+ clustering_job_id: str = "",
) -> dict[int, ClusterLabel]:
"""Generate titles and descriptions for all clusters using the labeling agent.
@@ -81,6 +85,11 @@ def generate_cluster_labels(
team_id=team.id,
cluster_data=cluster_data,
all_trace_summaries=all_summaries,
+ trace_id=trace_id,
+ session_id=session_id,
+ clustering_run_id=clustering_run_id,
+ clustering_job_id=clustering_job_id,
+ analysis_level=analysis_level,
)
return result_labels
diff --git a/posthog/temporal/ai_observability/trace_clustering/labeling_agent/graph.py b/posthog/temporal/ai_observability/trace_clustering/labeling_agent/graph.py
index 0430713ba43d..c8a9c50319cc 100644
--- a/posthog/temporal/ai_observability/trace_clustering/labeling_agent/graph.py
+++ b/posthog/temporal/ai_observability/trace_clustering/labeling_agent/graph.py
@@ -1,19 +1,22 @@
"""LangGraph agent for cluster labeling using create_react_agent."""
+import uuid
from typing import Any
import structlog
from langchain_core.messages import HumanMessage
from langgraph.prebuilt import create_react_agent
+from posthog.llm.gateway_client import team_distinct_id
from posthog.temporal.ai_observability.clustering_agent import fill_missing_labels, get_labeling_llm
+from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks
from posthog.temporal.ai_observability.trace_clustering.labeling_agent.prompts import CLUSTER_LABELING_SYSTEM_PROMPT
from posthog.temporal.ai_observability.trace_clustering.labeling_agent.state import (
ClusterLabelingState,
ClusterTraceData,
)
from posthog.temporal.ai_observability.trace_clustering.labeling_agent.tools import LABELING_TOOLS
-from posthog.temporal.ai_observability.trace_clustering.models import ClusterLabel, TraceSummary
+from posthog.temporal.ai_observability.trace_clustering.models import AnalysisLevel, ClusterLabel, TraceSummary
logger = structlog.get_logger(__name__)
@@ -23,6 +26,11 @@ def run_labeling_agent(
cluster_data: dict[int, ClusterTraceData],
all_trace_summaries: dict[str, TraceSummary],
max_iterations: int | None = None,
+ trace_id: str = "",
+ session_id: str = "",
+ clustering_run_id: str = "",
+ clustering_job_id: str = "",
+ analysis_level: AnalysisLevel = "trace",
) -> dict[int, ClusterLabel]:
"""Run the cluster labeling agent and return generated labels.
@@ -43,8 +51,23 @@ def run_labeling_agent(
LABELING_AGENT_TIMEOUT,
)
- # Create LLM client
- llm = get_labeling_llm(LABELING_AGENT_MODEL, LABELING_AGENT_TIMEOUT)
+ resolved_trace_id = trace_id or str(uuid.uuid4())
+ resolved_session_id = session_id or resolved_trace_id
+ resolved_distinct_id = team_distinct_id(team_id)
+ observability_properties = {
+ "team_id": str(team_id),
+ "analysis_level": analysis_level,
+ **({"clustering_run_id": clustering_run_id} if clustering_run_id else {}),
+ **({"clustering_job_id": clustering_job_id} if clustering_job_id else {}),
+ }
+ llm = get_labeling_llm(
+ LABELING_AGENT_MODEL,
+ LABELING_AGENT_TIMEOUT,
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
+ properties=observability_properties,
+ distinct_id=resolved_distinct_id,
+ )
# Create the agent using prebuilt pattern
agent = create_react_agent(
@@ -63,11 +86,19 @@ def run_labeling_agent(
"current_labels": {},
}
+ callbacks = build_langchain_callbacks(
+ distinct_id=resolved_distinct_id,
+ trace_id=resolved_trace_id,
+ session_id=resolved_session_id,
+ ai_product="aio_clustering",
+ properties=observability_properties,
+ )
+
# Run the agent
try:
result = agent.invoke(
initial_state,
- {"recursion_limit": LABELING_AGENT_RECURSION_LIMIT},
+ {"recursion_limit": LABELING_AGENT_RECURSION_LIMIT, "callbacks": callbacks},
)
logger.info(
diff --git a/posthog/temporal/ai_observability/trace_clustering/models.py b/posthog/temporal/ai_observability/trace_clustering/models.py
index 9bf2d569f80f..d09946742508 100644
--- a/posthog/temporal/ai_observability/trace_clustering/models.py
+++ b/posthog/temporal/ai_observability/trace_clustering/models.py
@@ -271,10 +271,20 @@ class GenerateLabelsActivityInputs:
# Fields with defaults must come after fields without defaults
analysis_level: AnalysisLevel = "trace" # "trace" or "generation"
batch_run_ids: dict[str, str] = field(default_factory=dict) # item_id -> batch_run_id for linking to summaries
+ trace_id: str = ""
+ session_id: str = ""
+ clustering_run_id: str = ""
+ clustering_job_id: str = ""
@property
def properties_to_log(self) -> dict[str, Any]:
- return {"team_id": self.team_id}
+ return {
+ "team_id": self.team_id,
+ "trace_id": self.trace_id,
+ "session_id": self.session_id,
+ "clustering_run_id": self.clustering_run_id,
+ "clustering_job_id": self.clustering_job_id,
+ }
@dataclass
diff --git a/posthog/temporal/ai_observability/trace_clustering/tests/test_labeling_agent.py b/posthog/temporal/ai_observability/trace_clustering/tests/test_labeling_agent.py
index cf9623d60346..ca44b04c380a 100644
--- a/posthog/temporal/ai_observability/trace_clustering/tests/test_labeling_agent.py
+++ b/posthog/temporal/ai_observability/trace_clustering/tests/test_labeling_agent.py
@@ -2,7 +2,7 @@
import json
-from unittest.mock import MagicMock, patch
+from unittest.mock import ANY, MagicMock, patch
from langchain_core.messages import HumanMessage
@@ -370,11 +370,14 @@ class TestFillMissingLabels:
class TestRunLabelingAgentIntegration:
+ @patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.build_langchain_callbacks")
@patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.get_labeling_llm")
@patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.create_react_agent")
- def test_runs_agent_and_returns_labels(self, mock_create_agent, mock_get_labeling_llm):
+ def test_runs_agent_and_returns_labels(self, mock_create_agent, mock_get_labeling_llm, mock_build_callbacks):
mock_llm = MagicMock()
mock_get_labeling_llm.return_value = mock_llm
+ callbacks = [MagicMock()]
+ mock_build_callbacks.return_value = callbacks
mock_agent = MagicMock()
mock_create_agent.return_value = mock_agent
@@ -394,11 +397,30 @@ class TestRunLabelingAgentIntegration:
team_id=1,
cluster_data=cluster_data,
all_trace_summaries={},
+ trace_id="trace-clustering-run-1",
+ session_id="trace-clustering-run-1:session",
+ clustering_run_id="trace-clustering-run-1",
+ clustering_job_id="clustering-job-1",
+ analysis_level="trace",
)
assert result[0].title == "Generated Label"
assert result[1].title == "Cluster 1"
mock_create_agent.assert_called_once()
+ mock_get_labeling_llm.assert_called_once_with(
+ ANY,
+ ANY,
+ trace_id="trace-clustering-run-1",
+ session_id="trace-clustering-run-1:session",
+ properties={
+ "team_id": "1",
+ "analysis_level": "trace",
+ "clustering_run_id": "trace-clustering-run-1",
+ "clustering_job_id": "clustering-job-1",
+ },
+ distinct_id="team-1",
+ )
+ assert mock_agent.invoke.call_args.args[1]["callbacks"] == callbacks
@patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.get_labeling_llm")
@patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.create_react_agent")
@@ -421,6 +443,9 @@ class TestRunLabelingAgentIntegration:
)
assert result[0].title == "Cluster 0"
+ observability_kwargs = mock_get_labeling_llm.call_args.kwargs
+ assert observability_kwargs["session_id"] == observability_kwargs["trace_id"]
+ assert observability_kwargs["distinct_id"] == "team-1"
@patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.get_labeling_llm")
@patch("posthog.temporal.ai_observability.trace_clustering.labeling_agent.graph.create_react_agent")
diff --git a/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py b/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py
index eed17f12659a..e61dce45c406 100644
--- a/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py
+++ b/posthog/temporal/ai_observability/trace_clustering/tests/test_workflow.py
@@ -1,8 +1,10 @@
"""Tests for trace clustering workflow."""
import uuid
+from datetime import UTC, datetime
import pytest
+from unittest.mock import patch
import numpy as np
from temporalio import activity
@@ -15,6 +17,7 @@ from posthog.temporal.ai_observability.trace_clustering.models import (
ClusterAggregateMetrics,
ClusteringActivityInputs,
ClusteringComputeResult,
+ ClusteringMetrics,
ClusteringResult,
ClusteringWorkflowInputs,
ClusterItem,
@@ -273,6 +276,81 @@ class TestActivityInputOutputModels:
assert inputs.job_name == ""
+class TestLabelingWorkflowWiring:
+ @pytest.mark.asyncio
+ async def test_forwards_workflow_run_identity_to_labeling(self) -> None:
+ trace_uuid = uuid.UUID("11111111-1111-4111-8111-111111111111")
+ compute_result = ClusteringComputeResult(
+ clustering_run_id="1_trace_20250108_000000_job-1",
+ items=[ClusterItem(trace_id="trace-1")],
+ labels=[0],
+ centroids=[[0.0, 0.0]],
+ distances=[[0.0]],
+ coords_2d=[[0.0, 0.0]],
+ centroid_coords_2d=[[0.0, 0.0]],
+ probabilities=[1.0],
+ )
+ emitted_result = ClusteringResult(
+ clustering_run_id=compute_result.clustering_run_id,
+ team_id=1,
+ timestamp="2025-01-08T00:00:00+00:00",
+ window_start="2025-01-01T00:00:00+00:00",
+ window_end="2025-01-08T00:00:00+00:00",
+ metrics=ClusteringMetrics(total_items_analyzed=1, num_clusters=1, duration_seconds=1.0),
+ clusters=[],
+ )
+ activity_inputs: list[object] = []
+ responses = iter(
+ [
+ compute_result,
+ GenerateLabelsActivityOutputs(
+ cluster_labels={0: ClusterLabel(title="Cluster", description="Description")}
+ ),
+ {},
+ emitted_result,
+ ]
+ )
+
+ async def fake_execute_activity(_activity: object, *, args: list[object], **_kwargs: object) -> object:
+ activity_inputs.append(args[0])
+ return next(responses)
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.trace_clustering.workflow.workflow.execute_activity",
+ new=fake_execute_activity,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.trace_clustering.workflow.workflow.now",
+ return_value=datetime(2025, 1, 8, tzinfo=UTC),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.trace_clustering.workflow.workflow.uuid4",
+ return_value=trace_uuid,
+ ),
+ patch("posthog.temporal.ai_observability.trace_clustering.workflow.record_items_analyzed"),
+ patch("posthog.temporal.ai_observability.trace_clustering.workflow.record_noise_points"),
+ patch("posthog.temporal.ai_observability.trace_clustering.workflow.record_clusters_generated"),
+ ):
+ await DailyTraceClusteringWorkflow().run(
+ ClusteringWorkflowInputs(team_id=1, job_id="job-1", job_name="Job 1")
+ )
+
+ label_inputs = activity_inputs[1]
+ assert isinstance(label_inputs, GenerateLabelsActivityInputs)
+ assert label_inputs.trace_id == str(trace_uuid)
+ assert label_inputs.session_id == f"{trace_uuid}:session"
+ assert label_inputs.clustering_run_id == compute_result.clustering_run_id
+ assert label_inputs.clustering_job_id == "job-1"
+ assert label_inputs.properties_to_log == {
+ "team_id": 1,
+ "trace_id": str(trace_uuid),
+ "session_id": f"{trace_uuid}:session",
+ "clustering_run_id": compute_result.clustering_run_id,
+ "clustering_job_id": "job-1",
+ }
+
+
class TestEmptyComputeResultShortCircuit:
"""Empty compute results must not trigger labeling/aggregates/emission.
@@ -354,8 +432,6 @@ class TestComputeActivityCapacityBackoff:
@pytest.mark.asyncio
async def test_clickhouse_at_capacity_raises_jittered_backoff(self):
- from unittest.mock import patch
-
from temporalio.exceptions import ApplicationError
from temporalio.testing import ActivityEnvironment
diff --git a/posthog/temporal/ai_observability/trace_clustering/workflow.py b/posthog/temporal/ai_observability/trace_clustering/workflow.py
index 738dfd99da41..67fc7a8c162c 100644
--- a/posthog/temporal/ai_observability/trace_clustering/workflow.py
+++ b/posthog/temporal/ai_observability/trace_clustering/workflow.py
@@ -218,6 +218,7 @@ class DailyTraceClusteringWorkflow(PostHogWorkflow):
# Compute per-item metadata for labeling (O(n) instead of O(n × k))
item_metadata = _compute_item_labeling_metadata(compute_result)
+ trace_id = str(workflow.uuid4())
# Activity 2: Generate LLM labels (longer timeout for agent run)
labels_result = await workflow.execute_activity(
@@ -233,6 +234,10 @@ class DailyTraceClusteringWorkflow(PostHogWorkflow):
window_end=window_end,
analysis_level=compute_result.analysis_level,
batch_run_ids=compute_result.batch_run_ids,
+ trace_id=trace_id,
+ session_id=f"{trace_id}:session",
+ clustering_run_id=compute_result.clustering_run_id,
+ clustering_job_id=inputs.job_id,
)
],
start_to_close_timeout=LLM_ACTIVITY_TIMEOUT,
diff --git a/products/ai_observability/backend/api/evaluation_summary.py b/products/ai_observability/backend/api/evaluation_summary.py
index c822f1fd731f..48f9af7cfcb6 100644
--- a/products/ai_observability/backend/api/evaluation_summary.py
+++ b/products/ai_observability/backend/api/evaluation_summary.py
@@ -409,6 +409,7 @@ Data is fetched server-side by evaluation ID to ensure data integrity.
summary = async_to_sync(summarize_evaluation_runs)(
evaluation_runs=runs,
team_id=self.team_id,
+ evaluation_id=evaluation_id,
model=OpenAIModel.GPT_5_MINI,
filter_type=filter_type,
evaluation_name=evaluation.name,
diff --git a/products/ai_observability/backend/api/test/test_evaluation_summary.py b/products/ai_observability/backend/api/test/test_evaluation_summary.py
index 39af37b09081..ce4696d0a763 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_summary.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_summary.py
@@ -148,7 +148,8 @@ class TestEvaluationSummaryAPI(APIBaseTest):
),
)
- mock_async_to_sync.return_value = lambda *args, **kwargs: mock_summary
+ mock_generate_summary = MagicMock(return_value=mock_summary)
+ mock_async_to_sync.return_value = mock_generate_summary
response = self.client.post(
f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
@@ -160,6 +161,7 @@ class TestEvaluationSummaryAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_200_OK
+ assert mock_generate_summary.call_args.kwargs["evaluation_id"] == str(self.evaluation.id)
data = response.data
assert "overall_assessment" in data
diff --git a/products/ai_observability/backend/summarization/llm/evaluation_summary.py b/products/ai_observability/backend/summarization/llm/evaluation_summary.py
index c902b44725f7..5a504355c3b2 100644
--- a/products/ai_observability/backend/summarization/llm/evaluation_summary.py
+++ b/products/ai_observability/backend/summarization/llm/evaluation_summary.py
@@ -10,6 +10,7 @@ import asyncio
import contextlib
from collections.abc import AsyncIterator
from typing import Any, Literal, TypeVar, cast
+from uuid import uuid4
import structlog
from openai import AsyncOpenAI
@@ -19,7 +20,7 @@ from redis.exceptions import LockError
from rest_framework import exceptions
from posthog import redis as posthog_redis
-from posthog.llm.gateway_client import build_async_openai_client
+from posthog.llm.gateway_client import build_async_openai_client, team_distinct_id
from ..constants import (
EVALUATION_SUMMARY_CHUNK_SIZE,
@@ -485,6 +486,9 @@ async def _merge_summaries(
async def _generate_evaluation_summary(
evaluation_runs: list[dict],
team_id: int,
+ evaluation_id: str,
+ trace_id: str,
+ session_id: str,
model: OpenAIModel,
filter_type: str,
evaluation_name: str,
@@ -500,7 +504,20 @@ async def _generate_evaluation_summary(
"evaluation_prompt": evaluation_prompt,
"max_candidates": EVALUATION_SUMMARY_CHUNK_SIZE,
}
- client = build_async_openai_client("llma_eval_summary", ai_product="aio_eval_summary")
+ resolved_distinct_id = user_distinct_id or team_distinct_id(team_id)
+ observability_properties = {
+ "team_id": str(team_id),
+ "filter_type": filter_type,
+ **({"evaluation_id": evaluation_id} if evaluation_id else {}),
+ }
+ client = build_async_openai_client(
+ "llma_eval_summary",
+ ai_product="aio_eval_summary",
+ trace_id=trace_id,
+ session_id=session_id,
+ properties=observability_properties,
+ distinct_id=resolved_distinct_id,
+ )
if len(evaluation_runs) <= EVALUATION_SUMMARY_CHUNK_SIZE:
single_system_prompt = load_summarization_template("prompts/evaluation_summary.djt", prompt_context)
single_user_prompt = _build_runs_prompt(evaluation_runs)
@@ -511,7 +528,7 @@ async def _generate_evaluation_summary(
system_prompt=single_system_prompt,
user_prompt=single_user_prompt,
team_id=team_id,
- user_distinct_id=user_distinct_id,
+ user_distinct_id=resolved_distinct_id,
response_model=EvaluationSummaryResponse,
schema_name="evaluation_summary",
)
@@ -533,7 +550,7 @@ async def _generate_evaluation_summary(
system_prompt=map_system_prompt,
evaluation_runs=chunk,
team_id=team_id,
- user_distinct_id=user_distinct_id,
+ user_distinct_id=resolved_distinct_id,
)
batch_candidates = list(await asyncio.gather(*(summarize_chunk(chunk) for chunk in chunks)))
@@ -544,7 +561,7 @@ async def _generate_evaluation_summary(
statistics=statistics,
prompt_context=prompt_context,
team_id=team_id,
- user_distinct_id=user_distinct_id,
+ user_distinct_id=resolved_distinct_id,
llm_call_semaphore=llm_call_semaphore,
)
summary.statistics = statistics
@@ -555,6 +572,7 @@ async def summarize_evaluation_runs(
evaluation_runs: list[dict],
team_id: int,
model: OpenAIModel,
+ evaluation_id: str = "",
filter_type: str = "all",
evaluation_name: str = "",
evaluation_description: str = "",
@@ -571,6 +589,7 @@ async def summarize_evaluation_runs(
evaluation_runs: List of dicts with 'generation_id' (str), 'result' (bool or None), and 'reasoning' (str)
team_id: Team ID for logging and tracking
model: OpenAI model to use
+ evaluation_id: Evaluation identifier attached as observability metadata
filter_type: The filter applied ('all', 'pass', 'fail', 'na')
evaluation_name: Name of the evaluation being summarized
evaluation_description: Description of what the evaluation tests for
@@ -583,11 +602,16 @@ async def summarize_evaluation_runs(
if not evaluation_runs:
raise exceptions.ValidationError("No evaluation runs provided")
+ trace_id = str(uuid4())
+ session_id = str(uuid4())
try:
async with _team_generation_lock(team_id):
return await _generate_evaluation_summary(
evaluation_runs=evaluation_runs,
team_id=team_id,
+ evaluation_id=evaluation_id,
+ trace_id=trace_id,
+ session_id=session_id,
model=model,
filter_type=filter_type,
evaluation_name=evaluation_name,
@@ -598,5 +622,13 @@ async def summarize_evaluation_runs(
except exceptions.APIException:
raise
except Exception as error:
- logger.exception("evaluation_summary_failed", team_id=team_id, model=str(model), error=str(error))
+ logger.exception(
+ "evaluation_summary_failed",
+ team_id=team_id,
+ evaluation_id=evaluation_id,
+ trace_id=trace_id,
+ session_id=session_id,
+ model=str(model),
+ error=str(error),
+ )
raise exceptions.APIException("Failed to generate evaluation summary") from error
diff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.py
index 39a42906e274..cea85e2a75ab 100644
--- a/products/ai_observability/backend/summarization/tests/test_providers.py
+++ b/products/ai_observability/backend/summarization/tests/test_providers.py
@@ -2,6 +2,7 @@ import re
import json
import asyncio
from typing import Any
+from uuid import UUID
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -183,7 +184,10 @@ def valid_evaluation_summary_json():
class TestSummarizeEvaluationRuns:
- def test_routes_through_async_gateway_builder_and_passes_timeout(self, valid_evaluation_summary_json):
+ @pytest.mark.parametrize(("user_distinct_id", "expected_distinct_id"), [("user-1", "user-1"), ("", "team-1")])
+ def test_routes_through_async_gateway_builder_and_passes_timeout(
+ self, valid_evaluation_summary_json, user_distinct_id, expected_distinct_id
+ ):
mock_response = MagicMock()
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = valid_evaluation_summary_json
@@ -199,14 +203,73 @@ class TestSummarizeEvaluationRuns:
summarize_evaluation_runs(
evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],
team_id=1,
+ evaluation_id="evaluation-1",
model=OpenAIModel.GPT_4_1_MINI,
+ user_distinct_id=user_distinct_id,
)
)
- mock_builder.assert_called_once_with("llma_eval_summary", ai_product="aio_eval_summary")
+ mock_builder.assert_called_once()
+ builder_kwargs = mock_builder.call_args.kwargs
+ trace_id = UUID(builder_kwargs["trace_id"])
+ session_id = UUID(builder_kwargs["session_id"])
+ assert session_id != trace_id
+ assert builder_kwargs["session_id"] != "evaluation-1"
+ assert builder_kwargs["distinct_id"] == expected_distinct_id
+ assert builder_kwargs["properties"] == {
+ "team_id": "1",
+ "filter_type": "all",
+ "evaluation_id": "evaluation-1",
+ }
+ assert mock_client.chat.completions.create.call_args.kwargs["user"] == expected_distinct_id
assert mock_client.chat.completions.create.call_args.kwargs["timeout"] == SUMMARIZATION_TIMEOUT
assert result.overall_assessment == "Mostly passing."
+ def test_failure_log_includes_evaluation_trace_and_session(self) -> None:
+ trace_id = UUID("6f6905aa-00d2-4df7-a5e4-e1c06d934c23")
+ session_id = UUID("7dfda50a-5710-45b1-97a3-30d98a07c1da")
+
+ lock_context = MagicMock()
+ lock_context.__aenter__ = AsyncMock(return_value=None)
+ lock_context.__aexit__ = AsyncMock(return_value=None)
+
+ with (
+ patch(
+ "products.ai_observability.backend.summarization.llm.evaluation_summary._team_generation_lock",
+ return_value=lock_context,
+ ),
+ patch(
+ "products.ai_observability.backend.summarization.llm.evaluation_summary.uuid4",
+ side_effect=[trace_id, session_id],
+ ),
+ patch(
+ "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client",
+ side_effect=RuntimeError("gateway unavailable"),
+ ),
+ patch(
+ "products.ai_observability.backend.summarization.llm.evaluation_summary.logger.exception"
+ ) as mock_logger_exception,
+ ):
+ with pytest.raises(exceptions.APIException, match="Failed to generate evaluation summary"):
+ asyncio.run(
+ summarize_evaluation_runs(
+ evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],
+ team_id=1,
+ evaluation_id="evaluation-1",
+ model=OpenAIModel.GPT_4_1_MINI,
+ )
+ )
+
+ mock_logger_exception.assert_called_once_with(
+ "evaluation_summary_failed",
+ team_id=1,
+ evaluation_id="evaluation-1",
+ trace_id=str(trace_id),
+ session_id=str(session_id),
+ model=str(OpenAIModel.GPT_4_1_MINI),
+ error="gateway unavailable",
+ )
+
def test_concurrent_requests_are_limited_per_team(self, valid_evaluation_summary_json: str) -> None:
mock_response = MagicMock()
mock_response.choices = [MagicMock()]
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.md
index 3521c3194058..94c9bb291be0 100644
--- a/services/llm-gateway/PARITY.md
+++ b/services/llm-gateway/PARITY.md
@@ -31,7 +31,7 @@ When a gap closes, new work uses the Go gateway and affected callers should migr
| 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 Go host selection across OpenAI, Anthropic, Azure OpenAI, Bedrock, or selected Modal models. |
-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). These builders keep 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 OpenAI builders forward caller-selected distinct IDs, traces, sessions, and metadata while keeping a temporary Python fallback during rollout.
### ⛔ Stay on the Python gateway for now
@@ -52,6 +52,7 @@ These are compatibility checks, not automatic blockers:
- **Credential:** Go accepts the credential type and projects the correct team, scope, and revocation state.
- **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.
+- **Session attribution:** Go main does not support native sessions yet. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id` as a gateway-owned `$ai_session_id`; callers must wait for that change to deploy.
- **Provider behavior:** health-based routing or strict `X-PostHog-Provider` pinning matches the caller's fallback requirements.
- **Wire behavior:** request fields, streaming chunks, errors, timeouts, and retries match what the caller handles.
- **Metadata:** Python per-key property and feature flag headers are converted to the Go JSON properties header.
@@ -70,6 +71,7 @@ These are compatibility checks, not automatic blockers:
| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, and router categories. | Broader LiteLLM model acceptance and Python product allowlists. |
| Routing and failure behavior | Health-based host choice, 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 | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |
## Migration checklist
@@ -85,10 +87,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-07-31 against:
+Last verified on 2026-08-06 against:
-- `PostHog/posthog` master at `75c2b2ff6845097a3eb6dc5214e3f4f660395fb8`
-- `PostHog/ai-gateway` main at `ea8230b6dbc4ebf6c4be83d359e561477a13b215`
+- `PostHog/posthog` master at `64bcdbd983585d754d6a8e5c975f0a0122eb6510`
+- `PostHog/ai-gateway` main at `e2e28a738e701d107e57d12c6ed244a50af2b2ac`
## References