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(llma): offline-evals experiment-items AI table migration (#57805)

Carlos Marchal13d3d1486954
diff --git a/ee/hogai/eval/sandboxed/trace_events.py b/ee/hogai/eval/sandboxed/trace_events.py
index 3058e0200a08..e267205b596f 100644
--- a/ee/hogai/eval/sandboxed/trace_events.py
+++ b/ee/hogai/eval/sandboxed/trace_events.py
@@ -320,8 +320,10 @@ def emit_evaluation_events(
}
if score_value is not None:
properties["$ai_score"] = score_value
+ properties["$ai_trace_id"] = trace_id or str(uuid.uuid4())
if trace_id:
- properties["$ai_trace_id"] = trace_id
+ properties["$ai_target_id"] = trace_id
+ properties["$ai_target_type"] = "trace_id"
if isinstance(result.input, dict):
prompt = result.input.get("prompt", "")
if prompt:
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index a99c81498837..39c69a17761d 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -83,6 +83,7 @@ from products.llm_analytics.backend.api import (
EvaluationRunViewSet,
EvaluationViewSet,
LLMAnalyticsClusteringRunViewSet,
+ LLMAnalyticsOfflineEvaluationsViewSet,
LLMAnalyticsSentimentViewSet,
LLMAnalyticsSummarizationViewSet,
LLMAnalyticsTextReprViewSet,
@@ -1467,6 +1468,13 @@ environments_router.register(
["team_id"],
)
+environments_router.register(
+ r"llm_analytics/offline_evaluations",
+ LLMAnalyticsOfflineEvaluationsViewSet,
+ "environment_llm_analytics_offline_evaluations",
+ ["team_id"],
+)
+
environments_router.register(
r"llm_analytics/review_queue_items",
ReviewQueueItemViewSet,
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index c6c13a35d282..c08d896e517f 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2217,14 +2217,24 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
},
"$ai_target_event_id": {
"label": "AI Target Event ID (LLM)",
- "description": "The unique identifier of the event being evaluated.",
+ "description": "Deprecated — use $ai_target_id with $ai_target_type instead. The unique identifier of the event being evaluated.",
"examples": ["c9222e05-8708-41b8-98ea-d4a21849e761"],
},
"$ai_target_event_type": {
"label": "AI Target Event Type (LLM)",
- "description": "The type of event being evaluated (e.g., $ai_generation).",
+ "description": "Deprecated — use $ai_target_type instead. The type of event being evaluated (e.g., $ai_generation).",
"examples": ["$ai_generation", "$ai_span"],
},
+ "$ai_target_id": {
+ "label": "AI Target ID (LLM)",
+ "description": "Identifier of the entity this evaluation targets. Pair with $ai_target_type to know which ID space it belongs to (event UUID, trace ID, etc.).",
+ "examples": ["c9222e05-8708-41b8-98ea-d4a21849e761"],
+ },
+ "$ai_target_type": {
+ "label": "AI Target Type (LLM)",
+ "description": "ID space of $ai_target_id. `generation_uuid` resolves against `events.uuid`; `trace_id` resolves against the `$ai_trace_id` property.",
+ "examples": ["generation_uuid", "trace_id"],
+ },
"$ai_metric_name": {
"label": "AI Metric Name (LLM)",
"description": "The name assigned to the metric used to evaluate the LLM trace.",
diff --git a/posthog/temporal/llm_analytics/run_evaluation.py b/posthog/temporal/llm_analytics/run_evaluation.py
index 8235868ae28a..baf9d081fe18 100644
--- a/posthog/temporal/llm_analytics/run_evaluation.py
+++ b/posthog/temporal/llm_analytics/run_evaluation.py
@@ -1013,6 +1013,8 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> N
"$ai_evaluation_reasoning": result["reasoning"],
"$ai_target_event_id": event_data["uuid"],
"$ai_target_event_type": event_data["event"],
+ "$ai_target_id": event_data["uuid"],
+ "$ai_target_type": "generation_uuid",
"$ai_trace_id": source_props.get("$ai_trace_id"),
# Carry the trigger user's session_id from the source event so evals
# can link back to the session recording that originated the trace.
diff --git a/posthog/temporal/llm_analytics/run_tagger.py b/posthog/temporal/llm_analytics/run_tagger.py
index 30ffa47c0c06..0d808253976e 100644
--- a/posthog/temporal/llm_analytics/run_tagger.py
+++ b/posthog/temporal/llm_analytics/run_tagger.py
@@ -545,6 +545,8 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:
"$ai_tagger_start_time": start_time.isoformat(),
"$ai_target_event_id": event_data["uuid"],
"$ai_target_event_type": event_data["event"],
+ "$ai_target_id": event_data["uuid"],
+ "$ai_target_type": "generation_uuid",
"$ai_trace_id": properties_raw.get("$ai_trace_id"),
}
diff --git a/products/llm_analytics/backend/api/__init__.py b/products/llm_analytics/backend/api/__init__.py
index c36f20f92164..9ebe72699008 100644
--- a/products/llm_analytics/backend/api/__init__.py
+++ b/products/llm_analytics/backend/api/__init__.py
@@ -8,6 +8,7 @@ from .evaluation_runs import EvaluationRunViewSet
from .evaluation_summary import LLMEvaluationSummaryViewSet
from .evaluations import EvaluationViewSet
from .models import LLMModelsViewSet
+from .offline_evaluations import LLMAnalyticsOfflineEvaluationsViewSet
from .provider_keys import LLMProviderKeyValidationViewSet, LLMProviderKeyViewSet
from .proxy import SUPPORTED_MODELS_WITH_THINKING, LLMProxyViewSet
from .review_queues import ReviewQueueItemViewSet, ReviewQueueViewSet
@@ -42,6 +43,7 @@ __all__ = [
"ReviewQueueItemViewSet",
"ScoreDefinitionViewSet",
"LLMAnalyticsSentimentViewSet",
+ "LLMAnalyticsOfflineEvaluationsViewSet",
"TaggerViewSet",
"TraceReviewViewSet",
]
diff --git a/products/llm_analytics/backend/api/offline_evaluations.py b/products/llm_analytics/backend/api/offline_evaluations.py
new file mode 100644
index 000000000000..5e7ce32ba36e
--- /dev/null
+++ b/products/llm_analytics/backend/api/offline_evaluations.py
@@ -0,0 +1,262 @@
+from collections import namedtuple
+
+import structlog
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.hogql import ast
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.api.monitoring import monitor
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.permissions import AccessControlPermission
+
+from products.llm_analytics.backend.api.metrics import llma_track_latency
+
+logger = structlog.get_logger(__name__)
+
+OFFLINE_EXPERIMENT_ITEMS_LIMIT = 20000
+
+# Preflight on `events` so the `(team_id, toDate(timestamp), event)` sort
+# key prunes by date; `posthog.ai_events` is keyed `(team_id, trace_id,
+# timestamp)` and can't prune until trace_id is bounded.
+_OFFLINE_EXPERIMENT_ITEMS_PREFLIGHT_SQL = """
+SELECT
+ nullIf(properties.$ai_experiment_item_id, '') as item_id,
+ argMax(properties.$ai_experiment_item_name, timestamp) as experiment_item_name,
+ argMax(properties.$ai_experiment_name, timestamp) as experiment_name,
+ nullIf(properties.$ai_metric_name, '') as metric_name,
+ nullIf(properties.$ai_metric_version, '') as metric_version,
+ argMax(properties.$ai_status, timestamp) as status,
+ argMax(properties.$ai_score, timestamp) as score,
+ argMax(properties.$ai_score_min, timestamp) as score_min,
+ argMax(properties.$ai_score_max, timestamp) as score_max,
+ argMax(properties.$ai_result_type, timestamp) as result_type,
+ argMax(properties.$ai_reasoning, timestamp) as reasoning,
+ argMax(properties.$ai_trace_id, timestamp) as trace_id,
+ argMax(properties.$ai_target_id, timestamp) as target_id,
+ argMax(properties.$ai_target_type, timestamp) as target_type,
+ argMax(properties.$ai_dataset_id, timestamp) as dataset_id,
+ argMax(properties.$ai_dataset_item_id, timestamp) as dataset_item_id,
+ argMax(properties.$ai_expected, timestamp) as ai_expected,
+ max(timestamp) as last_seen_at,
+ min(timestamp) as first_seen_at
+FROM events
+WHERE
+ event = '$ai_evaluation'
+ AND properties.$ai_experiment_id = {experiment_id}
+ AND nullIf(properties.$ai_experiment_item_id, '') IS NOT NULL
+ AND ({date_from_is_null} OR timestamp >= parseDateTimeBestEffort({date_from}))
+ AND ({date_to_is_null} OR timestamp <= parseDateTimeBestEffort({date_to}))
+GROUP BY item_id, metric_name, metric_version
+ORDER BY last_seen_at DESC
+LIMIT {limit}
+"""
+
+_OFFLINE_EXPERIMENT_ITEMS_HEAVY_SQL = """
+SELECT
+ trace_id,
+ argMax(input, timestamp) as ai_input,
+ argMax(output, timestamp) as ai_output
+FROM posthog.ai_events AS ai_events
+WHERE event = '$ai_evaluation'
+ AND trace_id IN {trace_ids}
+ AND timestamp >= {ts_start}
+ AND timestamp <= {ts_end}
+GROUP BY trace_id
+"""
+
+_PreflightRow = namedtuple(
+ "_PreflightRow",
+ [
+ "item_id",
+ "experiment_item_name",
+ "experiment_name",
+ "metric_name",
+ "metric_version",
+ "status",
+ "score",
+ "score_min",
+ "score_max",
+ "result_type",
+ "reasoning",
+ "trace_id",
+ "target_id",
+ "target_type",
+ "dataset_id",
+ "dataset_item_id",
+ "ai_expected",
+ "last_seen_at",
+ "first_seen_at",
+ ],
+)
+
+
+class OfflineExperimentItemsRequestSerializer(serializers.Serializer):
+ experiment_id = serializers.CharField(
+ required=True,
+ allow_blank=False,
+ help_text="`$ai_experiment_id` whose offline-evaluation items to return.",
+ )
+ date_from = serializers.CharField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.",
+ )
+ date_to = serializers.CharField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.",
+ )
+
+
+class OfflineExperimentItemsResponseSerializer(serializers.Serializer):
+ results = serializers.ListField(
+ child=serializers.ListField(),
+ help_text="Tuple-positional rows; positions match `RawOfflineExperimentMetricRow` in the frontend.",
+ )
+
+
+class LLMAnalyticsOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "llm_analytics"
+ scope_object_read_actions = ["experiment_items"]
+ permission_classes = [AccessControlPermission]
+
+ @extend_schema(
+ request=OfflineExperimentItemsRequestSerializer,
+ responses={
+ 200: OfflineExperimentItemsResponseSerializer,
+ 400: OpenApiTypes.OBJECT,
+ 500: OpenApiTypes.OBJECT,
+ },
+ tags=["LLM Analytics"],
+ )
+ @action(detail=False, methods=["post"], url_path="experiment_items")
+ @llma_track_latency("llma_offline_evaluations_experiment_items")
+ @monitor(feature=None, endpoint="llma_offline_evaluations_experiment_items", method="POST")
+ def experiment_items(self, request: Request, **kwargs) -> Response:
+ serializer = OfflineExperimentItemsRequestSerializer(data=request.data)
+ if not serializer.is_valid():
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+
+ experiment_id: str = serializer.validated_data["experiment_id"]
+ date_from: str | None = serializer.validated_data.get("date_from") or None
+ date_to: str | None = serializer.validated_data.get("date_to") or None
+
+ # Parse-time, not execute-time: `properties.$ai_* + GROUP BY +
+ # {placeholder}` trips `HogVMException: Global variable not found:
+ # properties` in bytecode. parse_select-time substitution embeds
+ # Constants into the AST and bypasses the bytecode path.
+ preflight_placeholders: dict[str, ast.Expr] = {
+ "experiment_id": ast.Constant(value=experiment_id),
+ # `parseDateTimeBestEffort` rejects "", so the `_is_null` flags
+ # short-circuit the range filter when no bound was passed.
+ "date_from": ast.Constant(value=date_from or ""),
+ "date_to": ast.Constant(value=date_to or ""),
+ "date_from_is_null": ast.Constant(value=date_from is None),
+ "date_to_is_null": ast.Constant(value=date_to is None),
+ "limit": ast.Constant(value=OFFLINE_EXPERIMENT_ITEMS_LIMIT),
+ }
+ preflight_query = parse_select(_OFFLINE_EXPERIMENT_ITEMS_PREFLIGHT_SQL, placeholders=preflight_placeholders)
+
+ with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):
+ try:
+ preflight_result = execute_hogql_query(
+ query=preflight_query,
+ placeholders={},
+ team=self.team,
+ query_type="LLMOfflineEvaluationItemsResolve",
+ limit_context=LimitContext.QUERY,
+ )
+ except Exception as e:
+ logger.exception(
+ "Failed to resolve offline evaluation experiment items",
+ team_id=self.team_id,
+ experiment_id=experiment_id,
+ error=str(e),
+ )
+ return Response(
+ {"error": "Failed to fetch offline evaluation items"},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ preflight_rows = [_PreflightRow(*row) for row in (preflight_result.results or [])]
+ if not preflight_rows:
+ return Response({"results": []}, status=status.HTTP_200_OK)
+
+ traced_rows = [row for row in preflight_rows if row.trace_id]
+ trace_ids = [str(row.trace_id) for row in traced_rows]
+ ai_input_output_by_trace: dict[str, tuple] = {}
+
+ if trace_ids:
+ ts_start = min(row.first_seen_at for row in traced_rows)
+ ts_end = max(row.last_seen_at for row in traced_rows)
+
+ heavy_query = parse_select(_OFFLINE_EXPERIMENT_ITEMS_HEAVY_SQL)
+ try:
+ heavy_result = execute_with_ai_events_fallback(
+ query=heavy_query,
+ placeholders={
+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
+ "ts_start": ast.Constant(value=ts_start),
+ "ts_end": ast.Constant(value=ts_end),
+ },
+ team=self.team,
+ query_type="LLMOfflineEvaluationItems",
+ limit_context=LimitContext.QUERY,
+ )
+ except Exception as e:
+ logger.exception(
+ "Failed to fetch offline evaluation items heavy columns",
+ team_id=self.team_id,
+ experiment_id=experiment_id,
+ error=str(e),
+ )
+ return Response(
+ {"error": "Failed to fetch offline evaluation items"},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ ai_input_output_by_trace = {
+ str(trace_id): (ai_input, ai_output)
+ for trace_id, ai_input, ai_output in (heavy_result.results or [])
+ }
+
+ results = []
+ for row in preflight_rows:
+ ai_input, ai_output = ai_input_output_by_trace.get(str(row.trace_id), (None, None))
+ results.append(
+ [
+ row.item_id,
+ row.experiment_item_name,
+ row.experiment_name,
+ row.metric_name,
+ row.metric_version,
+ row.status,
+ row.score,
+ row.score_min,
+ row.score_max,
+ row.result_type,
+ row.reasoning,
+ row.trace_id,
+ row.dataset_id,
+ row.dataset_item_id,
+ ai_input,
+ ai_output,
+ row.ai_expected,
+ row.last_seen_at,
+ row.target_id,
+ row.target_type,
+ ]
+ )
+ return Response({"results": results}, status=status.HTTP_200_OK)
diff --git a/products/llm_analytics/backend/api/test/test_offline_evaluations.py b/products/llm_analytics/backend/api/test/test_offline_evaluations.py
new file mode 100644
index 000000000000..0641131eb9fe
--- /dev/null
+++ b/products/llm_analytics/backend/api/test/test_offline_evaluations.py
@@ -0,0 +1,342 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+
+class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
+ URL: str = ""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.URL = f"/api/environments/{self.team.id}/llm_analytics/offline_evaluations/experiment_items/"
+
+ def _make_response(self, rows: list[list[Any]]) -> MagicMock:
+ response = MagicMock()
+ response.results = rows
+ return response
+
+ def _preflight_row(
+ self,
+ item_id: str = "item-1",
+ experiment_item_name: str | None = "case A",
+ experiment_name: str | None = "exp-name",
+ metric_name: str = "accuracy",
+ metric_version: str = "1",
+ eval_status: str | None = "completed",
+ score: Any = 0.9,
+ score_min: Any = 0.0,
+ score_max: Any = 1.0,
+ result_type: str | None = "numeric",
+ reasoning: str | None = "looks good",
+ trace_id: str | None = "trace-1",
+ target_id: str | None = "trace-1",
+ target_type: str | None = "trace_id",
+ dataset_id: str | None = "ds-1",
+ dataset_item_id: str | None = "ds-item-1",
+ ai_expected: str | None = "expected",
+ last_seen_at: Any = "2026-04-27T07:00:00+00:00",
+ first_seen_at: Any = "2026-04-27T06:50:00+00:00",
+ ) -> list[Any]:
+ return [
+ item_id,
+ experiment_item_name,
+ experiment_name,
+ metric_name,
+ metric_version,
+ eval_status,
+ score,
+ score_min,
+ score_max,
+ result_type,
+ reasoning,
+ trace_id,
+ target_id,
+ target_type,
+ dataset_id,
+ dataset_item_id,
+ ai_expected,
+ last_seen_at,
+ first_seen_at,
+ ]
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_missing_experiment_id_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ response = self.client.post(self.URL, {}, content_type="application/json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert mock_preflight.call_count == 0
+ assert mock_heavy.call_count == 0
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_empty_experiment_id_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ response = self.client.post(self.URL, {"experiment_id": ""}, content_type="application/json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert mock_preflight.call_count == 0
+ assert mock_heavy.call_count == 0
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_returns_rows_in_20_column_tuple_order(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ mock_preflight.return_value = self._make_response(
+ [
+ self._preflight_row(
+ item_id="item-1",
+ trace_id="trace-1",
+ last_seen_at="2026-04-27T07:00:00+00:00",
+ first_seen_at="2026-04-27T06:50:00+00:00",
+ ),
+ ]
+ )
+ mock_heavy.return_value = self._make_response(
+ [["trace-1", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hi"}]']]
+ )
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body == {
+ "results": [
+ [
+ "item-1",
+ "case A",
+ "exp-name",
+ "accuracy",
+ "1",
+ "completed",
+ 0.9,
+ 0.0,
+ 1.0,
+ "numeric",
+ "looks good",
+ "trace-1",
+ "ds-1",
+ "ds-item-1",
+ '[{"role":"user","content":"hi"}]',
+ '[{"role":"assistant","content":"hi"}]',
+ "expected",
+ "2026-04-27T07:00:00+00:00",
+ "trace-1",
+ "trace_id",
+ ]
+ ]
+ }
+ assert mock_preflight.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItemsResolve"
+ assert mock_heavy.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItems"
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_empty_preflight_skips_heavy_query(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ mock_preflight.return_value = self._make_response([])
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"results": []}
+ assert mock_heavy.call_count == 0
+
+ @parameterized.expand(
+ [
+ ("blank_string", ""),
+ ("none", None),
+ ]
+ )
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_blank_only_trace_ids_short_circuit_heavy(
+ self, _name: str, blank_value: Any, mock_preflight: MagicMock, mock_heavy: MagicMock
+ ) -> None:
+ mock_preflight.return_value = self._make_response([self._preflight_row(item_id="item-1", trace_id=blank_value)])
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert len(body["results"]) == 1
+ assert body["results"][0][14] is None
+ assert body["results"][0][15] is None
+ assert mock_heavy.call_count == 0
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_preflight_failure_returns_500(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ mock_preflight.side_effect = RuntimeError("clickhouse boom")
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert mock_heavy.call_count == 0
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_heavy_failure_returns_500(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ mock_preflight.return_value = self._make_response([self._preflight_row()])
+ mock_heavy.side_effect = RuntimeError("clickhouse boom")
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_preflight_targets_events_and_heavy_targets_ai_events(
+ self, mock_preflight: MagicMock, mock_heavy: MagicMock
+ ) -> None:
+ from posthog.hogql import ast
+
+ mock_preflight.return_value = self._make_response(
+ [
+ self._preflight_row(
+ item_id="item-1",
+ trace_id="trace-1",
+ last_seen_at=datetime(2026, 4, 27, 7, 0, tzinfo=UTC),
+ first_seen_at=datetime(2026, 4, 27, 6, 50, tzinfo=UTC),
+ ),
+ self._preflight_row(
+ item_id="item-2",
+ trace_id="trace-2",
+ last_seen_at=datetime(2026, 4, 27, 6, 30, tzinfo=UTC),
+ first_seen_at=datetime(2026, 4, 27, 6, 0, tzinfo=UTC),
+ ),
+ ]
+ )
+ mock_heavy.return_value = self._make_response(
+ [
+ ["trace-1", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hi"}]'],
+ ["trace-2", '[{"role":"user","content":"hello"}]', '[{"role":"assistant","content":"hello"}]'],
+ ]
+ )
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ preflight_query = mock_preflight.call_args.kwargs["query"]
+ preflight_select = cast(ast.SelectQuery, preflight_query)
+ # nosemgrep: hogql-no-string-table-chain
+ assert preflight_select.select_from.table.chain == ["events"] # type: ignore[union-attr]
+
+ heavy_query = mock_heavy.call_args.kwargs["query"]
+ heavy_select = cast(ast.SelectQuery, heavy_query)
+ # nosemgrep: hogql-no-string-table-chain
+ assert heavy_select.select_from.table.chain == ["posthog", "ai_events"] # type: ignore[union-attr]
+
+ heavy_placeholders = mock_heavy.call_args.kwargs["placeholders"]
+ trace_id_values = [c.value for c in heavy_placeholders["trace_ids"].exprs]
+ assert trace_id_values == ["trace-1", "trace-2"]
+ assert heavy_placeholders["ts_start"].value == datetime(2026, 4, 27, 6, 0, tzinfo=UTC)
+ assert heavy_placeholders["ts_end"].value == datetime(2026, 4, 27, 7, 0, tzinfo=UTC)
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_traces_without_heavy_match_get_null_input_output(
+ self, mock_preflight: MagicMock, mock_heavy: MagicMock
+ ) -> None:
+ mock_preflight.return_value = self._make_response(
+ [
+ self._preflight_row(item_id="item-1", trace_id="trace-1"),
+ self._preflight_row(item_id="item-2", trace_id="trace-2"),
+ ]
+ )
+ mock_heavy.return_value = self._make_response(
+ [["trace-1", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hi"}]']]
+ )
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert len(body["results"]) == 2
+ assert body["results"][0][14] == '[{"role":"user","content":"hi"}]'
+ assert body["results"][0][15] == '[{"role":"assistant","content":"hi"}]'
+ assert body["results"][1][14] is None
+ assert body["results"][1][15] is None
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_omitted_dates_inline_as_null_guards(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ from posthog.hogql import ast
+ from posthog.hogql.visitor import TraversingVisitor
+
+ mock_preflight.return_value = self._make_response([])
+
+ response = self.client.post(
+ self.URL,
+ {"experiment_id": "exp-1"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert mock_preflight.call_args.kwargs["placeholders"] == {}
+
+ query = mock_preflight.call_args.kwargs["query"]
+ true_constants: list[ast.Constant] = []
+
+ class _BoolCounter(TraversingVisitor):
+ def visit_constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, bool) and node.value is True:
+ true_constants.append(node)
+ super().visit_constant(node)
+
+ _BoolCounter().visit(query)
+ assert len(true_constants) >= 2
+
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_with_ai_events_fallback")
+ @patch("products.llm_analytics.backend.api.offline_evaluations.execute_hogql_query")
+ def test_provided_dates_are_inlined_into_query(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:
+ from posthog.hogql import ast
+ from posthog.hogql.visitor import TraversingVisitor
+
+ mock_preflight.return_value = self._make_response([])
+
+ response = self.client.post(
+ self.URL,
+ {
+ "experiment_id": "exp-1",
+ "date_from": "2026-04-01T00:00:00Z",
+ "date_to": "2026-04-30T00:00:00Z",
+ },
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert mock_preflight.call_args.kwargs["placeholders"] == {}
+
+ query = mock_preflight.call_args.kwargs["query"]
+ string_constants: list[str] = []
+
+ class _StringCollector(TraversingVisitor):
+ def visit_constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str):
+ string_constants.append(node.value)
+ super().visit_constant(node)
+
+ _StringCollector().visit(query)
+ assert "exp-1" in string_constants
+ assert "2026-04-01T00:00:00Z" in string_constants
+ assert "2026-04-30T00:00:00Z" in string_constants
diff --git a/products/llm_analytics/frontend/evaluations/components/OfflineEvaluationsTab.tsx b/products/llm_analytics/frontend/evaluations/components/OfflineEvaluationsTab.tsx
index 96d797917b5b..da11b42e9209 100644
--- a/products/llm_analytics/frontend/evaluations/components/OfflineEvaluationsTab.tsx
+++ b/products/llm_analytics/frontend/evaluations/components/OfflineEvaluationsTab.tsx
@@ -82,13 +82,14 @@ function MetricIndicators({ value }: { value: OfflineMetricValue }): JSX.Element
</Tooltip>
) : null
- const traceIndicator = value.traceId ? (
- <Tooltip title={<div className="font-mono text-xs">{value.traceId}</div>}>
- <Link to={urls.llmAnalyticsTrace(value.traceId)} className="text-muted">
- <IconExternal className="size-3" />
- </Link>
- </Tooltip>
- ) : null
+ const traceIndicator =
+ value.targetType === 'trace_id' && value.targetId ? (
+ <Tooltip title={<div className="font-mono text-xs">{value.targetId}</div>}>
+ <Link to={urls.llmAnalyticsTrace(value.targetId)} className="text-muted">
+ <IconExternal className="size-3" />
+ </Link>
+ </Tooltip>
+ ) : null
if (!traceIndicator && !reasoningIndicator) {
return null
diff --git a/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.test.ts b/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.test.ts
index 4eff7b885f28..41cf2eef9dbc 100644
--- a/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.test.ts
+++ b/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.test.ts
@@ -41,6 +41,8 @@ describe('offlineEvaluationsLogic mapping helpers', () => {
'output one',
'expected one',
'2026-01-03T00:00:00Z',
+ 'trace-1',
+ 'trace_id',
],
[
'item-1',
@@ -61,6 +63,8 @@ describe('offlineEvaluationsLogic mapping helpers', () => {
null,
null,
'2026-01-04T00:00:00Z',
+ null,
+ null,
],
[
'item-2',
@@ -81,6 +85,8 @@ describe('offlineEvaluationsLogic mapping helpers', () => {
'output two',
'expected two',
'2026-01-05T00:00:00Z',
+ null,
+ null,
],
])
@@ -129,6 +135,8 @@ describe('offlineEvaluationsLogic mapping helpers', () => {
resultType: 'numeric',
reasoning: 'The answer matches the expected output exactly.',
traceId: 'trace-1',
+ targetId: 'trace-1',
+ targetType: 'trace_id',
})
expect(items[1].metrics['toxicity::2']).toEqual({
@@ -139,6 +147,8 @@ describe('offlineEvaluationsLogic mapping helpers', () => {
resultType: 'numeric',
reasoning: 'The model output contains disallowed language.',
traceId: null,
+ targetId: null,
+ targetType: null,
})
})
})
diff --git a/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.ts b/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.ts
index 9c0ef92edb3a..c4e2858873cc 100644
--- a/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.ts
+++ b/products/llm_analytics/frontend/evaluations/offlineEvaluationsLogic.ts
@@ -9,12 +9,13 @@ import { dateStringToDayJs, isValidRelativeOrAbsoluteDate } from 'lib/utils'
import { removeProjectIdIfPresent } from 'lib/utils/router-utils'
import { urls } from 'scenes/urls'
+import { getCurrentTeamId } from '~/lib/utils/getAppContext'
import { hogql } from '~/queries/utils'
+import { llmAnalyticsOfflineEvaluationsExperimentItemsCreate } from '../generated/api'
import type { offlineEvaluationsLogicType } from './offlineEvaluationsLogicType'
const OFFLINE_EXPERIMENTS_LIMIT = 200
-const OFFLINE_EXPERIMENT_ITEMS_LIMIT = 20000
const INITIAL_OFFLINE_DATE_FROM = 'dStart' as string | null
const INITIAL_OFFLINE_DATE_TO = null as string | null
@@ -55,6 +56,8 @@ type RawOfflineExperimentMetricRow = [
ai_output: HogQLPrimitive,
ai_expected: HogQLPrimitive,
last_seen_at: HogQLPrimitive,
+ target_id: HogQLPrimitive,
+ target_type: HogQLPrimitive,
]
export interface OfflineEvaluationsLogicProps {
@@ -85,6 +88,8 @@ export interface OfflineMetricValue {
resultType: string | null
reasoning: string | null
traceId: string | null
+ targetId: string | null
+ targetType: string | null
}
export interface OfflineExperimentItem {
@@ -118,15 +123,19 @@ function getEmptyOfflineExperimentData(): OfflineExperimentData {
}
}
+function parseOfflineDateFilter(dateFilter: OfflineDateFilter): { dateFrom: string | null; dateTo: string | null } {
+ return {
+ dateFrom: dateFilter.dateFrom ? (dateStringToDayJs(dateFilter.dateFrom)?.toISOString() ?? null) : null,
+ dateTo: dateFilter.dateTo ? (dateStringToDayJs(dateFilter.dateTo)?.toISOString() ?? null) : null,
+ }
+}
+
function getOfflineDateClauses(dateFilter: OfflineDateFilter): { dateFromClause: string; dateToClause: string } {
- const parsedDateFrom = dateFilter.dateFrom ? dateStringToDayJs(dateFilter.dateFrom) : null
- const parsedDateTo = dateFilter.dateTo ? dateStringToDayJs(dateFilter.dateTo) : null
+ const { dateFrom, dateTo } = parseOfflineDateFilter(dateFilter)
return {
- dateFromClause: parsedDateFrom
- ? `AND timestamp >= parseDateTimeBestEffort('${parsedDateFrom.toISOString()}')`
- : '',
- dateToClause: parsedDateTo ? `AND timestamp <= parseDateTimeBestEffort('${parsedDateTo.toISOString()}')` : '',
+ dateFromClause: dateFrom ? `AND timestamp >= parseDateTimeBestEffort('${dateFrom}')` : '',
+ dateToClause: dateTo ? `AND timestamp <= parseDateTimeBestEffort('${dateTo}')` : '',
}
}
@@ -254,6 +263,8 @@ export function mapOfflineExperimentItems(rows: RawOfflineExperimentMetricRow[])
const output = asString(row[15])
const expected = asString(row[16])
const rowLastSeenAt = asString(row[17])
+ const targetId = asString(row[18])
+ const targetType = asString(row[19])
const existing = itemsById.get(itemId)
const currentItem: OfflineExperimentItem = existing
@@ -303,6 +314,8 @@ export function mapOfflineExperimentItems(rows: RawOfflineExperimentMetricRow[])
resultType: asString(row[9]),
reasoning: asString(row[10]),
traceId,
+ targetId,
+ targetType,
}
}
@@ -434,42 +447,15 @@ export const offlineEvaluationsLogic = kea<offlineEvaluationsLogicType>([
return getEmptyOfflineExperimentData()
}
- const { dateFromClause, dateToClause } = getOfflineDateClauses(values.offlineDateFilter)
-
try {
- const response = await api.queryHogQL(
- hogql`
- SELECT
- ${hogql.raw(EXPERIMENT_ITEM_ID_EXPRESSION)} as item_id,
- argMax(properties.$ai_experiment_item_name, timestamp) as experiment_item_name,
- argMax(properties.$ai_experiment_name, timestamp) as experiment_name,
- ${hogql.raw(METRIC_NAME_EXPRESSION)} as metric_name,
- ${hogql.raw(METRIC_VERSION_EXPRESSION)} as metric_version,
- argMax(properties.$ai_status, timestamp) as status,
- argMax(properties.$ai_score, timestamp) as score,
- argMax(properties.$ai_score_min, timestamp) as score_min,
- argMax(properties.$ai_score_max, timestamp) as score_max,
- argMax(properties.$ai_result_type, timestamp) as result_type,
- argMax(properties.$ai_reasoning, timestamp) as reasoning,
- argMax(properties.$ai_trace_id, timestamp) as trace_id,
- argMax(properties.$ai_dataset_id, timestamp) as dataset_id,
- argMax(properties.$ai_dataset_item_id, timestamp) as dataset_item_id,
- argMax(properties.$ai_input, timestamp) as ai_input,
- argMax(properties.$ai_output, timestamp) as ai_output,
- argMax(properties.$ai_expected, timestamp) as ai_expected,
- max(timestamp) as last_seen_at
- FROM events
- WHERE
- event = '$ai_evaluation'
- AND properties.$ai_experiment_id = ${selectedExperimentId}
- AND ${hogql.raw(EXPERIMENT_ITEM_ID_EXPRESSION)} IS NOT NULL
- ${hogql.raw(dateFromClause)}
- ${hogql.raw(dateToClause)}
- GROUP BY item_id, metric_name, metric_version
- ORDER BY last_seen_at DESC
- LIMIT ${OFFLINE_EXPERIMENT_ITEMS_LIMIT}
- `,
- { productKey: 'llm_analytics', scene: 'LLMAnalyticsEvaluations' }
+ const { dateFrom, dateTo } = parseOfflineDateFilter(values.offlineDateFilter)
+ const response = await llmAnalyticsOfflineEvaluationsExperimentItemsCreate(
+ String(getCurrentTeamId()),
+ {
+ experiment_id: selectedExperimentId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ }
)
return mapOfflineExperimentItems((response.results || []) as RawOfflineExperimentMetricRow[])
diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.ts
index 351bff59e067..c947469cc298 100644
--- a/products/llm_analytics/frontend/generated/api.schemas.ts
+++ b/products/llm_analytics/frontend/generated/api.schemas.ts
@@ -868,6 +868,26 @@ export interface LLMModelsListResponseApi {
models: LLMModelInfoApi[]
}
+export interface OfflineExperimentItemsRequestApi {
+ /** `$ai_experiment_id` whose offline-evaluation items to return. */
+ experiment_id: string
+ /**
+ * Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.
+ * @nullable
+ */
+ date_from?: string | null
+ /**
+ * Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.
+ * @nullable
+ */
+ date_to?: string | null
+}
+
+export interface OfflineExperimentItemsResponseApi {
+ /** Tuple-positional rows; positions match `RawOfflineExperimentMetricRow` in the frontend. */
+ results: unknown[][]
+}
+
export interface PaginatedLLMProviderKeyListApi {
count: number
/** @nullable */
@@ -2277,6 +2297,10 @@ export const LlmAnalyticsModelsRetrieveProvider = {
TogetherAi: 'together_ai',
} as const
+export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate400 = { [key: string]: unknown }
+
+export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate500 = { [key: string]: unknown }
+
export type LlmAnalyticsProviderKeyValidationsCreate200 = { [key: string]: unknown }
export type LlmAnalyticsProviderKeysListParams = {
diff --git a/products/llm_analytics/frontend/generated/api.ts b/products/llm_analytics/frontend/generated/api.ts
index f33981096354..bcc5ff38874d 100644
--- a/products/llm_analytics/frontend/generated/api.ts
+++ b/products/llm_analytics/frontend/generated/api.ts
@@ -60,6 +60,8 @@ import type {
LlmSkillsNameFilesRetrieveParams,
LlmSkillsNameRetrieveParams,
LlmSkillsResolveNameRetrieveParams,
+ OfflineExperimentItemsRequestApi,
+ OfflineExperimentItemsResponseApi,
PaginatedClusteringJobListApi,
PaginatedDatasetItemListApi,
PaginatedDatasetListApi,
@@ -757,6 +759,26 @@ export const llmAnalyticsModelsRetrieve = async (
})
}
+export const getLlmAnalyticsOfflineEvaluationsExperimentItemsCreateUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/llm_analytics/offline_evaluations/experiment_items/`
+}
+
+export const llmAnalyticsOfflineEvaluationsExperimentItemsCreate = async (
+ projectId: string,
+ offlineExperimentItemsRequestApi: OfflineExperimentItemsRequestApi,
+ options?: RequestInit
+): Promise<OfflineExperimentItemsResponseApi> => {
+ return apiMutator<OfflineExperimentItemsResponseApi>(
+ getLlmAnalyticsOfflineEvaluationsExperimentItemsCreateUrl(projectId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(offlineExperimentItemsRequestApi),
+ }
+ )
+}
+
/**
* Validate LLM provider API keys without persisting them
*/
diff --git a/products/llm_analytics/frontend/generated/api.zod.ts b/products/llm_analytics/frontend/generated/api.zod.ts
index 23541a85b81d..26b5337d883c 100644
--- a/products/llm_analytics/frontend/generated/api.zod.ts
+++ b/products/llm_analytics/frontend/generated/api.zod.ts
@@ -769,6 +769,18 @@ export const LlmAnalyticsEvaluationSummaryCreateBody = /* @__PURE__ */ zod
})
.describe('Request serializer for evaluation summary - accepts IDs only, fetches data server-side.')
+export const LlmAnalyticsOfflineEvaluationsExperimentItemsCreateBody = /* @__PURE__ */ zod.object({
+ experiment_id: zod.string().describe('`$ai_experiment_id` whose offline-evaluation items to return.'),
+ date_from: zod
+ .string()
+ .nullish()
+ .describe('Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.'),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe('Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.'),
+})
+
export const llmAnalyticsProviderKeysCreateBodyNameMax = 255
export const llmAnalyticsProviderKeysCreateBodyApiVersionMax = 20
diff --git a/products/llm_analytics/mcp/tools.yaml b/products/llm_analytics/mcp/tools.yaml
index 41041c01fff8..9663fd7497a4 100644
--- a/products/llm_analytics/mcp/tools.yaml
+++ b/products/llm_analytics/mcp/tools.yaml
@@ -14,6 +14,9 @@ ui_apps:
data_type: LLMCostsData
view_component: LLMCostsView
tools:
+ llm-analytics-offline-evaluations-experiment-items-create:
+ operation: llm_analytics_offline_evaluations_experiment_items_create
+ enabled: false
llm-analytics-sentiment-generations-create:
operation: llm_analytics_sentiment_generations_create
enabled: false
diff --git a/products/signals/eval/capture.py b/products/signals/eval/capture.py
index 3dff0e3758c0..dab7efd97b53 100644
--- a/products/signals/eval/capture.py
+++ b/products/signals/eval/capture.py
@@ -55,6 +55,7 @@ def capture_evaluation(
"$ai_evaluation_result": 1.0 if passed else 0.0,
"$ai_status": metric.status,
"$ai_dataset_id": dataset_id,
+ "$ai_trace_id": str(uuid.uuid4()),
}
if metric.description:
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 764b95345d11..433a6dfdb19b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -23546,6 +23546,26 @@ export namespace Schemas {
event_definition_id?: string | null;
}
+ export interface OfflineExperimentItemsRequest {
+ /** `$ai_experiment_id` whose offline-evaluation items to return. */
+ experiment_id: string;
+ /**
+ * Lower bound on `timestamp` (ISO-8601). Omit to leave the lower bound open.
+ * @nullable
+ */
+ date_from?: string | null;
+ /**
+ * Upper bound on `timestamp` (ISO-8601). Omit to leave the upper bound open.
+ * @nullable
+ */
+ date_to?: string | null;
+ }
+
+ export interface OfflineExperimentItemsResponse {
+ /** Tuple-positional rows; positions match `RawOfflineExperimentMetricRow` in the frontend. */
+ results: unknown[][];
+ }
+
/**
* * `later` - Later
* `other` - Other
@@ -42338,6 +42358,10 @@ export namespace Schemas {
TogetherAi: 'together_ai',
} as const;
+ export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate400 = { [key: string]: unknown };
+
+ export type LlmAnalyticsOfflineEvaluationsExperimentItemsCreate500 = { [key: string]: unknown };
+
export type LlmAnalyticsProviderKeyValidationsCreate200 = { [key: string]: unknown };
export type LlmAnalyticsProviderKeysListParams = {