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.

fix(alerts): attach langchain callback so alert investigation agent emits LLM analytics (#59189)

Andrew Maguire597fb9b909da
diff --git a/posthog/temporal/ai/anomaly_investigation/runner.py b/posthog/temporal/ai/anomaly_investigation/runner.py
index b7eede57f439..24b1ae7e9d78 100644
--- a/posthog/temporal/ai/anomaly_investigation/runner.py
+++ b/posthog/temporal/ai/anomaly_investigation/runner.py
@@ -12,12 +12,17 @@ message with no tool calls, or on budget exhaustion.
from __future__ import annotations
import json
+import uuid
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any
+import posthoganalytics
+from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
+from langchain_core.runnables import RunnableConfig
+from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from pydantic import BaseModel, ValidationError
from posthog.models import Team, User
@@ -153,6 +158,13 @@ async def run_investigation(
)
llm_with_final_report = llm.bind_tools([final_report_tool], tool_choice=FINAL_REPORT_TOOL_NAME)
+ # Without a langchain CallbackHandler attached, MaxChatAnthropic's posthog_properties
+ # never reach LLM analytics — langchain-anthropic itself doesn't emit $ai_* events.
+ # Attach one here so every generation/span this agent makes shows up under
+ # ai_product=alert_investigation_agent, matching the convention used by other
+ # Temporal-driven agents (see llma_eval_reports/report_agent/graph.py).
+ config: RunnableConfig = {"callbacks": _build_callbacks(team=team, alert=alert)}
+
messages: list[Any] = [
SystemMessage(content=SYSTEM_PROMPT),
HumanMessage(content=anomaly_context),
@@ -178,7 +190,7 @@ async def run_investigation(
if heartbeat is not None:
heartbeat()
try:
- final = await llm_with_final_report.ainvoke(messages)
+ final = await llm_with_final_report.ainvoke(messages, config=config)
except Exception as err:
# Swallow final-turn failures and return an inconclusive report rather than
# bouncing off Temporal retries — MaxChatAnthropic already exhausted its
@@ -197,7 +209,7 @@ async def run_investigation(
break
try:
- response = await llm_with_tools.ainvoke(messages)
+ response = await llm_with_tools.ainvoke(messages, config=config)
except Exception as err:
logger.warning("anomaly_investigation.llm_invoke_error", extra={"error": str(err)})
return InvestigationRunResult(
@@ -249,6 +261,28 @@ async def run_investigation(
return InvestigationRunResult(report=report, tool_calls_used=tool_calls_used, model=AGENT_MODEL)
+def _build_callbacks(*, team: Team, alert: AlertConfiguration | None) -> list[BaseCallbackHandler]:
+ callbacks: list[BaseCallbackHandler] = []
+ client = posthoganalytics.default_client
+ if client is None:
+ return callbacks
+ properties: dict[str, Any] = {
+ "ai_product": "alert_investigation_agent",
+ "team_id": team.id,
+ }
+ if alert is not None:
+ properties["alert_id"] = str(alert.id)
+ callbacks.append(
+ CallbackHandler(
+ client,
+ distinct_id=str(team.id),
+ trace_id=f"alert-investigation-{uuid.uuid4()}",
+ properties=properties,
+ )
+ )
+ return callbacks
+
+
def _parse_report_message(message: Any) -> InvestigationReport | None:
return _report_from_tool_calls(getattr(message, "tool_calls", None) or [])
diff --git a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
index ac84e140fcfc..7917e31ecfe0 100644
--- a/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
+++ b/posthog/temporal/tests/ai/test_anomaly_investigation_runner.py
@@ -1,5 +1,9 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
from posthog.temporal.ai.anomaly_investigation.runner import (
FINAL_REPORT_TOOL_NAME,
+ _build_callbacks,
_parse_report,
_report_from_tool_calls,
)
@@ -56,3 +60,50 @@ def test_parse_report_keeps_plain_json_fallback() -> None:
assert report.verdict == "inconclusive"
assert report.summary == "Need manual review."
+
+
+ "alert_id,expected_properties",
+ [
+ pytest.param(
+ "alert-uuid",
+ {"ai_product": "alert_investigation_agent", "team_id": 314, "alert_id": "alert-uuid"},
+ id="with_alert",
+ ),
+ pytest.param(
+ None,
+ {"ai_product": "alert_investigation_agent", "team_id": 314},
+ id="without_alert",
+ ),
+ ],
+)
+def test_build_callbacks_tags_ai_product_for_llm_analytics(alert_id, expected_properties) -> None:
+ team = MagicMock(id=314)
+ alert = MagicMock(id=alert_id) if alert_id is not None else None
+ sentinel_client = MagicMock(name="default_client")
+
+ with (
+ patch("posthog.temporal.ai.anomaly_investigation.runner.posthoganalytics") as mock_module,
+ patch("posthog.temporal.ai.anomaly_investigation.runner.CallbackHandler") as mock_handler,
+ ):
+ mock_module.default_client = sentinel_client
+
+ callbacks = _build_callbacks(team=team, alert=alert)
+
+ assert callbacks == [mock_handler.return_value]
+ mock_handler.assert_called_once()
+ args, kwargs = mock_handler.call_args
+ assert args[0] is sentinel_client
+ assert kwargs["distinct_id"] == "314"
+ assert kwargs["trace_id"].startswith("alert-investigation-")
+ assert kwargs["properties"] == expected_properties
+
+
+def test_build_callbacks_skips_when_default_client_missing() -> None:
+ team = MagicMock(id=1)
+
+ with patch("posthog.temporal.ai.anomaly_investigation.runner.posthoganalytics") as mock_module:
+ mock_module.default_client = None
+ callbacks = _build_callbacks(team=team, alert=None)
+
+ assert callbacks == []