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(ai-observability): route eval-report agent through the ai-gateway (#65043)

Brandond2c98a8f3858
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 9aa74d214e65..8acdaac9ec8b 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -1,21 +1,16 @@
"""LangGraph agent for evaluation report generation using create_react_agent."""
-import os
import uuid
from typing import Any
-from django.conf import settings
-
import structlog
import posthoganalytics
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import HumanMessage
from langchain_core.runnables import RunnableConfig
-from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from posthoganalytics.ai.langchain.callbacks import CallbackHandler
-from posthog.cloud_utils import is_cloud
from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import EVAL_REPORT_SYSTEM_PROMPT
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
@@ -30,27 +25,11 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_ch_ts,
_fetch_period_counts,
)
+from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
logger = structlog.get_logger(__name__)
-def _get_llm(model: str, timeout: float) -> ChatOpenAI:
- """Create an OpenAI chat client for the report agent."""
- if not settings.DEBUG and not is_cloud():
- raise Exception("AI features are only available in PostHog Cloud")
-
- api_key = os.environ.get("OPENAI_API_KEY")
- if not api_key:
- raise Exception("OpenAI API key is not configured")
-
- return ChatOpenAI(
- model=model,
- api_key=api_key,
- timeout=timeout,
- max_retries=2,
- )
-
-
def _compute_metrics(
team_id: int,
evaluation_id: str,
@@ -203,7 +182,7 @@ def run_eval_report_agent(
# fallback path, so guarantee they're ready before the agent even runs.
metrics = _compute_metrics(team_id, evaluation_id, period_start, period_end, previous_period_start)
- llm = _get_llm(EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT)
+ llm = build_langchain_chat_client(EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports")
description_section = f"Description: {evaluation_description}\n" if evaluation_description else ""
prompt_section = f"Evaluation prompt/criteria:\n```\n{evaluation_prompt}\n```\n" if evaluation_prompt else ""
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 389a042cc879..c8cacc1f6ae9 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
@@ -1,9 +1,12 @@
"""Tests for the v2 graph helpers: _fallback_content and _validate_agent_output."""
+from unittest.mock import MagicMock, patch
+
from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.temporal.ai_observability.eval_reports.report_agent import graph
from posthog.temporal.ai_observability.eval_reports.report_agent.graph import (
_append_references_section,
_fallback_content,
@@ -206,3 +209,51 @@ class TestAppendReferencesSection(SimpleTestCase):
# Agent's last section is preserved
self.assertEqual(content.sections[MAX_REPORT_SECTIONS - 1].title, f"S{MAX_REPORT_SECTIONS - 1}")
self.assertEqual(content.sections[-1].title, "References")
+
+
+class TestRunEvalReportAgentRouting(SimpleTestCase):
+ """The report agent builds its LLM client via the shared ai-gateway helper.
+
+ Pins the gateway routing at the call site: reverting to a direct ChatOpenAI(...)
+ fails this test even though the agent run itself is mocked out.
+ """
+
+ @patch.object(graph, "posthoganalytics")
+ @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):
+ 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 = {
+ "report": EvalReportContent(
+ title="A report",
+ sections=[ReportSection(title="Summary", content="A finding.")],
+ metrics=EvalReportMetrics(),
+ )
+ }
+ mock_create_agent.return_value = mock_agent
+
+ graph.run_eval_report_agent(
+ team_id=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",
+ )
+
+ mock_build_llm.assert_called_once_with(
+ EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports"
+ )
+ # 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)