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): show eval reports in self-driving (#81479)

Radu Raiceaa16b05e1b255
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 93acd16128e3..497548dead4d 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -47,6 +47,7 @@ const ERROR_FILTER_ALLOW_LIST = [
'loadDatasetItemDetails', // Dataset item modals render their own retry state
'loadDatasetItemVersions', // Dataset item modals render their own retry state
'exportDataset', // Dataset scenes render their own retry state
+ 'loadSelfDrivingEvaluationReports', // The self-driving eval table renders its own retry state
'loadToolDataEvents',
'loadPrChecks', // Polled in the Inbox report detail; the CI checks section renders its own error state
'loadPrComments', // The Inbox report detail's PR comments section renders its own error state
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index 39a7aa8e1e89..1c25ed9f0339 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -4,7 +4,7 @@ import datetime as dt
from typing import Any, cast
from django.conf import settings
-from django.db.models import QuerySet
+from django.db.models import Count, Max, QuerySet
from django.utils import timezone
import structlog
@@ -78,6 +78,31 @@ def validate_report_schedule_rrule(rrule_string: str) -> None:
class EvaluationReportSerializer(serializers.ModelSerializer):
+ generated_report_count = serializers.SerializerMethodField(
+ help_text="Number of reports generated from this evaluation report config.",
+ )
+ last_generated_at = serializers.SerializerMethodField(
+ help_text="When the most recent report was generated, or null if no reports have been generated.",
+ )
+
+ @extend_schema_field(
+ serializers.IntegerField(help_text="Number of reports generated from this evaluation report config.")
+ )
+ def get_generated_report_count(self, report: EvaluationReport) -> int:
+ annotated_count = getattr(report, "generated_report_count", None)
+ return annotated_count if isinstance(annotated_count, int) else report.runs.count()
+
+ @extend_schema_field(
+ serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the most recent report was generated, or null if no reports have been generated.",
+ )
+ )
+ def get_last_generated_at(self, report: EvaluationReport) -> dt.datetime | None:
+ if "last_generated_at" in report.__dict__:
+ return cast(dt.datetime | None, report.__dict__["last_generated_at"])
+ return report.runs.values_list("created_at", flat=True).first()
+
class Meta:
model = EvaluationReport
fields = [
@@ -93,6 +118,8 @@ class EvaluationReportSerializer(serializers.ModelSerializer):
"enabled",
"deleted",
"last_delivered_at",
+ "generated_report_count",
+ "last_generated_at",
"report_prompt_guidance",
"trigger_threshold",
"cooldown_minutes",
@@ -562,7 +589,12 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse
def safely_get_queryset(self, queryset: QuerySet[EvaluationReport]) -> QuerySet[EvaluationReport]:
report_queryset = cast(
EvaluationReportQuerySet,
- queryset.filter(team_id=self.team_id).order_by("-created_at"),
+ queryset.filter(team_id=self.team_id)
+ .annotate(
+ generated_report_count=Count("runs"),
+ last_generated_at=Max("runs__created_at"),
+ )
+ .order_by("-created_at"),
)
# Generate validates eligibility explicitly so unsupported legacy rows return a useful 400.
if self.action != "generate":
diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.py
index c2737e5f2325..e94e60a00d93 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py
@@ -262,8 +262,25 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_list_reports(self):
- self._create_report(rrule="FREQ=DAILY", timezone_name="UTC")
- self._create_report(evaluation=self._create_boolean_evaluation())
+ report_with_runs = self._create_report(rrule="FREQ=DAILY", timezone_name="UTC")
+ report_without_runs = self._create_report(evaluation=self._create_boolean_evaluation())
+ with freeze_time("2026-08-10T12:00:00Z"):
+ EvaluationReportRun.objects.create(
+ report=report_with_runs,
+ content={},
+ metadata={},
+ period_start=timezone.now() - dt.timedelta(hours=1),
+ period_end=timezone.now(),
+ )
+ with freeze_time("2026-08-11T12:00:00Z"):
+ EvaluationReportRun.objects.create(
+ report=report_with_runs,
+ content={},
+ metadata={},
+ period_start=timezone.now() - dt.timedelta(hours=1),
+ period_end=timezone.now(),
+ )
+
response = self.client.get(self.base_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
results = response.json()["results"]
@@ -273,6 +290,12 @@ class TestEvaluationReportApi(APIBaseTest):
for field in ("delivery_targets", "rrule", "starts_at", "timezone_name", "report_prompt_guidance"):
self.assertIn(field, first)
+ results_by_id = {result["id"]: result for result in results}
+ self.assertEqual(results_by_id[str(report_with_runs.id)]["generated_report_count"], 2)
+ self.assertEqual(results_by_id[str(report_with_runs.id)]["last_generated_at"], "2026-08-11T12:00:00Z")
+ self.assertEqual(results_by_id[str(report_without_runs.id)]["generated_report_count"], 0)
+ self.assertIsNone(results_by_id[str(report_without_runs.id)]["last_generated_at"])
+
def test_list_filters_by_evaluation(self) -> None:
report = self._create_report()
self._create_report(evaluation=self._create_boolean_evaluation())
diff --git a/products/ai_observability/frontend/evaluations/evaluationNavigation.ts b/products/ai_observability/frontend/evaluations/evaluationNavigation.ts
index a1aee4521847..0c97f63e32d9 100644
--- a/products/ai_observability/frontend/evaluations/evaluationNavigation.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationNavigation.ts
@@ -10,7 +10,13 @@ export interface EvaluationBackTarget {
}
function searchParamsWithoutEvaluationSource(searchParams: Record<string, any>): Record<string, any> {
- const { returnTo: _returnTo, template: _template, type: _type, ...remainingSearchParams } = searchParams
+ const {
+ evaluation_tab: _evaluationTab,
+ returnTo: _returnTo,
+ template: _template,
+ type: _type,
+ ...remainingSearchParams
+ } = searchParams
return remainingSearchParams
}
diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
index bd300b25322d..e981ee28140d 100644
--- a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
@@ -1,10 +1,11 @@
-import { evaluationsList } from '../generated/api'
-import type { EvaluationApi } from '../generated/api.schemas'
-import { listAllEvaluations } from './evaluationsApi'
+import { evaluationsList, llmAnalyticsEvaluationReportsList } from '../generated/api'
+import type { EvaluationApi, EvaluationReportApi } from '../generated/api.schemas'
+import { listAllEvaluationReports, listAllEvaluations } from './evaluationsApi'
jest.mock('../generated/api', () => ({
evaluationsList: jest.fn(),
evaluationsPartialUpdate: jest.fn(),
+ llmAnalyticsEvaluationReportsList: jest.fn(),
}))
const evaluationApi = (id: string): EvaluationApi => ({
@@ -39,9 +40,33 @@ const evaluationApi = (id: string): EvaluationApi => ({
deleted: false,
})
+const evaluationReportApi = (id: string, evaluation: string): EvaluationReportApi => ({
+ id,
+ evaluation,
+ frequency: 'scheduled',
+ rrule: 'FREQ=DAILY',
+ starts_at: '2024-01-01T00:00:00Z',
+ timezone_name: 'UTC',
+ next_delivery_date: '2024-01-02T00:00:00Z',
+ delivery_targets: [],
+ max_sample_size: 200,
+ enabled: true,
+ deleted: false,
+ last_delivered_at: null,
+ generated_report_count: 0,
+ last_generated_at: null,
+ report_prompt_guidance: '',
+ trigger_threshold: null,
+ cooldown_minutes: 60,
+ daily_run_cap: 10,
+ created_by: null,
+ created_at: '2024-01-01T00:00:00Z',
+})
+
describe('evaluationsApi', () => {
beforeEach(() => {
jest.mocked(evaluationsList).mockReset()
+ jest.mocked(llmAnalyticsEvaluationReportsList).mockReset()
})
it('loads every evaluations page', async () => {
@@ -66,4 +91,27 @@ describe('evaluationsApi', () => {
expect(evaluationsList).toHaveBeenNthCalledWith(1, '1', { limit: 100, offset: 0 })
expect(evaluationsList).toHaveBeenNthCalledWith(2, '1', { limit: 100, offset: 1 })
})
+
+ it('loads every evaluation report page', async () => {
+ jest.mocked(llmAnalyticsEvaluationReportsList)
+ .mockResolvedValueOnce({
+ count: 2,
+ next: '/api/projects/1/llm_analytics/evaluation_reports/?limit=100&offset=1',
+ previous: null,
+ results: [evaluationReportApi('report-1', 'evaluation-1')],
+ })
+ .mockResolvedValueOnce({
+ count: 2,
+ next: null,
+ previous: '/api/projects/1/llm_analytics/evaluation_reports/?limit=100',
+ results: [evaluationReportApi('report-2', 'evaluation-2')],
+ })
+
+ await expect(listAllEvaluationReports('1')).resolves.toEqual([
+ expect.objectContaining({ id: 'report-1', evaluation: 'evaluation-1' }),
+ expect.objectContaining({ id: 'report-2', evaluation: 'evaluation-2' }),
+ ])
+ expect(llmAnalyticsEvaluationReportsList).toHaveBeenNthCalledWith(1, '1', { limit: 100, offset: 0 })
+ expect(llmAnalyticsEvaluationReportsList).toHaveBeenNthCalledWith(2, '1', { limit: 100, offset: 1 })
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.ts
index cbcf59f21c80..e57d898ad301 100644
--- a/products/ai_observability/frontend/evaluations/evaluationsApi.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.ts
@@ -1,10 +1,11 @@
import type { AnyPropertyFilter } from '~/types'
-import { evaluationsList, evaluationsPartialUpdate } from '../generated/api'
-import type { EvaluationApi, PatchedEvaluationApi } from '../generated/api.schemas'
+import { evaluationsList, evaluationsPartialUpdate, llmAnalyticsEvaluationReportsList } from '../generated/api'
+import type { EvaluationApi, EvaluationReportApi, PatchedEvaluationApi } from '../generated/api.schemas'
import type { EvaluationConfig, ModelConfiguration } from './types'
const EVALUATIONS_PAGE_SIZE = 100
+const EVALUATION_REPORTS_PAGE_SIZE = 100
function isPropertyFilter(value: unknown): value is AnyPropertyFilter {
return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -116,6 +117,24 @@ export async function listAllEvaluations(projectId: string): Promise<EvaluationC
}
}
+export async function listAllEvaluationReports(projectId: string): Promise<EvaluationReportApi[]> {
+ const reports: EvaluationReportApi[] = []
+ let offset = 0
+
+ while (true) {
+ const response = await llmAnalyticsEvaluationReportsList(projectId, {
+ limit: EVALUATION_REPORTS_PAGE_SIZE,
+ offset,
+ })
+ reports.push(...response.results)
+
+ if (!response.next || response.results.length === 0) {
+ return reports
+ }
+ offset += response.results.length
+ }
+}
+
export async function patchEvaluation(
projectId: string,
evaluationId: string,
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index c94f12815bd7..babc0d061907 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -1,6 +1,8 @@
-import { router } from 'kea-router'
+import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { urls } from 'scenes/urls'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -723,6 +725,26 @@ return result`,
})
})
+ describe('routing', () => {
+ it('opens a direct configuration link and keeps tab changes in the URL', async () => {
+ router.actions.push(
+ combineUrl(urls.aiObservabilityEvaluation('eval-123'), {
+ evaluation_tab: 'configuration',
+ }).url
+ )
+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess']).toMatchValues({
+ activeTab: 'configuration',
+ })
+
+ logic.actions.setActiveTab('runs')
+
+ expect(router.values.searchParams.evaluation_tab).toBeUndefined()
+ })
+ })
+
describe('async flows', () => {
describe('loadEvaluation', () => {
it('initializes new evaluation with default values', async () => {
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 7dd545897a44..bbc86413158f 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -1,11 +1,12 @@
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { router, urlToAction } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
import { MaxContextInput, createMaxContextHelpers } from '~/scenes/max/maxTypes'
import { Breadcrumb } from '~/types'
@@ -63,6 +64,11 @@ export const DEFAULT_SESSION_QUIET_PERIOD_SECONDS = 60 * 60
export const DEFAULT_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60
const AGGREGATE_TARGETS: EvaluationTarget[] = ['trace', 'session']
+const EVALUATION_DETAIL_TABS = new Set(['configuration', 'reports', 'runs'])
+
+function evaluationDetailTab(value: unknown): string | null {
+ return typeof value === 'string' && EVALUATION_DETAIL_TABS.has(value) ? value : null
+}
function seedSettleConfig(target: EvaluationTarget, strategy: EvaluationSettleStrategy): EvaluationTargetConfig {
if (!AGGREGATE_TARGETS.includes(target)) {
@@ -312,6 +318,7 @@ export interface llmEvaluationLogicActions {
}
loadEvaluationSuccess: (evaluation: EvaluationConfig | null) => {
evaluation: EvaluationConfig | null
+ requestedTab: string | null
}
loadRunsStats: () => any
loadRunsStatsFailure: (
@@ -523,7 +530,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
saveEvaluationSuccess: (evaluation: EvaluationConfig) => ({ evaluation }),
saveEvaluationFailure: (error: string) => ({ error }),
loadEvaluation: true,
- loadEvaluationSuccess: (evaluation: EvaluationConfig | null) => ({ evaluation }),
+ loadEvaluationSuccess: (evaluation: EvaluationConfig | null) => ({
+ evaluation,
+ requestedTab: evaluationDetailTab(router.values.searchParams.evaluation_tab),
+ }),
resetEvaluation: true,
// Evaluation runs actions
@@ -870,7 +880,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
{
setActiveTab: (_, { tab }) => tab,
// Show runs tab for existing evaluations, configuration for new
- loadEvaluationSuccess: (_, { evaluation }) => (evaluation?.id ? 'runs' : 'configuration'),
+ loadEvaluationSuccess: (_, { evaluation, requestedTab }) =>
+ requestedTab ?? (evaluation?.id ? 'runs' : 'configuration'),
},
],
}),
@@ -1343,8 +1354,14 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
],
}),
- urlToAction(({ actions, props }) => ({
- '/ai-evals/evaluations/:id': ({ id }, _, __, { method }) => {
+ urlToAction(({ actions, props, values }) => ({
+ [urls.aiObservabilityEvaluation(':id')]: ({ id }, searchParams, __, { method }) => {
+ const requestedTab =
+ evaluationDetailTab(searchParams.evaluation_tab) ?? (id === 'new' ? 'configuration' : 'runs')
+ if (requestedTab !== values.activeTab) {
+ actions.setActiveTab(requestedTab)
+ }
+
// Only reload when navigating to a different evaluation, not on search param changes (e.g., pagination)
const newEvaluationId = id && id !== 'new' ? id : 'new'
if (method === 'PUSH' && newEvaluationId !== props.evaluationId) {
@@ -1356,6 +1373,23 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
},
})),
+ actionToUrl(({ props }) => ({
+ setActiveTab: ({ tab }) => {
+ const defaultTab = props.evaluationId === 'new' ? 'configuration' : 'runs'
+ const evaluationTab = tab === defaultTab ? undefined : tab
+ if (router.values.searchParams.evaluation_tab === evaluationTab) {
+ return
+ }
+
+ return [
+ router.values.location.pathname,
+ { ...router.values.searchParams, evaluation_tab: evaluationTab },
+ router.values.hashParams,
+ { replace: true },
+ ]
+ },
+ })),
+
afterMount(({ actions, props }) => {
actions.loadProviderKeys()
actions.loadEvaluation()
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
index a847741681ab..8af4d5043c83 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
@@ -65,6 +65,7 @@ export interface llmEvaluationsLogicValues {
evaluationDirectoriesLoading: boolean
evaluations: EvaluationConfig[]
evaluationsFilter: string
+ evaluationsLoadFailed: boolean
evaluationsLoading: boolean
filteredEvaluations: EvaluationConfig[]
movingEvaluationId: string | null
@@ -118,6 +119,9 @@ export interface llmEvaluationsLogicActions {
loadEvaluations: () => {
value: true
}
+ loadEvaluationsFailure: () => {
+ value: true
+ }
loadEvaluationsSuccess: (evaluations: EvaluationConfig[]) => {
evaluations: EvaluationConfig[]
}
@@ -247,6 +251,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
actions({
setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
loadEvaluations: true,
+ loadEvaluationsFailure: true,
loadEvaluationsSuccess: (evaluations: EvaluationConfig[]) => ({ evaluations }),
deleteEvaluation: (id: string) => ({ id }),
deleteEvaluationSuccess: (id: string) => ({ id }),
@@ -320,6 +325,15 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
false,
{
loadEvaluations: () => true,
+ loadEvaluationsFailure: () => false,
+ loadEvaluationsSuccess: () => false,
+ },
+ ],
+ evaluationsLoadFailed: [
+ false,
+ {
+ loadEvaluations: () => false,
+ loadEvaluationsFailure: () => true,
loadEvaluationsSuccess: () => false,
},
],
@@ -408,7 +422,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
actions.loadEvaluationsSuccess(await listAllEvaluations(teamId.toString()))
} catch (error) {
console.error('Failed to load evaluations:', error)
- actions.loadEvaluationsSuccess([])
+ actions.loadEvaluationsFailure()
}
},
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 4adfea0a3bf0..230540ecc169 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1442,6 +1442,13 @@ export interface EvaluationReportApi {
readonly deleted: boolean
/** @nullable */
readonly last_delivered_at: string | null
+ /** Number of reports generated from this evaluation report config. */
+ readonly generated_report_count: number
+ /**
+ * When the most recent report was generated, or null if no reports have been generated.
+ * @nullable
+ */
+ readonly last_generated_at: string | null
/** Optional custom instructions appended to the AI report prompt to steer focus, scope, or section choices without modifying the base prompt. */
report_prompt_guidance?: string
/**
@@ -1511,6 +1518,13 @@ export interface EvaluationReportUpdateApi {
readonly deleted: boolean
/** @nullable */
readonly last_delivered_at: string | null
+ /** Number of reports generated from this evaluation report config. */
+ readonly generated_report_count: number
+ /**
+ * When the most recent report was generated, or null if no reports have been generated.
+ * @nullable
+ */
+ readonly last_generated_at: string | null
/** Optional custom instructions appended to the AI report prompt to steer focus, scope, or section choices without modifying the base prompt. */
report_prompt_guidance?: string
/**
@@ -1571,6 +1585,13 @@ export interface PatchedEvaluationReportUpdateApi {
readonly deleted?: boolean
/** @nullable */
readonly last_delivered_at?: string | null
+ /** Number of reports generated from this evaluation report config. */
+ readonly generated_report_count?: number
+ /**
+ * When the most recent report was generated, or null if no reports have been generated.
+ * @nullable
+ */
+ readonly last_generated_at?: string | null
/** Optional custom instructions appended to the AI report prompt to steer focus, scope, or section choices without modifying the base prompt. */
report_prompt_guidance?: string
/**
diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx
index 0f40d16e7d30..2c0ff9c2c8a8 100644
--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx
+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.test.tsx
@@ -3,12 +3,24 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
+import { router } from 'kea-router'
import type { ReactNode } from 'react'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import * as aiObservabilityApi from '../generated/api'
import { AIObservabilitySelfDriving } from './AIObservabilitySelfDriving'
+jest.mock('../generated/api', () => ({
+ evaluationDirectoriesList: jest.fn(),
+ evaluationsList: jest.fn(),
+ llmAnalyticsEvaluationReportsList: jest.fn(),
+}))
+
jest.mock('products/signals/frontend/generated/api', () => ({
signalsScoutConfigList: jest.fn(() => new Promise(() => {})),
signalsScoutMetadataGet: jest.fn(() => new Promise(() => {})),
@@ -20,14 +32,105 @@ jest.mock('products/signals/frontend/inbox/components/config/scouts/ScoutCreateB
describe('AIObservabilitySelfDriving', () => {
beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },
+ '/api/environments/:teamId/llm_analytics/evaluation_config/': {
+ active_provider_key: null,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ },
+ },
+ })
initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_START_WITH_AI], {
+ [FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_START_WITH_AI]: true,
+ })
+ jest.mocked(aiObservabilityApi.evaluationDirectoriesList).mockResolvedValue([])
+ jest.mocked(aiObservabilityApi.evaluationsList).mockResolvedValue({
+ count: 2,
+ next: null,
+ previous: null,
+ results: [
+ {
+ id: 'evaluation-enabled',
+ name: 'Correctness check',
+ description: 'Checks whether answers are correct.',
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: 'Is the answer correct?' },
+ output_type: 'boolean',
+ output_config: {},
+ conditions: [],
+ target: 'generation',
+ model_configuration: null,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ created_by: null,
+ deleted: false,
+ },
+ {
+ id: 'evaluation-disabled',
+ name: 'Tone check',
+ description: 'Checks the tone of each answer.',
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'hog',
+ evaluation_config: { source: 'return true' },
+ output_type: 'boolean',
+ output_config: {},
+ conditions: [],
+ target: 'generation',
+ model_configuration: null,
+ created_at: '2024-01-02T00:00:00Z',
+ updated_at: '2024-01-02T00:00:00Z',
+ created_by: null,
+ deleted: false,
+ },
+ ],
+ })
+ jest.mocked(aiObservabilityApi.llmAnalyticsEvaluationReportsList).mockResolvedValue({
+ count: 1,
+ next: null,
+ previous: null,
+ results: [
+ {
+ id: 'report-enabled',
+ evaluation: 'evaluation-enabled',
+ frequency: 'scheduled',
+ rrule: 'FREQ=DAILY',
+ starts_at: '2024-01-01T00:00:00Z',
+ timezone_name: 'UTC',
+ next_delivery_date: '2024-01-02T00:00:00Z',
+ delivery_targets: [],
+ max_sample_size: 200,
+ enabled: true,
+ deleted: false,
+ last_delivered_at: null,
+ generated_report_count: 4,
+ last_generated_at: '2024-01-03T00:00:00Z',
+ report_prompt_guidance: '',
+ trigger_threshold: null,
+ cooldown_minutes: 60,
+ daily_run_cap: 10,
+ created_by: null,
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ],
+ })
})
afterEach(() => {
cleanup()
})
- it('renders scout templates and links to the self-driving docs', async () => {
+ it('renders scout templates and evaluation report status', async () => {
render(
<Provider>
<AIObservabilitySelfDriving />
@@ -47,5 +150,84 @@ describe('AIObservabilitySelfDriving', () => {
expect(screen.getByText('ai-observability').closest('p')).toHaveTextContent(
'Add the ai-observability label to a scout for it to appear here.'
)
+
+ expect(await screen.findByText('Correctness check')).toBeInTheDocument()
+ expect(screen.getByText('Tone check')).toBeInTheDocument()
+ expect(screen.getByText('Enabled')).toBeInTheDocument()
+ expect(screen.getByText('Disabled')).toBeInTheDocument()
+ expect(
+ screen.getByText(/Signals from evals are only generated if eval reports are enabled/)
+ ).toBeInTheDocument()
+ expect(screen.getByText('Reports generated')).toBeInTheDocument()
+ expect(screen.getByText('Last generated')).toBeInTheDocument()
+ expect(screen.getByText('4')).toBeInTheDocument()
+ expect(screen.getAllByText('Never')).toHaveLength(1)
+
+ const evalReportsDocsLink = screen.getByText('Learn more').closest('a')
+ expect(evalReportsDocsLink).toHaveAttribute(
+ 'href',
+ 'https://posthog.com/docs/ai-observability/self-driving#eval-reports'
+ )
+ expect(evalReportsDocsLink).toHaveAttribute('target', '_blank')
+
+ const editLinks = screen.getAllByText('Edit').map((button) => button.closest('a'))
+ expect(editLinks[0]).toHaveAttribute(
+ 'href',
+ '/project/997/ai-evals/evaluations/evaluation-enabled?evaluation_tab=configuration'
+ )
+ expect(editLinks[1]).toHaveAttribute(
+ 'href',
+ '/project/997/ai-evals/evaluations/evaluation-disabled?evaluation_tab=configuration'
+ )
+
+ await userEvent.click(screen.getByText('Correctness check'))
+ expect(router.values.location.pathname).toBe('/project/997/ai-evals/evaluations/evaluation-enabled')
+ expect(router.values.searchParams).toEqual(expect.objectContaining({ evaluation_tab: 'configuration' }))
+ })
+
+ it('guides users without evals to templates or their agent', async () => {
+ jest.mocked(aiObservabilityApi.evaluationsList).mockResolvedValue({
+ count: 0,
+ next: null,
+ previous: null,
+ results: [],
+ })
+
+ render(
+ <Provider>
+ <AIObservabilitySelfDriving />
+ </Provider>
+ )
+
+ expect(await screen.findByText("You don't have any evals yet")).toBeInTheDocument()
+ const createEvalButton = screen.getByText('Create an eval')
+ expect(createEvalButton.closest('a')).toHaveAttribute('href', '/project/997/ai-evals/evaluations')
+ expect(screen.getByText(/Use the connected PostHog MCP server/)).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="ai-observability-evaluations-table"]')).not.toBeInTheDocument()
+ })
+
+ it('shows a retry instead of the empty state when evals fail to load', async () => {
+ const consoleError = jest.spyOn(console, 'error').mockImplementation()
+ jest.mocked(aiObservabilityApi.evaluationsList).mockRejectedValueOnce(new Error('Request failed'))
+
+ render(
+ <Provider>
+ <AIObservabilitySelfDriving />
+ </Provider>
+ )
+
+ const errorMessage = await screen.findByText("We couldn't load your evals. Try again in a moment.")
+ expect(errorMessage).toBeInTheDocument()
+ expect(screen.queryByText("You don't have any evals yet")).not.toBeInTheDocument()
+
+ const errorBanner = errorMessage.closest('.LemonBanner')
+ expect(errorBanner).toBeInTheDocument()
+ const retryButton = errorBanner?.querySelector('button')
+ expect(retryButton).toBeInTheDocument()
+ await userEvent.click(retryButton as HTMLButtonElement)
+
+ expect(await screen.findByText('Correctness check')).toBeInTheDocument()
+ expect(aiObservabilityApi.evaluationsList).toHaveBeenCalledTimes(2)
+ consoleError.mockRestore()
})
})
diff --git a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx
index f81c1efdacba..d5be37f4dd5e 100644
--- a/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx
+++ b/products/ai_observability/frontend/selfDriving/AIObservabilitySelfDriving.tsx
@@ -1,19 +1,38 @@
import { useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
import { IconCalendar, IconQuestion, IconUser, IconWarning } from '@posthog/icons'
-import { LemonBanner, LemonCard, LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { MCPUseCaseCard } from 'lib/components/MCPHint/MCPUseCaseCard'
+import { TZLabel } from 'lib/components/TZLabel'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { Link } from 'lib/lemon-ui/Link'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { urls } from 'scenes/urls'
import { ScoutCreateButton } from 'products/signals/frontend/inbox/components/config/scouts/ScoutCreateButton'
import { ScoutRowCard } from 'products/signals/frontend/inbox/components/config/scouts/ScoutRowCard'
import { scoutFleetLogic } from 'products/signals/frontend/inbox/logics/scoutFleetLogic'
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
+import type { EvaluationConfig } from '../evaluations/types'
import {
AI_OBSERVABILITY_SCOUT_TEMPLATES,
AIObservabilityScoutTemplate,
isAIObservabilityScout,
} from './aiObservabilityScoutTemplates'
+import { aiObservabilitySelfDrivingLogic } from './aiObservabilitySelfDrivingLogic'
const SCOUTS_DOCS_URL = 'https://posthog.com/docs/ai-observability/self-driving'
+const EVAL_REPORTS_DOCS_URL = `${SCOUTS_DOCS_URL}#eval-reports`
+
+function evaluationEditUrl(evaluationId: string): string {
+ return combineUrl(urls.aiObservabilityEvaluation(evaluationId), {
+ evaluation_tab: 'configuration',
+ }).url
+}
const TEMPLATE_ICONS: Record<AIObservabilityScoutTemplate['key'], JSX.Element> = {
'daily-digest': <IconCalendar />,
@@ -50,10 +69,65 @@ function ScoutTemplateCard({ template }: { template: AIObservabilityScoutTemplat
}
export function AIObservabilitySelfDriving(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
const { scoutConfigs, scoutConfigsLoading, deletingScoutIds, updatingScoutIds } = useValues(scoutFleetLogic)
const { deleteScout, loadScoutConfigs, updateScoutConfig } = useActions(scoutFleetLogic)
+ const { evaluations, evaluationsLoadFailed, evaluationsLoading } = useValues(llmEvaluationsLogic)
+ const { loadEvaluations } = useActions(llmEvaluationsLogic)
+ const { evaluationReportsByEvaluationId, evaluationReportsLoading } = useValues(aiObservabilitySelfDrivingLogic)
+ const { loadSelfDrivingEvaluationReports } = useActions(aiObservabilitySelfDrivingLogic)
const aiObservabilityScouts = scoutConfigs?.filter(isAIObservabilityScout) ?? []
+ const evaluationColumns: LemonTableColumns<EvaluationConfig> = [
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, evaluation) => (
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate font-semibold">{evaluation.name}</span>
+ <span className="min-h-4 truncate text-xs text-muted">{evaluation.description ?? ''}</span>
+ </div>
+ ),
+ },
+ {
+ title: 'Eval reports',
+ key: 'reports',
+ render: (_, evaluation) => {
+ if (evaluationReportsByEvaluationId === null) {
+ return <LemonTag type="muted">Unavailable</LemonTag>
+ }
+
+ return evaluationReportsByEvaluationId[evaluation.id]?.enabled ? (
+ <LemonTag type="success">Enabled</LemonTag>
+ ) : (
+ <LemonTag type="muted">Disabled</LemonTag>
+ )
+ },
+ },
+ {
+ title: 'Reports generated',
+ key: 'generated_report_count',
+ render: (_, evaluation) => {
+ if (evaluationReportsByEvaluationId === null) {
+ return 'Unavailable'
+ }
+
+ return evaluationReportsByEvaluationId[evaluation.id]?.generated_report_count ?? 0
+ },
+ },
+ {
+ title: 'Last generated',
+ key: 'last_generated_at',
+ render: (_, evaluation) => {
+ if (evaluationReportsByEvaluationId === null) {
+ return 'Unavailable'
+ }
+
+ const lastGeneratedAt = evaluationReportsByEvaluationId[evaluation.id]?.last_generated_at
+ return lastGeneratedAt ? <TZLabel time={lastGeneratedAt} /> : 'Never'
+ },
+ },
+ ]
let scoutsContent: JSX.Element
if (scoutConfigsLoading && scoutConfigs === null) {
@@ -143,6 +217,98 @@ export function AIObservabilitySelfDriving(): JSX.Element {
</div>
{scoutsContent}
</section>
+
+ <section className="flex flex-col gap-2">
+ <div>
+ <div className="flex items-center gap-2">
+ <h2 className="m-0 text-base font-semibold">Your evals</h2>
+ {!evaluationsLoading && !evaluationsLoadFailed ? (
+ <LemonTag type="muted" size="small">
+ {evaluations.length}
+ </LemonTag>
+ ) : null}
+ </div>
+ <p className="m-0 text-sm text-muted">
+ Signals from evals are only generated if eval reports are enabled.{' '}
+ <Link to={EVAL_REPORTS_DOCS_URL} target="_blank" targetBlankIcon>
+ Learn more
+ </Link>
+ </p>
+ </div>
+ {!evaluationsLoadFailed &&
+ !evaluationsLoading &&
+ evaluations.length > 0 &&
+ evaluationReportsByEvaluationId === null &&
+ !evaluationReportsLoading ? (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: () => loadSelfDrivingEvaluationReports() }}
+ data-attr="ai-observability-evaluation-reports-load-error"
+ >
+ We couldn't load evaluation report statuses. Try again in a moment.
+ </LemonBanner>
+ ) : null}
+ {evaluationsLoadFailed ? (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: loadEvaluations }}
+ data-attr="ai-observability-evaluations-load-error"
+ >
+ We couldn't load your evals. Try again in a moment.
+ </LemonBanner>
+ ) : evaluationsLoading ? (
+ <div className="flex flex-col gap-2">
+ <LemonSkeleton className="h-10 w-full rounded" />
+ <LemonSkeleton className="h-10 w-full rounded" />
+ </div>
+ ) : evaluations.length === 0 ? (
+ <LemonCard hoverEffect={false} className="flex w-full flex-col items-start gap-3 p-4">
+ <h3 className="m-0 text-sm font-semibold">You don't have any evals yet</h3>
+ <LemonButton
+ type="primary"
+ to={urls.aiObservabilityEvaluations()}
+ data-attr="create-ai-observability-eval"
+ >
+ Create an eval
+ </LemonButton>
+ {featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_START_WITH_AI] ? (
+ <MCPUseCaseCard
+ surfaceKey="ai_observability_evaluations.create"
+ className="!mt-1 w-full max-w-2xl"
+ />
+ ) : null}
+ </LemonCard>
+ ) : (
+ <LemonTable
+ columns={evaluationColumns}
+ dataSource={evaluations}
+ loading={evaluationReportsLoading}
+ loadingSkeletonRows={2}
+ rowKey="id"
+ nouns={['eval', 'evals']}
+ data-attr="ai-observability-evaluations-table"
+ onRow={(evaluation) => ({
+ className: 'cursor-pointer hover:bg-surface-secondary',
+ onClick: (event) => {
+ if ((event.target as HTMLElement).closest('button, a, [role="button"]')) {
+ return
+ }
+ router.actions.push(evaluationEditUrl(evaluation.id))
+ },
+ })}
+ rowActions={(evaluation) => (
+ <LemonButton
+ type="secondary"
+ size="small"
+ to={evaluationEditUrl(evaluation.id)}
+ data-attr="edit-ai-observability-evaluation"
+ >
+ Edit
+ </LemonButton>
+ )}
+ />
+ )}
+ </section>
</div>
)
}
diff --git a/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.ts b/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.ts
new file mode 100644
index 000000000000..71a888a61fc6
--- /dev/null
+++ b/products/ai_observability/frontend/selfDriving/aiObservabilitySelfDrivingLogic.ts
@@ -0,0 +1,81 @@
+import { MakeLogicType, afterMount, kea, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { listAllEvaluationReports } from '../evaluations/evaluationsApi'
+import type { EvaluationReportApi } from '../generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiObservabilitySelfDrivingLogicValues {
+ evaluationReports: EvaluationReportApi[] | null
+ evaluationReportsByEvaluationId: Record<string, EvaluationReportApi> | null
+ evaluationReportsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiObservabilitySelfDrivingLogicActions {
+ loadSelfDrivingEvaluationReports: () => any
+ loadSelfDrivingEvaluationReportsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSelfDrivingEvaluationReportsSuccess: (
+ evaluationReports: EvaluationReportApi[],
+ payload?: any
+ ) => {
+ evaluationReports: EvaluationReportApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiObservabilitySelfDrivingLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ evaluationReportsByEvaluationId: (
+ evaluationReports: EvaluationReportApi[] | null
+ ) => Record<string, EvaluationReportApi> | null
+ }
+}
+
+export type aiObservabilitySelfDrivingLogicType = MakeLogicType<
+ aiObservabilitySelfDrivingLogicValues,
+ aiObservabilitySelfDrivingLogicActions,
+ Record<string, any>,
+ aiObservabilitySelfDrivingLogicMeta
+>
+
+export const aiObservabilitySelfDrivingLogic = kea<aiObservabilitySelfDrivingLogicType>([
+ path(['products', 'ai_observability', 'selfDriving', 'aiObservabilitySelfDrivingLogic']),
+
+ loaders({
+ evaluationReports: [
+ null as EvaluationReportApi[] | null,
+ {
+ loadSelfDrivingEvaluationReports: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ return teamId ? await listAllEvaluationReports(teamId.toString()) : []
+ },
+ },
+ ],
+ }),
+
+ selectors({
+ evaluationReportsByEvaluationId: [
+ (selectors) => [selectors.evaluationReports],
+ (reports: EvaluationReportApi[] | null): Record<string, EvaluationReportApi> | null =>
+ reports
+ ? Object.fromEntries(
+ reports.filter((report) => !report.deleted).map((report) => [report.evaluation, report])
+ )
+ : null,
+ ],
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadSelfDrivingEvaluationReports()
+ }),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ffb0eb46088c..e44485d60fbb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -28913,6 +28913,13 @@ export namespace Schemas {
readonly deleted: boolean;
/** @nullable */
readonly last_delivered_at: string | null;
+ /** Number of reports generated from this evaluation report config. */
+ readonly generated_report_count: number;
+ /**
+ * When the most recent report was generated, or null if no reports have been generated.
+ * @nullable
+ */
+ readonly last_generated_at: string | null;
/** Optional custom instructions appended to the AI report prompt to steer focus, scope, or section choices without modifying the base prompt. */
report_prompt_guidance?: string;
/**
@@ -29114,6 +29121,13 @@ export namespace Schemas {
readonly deleted: boolean;
/** @nullable */
readonly last_delivered_at: string | null;
+ /** Number of reports generated from this evaluation report config. */
+ readonly generated_report_count: number;
+ /**
+ * When the most recent report was generated, or null if no reports have been generated.
+ * @nullable
+ */
+ readonly last_generated_at: string | null;
/** Optional custom instructions appended to the AI report prompt to steer focus, scope, or section choices without modifying the base prompt. */
report_prompt_guidance?: string;
/**
@@ -54789,6 +54803,13 @@ export namespace Schemas {
readonly deleted?: boolean;
/** @nullable */
readonly last_delivered_at?: string | null;
+ /** Number of reports generated from this evaluation report config. */
+ readonly generated_report_count?: number;
+ /**
+ * When the most recent report was generated, or null if no reports have been generated.
+ * @nullable
+ */
+ readonly last_generated_at?: string | null;
/** Optional custom instructions appended to the AI report prompt to steer focus, scope, or section choices without modifying the base prompt. */
report_prompt_guidance?: string;
/**