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 OpenAI summarization through the ai-gateway (#65044)

Brandon77dfc2976341
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index f0c825290ec6..29c3db553efe 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -1,11 +1,16 @@
+import json
from typing import Literal
+from urllib.parse import urlparse
from django.conf import settings
import httpx
+import structlog
from anthropic import AsyncAnthropic
from openai import AsyncOpenAI, OpenAI
+logger = structlog.get_logger(__name__)
+
Product = Literal[
"llm_gateway",
"posthog_code",
@@ -153,3 +158,78 @@ def get_async_anthropic_gateway_client(
default_headers=default_headers or None,
http_client=httpx.AsyncClient(trust_env=False),
)
+
+
+def _gateway_misconfig(url: str, api_key: str) -> str | None:
+ """Return a reason string if the gateway env is half-applied or malformed, else None."""
+ if not (url and api_key):
+ return "AI_GATEWAY_URL and AI_GATEWAY_API_KEY must be set together"
+ # The SDK appends /chat/completions, so base_url must already carry the /v1 path.
+ if not urlparse(url).path.rstrip("/").endswith("/v1"):
+ return "AI_GATEWAY_URL must include the OpenAI base path, e.g. https://<host>/v1"
+ return None
+
+
+def resolve_ai_gateway_config() -> tuple[str, str] | None:
+ """Return the validated (url, api_key) for the internal Go ai-gateway, or None.
+
+ None when neither env var is set (the caller uses its normal path), and ALSO when the config
+ is half-applied or the URL is malformed: that logs a warning and returns None so the caller
+ falls back to the current flow rather than failing the call (the fallback comes out once
+ rollout completes).
+ """
+ url, api_key = settings.AI_GATEWAY_URL, settings.AI_GATEWAY_API_KEY
+ if not (url or api_key):
+ return None
+ misconfig = _gateway_misconfig(url, api_key)
+ if misconfig:
+ logger.warning("ai_gateway_misconfigured_falling_back", reason=misconfig)
+ return None
+ return url, api_key
+
+
+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. Don't use a ``$ai_`` prefix — the
+ gateway strips those as reserved.
+ """
+ if not ai_product:
+ return None
+ return {"X-PostHog-Properties": json.dumps({"ai_product": ai_product})}
+
+
+def build_openai_client(product: Product, ai_product: 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``).
+ trust_env=False keeps the in-cluster call off the egress proxy.
+ """
+ gateway = resolve_ai_gateway_config()
+ if gateway:
+ url, api_key = gateway
+ return OpenAI(
+ api_key=api_key,
+ base_url=url,
+ default_headers=ai_product_headers(ai_product),
+ http_client=httpx.Client(trust_env=False),
+ )
+ return get_llm_client(product)
+
+
+def build_async_openai_client(product: Product, ai_product: str | None = None) -> AsyncOpenAI:
+ """Async variant of :func:`build_openai_client`."""
+ gateway = resolve_ai_gateway_config()
+ if gateway:
+ url, api_key = gateway
+ return AsyncOpenAI(
+ api_key=api_key,
+ base_url=url,
+ default_headers=ai_product_headers(ai_product),
+ http_client=httpx.AsyncClient(trust_env=False),
+ )
+ return get_async_llm_client(product)
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 1ef0f9c128af..13bd3866c643 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -1,9 +1,23 @@
+import json
from typing import get_args
import pytest
from unittest.mock import patch
-from posthog.llm.gateway_client import Product, get_async_anthropic_gateway_client, get_async_llm_client, get_llm_client
+from django.test import override_settings
+
+from posthog.llm.gateway_client import (
+ Product,
+ build_async_openai_client,
+ build_openai_client,
+ get_async_anthropic_gateway_client,
+ get_async_llm_client,
+ get_llm_client,
+ resolve_ai_gateway_config,
+)
+
+AI_GATEWAY_URL = "https://ai-gateway.example/v1"
+AI_GATEWAY_KEY = "phs_project_secret"
class TestGetLlmClient:
@@ -157,3 +171,82 @@ class TestGetAsyncAnthropicGatewayClient:
)
assert client.default_headers.get("x-posthog-use-bedrock-fallback") == expected_header_value
+
+
+class TestResolveAIGatewayConfig:
+ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
+ def test_returns_none_when_both_unset(self):
+ assert resolve_ai_gateway_config() is None
+
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
+ def test_returns_pair_when_both_set(self):
+ assert resolve_ai_gateway_config() == (AI_GATEWAY_URL, AI_GATEWAY_KEY)
+
+ @pytest.mark.parametrize(
+ "url,key,reason",
+ [
+ (AI_GATEWAY_URL, "", "must be set together"),
+ ("", AI_GATEWAY_KEY, "must be set together"),
+ ("https://ai-gateway.example", AI_GATEWAY_KEY, "OpenAI base path"),
+ ],
+ )
+ def test_misconfig_falls_back_to_none_and_logs(self, url, key, reason):
+ # Radu review: a misconfig logs and returns None so callers fall back, never raises.
+ with (
+ override_settings(AI_GATEWAY_URL=url, AI_GATEWAY_API_KEY=key),
+ patch("posthog.llm.gateway_client.logger") as mock_logger,
+ ):
+ assert resolve_ai_gateway_config() is None
+
+ mock_logger.warning.assert_called_once()
+ assert reason in str(mock_logger.warning.call_args)
+
+
+class TestBuildOpenAIClient:
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
+ @patch("posthog.llm.gateway_client.httpx.Client")
+ @patch("posthog.llm.gateway_client.OpenAI")
+ def test_gateway_mode_routes_to_slugless_go_gateway_with_ai_product(self, mock_openai, mock_httpx):
+ result = build_openai_client("llma_summarization", ai_product="aio_summarization")
+
+ mock_httpx.assert_called_once_with(trust_env=False)
+ mock_openai.assert_called_once_with(
+ api_key=AI_GATEWAY_KEY,
+ base_url=AI_GATEWAY_URL,
+ default_headers={"X-PostHog-Properties": json.dumps({"ai_product": "aio_summarization"})},
+ http_client=mock_httpx.return_value,
+ )
+ assert result is mock_openai.return_value
+
+ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")
+ @patch("posthog.llm.gateway_client.get_llm_client")
+ 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")
+ assert result is mock_get_llm_client.return_value
+
+
+class TestBuildAsyncOpenAIClient:
+ @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_routes_to_slugless_go_gateway_with_ai_product(self, mock_async_openai, mock_httpx):
+ result = build_async_openai_client("llma_eval_summary", ai_product="aio_eval_summary")
+
+ mock_httpx.assert_called_once_with(trust_env=False)
+ mock_async_openai.assert_called_once_with(
+ api_key=AI_GATEWAY_KEY,
+ base_url=AI_GATEWAY_URL,
+ default_headers={"X-PostHog-Properties": json.dumps({"ai_product": "aio_eval_summary"})},
+ http_client=mock_httpx.return_value,
+ )
+ 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")
+ assert result is mock_get_async.return_value
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 8acdaac9ec8b..0acc7087ea69 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -11,6 +11,7 @@ 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.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,
@@ -234,12 +235,10 @@ def run_eval_report_agent(
from posthog.temporal.ai_observability.eval_reports.metrics import increment_errors, increment_report_generated
- # Tag every LLM call made by this agent run so they show up under `ai_product =
- # llma_eval_reports` in AI observability, matching the convention used by other
- # PostHog internal AI features. Trace id is unique per run so each invocation
- # is its own trace; distinct id is the team so traces group by project.
+ # 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:
+ if posthoganalytics.default_client and resolve_ai_gateway_config() is None:
callbacks.append(
CallbackHandler(
posthoganalytics.default_client,
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 c8cacc1f6ae9..78f1e88ccb17 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
@@ -257,3 +257,72 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
)
# 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 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):
+ 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",
+ )
+ 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()
+
+ @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_direct_mode_attaches_tagged_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()
+ mock_resolve.return_value = None # no gateway -> direct OpenAI, SDK must capture the event
+
+ callbacks = self._run_and_get_callbacks(mock_create_agent)
+
+ 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")
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.py
index a66c3f284050..8a70ccb0e33b 100644
--- a/posthog/temporal/ai_observability/llm_endpoint.py
+++ b/posthog/temporal/ai_observability/llm_endpoint.py
@@ -1,69 +1,49 @@
-"""OpenAI-compatible client for the cluster-labeling agents, routed through the
-ai-gateway when AI_GATEWAY_URL + AI_GATEWAY_API_KEY are set, else direct to OpenAI."""
+"""ChatOpenAI client for the labeling/report agents, routed through the internal
+Go ai-gateway when AI_GATEWAY_URL + AI_GATEWAY_API_KEY are set, else direct to OpenAI.
+
+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.
+"""
import os
-import json
-from urllib.parse import urlparse
from django.conf import settings
import httpx
-import structlog
from langchain_openai import ChatOpenAI
from posthog.cloud_utils import is_cloud
-
-logger = structlog.get_logger(__name__)
+from posthog.llm.gateway_client import ai_product_headers, resolve_ai_gateway_config
def build_langchain_chat_client(model: str, timeout: float, ai_product: str | None = None) -> ChatOpenAI:
- """Return a ChatOpenAI client for cluster labeling. Cloud/DEBUG only.
+ """Return a ChatOpenAI client for the labeling/report agents. Cloud/DEBUG only.
- Routes through the ai-gateway when AI_GATEWAY_URL + AI_GATEWAY_API_KEY are both set and the
- URL is well-formed; on a misconfiguration it logs and falls back to direct OpenAI so a
- half-applied rollout config can't break labeling. 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`` event via the gateway's ``X-PostHog-Properties`` header.
+ 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.
"""
if not settings.DEBUG and not is_cloud():
raise Exception("AI features are only available in PostHog Cloud")
- url, api_key = settings.AI_GATEWAY_URL, settings.AI_GATEWAY_API_KEY
- if url or api_key:
- misconfig = _gateway_misconfig(url, api_key)
- if misconfig:
- logger.warning("ai_gateway_misconfigured_falling_back", reason=misconfig)
- else:
- return ChatOpenAI(
- model=model,
- api_key=api_key,
- base_url=url,
- timeout=timeout,
- max_retries=2,
- default_headers=_ai_product_headers(ai_product),
- # 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),
- )
+ gateway = resolve_ai_gateway_config()
+ if gateway:
+ url, api_key = gateway
+ return ChatOpenAI(
+ model=model,
+ api_key=api_key,
+ base_url=url,
+ timeout=timeout,
+ max_retries=2,
+ default_headers=ai_product_headers(ai_product),
+ # 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),
+ )
direct_key = os.environ.get("OPENAI_API_KEY")
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 _gateway_misconfig(url: str, api_key: str) -> str | None:
- """Return a reason string if the gateway env is half-applied or malformed, else None."""
- if not (url and api_key):
- return "AI_GATEWAY_URL and AI_GATEWAY_API_KEY must be set together"
- # The SDK appends /chat/completions, so base_url must already carry the /v1 path.
- if not urlparse(url).path.rstrip("/").endswith("/v1"):
- return "AI_GATEWAY_URL must include the OpenAI base path, e.g. https://<host>/v1"
- return None
-
-
-def _ai_product_headers(ai_product: str | None) -> dict[str, str] | None:
- """X-PostHog-Properties header tagging the captured generation with its AIO product."""
- if not ai_product:
- return None
- return {"X-PostHog-Properties": json.dumps({"ai_product": ai_product})}
diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
index 7e8c7a0625ed..d1e4e76bd0b2 100644
--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
@@ -55,7 +55,8 @@ class TestBuildOpenAIChatClient:
with (
override_settings(DEBUG=True, AI_GATEWAY_URL=gateway_url, AI_GATEWAY_API_KEY=gateway_key),
patch.dict("os.environ", {"OPENAI_API_KEY": "sk-direct"}, clear=False),
- patch("posthog.temporal.ai_observability.llm_endpoint.logger") as mock_logger,
+ # the shared resolver in gateway_client owns the misconfig warning
+ patch("posthog.llm.gateway_client.logger") as mock_logger,
):
client = build_langchain_chat_client("gpt-5.4", 600.0)
diff --git a/products/ai_observability/backend/summarization/llm/evaluation_summary.py b/products/ai_observability/backend/summarization/llm/evaluation_summary.py
index af73ea35884a..cb21d1b2d18b 100644
--- a/products/ai_observability/backend/summarization/llm/evaluation_summary.py
+++ b/products/ai_observability/backend/summarization/llm/evaluation_summary.py
@@ -1,13 +1,13 @@
-"""LLM gateway-based evaluation summary generation."""
+"""Evaluation summary generation, routed through the internal Go ai-gateway when
+configured, else the Python LLM gateway."""
from typing import Any, cast
import structlog
-from openai import AsyncOpenAI
from openai.types.chat import ChatCompletionMessageParam
from rest_framework import exceptions
-from posthog.llm.gateway_client import get_llm_client
+from posthog.llm.gateway_client import build_async_openai_client
from ..constants import SUMMARIZATION_TIMEOUT
from ..models import OpenAIModel
@@ -86,12 +86,7 @@ async def summarize_evaluation_runs(
{runs_text}"""
- sync_client = get_llm_client("llma_eval_summary")
- client = AsyncOpenAI(
- base_url=sync_client.base_url,
- api_key=sync_client.api_key,
- timeout=SUMMARIZATION_TIMEOUT,
- )
+ client = build_async_openai_client("llma_eval_summary", ai_product="aio_eval_summary")
messages: list[ChatCompletionMessageParam] = [
{"role": "system", "content": system_prompt},
@@ -103,6 +98,7 @@ async def summarize_evaluation_runs(
model=str(model),
messages=messages,
user=user_distinct_id or "llma-evaluation-summarization",
+ timeout=SUMMARIZATION_TIMEOUT,
response_format=cast(
Any,
{
diff --git a/products/ai_observability/backend/summarization/llm/openai.py b/products/ai_observability/backend/summarization/llm/openai.py
index 417f4a441872..660e84f6413f 100644
--- a/products/ai_observability/backend/summarization/llm/openai.py
+++ b/products/ai_observability/backend/summarization/llm/openai.py
@@ -1,4 +1,5 @@
-"""OpenAI provider for LLM summarization via LLM gateway."""
+"""OpenAI provider for LLM summarization, routed through the internal Go ai-gateway
+when configured, else the Python LLM gateway."""
from typing import Any, cast
@@ -6,7 +7,7 @@ import structlog
from openai.types.chat import ChatCompletionMessageParam
from rest_framework import exceptions
-from posthog.llm.gateway_client import get_llm_client
+from posthog.llm.gateway_client import build_openai_client
from ..constants import SUMMARIZATION_TIMEOUT
from ..models import OpenAIModel, SummarizationMode
@@ -27,7 +28,7 @@ def summarize_with_openai(
system_prompt = load_summarization_template(f"prompts/system_{mode}.djt", {})
user_prompt = load_summarization_template("prompts/user.djt", {"text_repr": text_repr})
- client = get_llm_client("llma_summarization")
+ client = build_openai_client("llma_summarization", ai_product="aio_summarization")
messages: list[ChatCompletionMessageParam] = [
{"role": "system", "content": system_prompt},
diff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.py
index 270e41231164..045b10415b94 100644
--- a/products/ai_observability/backend/summarization/tests/test_providers.py
+++ b/products/ai_observability/backend/summarization/tests/test_providers.py
@@ -1,10 +1,13 @@
import json
+import asyncio
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from rest_framework import exceptions
+from products.ai_observability.backend.summarization.constants import SUMMARIZATION_TIMEOUT
+from products.ai_observability.backend.summarization.llm.evaluation_summary import summarize_evaluation_runs
from products.ai_observability.backend.summarization.llm.openai import summarize_with_openai
from products.ai_observability.backend.summarization.llm.schema import SummarizationResponse
from products.ai_observability.backend.summarization.models import OpenAIModel, SummarizationMode
@@ -28,7 +31,7 @@ class TestSummarizeWithOpenAI:
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = valid_response_json
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
@@ -42,14 +45,14 @@ class TestSummarizeWithOpenAI:
assert isinstance(result, SummarizationResponse)
assert result.title == "Test Summary"
- mock_get_client.assert_called_once_with("llma_summarization")
+ mock_get_client.assert_called_once_with("llma_summarization", ai_product="aio_summarization")
def test_empty_response_raises_validation_error(self):
mock_response = MagicMock()
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = None
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
@@ -63,7 +66,7 @@ class TestSummarizeWithOpenAI:
)
def test_api_error_raises_api_exception(self):
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.side_effect = Exception("API Error")
@@ -81,7 +84,7 @@ class TestSummarizeWithOpenAI:
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = valid_response_json
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
@@ -101,7 +104,7 @@ class TestSummarizeWithOpenAI:
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = valid_response_json
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
@@ -122,7 +125,7 @@ class TestSummarizeWithOpenAI:
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = valid_response_json
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
@@ -142,7 +145,7 @@ class TestSummarizeWithOpenAI:
mock_response.choices = [MagicMock()]
mock_response.choices[0].message.content = valid_response_json
- with patch("products.ai_observability.backend.summarization.llm.openai.get_llm_client") as mock_get_client:
+ with patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client:
mock_client = MagicMock()
mock_get_client.return_value = mock_client
mock_client.chat.completions.create.return_value = mock_response
@@ -157,3 +160,44 @@ class TestSummarizeWithOpenAI:
call_kwargs = mock_client.chat.completions.create.call_args[1]
assert call_kwargs["response_format"]["type"] == "json_schema"
assert call_kwargs["response_format"]["json_schema"]["strict"] is True
+
+
+def valid_evaluation_summary_json():
+ return json.dumps(
+ {
+ "overall_assessment": "Mostly passing.",
+ "pass_patterns": [],
+ "fail_patterns": [],
+ "na_patterns": [],
+ "recommendations": [],
+ "statistics": {"total_analyzed": 1, "pass_count": 1, "fail_count": 0, "na_count": 0},
+ }
+ )
+
+
+class TestSummarizeEvaluationRuns:
+ def test_routes_through_async_gateway_builder_and_passes_timeout(self, valid_evaluation_summary_json):
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = valid_evaluation_summary_json
+
+ with patch(
+ "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client"
+ ) as mock_builder:
+ mock_client = MagicMock()
+ mock_client.chat.completions.create = AsyncMock(return_value=mock_response)
+ mock_builder.return_value = mock_client
+
+ result = asyncio.run(
+ summarize_evaluation_runs(
+ evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],
+ team_id=1,
+ model=OpenAIModel.GPT_4_1_MINI,
+ )
+ )
+
+ mock_builder.assert_called_once_with("llma_eval_summary", ai_product="aio_eval_summary")
+ # timeout moved off the client constructor onto the per-call create()
+ assert mock_client.chat.completions.create.call_args.kwargs["timeout"] == SUMMARIZATION_TIMEOUT
+ assert result.overall_assessment == "Mostly passing."