: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-observability): make cluster labeling routable through the ai-gateway (#64448)
Brandona481fae183f1
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 0d6188788316..d01dfb157c6b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -973,6 +973,11 @@ ELEMENT_STATS_DEFAULT_LIMIT = get_from_env("ELEMENT_STATS_DEFAULT_LIMIT", 50_000AI_GATEWAY_INTERNAL_URL = get_from_env("AI_GATEWAY_INTERNAL_URL", "")AI_GATEWAY_INTERNAL_TOKEN = get_from_env("AI_GATEWAY_INTERNAL_TOKEN", "")+# AI gateway inference endpoint: OpenAI-compatible URL (include /v1) + phs_ project+# secret for routing LLM calls through the gateway. Unset = direct to the provider.+AI_GATEWAY_URL = get_from_env("AI_GATEWAY_URL", "")+AI_GATEWAY_API_KEY = get_from_env("AI_GATEWAY_API_KEY", "")+# Sharing configuration settingsSHARING_TOKEN_GRACE_PERIOD_SECONDS = 60 * 5 # 5 minutesdiff --git a/posthog/temporal/ai_observability/clustering_agent/__init__.py b/posthog/temporal/ai_observability/clustering_agent/__init__.pyindex 5f414f923372..c92f2e5dd89d 100644--- a/posthog/temporal/ai_observability/clustering_agent/__init__.py+++ b/posthog/temporal/ai_observability/clustering_agent/__init__.py@@ -8,37 +8,22 @@ duplicate; the level-specific prompts, tools, and state TypedDicts live witheach individual agent so per-level prompt iteration stays local."""-import os--from django.conf import settings-from langchain_openai import ChatOpenAI-from posthog.cloud_utils import is_cloud+from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_clientfrom posthog.temporal.ai_observability.trace_clustering.constants import NOISE_CLUSTER_IDfrom posthog.temporal.ai_observability.trace_clustering.models import ClusterLabeldef get_labeling_llm(model: str, timeout: float) -> ChatOpenAI:- """Return an OpenAI chat client configured for cluster labeling.+ """Return a ChatOpenAI client for cluster labeling.- Enforces the same environment guardrails the trace clustering agent has- always used: AI features only run in Cloud or local DEBUG builds, and the- OpenAI key must be explicitly configured.+ Shared by the trace and evaluation labeling agents. Routes through the+ ai-gateway when configured; see+ ``posthog.temporal.ai_observability.llm_endpoint``. Enforces the same+ guardrail as before: AI features only run in Cloud or local DEBUG builds."""- 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,- )+ return build_langchain_chat_client(model, timeout, ai_product="aio_clustering")def fill_missing_labels(diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.pynew file mode 100644index 000000000000..a66c3f284050--- /dev/null+++ b/posthog/temporal/ai_observability/llm_endpoint.py@@ -0,0 +1,69 @@+"""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."""++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__)+++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.++ 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.+ """+ 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),+ )++ 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.pynew file mode 100644index 000000000000..7e8c7a0625ed--- /dev/null+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py@@ -0,0 +1,83 @@+"""Tests for clustering labeling client construction (ai-gateway vs direct OpenAI)."""++import json++import pytest+from unittest.mock import patch++from django.test import override_settings++from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client++GATEWAY_URL = "https://gateway.example/v1"+GATEWAY_KEY = "phs_project_secret"+++class TestBuildOpenAIChatClient:+ @pytest.mark.parametrize(+ "gateway_url,gateway_key,expected_base,expected_key,custom_http_client",+ [+ (GATEWAY_URL, GATEWAY_KEY, GATEWAY_URL, GATEWAY_KEY, True),+ (None, None, None, "sk-direct", False),+ ],+ )+ def test_routing_resolves_endpoint_and_credentials(+ self, gateway_url, gateway_key, expected_base, expected_key, custom_http_client+ ):+ 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),+ ):+ client = build_langchain_chat_client("gpt-5.4", 600.0)++ assert client.openai_api_base == expected_base+ api_key = client.openai_api_key+ assert api_key is not None+ assert api_key.get_secret_value() == expected_key+ # Gateway mode injects a trust_env=False http client; direct mode uses the SDK default.+ if custom_http_client:+ assert client.http_client is not None+ assert client.http_async_client is not None+ else:+ assert client.http_client is None++ @pytest.mark.parametrize(+ "gateway_url,gateway_key,reason",+ [+ (GATEWAY_URL, None, "must be set together"),+ (None, GATEWAY_KEY, "must be set together"),+ ("https://gateway.example", GATEWAY_KEY, "OpenAI base path"),+ ],+ )+ def test_misconfigured_gateway_falls_back_to_direct_and_logs(self, gateway_url, gateway_key, reason):+ # Radu review: a half-applied / malformed gateway config falls back to the direct provider+ # rather than failing the call, and logs loudly so a broken rollout config is visible.+ 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,+ ):+ client = build_langchain_chat_client("gpt-5.4", 600.0)++ assert client.openai_api_base is None+ api_key = client.openai_api_key+ assert api_key is not None+ assert api_key.get_secret_value() == "sk-direct"+ mock_logger.warning.assert_called_once()+ assert reason in str(mock_logger.warning.call_args)++ @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")++ assert mock_chat.call_args.kwargs["default_headers"] == {+ "X-PostHog-Properties": json.dumps({"ai_product": "aio_clustering"})+ }++ @override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY)+ def test_gateway_mode_without_ai_product_omits_header(self):+ with patch("posthog.temporal.ai_observability.llm_endpoint.ChatOpenAI") as mock_chat:+ build_langchain_chat_client("gpt-5.4", 600.0)++ assert mock_chat.call_args.kwargs["default_headers"] is None