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): run evaluation reports on the flex service tier (#98662)

Bernat Torresdb51ee0580a9
diff --git a/posthog/temporal/ai_observability/clustering_agent/__init__.py b/posthog/temporal/ai_observability/clustering_agent/__init__.py
index e15344188b2c..9dbb853817b0 100644
--- a/posthog/temporal/ai_observability/clustering_agent/__init__.py
+++ b/posthog/temporal/ai_observability/clustering_agent/__init__.py
@@ -12,18 +12,10 @@ from collections.abc import Mapping
from langchain_openai import ChatOpenAI
-from posthog.llm.openai_flex import FLEX_CAPABLE_MODELS
-from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
+from posthog.temporal.ai_observability.llm_endpoint import build_flex_first_chat_client
from posthog.temporal.ai_observability.trace_clustering.constants import NOISE_CLUSTER_ID
from posthog.temporal.ai_observability.trace_clustering.models import ClusterLabel
-# Per-call timeouts, capped so no single call can outlive the 600s labeling activity: flex
-# 120s x 1 attempt (the standard-tier fallback call is the retry), standard 240s x 2 attempts.
-# The ai-gateway cuts non-streaming calls at ~290s anyway, so longer client timeouts are
-# unreachable.
-LABELING_FLEX_CALL_TIMEOUT = 120.0
-LABELING_STANDARD_CALL_TIMEOUT = 240.0
-
def get_labeling_llm(
model: str,
@@ -42,21 +34,18 @@ def get_labeling_llm(
``posthog.temporal.ai_observability.llm_endpoint``. Enforces the same
guardrail as before: AI features only run in Cloud or local DEBUG builds.
- Labeling runs as a daily batch, so allowlisted models request the flex
- service tier for half-price tokens; ``FlexFirstChatOpenAI`` retries a failed
- flex call on the standard tier.
+ Labeling runs as a daily batch, so it takes the flex service tier; see
+ ``build_flex_first_chat_client`` for the tier, timeout, and retry policy.
"""
- use_flex = flex and model in FLEX_CAPABLE_MODELS
- return build_langchain_chat_client(
+ return build_flex_first_chat_client(
model,
- LABELING_FLEX_CALL_TIMEOUT if use_flex else min(timeout, LABELING_STANDARD_CALL_TIMEOUT),
+ timeout,
ai_product="aio_clustering",
trace_id=trace_id,
session_id=session_id,
properties=properties,
distinct_id=distinct_id,
- service_tier="flex" if use_flex else None,
- max_retries=0 if use_flex else 1,
+ flex=flex,
)
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 4fd30a34b4dd..de7b91dd6d94 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -36,7 +36,7 @@ from posthog.temporal.ai_observability.eval_reports.targets import (
get_target_descriptor,
)
from posthog.temporal.ai_observability.eval_reports.types import RunEvalReportAgentInput
-from posthog.temporal.ai_observability.llm_endpoint import build_langchain_callbacks, build_langchain_chat_client
+from posthog.temporal.ai_observability.llm_endpoint import build_flex_first_chat_client, build_langchain_callbacks
logger = structlog.get_logger(__name__)
@@ -273,7 +273,7 @@ def run_eval_report_agent(
"evaluation_id": inputs.evaluation_id,
**({"report_id": inputs.report_id} if inputs.report_id else {}),
}
- llm = build_langchain_chat_client(
+ llm = build_flex_first_chat_client(
EVAL_REPORT_AGENT_MODEL,
EVAL_REPORT_AGENT_TIMEOUT,
ai_product="aio_eval_reports",
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 755f3bf82a48..3c9a9a3e26c8 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
@@ -404,7 +404,7 @@ class TestRunEvalReportAgentRouting(SimpleTestCase):
@patch.object(graph, "build_langchain_callbacks", return_value=[])
@patch.object(graph, "create_react_agent")
- @patch.object(graph, "build_langchain_chat_client")
+ @patch.object(graph, "build_flex_first_chat_client")
@patch.object(graph, "_compute_metrics")
def test_routes_llm_through_gateway_helper(
self, mock_metrics, mock_build_llm, mock_create_agent, _mock_build_callbacks
@@ -465,7 +465,7 @@ class TestRunEvalReportAgentDeadIdGuard(SimpleTestCase):
@patch.object(graph, "build_langchain_callbacks", return_value=[])
@patch.object(graph, "create_react_agent")
- @patch.object(graph, "build_langchain_chat_client")
+ @patch.object(graph, "build_flex_first_chat_client")
@patch.object(graph, "_compute_metrics")
def test_uncited_opaque_id_from_the_result_allowlist_falls_back(
self, mock_metrics, _mock_build_llm, mock_create_agent, _mock_build_callbacks
@@ -504,7 +504,7 @@ class TestRunEvalReportAgentDeadIdGuard(SimpleTestCase):
class TestRunEvalReportAgentMetricsUnavailable(SimpleTestCase):
- @patch.object(graph, "build_langchain_chat_client")
+ @patch.object(graph, "build_flex_first_chat_client")
@patch.object(graph, "create_react_agent")
@patch.object(graph, "_compute_metrics")
def test_metrics_unavailable_skips_agent_and_returns_fallback(
@@ -547,7 +547,7 @@ 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, "build_flex_first_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
@@ -605,7 +605,7 @@ class TestRunEvalReportAgentInstrumentation(SimpleTestCase):
@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, "build_flex_first_chat_client")
@patch.object(graph, "_compute_metrics")
def test_error_log_includes_report_trace_and_session(
self, mock_metrics, _mock_build_llm, mock_create_agent, _mock_build_callbacks, mock_logger_exception
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.py
index 7af14d07baa9..7ae81a265e91 100644
--- a/posthog/temporal/ai_observability/llm_endpoint.py
+++ b/posthog/temporal/ai_observability/llm_endpoint.py
@@ -28,7 +28,7 @@ from temporalio.exceptions import ApplicationError
from posthog.cloud_utils import is_cloud
from posthog.llm.gateway_client import ai_gateway_headers, resolve_ai_gateway_config
-from posthog.llm.openai_flex import is_flex_recoverable
+from posthog.llm.openai_flex import FLEX_CAPABLE_MODELS, is_flex_recoverable
logger = structlog.get_logger(__name__)
@@ -47,6 +47,9 @@ class FlexFirstChatOpenAI(ChatOpenAI):
turns instead of rerunning from scratch. Build flex clients with max_retries=0:
the tier switch is the retry. The first fallback latches the client to standard,
so a flex brownout costs one timeout per agent run, not one per call.
+
+ Build one through ``build_flex_first_chat_client`` rather than directly, so every
+ caller gets the same tier, timeout, and retry policy.
"""
_flex_latched: bool = PrivateAttr(default=False)
@@ -60,7 +63,7 @@ class FlexFirstChatOpenAI(ChatOpenAI):
if self._flex_latched or self.service_tier != "flex" or not is_flex_recoverable(error):
raise error
logger.warning(
- "labeling_flex_call_fell_back",
+ "flex_call_fell_back",
error_type=type(error).__name__,
status_code=getattr(error, "status_code", None),
model=self.model_name,
@@ -149,6 +152,49 @@ def build_langchain_chat_client(
)
+# Per-call timeouts, capped so no single call can outlive the activity that runs the agent:
+# flex 120s x 1 attempt (the standard-tier fallback call is the retry), standard 240s x 2
+# attempts. The ai-gateway cuts non-streaming calls at ~290s, so longer client timeouts are
+# unreachable.
+FLEX_CALL_TIMEOUT = 120.0
+STANDARD_CALL_TIMEOUT = 240.0
+
+
+def build_flex_first_chat_client(
+ model: str,
+ timeout: float,
+ *,
+ ai_product: str,
+ trace_id: str,
+ session_id: str,
+ properties: Mapping[str, str],
+ distinct_id: str,
+ flex: bool = True,
+) -> ChatOpenAI:
+ """Return a ChatOpenAI client that prefers the flex service tier.
+
+ The langchain agents behind this helper all run as scheduled batches with no user
+ waiting, so an allowlisted model requests flex for half-price tokens and
+ ``FlexFirstChatOpenAI`` retries a failed flex call on the standard tier.
+
+ A model outside the allowlist keeps the standard tier, because OpenAI decides flex
+ eligibility per model and the gpt-4.1 family rejects the service_tier field outright.
+ Pass ``flex=False`` to opt a caller out while keeping the bounded timeouts.
+ """
+ use_flex = flex and model in FLEX_CAPABLE_MODELS
+ return build_langchain_chat_client(
+ model,
+ FLEX_CALL_TIMEOUT if use_flex else min(timeout, STANDARD_CALL_TIMEOUT),
+ ai_product=ai_product,
+ trace_id=trace_id,
+ session_id=session_id,
+ properties=properties,
+ distinct_id=distinct_id,
+ service_tier="flex" if use_flex else None,
+ max_retries=0 if use_flex else 1,
+ )
+
+
def build_langchain_callbacks(
*,
distinct_id: str,
diff --git a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
index 59cd02f5ec1e..3ffa69354cc1 100644
--- a/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
+++ b/posthog/temporal/ai_observability/tests/test_llm_endpoint.py
@@ -12,12 +12,15 @@ import openai
from openai import APIStatusError, APITimeoutError, InternalServerError, RateLimitError
from temporalio.exceptions import ApplicationError
+from posthog.llm.openai_flex import FLEX_CAPABLE_MODELS
+from posthog.temporal.ai_observability.eval_reports.constants import EVAL_REPORT_AGENT_MODEL
from posthog.temporal.ai_observability.llm_endpoint import (
AI_FEATURES_CLOUD_ONLY_ERROR_TYPE,
FlexFirstChatOpenAI,
build_langchain_callbacks,
build_langchain_chat_client,
)
+from posthog.temporal.ai_observability.trace_clustering.constants import LABELING_AGENT_MODEL
from posthog.temporal.common.posthog_client import EXPECTED_CONTROL_FLOW_ERROR_TYPES
GATEWAY_URL = "https://gateway.example/v1"
@@ -211,12 +214,14 @@ class TestBuildOpenAIChatClient:
)
assert client.service_tier == expected_tier
+ @pytest.mark.parametrize("model", [EVAL_REPORT_AGENT_MODEL, LABELING_AGENT_MODEL])
+ def test_every_batch_agent_runs_a_flex_capable_model(self, model):
+ # A model outside the allowlist keeps working and silently doubles that agent's bill.
+ assert model in FLEX_CAPABLE_MODELS
+
def test_labeling_clients_bound_every_call_inside_the_activity_budget(self):
- from posthog.temporal.ai_observability.clustering_agent import (
- LABELING_FLEX_CALL_TIMEOUT,
- LABELING_STANDARD_CALL_TIMEOUT,
- get_labeling_llm,
- )
+ from posthog.temporal.ai_observability.clustering_agent import get_labeling_llm
+ from posthog.temporal.ai_observability.llm_endpoint import FLEX_CALL_TIMEOUT, STANDARD_CALL_TIMEOUT
with override_settings(DEBUG=True, AI_GATEWAY_URL=GATEWAY_URL, AI_GATEWAY_API_KEY=GATEWAY_KEY):
flex_client = get_labeling_llm(
@@ -228,10 +233,10 @@ class TestBuildOpenAIChatClient:
# Flex: 120s x 1 attempt (the standard-tier fallback call is the retry); standard: 240s x 2 = 480s.
# Both fit the 600s activity budget, where the old 600s x 3 attempts per call could not.
- assert flex_client.request_timeout == LABELING_FLEX_CALL_TIMEOUT
+ assert flex_client.request_timeout == FLEX_CALL_TIMEOUT
assert flex_client.max_retries == 0
assert standard_client.service_tier is None
- assert standard_client.request_timeout == LABELING_STANDARD_CALL_TIMEOUT
+ assert standard_client.request_timeout == STANDARD_CALL_TIMEOUT
assert standard_client.max_retries == 1