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): replace eval summarize button with a reports callout (#83338)

Radu Raicea9372e0165ea1
diff --git a/.agents/skills/improving-drf-endpoints/SKILL.md b/.agents/skills/improving-drf-endpoints/SKILL.md
index 08144fd1b9d3..66a73d556e3e 100644
--- a/.agents/skills/improving-drf-endpoints/SKILL.md
+++ b/.agents/skills/improving-drf-endpoints/SKILL.md
@@ -169,7 +169,7 @@ See [common-anti-patterns.md](references/common-anti-patterns.md) for before/aft
- **JSONField + @extend_schema_field:** `products/alerts/backend/api/alert.py`
- **@validated_request:** `products/tasks/backend/presentation/views/api.py`
-- **help_text + typed responses:** `products/ai_observability/backend/api/evaluation_summary.py`
+- **help_text + typed responses:** `products/ai_observability/backend/api/summarization.py`
- **Facade product:** `products/visual_review/backend/presentation/views.py`
## Related
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index 0cda551ca96c..02446eab83a4 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -885,7 +885,7 @@ class TestAIObservabilitySummarizationRateThrottle(SimpleTestCase):
_find_personal_api_key: Mock,
_team_can_bypass: Mock,
) -> None:
- request = Mock(user=Mock(is_authenticated=True), path="/api/projects/1/llm_analytics/evaluation_summary/")
+ request = Mock(user=Mock(is_authenticated=True), path="/api/projects/1/llm_analytics/summarization/")
view = Mock(team_id=1)
with patch.object(throttle_class, "rate", "1/minute"):
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index 58b4e96108f8..37d505233b75 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -7,7 +7,6 @@ from .evaluation_config import EvaluationConfigViewSet
from .evaluation_directories import EvaluationDirectoryViewSet
from .evaluation_reports import EvaluationReportViewSet
from .evaluation_runs import EvaluationRunViewSet
-from .evaluation_summary import LLMEvaluationSummaryViewSet
from .evaluations import EvaluationViewSet
from .models import LLMModelsViewSet
from .offline_evaluations import AIObservabilityOfflineEvaluationsViewSet
@@ -33,7 +32,6 @@ __all__ = [
"AIObservabilityTextReprViewSet",
"AIObservabilitySummarizationViewSet",
"AIObservabilityTranslateViewSet",
- "LLMEvaluationSummaryViewSet",
"SUPPORTED_MODELS_WITH_THINKING",
"DatasetViewSet",
"DatasetItemViewSet",
diff --git a/products/ai_observability/backend/api/evaluation_summary.py b/products/ai_observability/backend/api/evaluation_summary.py
deleted file mode 100644
index 48f9af7cfcb6..000000000000
--- a/products/ai_observability/backend/api/evaluation_summary.py
+++ /dev/null
@@ -1,475 +0,0 @@
-"""
-Django REST API endpoint for evaluation results summarization.
-
-This ViewSet provides AI-powered summarization of evaluation results,
-identifying patterns in passing and failing evaluations.
-
-Endpoints:
-- POST /api/environments/:id/llm_analytics/evaluation_summary/ - Summarize evaluation runs
-"""
-
-import time
-import hashlib
-from typing import cast
-
-from django.core.cache import cache
-
-import structlog
-from asgiref.sync import async_to_sync
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiExample, extend_schema
-from rest_framework import exceptions, serializers, status, viewsets
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
-
-from posthog.api.monitoring import monitor
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.event_usage import report_user_action
-from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
-from posthog.models import Team, User
-from posthog.permissions import AccessControlPermission
-from posthog.rate_limit import (
- AIObservabilitySummarizationBurstThrottle,
- AIObservabilitySummarizationDailyThrottle,
- AIObservabilitySummarizationSustainedThrottle,
-)
-
-from products.ai_observability.backend.api.metrics import llma_track_latency
-from products.ai_observability.backend.models.evaluations import Evaluation
-from products.ai_observability.backend.summarization.constants import EVALUATION_SUMMARY_MAX_RUNS
-from products.ai_observability.backend.summarization.llm.evaluation_summary import summarize_evaluation_runs
-from products.ai_observability.backend.summarization.models import OpenAIModel
-
-logger = structlog.get_logger(__name__)
-
-
-class EvaluationSummaryRequestSerializer(serializers.Serializer):
- """Request serializer for evaluation summary - accepts IDs only, fetches data server-side."""
-
- evaluation_id = serializers.UUIDField(help_text="UUID of the evaluation config to summarize")
- filter = serializers.ChoiceField(
- choices=["all", "pass", "fail", "na"],
- default="all",
- required=False,
- help_text="Filter type to apply ('all', 'pass', 'fail', or 'na')",
- )
- generation_ids = serializers.ListField(
- child=serializers.UUIDField(),
- required=False,
- max_length=EVALUATION_SUMMARY_MAX_RUNS,
- help_text=f"Optional: specific generation IDs to include in summary (max {EVALUATION_SUMMARY_MAX_RUNS})",
- )
- force_refresh = serializers.BooleanField(
- default=False,
- required=False,
- help_text="If true, bypass cache and generate a fresh summary",
- )
-
-
-class EvaluationPatternSerializer(serializers.Serializer):
- title = serializers.CharField()
- description = serializers.CharField()
- frequency = serializers.CharField()
- example_generation_ids = serializers.ListField(child=serializers.CharField())
-
-
-class EvaluationSummaryStatisticsSerializer(serializers.Serializer):
- total_analyzed = serializers.IntegerField()
- pass_count = serializers.IntegerField()
- fail_count = serializers.IntegerField()
- na_count = serializers.IntegerField()
-
-
-class EvaluationSummaryResponseSerializer(serializers.Serializer):
- overall_assessment = serializers.CharField()
- pass_patterns = EvaluationPatternSerializer(many=True)
- fail_patterns = EvaluationPatternSerializer(many=True)
- na_patterns = EvaluationPatternSerializer(many=True)
- recommendations = serializers.ListField(child=serializers.CharField())
- statistics = EvaluationSummaryStatisticsSerializer()
-
-
-class EvaluationSummaryThrottleResponseSerializer(serializers.Serializer):
- type = serializers.CharField(help_text="Error category")
- code = serializers.CharField(help_text="Machine-readable error code")
- detail = serializers.CharField(help_text="Why the request was throttled")
- attr = serializers.CharField(allow_null=True, help_text="Related request field, when applicable")
-
-
-def _fetch_evaluation_runs(
- team: Team,
- evaluation_id: str,
- filter_type: str = "all",
- generation_ids: list[str] | None = None,
- limit: int = EVALUATION_SUMMARY_MAX_RUNS,
-) -> list[dict]:
- """
- Fetch evaluation runs from ClickHouse using HogQL.
-
- Args:
- team: Team object to query for
- evaluation_id: UUID of the evaluation config
- filter_type: Filter to apply ('all', 'pass', 'fail', 'na')
- generation_ids: Optional list of specific generation IDs to fetch
- limit: Maximum number of runs to return
-
- Returns:
- List of dicts with: generation_id, result, reasoning
- """
- # Build WHERE conditions using HogQL AST for safe parameterization
- where_conditions: list[ast.Expr] = [
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["event"]),
- right=ast.Constant(value="$ai_evaluation"),
- ),
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["properties", "$ai_evaluation_id"]),
- right=ast.Constant(value=evaluation_id),
- ),
- ]
-
- # Add result filter conditions
- # Helper for "applicable is NULL or applicable != false" condition
- # This handles evaluations without N/A where applicable field is not set (NULL)
- def _applicable_or_null() -> ast.Expr:
- return ast.Or(
- exprs=[
- ast.Call(
- name="isNull",
- args=[ast.Field(chain=["properties", "$ai_evaluation_applicable"])],
- ),
- ast.CompareOperation(
- op=ast.CompareOperationOp.NotEq,
- left=ast.Field(chain=["properties", "$ai_evaluation_applicable"]),
- right=ast.Constant(value=False),
- ),
- ]
- )
-
- if filter_type == "pass":
- where_conditions.append(
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["properties", "$ai_evaluation_result"]),
- right=ast.Constant(value=True),
- )
- )
- where_conditions.append(_applicable_or_null())
- elif filter_type == "fail":
- where_conditions.append(
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["properties", "$ai_evaluation_result"]),
- right=ast.Constant(value=False),
- )
- )
- where_conditions.append(_applicable_or_null())
- elif filter_type == "na":
- where_conditions.append(
- ast.CompareOperation(
- op=ast.CompareOperationOp.Eq,
- left=ast.Field(chain=["properties", "$ai_evaluation_applicable"]),
- right=ast.Constant(value=False),
- )
- )
-
- # Add generation_ids filter if provided
- if generation_ids:
- where_conditions.append(
- ast.CompareOperation(
- op=ast.CompareOperationOp.In,
- left=ast.Field(chain=["properties", "$ai_target_event_id"]),
- right=ast.Tuple(exprs=[ast.Constant(value=str(gid)) for gid in generation_ids]),
- )
- )
-
- query = parse_select(
- """
- SELECT
- properties.$ai_target_event_id as generation_id,
- properties.$ai_evaluation_result as result,
- properties.$ai_evaluation_reasoning as reasoning,
- properties.$ai_evaluation_applicable as applicable
- FROM posthog.ai_events AS ai_events
- WHERE {where_clause}
- ORDER BY timestamp DESC
- LIMIT {limit}
- """
- )
-
- query_result = query_ai_events(
- query=query,
- placeholders={
- "where_clause": ast.And(exprs=where_conditions),
- "limit": ast.Constant(value=limit),
- },
- team=team,
- query_type="EvaluationSummaryFetchRuns",
- fall_back_to_events=True,
- )
-
- # Transform to expected format
- # Columns: generation_id (0), result (1), reasoning (2), applicable (3)
- return [
- {
- "generation_id": str(row[0]) if row[0] else "",
- "result": None if row[3] is False else row[1],
- "reasoning": row[2] or "",
- }
- for row in (query_result.results or [])
- ]
-
-
-class LLMEvaluationSummaryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- """
- ViewSet for evaluation results summarization.
-
- Provides AI-powered analysis of evaluation runs to identify patterns
- in passing and failing evaluations. Fetches data server-side by ID
- to prevent client-side data manipulation.
- """
-
- scope_object = "llm_analytics"
- permission_classes = [AccessControlPermission]
-
- def get_throttles(self):
- """Apply rate limiting to prevent abuse of summarization endpoint."""
- return [
- AIObservabilitySummarizationBurstThrottle(),
- AIObservabilitySummarizationSustainedThrottle(),
- AIObservabilitySummarizationDailyThrottle(),
- ]
-
- # Cache timeout in seconds (1 hour)
- CACHE_TIMEOUT = 3600
-
- def _validate_feature_access(self, request: Request) -> None:
- """Validate that the user is authenticated and AI data processing is approved."""
- if not request.user.is_authenticated:
- raise exceptions.NotAuthenticated()
-
- if not self.organization.is_ai_data_processing_approved:
- raise exceptions.PermissionDenied(
- "AI data processing must be approved by your organization before using summarization"
- )
-
- def _get_cache_key(self, evaluation_id: str, filter_type: str, runs: list[dict]) -> str:
- """Generate cache key for evaluation summary results.
-
- The key includes a hash of the generation_ids to detect when
- the underlying runs have changed. Uses SHA256 for collision resistance.
- """
- # Sort generation_ids for consistent hashing
- generation_ids = sorted(r["generation_id"] for r in runs)
- runs_hash = hashlib.sha256(",".join(generation_ids).encode()).hexdigest()[:12]
- return f"llm_eval_summary:{self.team_id}:{evaluation_id}:{filter_type}:{runs_hash}"
-
- @extend_schema(
- request=EvaluationSummaryRequestSerializer,
- responses={
- 200: EvaluationSummaryResponseSerializer,
- 400: OpenApiTypes.OBJECT,
- 403: OpenApiTypes.OBJECT,
- 404: OpenApiTypes.OBJECT,
- 429: EvaluationSummaryThrottleResponseSerializer,
- 500: OpenApiTypes.OBJECT,
- },
- examples=[
- OpenApiExample(
- "Evaluation Summary Request",
- description="Summarize evaluation results by ID",
- value={
- "evaluation_id": "550e8400-e29b-41d4-a716-446655440000",
- "filter": "all",
- "force_refresh": False,
- },
- request_only=True,
- ),
- OpenApiExample(
- "Success Response",
- value={
- "overall_assessment": "Evaluations show generally good quality with some factual accuracy issues.",
- "pass_patterns": [
- {
- "title": "Clear Communication",
- "description": "Responses consistently provided well-structured information",
- "frequency": "common",
- "example_generation_ids": ["gen_abc123", "gen_ghi789"],
- }
- ],
- "fail_patterns": [
- {
- "title": "Factual Errors",
- "description": "Some responses contained inaccurate information",
- "frequency": "occasional",
- "example_generation_ids": ["gen_def456"],
- }
- ],
- "na_patterns": [],
- "recommendations": [
- "Implement fact-checking for critical claims",
- "Add source citations where applicable",
- ],
- "statistics": {"total_analyzed": 3, "pass_count": 2, "fail_count": 1, "na_count": 0},
- },
- response_only=True,
- status_codes=["200"],
- ),
- ],
- description="""
-Generate an AI-powered summary of evaluation results.
-
-This endpoint analyzes evaluation runs and identifies patterns in passing
-and failing evaluations, providing actionable recommendations.
-
-Data is fetched server-side by evaluation ID to ensure data integrity.
-
-**Use Cases:**
-- Understand why evaluations are passing or failing
-- Identify systematic issues in LLM responses
-- Get recommendations for improving response quality
-- Review patterns across many evaluation runs at once
- """,
- tags=["AI observability"],
- )
- @llma_track_latency("llma_evaluation_summary")
- @monitor(feature=None, endpoint="llma_evaluation_summary", method="POST")
- def create(self, request: Request, **kwargs) -> Response:
- """
- Summarize evaluation runs.
-
- POST /api/environments/:id/llm_analytics/evaluation_summary/
- """
- self._validate_feature_access(request)
-
- serializer = EvaluationSummaryRequestSerializer(data=request.data)
- if not serializer.is_valid():
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
-
- try:
- evaluation_id = str(serializer.validated_data["evaluation_id"])
- filter_type = serializer.validated_data.get("filter", "all")
- generation_ids = serializer.validated_data.get("generation_ids")
- force_refresh = serializer.validated_data.get("force_refresh", False)
-
- # Convert UUIDs to strings if provided
- generation_id_strs: list[str] | None = None
- if generation_ids:
- generation_id_strs = [str(gid) for gid in generation_ids]
-
- # Fetch evaluation config from Postgres
- try:
- evaluation = Evaluation.objects.get(
- id=evaluation_id,
- team_id=self.team_id,
- deleted=False,
- )
- except Evaluation.DoesNotExist:
- return Response(
- {"error": f"Evaluation {evaluation_id} not found"},
- status=status.HTTP_404_NOT_FOUND,
- )
-
- # Fetch evaluation runs from ClickHouse using HogQL
- runs = _fetch_evaluation_runs(
- team=self.team,
- evaluation_id=evaluation_id,
- filter_type=filter_type,
- generation_ids=generation_id_strs,
- limit=EVALUATION_SUMMARY_MAX_RUNS,
- )
-
- if len(runs) == 0:
- return Response(
- {"error": "No evaluation runs found for the specified criteria"},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- cache_key = self._get_cache_key(evaluation_id, filter_type, runs)
-
- # Check cache unless force_refresh is requested
- if not force_refresh:
- cached_result = cache.get(cache_key)
- if cached_result is not None:
- logger.info(
- "Returning cached evaluation summary",
- evaluation_id=evaluation_id,
- filter_type=filter_type,
- team_id=self.team_id,
- )
- return Response(cached_result, status=status.HTTP_200_OK)
-
- user = cast(User, self.request.user)
- start_time = time.time()
- summary = async_to_sync(summarize_evaluation_runs)(
- evaluation_runs=runs,
- team_id=self.team_id,
- evaluation_id=evaluation_id,
- model=OpenAIModel.GPT_5_MINI,
- filter_type=filter_type,
- evaluation_name=evaluation.name,
- evaluation_description=evaluation.description or "",
- evaluation_prompt=evaluation.evaluation_config.get("prompt", ""),
- user_distinct_id=user.distinct_id or "",
- )
- duration_seconds = time.time() - start_time
-
- result = summary.model_dump()
-
- # Override LLM-generated stats with ground truth computed from fetched data
- result["statistics"] = {
- "total_analyzed": len(runs),
- "pass_count": sum(1 for r in runs if r["result"] is True),
- "fail_count": sum(1 for r in runs if r["result"] is False),
- "na_count": sum(1 for r in runs if r["result"] is None),
- }
-
- # Cache the result
- cache.set(cache_key, result, timeout=self.CACHE_TIMEOUT)
-
- logger.info(
- "Generated and cached evaluation summary",
- evaluation_id=evaluation_id,
- team_id=self.team_id,
- runs_count=len(runs),
- filter_type=filter_type,
- duration_seconds=duration_seconds,
- force_refresh=force_refresh,
- )
-
- report_user_action(
- user,
- "llma evaluation summary generated",
- {
- "evaluation_id": evaluation_id,
- "runs_count": len(runs),
- "filter": filter_type,
- "duration_seconds": duration_seconds,
- "force_refresh": force_refresh,
- "pass_count": result["statistics"]["pass_count"],
- "fail_count": result["statistics"]["fail_count"],
- "na_count": result["statistics"]["na_count"],
- },
- team=self.team,
- request=self.request,
- )
-
- return Response(result, status=status.HTTP_200_OK)
-
- except exceptions.APIException:
- raise
- except Exception as e:
- logger.exception(
- "Failed to generate evaluation summary",
- team_id=self.team_id,
- error=str(e),
- )
- return Response(
- {"error": "Failed to generate summary", "detail": "An error occurred while generating the summary"},
- status=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
diff --git a/products/ai_observability/backend/api/test/test_evaluation_summary.py b/products/ai_observability/backend/api/test/test_evaluation_summary.py
deleted file mode 100644
index ce4696d0a763..000000000000
--- a/products/ai_observability/backend/api/test/test_evaluation_summary.py
+++ /dev/null
@@ -1,413 +0,0 @@
-"""
-Tests for evaluation summary API endpoint.
-"""
-
-import uuid
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
-
-from rest_framework import exceptions, status
-
-from products.ai_observability.backend.models.evaluations import Evaluation
-from products.ai_observability.backend.summarization.constants import EVALUATION_SUMMARY_MAX_RUNS
-from products.ai_observability.backend.summarization.llm.evaluation_schema import (
- EvaluationPattern,
- EvaluationSummaryResponse,
- EvaluationSummaryStatistics,
-)
-
-
-class TestEvaluationSummaryAPI(APIBaseTest):
- """Test evaluation summary API endpoints."""
-
- def setUp(self):
- super().setUp()
- # Create an evaluation for tests
- self.evaluation = Evaluation.objects.create(
- team=self.team,
- name="Test Evaluation",
- description="Test description for evaluation",
- evaluation_type="llm_judge",
- evaluation_config={"prompt": "Evaluate if the response is accurate and helpful."},
- output_type="boolean",
- output_config={"allows_na": True},
- enabled=True,
- created_by=self.user,
- )
-
- def test_unauthenticated_user_cannot_access_endpoint(self):
- self.client.logout()
- response = self.client.post(f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/")
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
-
- def test_ai_consent_required(self):
- self.organization.is_ai_data_processing_approved = False
- self.organization.save()
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "all",
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_403_FORBIDDEN
- assert "AI data processing must be approved" in response.data["detail"]
-
- def test_missing_evaluation_id(self):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {},
- format="json",
- )
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "evaluation_id" in str(response.data).lower()
-
- def test_evaluation_not_found(self):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- fake_id = str(uuid.uuid4())
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": fake_id,
- "filter": "all",
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_404_NOT_FOUND
- assert fake_id in response.data["error"]
-
- @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")
- def test_no_runs_found(self, mock_fetch_runs):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- mock_fetch_runs.return_value = []
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "all",
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "No evaluation runs found" in response.data["error"]
-
- @patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")
- @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")
- def test_successful_summarization(self, mock_fetch_runs, mock_async_to_sync):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- mock_fetch_runs.return_value = [
- {"generation_id": "gen_001", "result": True, "reasoning": "Good response"},
- {"generation_id": "gen_002", "result": True, "reasoning": "Another good response"},
- {"generation_id": "gen_003", "result": False, "reasoning": "Response did not address user question"},
- ]
-
- mock_summary = EvaluationSummaryResponse(
- overall_assessment="Test assessment of evaluation results",
- pass_patterns=[
- EvaluationPattern(
- title="Clear Communication",
- description="Responses were well structured",
- frequency="common",
- example_reasoning="Good response with clear structure",
- example_generation_ids=["gen_001", "gen_002"],
- )
- ],
- fail_patterns=[
- EvaluationPattern(
- title="Missing Context",
- description="Some responses lacked context",
- frequency="occasional",
- example_reasoning="Response did not address user question",
- example_generation_ids=["gen_003"],
- )
- ],
- na_patterns=[],
- recommendations=["Improve context handling", "Add validation"],
- statistics=EvaluationSummaryStatistics(
- total_analyzed=3,
- pass_count=2,
- fail_count=1,
- na_count=0,
- ),
- )
-
- mock_generate_summary = MagicMock(return_value=mock_summary)
- mock_async_to_sync.return_value = mock_generate_summary
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "all",
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- assert mock_generate_summary.call_args.kwargs["evaluation_id"] == str(self.evaluation.id)
- data = response.data
-
- assert "overall_assessment" in data
- assert data["overall_assessment"] == "Test assessment of evaluation results"
-
- assert "pass_patterns" in data
- assert len(data["pass_patterns"]) == 1
- assert data["pass_patterns"][0]["title"] == "Clear Communication"
-
- assert "fail_patterns" in data
- assert len(data["fail_patterns"]) == 1
- assert data["fail_patterns"][0]["title"] == "Missing Context"
-
- assert "recommendations" in data
- assert len(data["recommendations"]) == 2
-
- # Stats are computed from fetched runs, not LLM output
- assert "statistics" in data
- assert data["statistics"]["total_analyzed"] == 3
- assert data["statistics"]["pass_count"] == 2
- assert data["statistics"]["fail_count"] == 1
- assert data["statistics"]["na_count"] == 0
-
- @patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")
- @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")
- def test_concurrent_summary_returns_throttled_response(
- self, mock_fetch_runs: MagicMock, mock_async_to_sync: MagicMock
- ) -> None:
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- mock_fetch_runs.return_value = [
- {"generation_id": "gen_001", "result": True, "reasoning": "Good response"},
- ]
- mock_async_to_sync.return_value.side_effect = exceptions.Throttled(
- detail="An evaluation summary is already being generated for this project. Try again when it finishes."
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "all",
- "force_refresh": True,
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
- assert response.data["code"] == "throttled"
- assert "already being generated for this project" in response.data["detail"]
-
- @patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")
- @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")
- def test_filter_parameter_passed_to_fetch(self, mock_fetch_runs, mock_async_to_sync):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- mock_fetch_runs.return_value = [
- {"generation_id": "gen_101", "result": True, "reasoning": "Good response 1"},
- {"generation_id": "gen_102", "result": True, "reasoning": "Good response 2"},
- ]
-
- mock_summary = EvaluationSummaryResponse(
- overall_assessment="Pass-only summary",
- pass_patterns=[],
- fail_patterns=[],
- na_patterns=[],
- recommendations=[],
- statistics=EvaluationSummaryStatistics(
- total_analyzed=2,
- pass_count=2,
- fail_count=0,
- na_count=0,
- ),
- )
-
- mock_async_to_sync.return_value = lambda *args, **kwargs: mock_summary
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "pass",
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
-
- # Verify filter was passed to _fetch_evaluation_runs
- mock_fetch_runs.assert_called_once()
- call_kwargs = mock_fetch_runs.call_args
- assert call_kwargs.kwargs["filter_type"] == "pass"
-
- @patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")
- @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")
- def test_generation_ids_filter(self, mock_fetch_runs, mock_async_to_sync):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- mock_fetch_runs.return_value = [
- {"generation_id": "gen_specific_1", "result": True, "reasoning": "Good"},
- ]
-
- mock_summary = EvaluationSummaryResponse(
- overall_assessment="Summary for specific runs",
- pass_patterns=[],
- fail_patterns=[],
- na_patterns=[],
- recommendations=[],
- statistics=EvaluationSummaryStatistics(
- total_analyzed=1,
- pass_count=1,
- fail_count=0,
- na_count=0,
- ),
- )
-
- mock_async_to_sync.return_value = lambda *args, **kwargs: mock_summary
-
- gen_id_1 = str(uuid.uuid4())
- gen_id_2 = str(uuid.uuid4())
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "all",
- "generation_ids": [gen_id_1, gen_id_2],
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
-
- # Verify generation_ids were passed to _fetch_evaluation_runs
- mock_fetch_runs.assert_called_once()
- call_kwargs = mock_fetch_runs.call_args
- assert call_kwargs.kwargs["generation_ids"] == [gen_id_1, gen_id_2]
-
- @patch("products.ai_observability.backend.api.evaluation_summary.async_to_sync")
- @patch("products.ai_observability.backend.api.evaluation_summary._fetch_evaluation_runs")
- def test_na_filter_and_null_results(self, mock_fetch_runs, mock_async_to_sync):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- mock_fetch_runs.return_value = [
- {"generation_id": "gen_na_001", "result": None, "reasoning": "The response was a clarifying question"},
- {"generation_id": "gen_na_002", "result": None, "reasoning": "Evaluation criteria did not apply"},
- ]
-
- mock_summary = EvaluationSummaryResponse(
- overall_assessment="N/A summary for evaluations that were not applicable",
- pass_patterns=[],
- fail_patterns=[],
- na_patterns=[
- EvaluationPattern(
- title="Out of Scope",
- description="Evaluation criteria did not apply",
- frequency="common",
- example_reasoning="The response was a clarifying question",
- example_generation_ids=["gen_na_001", "gen_na_002"],
- )
- ],
- recommendations=["Consider updating evaluation criteria"],
- statistics=EvaluationSummaryStatistics(
- total_analyzed=2,
- pass_count=0,
- fail_count=0,
- na_count=2,
- ),
- )
-
- mock_async_to_sync.return_value = lambda *args, **kwargs: mock_summary
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "filter": "na",
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK
- data = response.data
-
- assert data["statistics"]["na_count"] == 2
- assert len(data["na_patterns"]) == 1
- assert data["na_patterns"][0]["title"] == "Out of Scope"
-
- def test_max_generation_ids_limit(self):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- # Try to pass more than EVALUATION_SUMMARY_MAX_RUNS generation_ids
- generation_ids = [str(uuid.uuid4()) for _ in range(EVALUATION_SUMMARY_MAX_RUNS + 1)]
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(self.evaluation.id),
- "generation_ids": generation_ids,
- },
- format="json",
- )
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
-
- def test_evaluation_from_different_team_not_accessible(self):
- self.organization.is_ai_data_processing_approved = True
- self.organization.save()
-
- # Create another team
- other_team = self._create_another_team()
- other_evaluation = Evaluation.objects.create(
- team=other_team,
- name="Other Team Evaluation",
- evaluation_type="llm_judge",
- evaluation_config={"prompt": "Test"},
- output_type="boolean",
- output_config={},
- enabled=True,
- )
-
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/evaluation_summary/",
- {
- "evaluation_id": str(other_evaluation.id),
- "filter": "all",
- },
- format="json",
- )
-
- # Should return 404 since evaluation belongs to different team
- assert response.status_code == status.HTTP_404_NOT_FOUND
-
- def _create_another_team(self):
- from posthog.models import Organization, Project, Team
-
- org = Organization.objects.create(name="other-org")
- project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=org)
- team = Team.objects.create(
- id=project.id,
- project=project,
- organization=org,
- )
- return team
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index 8ddd9aaf02fb..a81f562d8a80 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -17,7 +17,6 @@ from products.ai_observability.backend.api import (
EvaluationReportViewSet,
EvaluationRunViewSet,
EvaluationViewSet,
- LLMEvaluationSummaryViewSet,
LLMModelsViewSet,
LLMProviderKeyValidationViewSet,
LLMProviderKeyViewSet,
@@ -66,12 +65,6 @@ def register_routes(routers: RouterRegistry) -> None:
"project_llm_analytics_summarization",
["team_id"],
)
- routers.projects.register(
- r"llm_analytics/evaluation_summary",
- LLMEvaluationSummaryViewSet,
- "project_llm_analytics_evaluation_summary",
- ["team_id"],
- )
routers.projects.register(
r"llm_analytics/translate", AIObservabilityTranslateViewSet, "project_llm_analytics_translate", ["team_id"]
)
diff --git a/products/ai_observability/backend/summarization/constants.py b/products/ai_observability/backend/summarization/constants.py
index ed0e2345bb77..ca360275da1f 100644
--- a/products/ai_observability/backend/summarization/constants.py
+++ b/products/ai_observability/backend/summarization/constants.py
@@ -8,16 +8,3 @@ DEFAULT_MODE = SummarizationMode.MINIMAL
# Timeout configuration (seconds)
SUMMARIZATION_TIMEOUT = 120
-
-# Evaluation summary limits
-EVALUATION_SUMMARY_MAX_RUNS = 250
-
-# Large or verbose inputs are summarized as a bounded concurrent map-reduce so no
-# individual ai-gateway request approaches its ~30s hard timeout.
-EVALUATION_SUMMARY_CHUNK_SIZE = 20
-EVALUATION_SUMMARY_PROMPT_MAX_CHARS = 20_000
-EVALUATION_SUMMARY_MIN_USER_PROMPT_CHARS = 4_000
-EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS = 2_000
-EVALUATION_SUMMARY_MAX_CONCURRENT_MAP_CALLS = 5
-EVALUATION_SUMMARY_GENERATION_LOCK_TIMEOUT_SECONDS = 10 * 60
-EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT = 4
diff --git a/products/ai_observability/backend/summarization/llm/evaluation_schema.py b/products/ai_observability/backend/summarization/llm/evaluation_schema.py
deleted file mode 100644
index 3c125f2a2d59..000000000000
--- a/products/ai_observability/backend/summarization/llm/evaluation_schema.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""
-Pydantic schema for structured evaluation summary outputs.
-"""
-
-from typing import Annotated, Literal
-
-from pydantic import BaseModel, ConfigDict, Field
-
-from ..constants import EVALUATION_SUMMARY_CHUNK_SIZE, EVALUATION_SUMMARY_MAX_RUNS
-
-
-class EvaluationPattern(BaseModel):
- """A pattern identified across evaluation results."""
-
- model_config = ConfigDict(extra="forbid")
-
- title: str = Field(description="Short title for the pattern (3-5 words)")
- description: str = Field(description="Detailed description of the pattern")
- frequency: str = Field(description="How common this pattern is: 'common', 'occasional', or 'rare'")
- example_reasoning: str = Field(
- description="An example reasoning from the evaluated runs that demonstrates this pattern"
- )
- example_generation_ids: list[str] = Field(description="List of 1-5 generation IDs that exemplify this pattern")
-
-
-class EvaluationSummaryStatistics(BaseModel):
- """Statistics about the analyzed evaluation runs."""
-
- model_config = ConfigDict(extra="forbid")
-
- total_analyzed: int = Field(description="Total number of evaluation runs analyzed")
- pass_count: int = Field(description="Number of passing evaluations")
- fail_count: int = Field(description="Number of failing evaluations")
- na_count: int = Field(description="Number of N/A (not applicable) evaluations")
-
-
-class EvaluationSummaryResponse(BaseModel):
- """Structured response from AI-powered evaluation summarization."""
-
- model_config = ConfigDict(extra="forbid")
-
- overall_assessment: str
- pass_patterns: list[EvaluationPattern]
- fail_patterns: list[EvaluationPattern]
- na_patterns: list[EvaluationPattern]
- recommendations: list[str]
- statistics: EvaluationSummaryStatistics
-
-
-class EvaluationPatternCandidate(BaseModel):
- model_config = ConfigDict(extra="forbid")
-
- result: Literal["pass", "fail", "na"] = Field(description="Result category for this candidate theme")
- title: str = Field(max_length=60, description="Short title for the candidate theme (3-5 words)")
- occurrence_count: int = Field(
- ge=1,
- le=EVALUATION_SUMMARY_MAX_RUNS,
- description="Exact number of evaluation runs represented by this theme",
- )
- example_reasoning: str = Field(
- max_length=240,
- description="Concise reasoning from one run that demonstrates this candidate theme",
- )
- example_generation_ids: list[Annotated[str, Field(max_length=64)]] = Field(
- min_length=1,
- max_length=3,
- description="List of 1-3 generation IDs that exemplify this theme",
- )
-
-
-class EvaluationSummaryMapResponse(BaseModel):
- model_config = ConfigDict(extra="forbid")
-
- patterns: list[EvaluationPatternCandidate] = Field(
- max_length=EVALUATION_SUMMARY_CHUNK_SIZE,
- description="Candidate themes representing evaluation runs",
- )
diff --git a/products/ai_observability/backend/summarization/llm/evaluation_summary.py b/products/ai_observability/backend/summarization/llm/evaluation_summary.py
deleted file mode 100644
index 5a504355c3b2..000000000000
--- a/products/ai_observability/backend/summarization/llm/evaluation_summary.py
+++ /dev/null
@@ -1,634 +0,0 @@
-"""Evaluation summary generation, routed through the internal Go ai-gateway when
-configured, else the Python LLM gateway.
-
-Large evaluations use a concurrent hierarchical map-reduce because one LLM call over all
-runs can trip the ai-gateway's ~30s hard timeout.
-"""
-
-import json
-import asyncio
-import contextlib
-from collections.abc import AsyncIterator
-from typing import Any, Literal, TypeVar, cast
-from uuid import uuid4
-
-import structlog
-from openai import AsyncOpenAI
-from openai.types.chat import ChatCompletionMessageParam
-from pydantic import BaseModel
-from redis.exceptions import LockError
-from rest_framework import exceptions
-
-from posthog import redis as posthog_redis
-from posthog.llm.gateway_client import build_async_openai_client, team_distinct_id
-
-from ..constants import (
- EVALUATION_SUMMARY_CHUNK_SIZE,
- EVALUATION_SUMMARY_GENERATION_LOCK_TIMEOUT_SECONDS,
- EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS,
- EVALUATION_SUMMARY_MAX_CONCURRENT_MAP_CALLS,
- EVALUATION_SUMMARY_MIN_USER_PROMPT_CHARS,
- EVALUATION_SUMMARY_PROMPT_MAX_CHARS,
- EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT,
- SUMMARIZATION_TIMEOUT,
-)
-from ..models import OpenAIModel
-from ..utils import load_summarization_template
-from .evaluation_schema import (
- EvaluationPatternCandidate,
- EvaluationSummaryMapResponse,
- EvaluationSummaryResponse,
- EvaluationSummaryStatistics,
-)
-
-logger = structlog.get_logger(__name__)
-
-StructuredResponse = TypeVar("StructuredResponse", bound=BaseModel)
-ResultCategory = Literal["pass", "fail", "na"]
-
-
-async def _team_generation_lock(team_id: int) -> AsyncIterator[None]:
- lock = posthog_redis.get_async_client().lock(
- f"llm_eval_summary_generation_lock:{team_id}",
- timeout=EVALUATION_SUMMARY_GENERATION_LOCK_TIMEOUT_SECONDS,
- blocking=False,
- )
- if not await lock.acquire(blocking=False):
- raise exceptions.Throttled(
- detail="An evaluation summary is already being generated for this project. Try again when it finishes."
- )
-
- try:
- yield
- finally:
- try:
- await lock.release()
- except LockError:
- logger.warning("evaluation_summary_generation_lock_release_failed", team_id=team_id)
-
-
-def _result_label(result: bool | None) -> str:
- if result is None:
- return "N/A"
- return "PASS" if result else "FAIL"
-
-
-def _result_category(result: bool | None) -> ResultCategory:
- if result is None:
- return "na"
- return "pass" if result else "fail"
-
-
-def _compute_statistics(evaluation_runs: list[dict]) -> EvaluationSummaryStatistics:
- return EvaluationSummaryStatistics(
- total_analyzed=len(evaluation_runs),
- pass_count=sum(1 for run in evaluation_runs if run["result"] is True),
- fail_count=sum(1 for run in evaluation_runs if run["result"] is False),
- na_count=sum(1 for run in evaluation_runs if run["result"] is None),
- )
-
-
-def _build_runs_prompt(evaluation_runs: list[dict]) -> str:
- runs_text = "\n\n".join(
- f"- Generation ID: {run['generation_id']}\n Result: {_result_label(run['result'])}\n Reasoning: {run['reasoning']}"
- for run in evaluation_runs
- )
-
- stats = _compute_statistics(evaluation_runs)
- stats_parts = []
- if stats.pass_count > 0:
- stats_parts.append(f"{stats.pass_count} passed")
- if stats.fail_count > 0:
- stats_parts.append(f"{stats.fail_count} failed")
- if stats.na_count > 0:
- stats_parts.append(f"{stats.na_count} N/A")
- stats_text = ", ".join(stats_parts) if stats_parts else "no results"
-
- return f"""Analyze these {len(evaluation_runs)} evaluation results ({stats_text}):
-
-{runs_text}"""
-
-
-def _available_user_prompt_chars(system_prompt: str) -> int:
- available_characters = EVALUATION_SUMMARY_PROMPT_MAX_CHARS - len(system_prompt)
- if available_characters < EVALUATION_SUMMARY_MIN_USER_PROMPT_CHARS:
- raise exceptions.ValidationError(
- "The evaluation context is too long to summarize. Shorten the evaluation prompt or description and try again."
- )
- return available_characters
-
-
-def _prompt_fits(system_prompt: str, user_prompt: str) -> bool:
- return len(system_prompt) + len(user_prompt) <= EVALUATION_SUMMARY_PROMPT_MAX_CHARS
-
-
-def _truncate_reasoning(reasoning: str) -> str:
- if len(reasoning) <= EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS:
- return reasoning
-
- marker = "\n...[truncated]...\n"
- available_characters = EVALUATION_SUMMARY_MAP_REASONING_MAX_CHARS - len(marker)
- prefix_length = (available_characters + 1) // 2
- suffix_length = available_characters // 2
- return f"{reasoning[:prefix_length]}{marker}{reasoning[-suffix_length:]}"
-
-
-def _build_bounded_chunks(evaluation_runs: list[dict], max_prompt_chars: int) -> list[list[dict]]:
- chunks: list[list[dict]] = []
- current_chunk: list[dict] = []
-
- for run in evaluation_runs:
- bounded_run = {**run, "reasoning": _truncate_reasoning(run["reasoning"])}
- proposed_chunk = [*current_chunk, bounded_run]
- proposed_prompt = _build_runs_prompt(proposed_chunk)
-
- if current_chunk and (
- len(proposed_chunk) > EVALUATION_SUMMARY_CHUNK_SIZE or len(proposed_prompt) > max_prompt_chars
- ):
- chunks.append(current_chunk)
- current_chunk = [bounded_run]
- else:
- current_chunk = proposed_chunk
-
- if len(_build_runs_prompt(current_chunk)) > max_prompt_chars:
- raise exceptions.ValidationError(
- "An evaluation result is too long to summarize. Shorten its reasoning and try again."
- )
-
- if current_chunk:
- chunks.append(current_chunk)
-
- return chunks
-
-
-def _map_response_schema(max_candidates: int, max_occurrences: int) -> dict[str, Any]:
- schema = EvaluationSummaryMapResponse.model_json_schema()
- schema["properties"]["patterns"]["maxItems"] = max_candidates
- schema["$defs"]["EvaluationPatternCandidate"]["properties"]["occurrence_count"]["maximum"] = max_occurrences
- return schema
-
-
-def _candidate_counts(candidates: list[EvaluationPatternCandidate]) -> dict[str, int]:
- counts = {"pass": 0, "fail": 0, "na": 0}
- for candidate in candidates:
- counts[candidate.result] += candidate.occurrence_count
- return counts
-
-
-def _run_counts(evaluation_runs: list[dict]) -> dict[str, int]:
- statistics = _compute_statistics(evaluation_runs)
- return {
- "pass": statistics.pass_count,
- "fail": statistics.fail_count,
- "na": statistics.na_count,
- }
-
-
-def _validate_map_response(response: EvaluationSummaryMapResponse, evaluation_runs: list[dict]) -> None:
- expected_counts = _run_counts(evaluation_runs)
- actual_counts = _candidate_counts(response.patterns)
- if actual_counts != expected_counts:
- raise ValueError(f"candidate counts {actual_counts} do not match run counts {expected_counts}")
-
- generation_results = {run["generation_id"]: _result_category(run["result"]) for run in evaluation_runs}
- if any(
- generation_results.get(generation_id) != candidate.result
- for candidate in response.patterns
- for generation_id in candidate.example_generation_ids
- ):
- raise ValueError("candidate response contains a generation ID from the wrong result category")
-
-
-def _validate_reduce_response(
- response: EvaluationSummaryMapResponse, input_candidates: list[EvaluationPatternCandidate]
-) -> None:
- input_counts = _candidate_counts(input_candidates)
- output_counts = _candidate_counts(response.patterns)
- if output_counts != input_counts:
- raise ValueError("reduced candidate counts do not match the input counts")
-
- generation_results = {
- generation_id: candidate.result
- for candidate in input_candidates
- for generation_id in candidate.example_generation_ids
- }
- if any(
- generation_results.get(generation_id) != candidate.result
- for candidate in response.patterns
- for generation_id in candidate.example_generation_ids
- ):
- raise ValueError("reduced response contains a generation ID from the wrong result category")
-
-
-def _build_candidates_prompt(
- candidates: list[EvaluationPatternCandidate], statistics: EvaluationSummaryStatistics
-) -> str:
- candidate_payload = json.dumps(
- [candidate.model_dump() for candidate in candidates],
- separators=(",", ":"),
- )
- return f"""Ground-truth statistics for the complete evaluation:
-{statistics.model_dump_json()}
-
-Candidate themes to consolidate:
-{candidate_payload}"""
-
-
-def _build_bounded_candidate_groups(
- candidates: list[EvaluationPatternCandidate],
- statistics: EvaluationSummaryStatistics,
- max_prompt_chars: int,
-) -> list[list[EvaluationPatternCandidate]]:
- groups: list[list[EvaluationPatternCandidate]] = []
- current_group: list[EvaluationPatternCandidate] = []
-
- for candidate in candidates:
- proposed_group = [*current_group, candidate]
- if current_group and len(_build_candidates_prompt(proposed_group, statistics)) > max_prompt_chars:
- groups.append(current_group)
- current_group = [candidate]
- else:
- current_group = proposed_group
-
- if len(_build_candidates_prompt(current_group, statistics)) > max_prompt_chars:
- raise exceptions.APIException(
- "Couldn't fit evaluation evidence within the summary prompt limit. Reduce the number of runs and try again."
- )
-
- if current_group:
- groups.append(current_group)
-
- return groups
-
-
-async def _run_structured_completion(
- client: AsyncOpenAI,
- model: OpenAIModel,
- system_prompt: str,
- user_prompt: str,
- team_id: int,
- user_distinct_id: str,
- response_model: type[StructuredResponse],
- schema_name: str,
- response_schema: dict[str, Any] | None = None,
-) -> StructuredResponse:
- messages: list[ChatCompletionMessageParam] = [
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
- ]
-
- response = await client.chat.completions.create(
- model=str(model),
- messages=messages,
- user=user_distinct_id or "llma-evaluation-summarization",
- timeout=SUMMARIZATION_TIMEOUT,
- response_format=cast(
- Any,
- {
- "type": "json_schema",
- "json_schema": {
- "name": schema_name,
- "strict": True,
- "schema": response_schema or response_model.model_json_schema(),
- },
- },
- ),
- )
-
- content = response.choices[0].message.content
- if not content:
- logger.error("evaluation_summary_empty_response", team_id=team_id, model=str(model))
- raise exceptions.APIException("Failed to generate evaluation summary: empty response")
-
- return response_model.model_validate_json(content)
-
-
-async def _run_map_completion(
- client: AsyncOpenAI,
- model: OpenAIModel,
- system_prompt: str,
- evaluation_runs: list[dict],
- team_id: int,
- user_distinct_id: str,
-) -> EvaluationSummaryMapResponse:
- last_error: ValueError | None = None
- for attempt in range(2):
- response = await _run_structured_completion(
- client=client,
- model=model,
- system_prompt=system_prompt,
- user_prompt=_build_runs_prompt(evaluation_runs),
- team_id=team_id,
- user_distinct_id=user_distinct_id,
- response_model=EvaluationSummaryMapResponse,
- schema_name="evaluation_summary_candidates",
- response_schema=_map_response_schema(
- max_candidates=len(evaluation_runs),
- max_occurrences=len(evaluation_runs),
- ),
- )
- try:
- _validate_map_response(response, evaluation_runs)
- return response
- except ValueError as error:
- last_error = error
- logger.warning(
- "evaluation_summary_map_response_invalid",
- team_id=team_id,
- model=str(model),
- attempt=attempt + 1,
- error=str(error),
- )
-
- raise exceptions.APIException("Couldn't generate a complete evaluation summary. Try again.") from last_error
-
-
-async def _run_reduce_completion(
- client: AsyncOpenAI,
- model: OpenAIModel,
- system_prompt: str,
- input_candidates: list[EvaluationPatternCandidate],
- statistics: EvaluationSummaryStatistics,
- team_id: int,
- user_distinct_id: str,
-) -> EvaluationSummaryMapResponse:
- result_category_count = sum(count > 0 for count in _candidate_counts(input_candidates).values())
- max_candidates = min(
- EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT * result_category_count,
- max(result_category_count, len(input_candidates) - 1),
- )
- max_occurrences = sum(candidate.occurrence_count for candidate in input_candidates)
- last_error: ValueError | None = None
-
- for attempt in range(2):
- response = await _run_structured_completion(
- client=client,
- model=model,
- system_prompt=system_prompt,
- user_prompt=_build_candidates_prompt(input_candidates, statistics),
- team_id=team_id,
- user_distinct_id=user_distinct_id,
- response_model=EvaluationSummaryMapResponse,
- schema_name="evaluation_summary_reduced_candidates",
- response_schema=_map_response_schema(
- max_candidates=max_candidates,
- max_occurrences=max_occurrences,
- ),
- )
- try:
- _validate_reduce_response(response, input_candidates)
- return response
- except ValueError as error:
- last_error = error
- logger.warning(
- "evaluation_summary_reduce_response_invalid",
- team_id=team_id,
- model=str(model),
- attempt=attempt + 1,
- error=str(error),
- )
-
- raise exceptions.APIException("Couldn't consolidate the evaluation summary. Try again.") from last_error
-
-
-async def _reduce_candidates_to_budget(
- client: AsyncOpenAI,
- model: OpenAIModel,
- candidates: list[EvaluationPatternCandidate],
- statistics: EvaluationSummaryStatistics,
- final_system_prompt: str,
- prompt_context: dict[str, Any],
- team_id: int,
- user_distinct_id: str,
- llm_call_semaphore: asyncio.Semaphore,
-) -> list[EvaluationPatternCandidate]:
- final_user_prompt_chars = _available_user_prompt_chars(final_system_prompt)
- reduce_system_prompt = load_summarization_template(
- "prompts/evaluation_summary_reduce.djt",
- {
- **prompt_context,
- "max_candidates_per_result": EVALUATION_SUMMARY_REDUCE_MAX_CANDIDATES_PER_RESULT,
- },
- )
- reduce_user_prompt_chars = _available_user_prompt_chars(reduce_system_prompt)
- reduced_candidates = candidates
-
- while len(_build_candidates_prompt(reduced_candidates, statistics)) > final_user_prompt_chars:
- groups = _build_bounded_candidate_groups(
- reduced_candidates,
- statistics,
- reduce_user_prompt_chars,
- )
-
- async def reduce_group(group: list[EvaluationPatternCandidate]) -> EvaluationSummaryMapResponse:
- if len(group) == 1:
- return EvaluationSummaryMapResponse(patterns=group)
- async with llm_call_semaphore:
- return await _run_reduce_completion(
- client=client,
- model=model,
- system_prompt=reduce_system_prompt,
- input_candidates=group,
- statistics=statistics,
- team_id=team_id,
- user_distinct_id=user_distinct_id,
- )
-
- reduced_groups = await asyncio.gather(*(reduce_group(group) for group in groups))
- next_candidates = [candidate for group in reduced_groups for candidate in group.patterns]
- if len(next_candidates) >= len(reduced_candidates):
- raise exceptions.APIException(
- "Couldn't reduce the evaluation evidence enough to generate a summary. Reduce the number of runs and try again."
- )
- reduced_candidates = next_candidates
-
- return reduced_candidates
-
-
-async def _merge_summaries(
- client: AsyncOpenAI,
- model: OpenAIModel,
- batch_candidates: list[EvaluationSummaryMapResponse],
- statistics: EvaluationSummaryStatistics,
- prompt_context: dict[str, Any],
- team_id: int,
- user_distinct_id: str,
- llm_call_semaphore: asyncio.Semaphore,
-) -> EvaluationSummaryResponse:
- merge_system_prompt = load_summarization_template("prompts/evaluation_summary_merge.djt", prompt_context)
- candidates = [candidate for batch in batch_candidates for candidate in batch.patterns]
- candidates = await _reduce_candidates_to_budget(
- client=client,
- model=model,
- candidates=candidates,
- statistics=statistics,
- final_system_prompt=merge_system_prompt,
- prompt_context=prompt_context,
- team_id=team_id,
- user_distinct_id=user_distinct_id,
- llm_call_semaphore=llm_call_semaphore,
- )
- merge_user_prompt = _build_candidates_prompt(candidates, statistics)
-
- return await _run_structured_completion(
- client=client,
- model=model,
- system_prompt=merge_system_prompt,
- user_prompt=merge_user_prompt,
- team_id=team_id,
- user_distinct_id=user_distinct_id,
- response_model=EvaluationSummaryResponse,
- schema_name="evaluation_summary",
- )
-
-
-async def _generate_evaluation_summary(
- evaluation_runs: list[dict],
- team_id: int,
- evaluation_id: str,
- trace_id: str,
- session_id: str,
- model: OpenAIModel,
- filter_type: str,
- evaluation_name: str,
- evaluation_description: str,
- evaluation_prompt: str,
- user_distinct_id: str,
-) -> EvaluationSummaryResponse:
- statistics = _compute_statistics(evaluation_runs)
- prompt_context = {
- "filter": filter_type,
- "evaluation_name": evaluation_name,
- "evaluation_description": evaluation_description,
- "evaluation_prompt": evaluation_prompt,
- "max_candidates": EVALUATION_SUMMARY_CHUNK_SIZE,
- }
- resolved_distinct_id = user_distinct_id or team_distinct_id(team_id)
- observability_properties = {
- "team_id": str(team_id),
- "filter_type": filter_type,
- **({"evaluation_id": evaluation_id} if evaluation_id else {}),
- }
- client = build_async_openai_client(
- "llma_eval_summary",
- ai_product="aio_eval_summary",
- trace_id=trace_id,
- session_id=session_id,
- properties=observability_properties,
- distinct_id=resolved_distinct_id,
- )
- if len(evaluation_runs) <= EVALUATION_SUMMARY_CHUNK_SIZE:
- single_system_prompt = load_summarization_template("prompts/evaluation_summary.djt", prompt_context)
- single_user_prompt = _build_runs_prompt(evaluation_runs)
- if _prompt_fits(single_system_prompt, single_user_prompt):
- summary = await _run_structured_completion(
- client=client,
- model=model,
- system_prompt=single_system_prompt,
- user_prompt=single_user_prompt,
- team_id=team_id,
- user_distinct_id=resolved_distinct_id,
- response_model=EvaluationSummaryResponse,
- schema_name="evaluation_summary",
- )
- summary.statistics = statistics
- return summary
-
- map_system_prompt = load_summarization_template("prompts/evaluation_summary_map.djt", prompt_context)
- chunks = _build_bounded_chunks(
- evaluation_runs,
- max_prompt_chars=_available_user_prompt_chars(map_system_prompt),
- )
- llm_call_semaphore = asyncio.Semaphore(EVALUATION_SUMMARY_MAX_CONCURRENT_MAP_CALLS)
-
- async def summarize_chunk(chunk: list[dict]) -> EvaluationSummaryMapResponse:
- async with llm_call_semaphore:
- return await _run_map_completion(
- client=client,
- model=model,
- system_prompt=map_system_prompt,
- evaluation_runs=chunk,
- team_id=team_id,
- user_distinct_id=resolved_distinct_id,
- )
-
- batch_candidates = list(await asyncio.gather(*(summarize_chunk(chunk) for chunk in chunks)))
- summary = await _merge_summaries(
- client=client,
- model=model,
- batch_candidates=batch_candidates,
- statistics=statistics,
- prompt_context=prompt_context,
- team_id=team_id,
- user_distinct_id=resolved_distinct_id,
- llm_call_semaphore=llm_call_semaphore,
- )
- summary.statistics = statistics
- return summary
-
-
-async def summarize_evaluation_runs(
- evaluation_runs: list[dict],
- team_id: int,
- model: OpenAIModel,
- evaluation_id: str = "",
- filter_type: str = "all",
- evaluation_name: str = "",
- evaluation_description: str = "",
- evaluation_prompt: str = "",
- user_distinct_id: str = "",
-) -> EvaluationSummaryResponse:
- """
- Generate summary of evaluation runs using LLM gateway with structured outputs.
-
- Runs are summarized in a single call when small. Larger sets use bounded map
- calls and hierarchical reduction so each request stays below the prompt limit.
-
- Args:
- evaluation_runs: List of dicts with 'generation_id' (str), 'result' (bool or None), and 'reasoning' (str)
- team_id: Team ID for logging and tracking
- model: OpenAI model to use
- evaluation_id: Evaluation identifier attached as observability metadata
- filter_type: The filter applied ('all', 'pass', 'fail', 'na')
- evaluation_name: Name of the evaluation being summarized
- evaluation_description: Description of what the evaluation tests for
- evaluation_prompt: The prompt used by the LLM judge
- user_distinct_id: Distinct ID of the user for analytics tracking
-
- Returns:
- Structured evaluation summary response
- """
- if not evaluation_runs:
- raise exceptions.ValidationError("No evaluation runs provided")
-
- trace_id = str(uuid4())
- session_id = str(uuid4())
- try:
- async with _team_generation_lock(team_id):
- return await _generate_evaluation_summary(
- evaluation_runs=evaluation_runs,
- team_id=team_id,
- evaluation_id=evaluation_id,
- trace_id=trace_id,
- session_id=session_id,
- model=model,
- filter_type=filter_type,
- evaluation_name=evaluation_name,
- evaluation_description=evaluation_description,
- evaluation_prompt=evaluation_prompt,
- user_distinct_id=user_distinct_id,
- )
- except exceptions.APIException:
- raise
- except Exception as error:
- logger.exception(
- "evaluation_summary_failed",
- team_id=team_id,
- evaluation_id=evaluation_id,
- trace_id=trace_id,
- session_id=session_id,
- model=str(model),
- error=str(error),
- )
- raise exceptions.APIException("Failed to generate evaluation summary") from error
diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt
deleted file mode 100644
index 4c258cf4ef9d..000000000000
--- a/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt
+++ /dev/null
@@ -1,105 +0,0 @@
-You are an expert at analyzing AI observability evaluation results. Your task is to analyze evaluation run results and identify patterns across them.
-
-## Evaluation Context
-
-**Evaluation Name:** {{ evaluation_name }}
-{% if evaluation_description %}
-**Description:** {{ evaluation_description }}
-{% endif %}
-
-**Evaluation criteria:**
-```
-{{ evaluation_prompt }}
-```
-
-Understanding these criteria is crucial - they define how a response is determined to pass, fail, or be N/A. Use this context to better understand the reasoning provided in each evaluation result.
-
-## Evaluation Results
-
-You are given a list of evaluation results, each containing:
-- generation_id: A unique identifier for this evaluation run
-- result: Whether the evaluation passed (PASS), failed (FAIL), or was not applicable (N/A)
-- reasoning: The explanation for the result
-
-{% if filter == 'all' %}
-Your goal is to:
-1. Identify common patterns in passing evaluations
-2. Identify common patterns in failing evaluations
-3. Identify common patterns in N/A evaluations (if any are present)
-4. Provide actionable recommendations for improving the evaluated LLM system
-{% elif filter == 'pass' %}
-Your goal is to:
-1. Focus ONLY on patterns in passing evaluations
-2. Understand what makes responses successful
-3. Provide recommendations for maintaining and replicating this success
-Note: Since you are only analyzing passing evaluations, leave fail_patterns and na_patterns as empty arrays.
-{% elif filter == 'fail' %}
-Your goal is to:
-1. Focus ONLY on patterns in failing evaluations
-2. Understand what causes responses to fail
-3. Provide actionable recommendations for fixing the identified issues
-Note: Since you are only analyzing failing evaluations, leave pass_patterns and na_patterns as empty arrays.
-{% elif filter == 'na' %}
-Your goal is to:
-1. Focus ONLY on patterns in N/A (not applicable) evaluations
-2. Understand why these evaluations were marked as not applicable
-3. Provide recommendations for improving evaluation applicability or filtering criteria
-Note: Since you are only analyzing N/A evaluations, leave pass_patterns and fail_patterns as empty arrays.
-{% endif %}
-
-IMPORTANT GUIDELINES:
-- Focus on the reasoning text to identify recurring themes and patterns
-- Group similar issues or successes together
-- Be specific about what patterns you observe
-- Limit to 0-4 patterns per category
-- Recommendations should be specific and actionable (2-4 total)
-- If there are no patterns for a category, return an empty array
-- For each pattern, include 1-5 generation_ids that exemplify the pattern
-
-PATTERN IDENTIFICATION:
-- Look for repeated phrases, similar concerns, or common themes
-- A pattern should appear in multiple evaluations to be worth noting
-- Use frequency terms: "common" (majority), "occasional" (several), "rare" (few)
-- Include the generation_ids of runs that match this pattern (pick 1-5 representative examples)
-
-STRUCTURED OUTPUT:
-You must return valid JSON matching this schema:
-{
- "overall_assessment": "Brief 1-2 sentence summary of evaluation quality and main findings",
- "pass_patterns": [
- {
- "title": "Clear Communication",
- "description": "Responses consistently provided clear, well-structured information",
- "frequency": "common",
- "example_generation_ids": ["gen_abc123", "gen_def456"]
- }
- ],
- "fail_patterns": [
- {
- "title": "Missing Context",
- "description": "Responses failed to consider important contextual information",
- "frequency": "occasional",
- "example_generation_ids": ["gen_xyz789"]
- }
- ],
- "na_patterns": [
- {
- "title": "Out of Scope",
- "description": "Evaluation criteria did not apply to the response type",
- "frequency": "common",
- "example_generation_ids": ["gen_qrs456", "gen_tuv789"]
- }
- ],
- "recommendations": [
- "Add more context from conversation history to improve response relevance",
- "Implement stricter validation for factual claims"
- ],
- "statistics": {
- "total_analyzed": 50,
- "pass_count": 35,
- "fail_count": 10,
- "na_count": 5
- }
-}
-
-Note: pass_patterns, fail_patterns, and na_patterns can be empty [] if no clear patterns are identified or if that category is not being analyzed.
diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary_map.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary_map.djt
deleted file mode 100644
index 09b5198d8856..000000000000
--- a/products/ai_observability/backend/summarization/prompts/evaluation_summary_map.djt
+++ /dev/null
@@ -1,40 +0,0 @@
-You are analyzing one batch from a larger AI observability evaluation. Extract evidence-rich candidate themes for a later reducer to consolidate across all batches.
-
-## Evaluation Context
-
-**Evaluation Name:** {{ evaluation_name }}
-{% if evaluation_description %}
-**Description:** {{ evaluation_description }}
-{% endif %}
-
-**Evaluation criteria:**
-```
-{{ evaluation_prompt }}
-```
-
-## Your task
-
-Partition the runs in this batch into semantically equivalent candidate themes. Each run must contribute to exactly one candidate in its result category, so occurrence counts remain additive and the number of candidates never exceeds the number of runs.
-
-For every candidate:
-- Set result to "pass", "fail", or "na" based on the runs in that candidate.
-- Include the exact number of matching runs in occurrence_count.
-- Preserve 1-3 real generation IDs and one concise representative reasoning example.
-- Keep the title concise enough for comparison with candidates from other batches.
-- Include every distinct candidate supported by the batch, even when only one run supports it. A theme that is rare locally may be common across the complete evaluation.
-
-Return at most {{ max_candidates }} candidates total.
-
-Do not write an overall assessment, recommendations, global frequency labels, or statistics. The reducer derives those from candidates across every batch.
-
-{% if filter == 'all' %}
-Extract pass, fail, and N/A candidates where present.
-{% elif filter == 'pass' %}
-Every candidate must have result "pass".
-{% elif filter == 'fail' %}
-Every candidate must have result "fail".
-{% elif filter == 'na' %}
-Every candidate must have result "na".
-{% endif %}
-
-Do not invent generation IDs or evidence that is not present in this batch.
diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary_merge.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary_merge.djt
deleted file mode 100644
index 17df141c25e5..000000000000
--- a/products/ai_observability/backend/summarization/prompts/evaluation_summary_merge.djt
+++ /dev/null
@@ -1,39 +0,0 @@
-You are an expert at analyzing AI observability evaluation results. One or more reduction steps have produced evidence-rich candidate themes. Consolidate them into a single coherent summary of the whole evaluation.
-
-## Evaluation Context
-
-**Evaluation Name:** {{ evaluation_name }}
-{% if evaluation_description %}
-**Description:** {{ evaluation_description }}
-{% endif %}
-
-**Evaluation criteria:**
-```
-{{ evaluation_prompt }}
-```
-
-## Your task
-
-You are given ground-truth statistics for the complete evaluation and candidate themes selected across all batches. Every candidate has a result category, an occurrence_count, example reasoning, and real generation IDs.
-
-Consolidate them into ONE final summary:
-- Merge candidates that describe the same underlying theme, even when their wording differs. Sum their occurrence_count values and combine representative generation IDs (keep 1-5 per pattern).
-- Judge each merged pattern's frequency from its summed occurrence count relative to the complete number of runs in that result category: "common" (majority), "occasional" (several but not a majority), or "rare" (few). Do not infer frequency from the number of batches containing it.
-- Write a single overall_assessment (1-2 sentences) reflecting the full evaluation, not any single batch.
-- Derive the 2-4 most important actionable recommendations from the merged evidence.
-
-{% if filter == 'all' %}
-Keep patterns in all three categories (pass, fail, N/A) where present.
-{% elif filter == 'pass' %}
-Only pass_patterns are relevant. Leave fail_patterns and na_patterns as empty arrays.
-{% elif filter == 'fail' %}
-Only fail_patterns are relevant. Leave pass_patterns and na_patterns as empty arrays.
-{% elif filter == 'na' %}
-Only na_patterns are relevant. Leave pass_patterns and fail_patterns as empty arrays.
-{% endif %}
-
-IMPORTANT GUIDELINES:
-- Limit to 0-4 patterns per category after merging.
-- Preserve real example_generation_ids and example reasoning from the candidates; do not invent new evidence.
-- Recommendations should be specific and actionable (2-4 total).
-- The statistics you return are not used and may be left as zeros; the caller computes the ground-truth counts.
diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary_reduce.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary_reduce.djt
deleted file mode 100644
index 344e36459831..000000000000
--- a/products/ai_observability/backend/summarization/prompts/evaluation_summary_reduce.djt
+++ /dev/null
@@ -1,21 +0,0 @@
-You are consolidating candidate themes from several batches of an AI observability evaluation. Produce a smaller set of evidence-rich candidates for another reduction step.
-
-## Evaluation context
-
-**Evaluation name:** {{ evaluation_name }}
-{% if evaluation_description %}
-**Description:** {{ evaluation_description }}
-{% endif %}
-
-**Evaluation criteria:**
-```
-{{ evaluation_prompt }}
-```
-
-## Your task
-
-Merge candidates that describe the same underlying theme, even when their wording differs. Sum occurrence_count for merged candidates and preserve 1-3 real generation IDs plus one representative reasoning example.
-
-Return at most {{ max_candidates_per_result }} candidates per result category. Every input occurrence_count must contribute to exactly one output candidate in the same result category. When distinct themes cannot all be retained, combine the lower-priority themes under a broader candidate instead of dropping their counts.
-
-Do not write an overall assessment, recommendations, frequency labels, or statistics. Do not invent generation IDs or evidence.
diff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.py
index cea85e2a75ab..8f4d3e8749ce 100644
--- a/products/ai_observability/backend/summarization/tests/test_providers.py
+++ b/products/ai_observability/backend/summarization/tests/test_providers.py
@@ -1,20 +1,10 @@
-import re
import json
-import asyncio
-from typing import Any
-from uuid import UUID
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
from rest_framework import exceptions
-from products.ai_observability.backend.summarization.constants import (
- EVALUATION_SUMMARY_MAX_RUNS,
- EVALUATION_SUMMARY_PROMPT_MAX_CHARS,
- SUMMARIZATION_TIMEOUT,
-)
-from products.ai_observability.backend.summarization.llm.evaluation_summary import summarize_evaluation_runs
from products.ai_observability.backend.summarization.llm.openai import summarize_with_openai
from products.ai_observability.backend.summarization.llm.schema import SummarizationResponse
from products.ai_observability.backend.summarization.models import OpenAIModel, SummarizationMode
@@ -167,291 +157,3 @@ class TestSummarizeWithOpenAI:
call_kwargs = mock_client.chat.completions.create.call_args[1]
assert call_kwargs["response_format"]["type"] == "json_schema"
assert call_kwargs["response_format"]["json_schema"]["strict"] is True
-
-
-def valid_evaluation_summary_json():
- return json.dumps(
- {
- "overall_assessment": "Mostly passing.",
- "pass_patterns": [],
- "fail_patterns": [],
- "na_patterns": [],
- "recommendations": [],
- "statistics": {"total_analyzed": 1, "pass_count": 1, "fail_count": 0, "na_count": 0},
- }
- )
-
-
-class TestSummarizeEvaluationRuns:
- @pytest.mark.parametrize(("user_distinct_id", "expected_distinct_id"), [("user-1", "user-1"), ("", "team-1")])
- def test_routes_through_async_gateway_builder_and_passes_timeout(
- self, valid_evaluation_summary_json, user_distinct_id, expected_distinct_id
- ):
- mock_response = MagicMock()
- mock_response.choices = [MagicMock()]
- mock_response.choices[0].message.content = valid_evaluation_summary_json
-
- with patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client"
- ) as mock_builder:
- mock_client = MagicMock()
- mock_client.chat.completions.create = AsyncMock(return_value=mock_response)
- mock_builder.return_value = mock_client
-
- result = asyncio.run(
- summarize_evaluation_runs(
- evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],
- team_id=1,
- evaluation_id="evaluation-1",
- model=OpenAIModel.GPT_4_1_MINI,
- user_distinct_id=user_distinct_id,
- )
- )
-
- mock_builder.assert_called_once()
- builder_kwargs = mock_builder.call_args.kwargs
- trace_id = UUID(builder_kwargs["trace_id"])
- session_id = UUID(builder_kwargs["session_id"])
- assert session_id != trace_id
- assert builder_kwargs["session_id"] != "evaluation-1"
- assert builder_kwargs["distinct_id"] == expected_distinct_id
- assert builder_kwargs["properties"] == {
- "team_id": "1",
- "filter_type": "all",
- "evaluation_id": "evaluation-1",
- }
- assert mock_client.chat.completions.create.call_args.kwargs["user"] == expected_distinct_id
- assert mock_client.chat.completions.create.call_args.kwargs["timeout"] == SUMMARIZATION_TIMEOUT
- assert result.overall_assessment == "Mostly passing."
-
- def test_failure_log_includes_evaluation_trace_and_session(self) -> None:
- trace_id = UUID("6f6905aa-00d2-4df7-a5e4-e1c06d934c23")
- session_id = UUID("7dfda50a-5710-45b1-97a3-30d98a07c1da")
-
- lock_context = MagicMock()
- lock_context.__aenter__ = AsyncMock(return_value=None)
- lock_context.__aexit__ = AsyncMock(return_value=None)
-
- with (
- patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary._team_generation_lock",
- return_value=lock_context,
- ),
- patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary.uuid4",
- side_effect=[trace_id, session_id],
- ),
- patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client",
- side_effect=RuntimeError("gateway unavailable"),
- ),
- patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary.logger.exception"
- ) as mock_logger_exception,
- ):
- with pytest.raises(exceptions.APIException, match="Failed to generate evaluation summary"):
- asyncio.run(
- summarize_evaluation_runs(
- evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],
- team_id=1,
- evaluation_id="evaluation-1",
- model=OpenAIModel.GPT_4_1_MINI,
- )
- )
-
- mock_logger_exception.assert_called_once_with(
- "evaluation_summary_failed",
- team_id=1,
- evaluation_id="evaluation-1",
- trace_id=str(trace_id),
- session_id=str(session_id),
- model=str(OpenAIModel.GPT_4_1_MINI),
- error="gateway unavailable",
- )
-
- def test_concurrent_requests_are_limited_per_team(self, valid_evaluation_summary_json: str) -> None:
- mock_response = MagicMock()
- mock_response.choices = [MagicMock()]
- mock_response.choices[0].message.content = valid_evaluation_summary_json
-
- async def run_summaries() -> None:
- first_call_started = asyncio.Event()
- release_first_call = asyncio.Event()
- completion_count = 0
-
- async def completion(**_kwargs: Any) -> MagicMock:
- nonlocal completion_count
- completion_count += 1
- if completion_count == 1:
- first_call_started.set()
- await release_first_call.wait()
- return mock_response
-
- with patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client"
- ) as mock_builder:
- mock_client = MagicMock()
- mock_client.chat.completions.create = AsyncMock(side_effect=completion)
- mock_builder.return_value = mock_client
-
- first_summary = asyncio.create_task(
- summarize_evaluation_runs(
- evaluation_runs=[{"generation_id": "g1", "result": True, "reasoning": "good"}],
- team_id=1,
- model=OpenAIModel.GPT_4_1_MINI,
- )
- )
- await first_call_started.wait()
-
- try:
- with pytest.raises(exceptions.Throttled, match="already being generated"):
- await summarize_evaluation_runs(
- evaluation_runs=[{"generation_id": "g2", "result": True, "reasoning": "also good"}],
- team_id=1,
- model=OpenAIModel.GPT_4_1_MINI,
- )
-
- different_team_result = await summarize_evaluation_runs(
- evaluation_runs=[{"generation_id": "g3", "result": True, "reasoning": "good"}],
- team_id=2,
- model=OpenAIModel.GPT_4_1_MINI,
- )
- assert different_team_result.overall_assessment == "Mostly passing."
- finally:
- release_first_call.set()
- await first_summary
-
- assert mock_client.chat.completions.create.await_count == 2
-
- asyncio.run(run_summaries())
-
- def test_large_run_set_bounds_every_request_and_retries_incomplete_maps(self) -> None:
- def response_with_content(content: str) -> MagicMock:
- response = MagicMock()
- response.choices = [MagicMock()]
- response.choices[0].message.content = content
- return response
-
- merged_response = response_with_content(
- json.dumps(
- {
- "overall_assessment": "The only failures were unsupported factual claims.",
- "pass_patterns": [],
- "fail_patterns": [],
- "na_patterns": [],
- "recommendations": ["Require citations for factual claims."],
- "statistics": {"total_analyzed": 0, "pass_count": 0, "fail_count": 0, "na_count": 0},
- }
- )
- )
-
- run_count = EVALUATION_SUMMARY_MAX_RUNS
- runs = [
- {
- "generation_id": f"g{i}",
- "result": i % 2 == 0,
- "reasoning": f"Distinct reasoning for run {i}. " + "r" * 2_000,
- }
- for i in range(run_count)
- ]
-
- returned_incomplete_map = False
-
- def completion_response(**kwargs: Any) -> MagicMock:
- nonlocal returned_incomplete_map
- schema_name = kwargs["response_format"]["json_schema"]["name"]
- if schema_name == "evaluation_summary":
- return merged_response
-
- user_prompt = kwargs["messages"][1]["content"]
- if schema_name == "evaluation_summary_candidates":
- if not returned_incomplete_map:
- returned_incomplete_map = True
- return response_with_content(json.dumps({"patterns": []}))
-
- prompt_runs = re.findall(r"- Generation ID: (.+)\n Result: (PASS|FAIL|N/A)", user_prompt)
- return response_with_content(
- json.dumps(
- {
- "patterns": [
- {
- "result": {"PASS": "pass", "FAIL": "fail", "N/A": "na"}[result],
- "title": f"Theme for {generation_id}".ljust(60, "x"),
- "occurrence_count": 1,
- "example_reasoning": f"Reasoning for {generation_id}".ljust(240, "r"),
- "example_generation_ids": [generation_id],
- }
- for generation_id, result in prompt_runs
- ]
- }
- )
- )
-
- candidates = json.loads(user_prompt.split("Candidate themes to consolidate:\n", 1)[1])
- reduced_candidates = []
- for result in ("pass", "fail", "na"):
- matching_candidates = [candidate for candidate in candidates if candidate["result"] == result]
- if matching_candidates:
- representative = {
- **matching_candidates[0],
- "occurrence_count": sum(candidate["occurrence_count"] for candidate in matching_candidates),
- "example_generation_ids": [
- generation_id
- for candidate in matching_candidates
- for generation_id in candidate["example_generation_ids"]
- ][:3],
- }
- reduced_candidates.append(representative)
- return response_with_content(json.dumps({"patterns": reduced_candidates}))
-
- with patch(
- "products.ai_observability.backend.summarization.llm.evaluation_summary.build_async_openai_client"
- ) as mock_builder:
- mock_client = MagicMock()
- mock_client.chat.completions.create = AsyncMock(side_effect=completion_response)
- mock_builder.return_value = mock_client
-
- result = asyncio.run(
- summarize_evaluation_runs(
- evaluation_runs=runs,
- team_id=1,
- model=OpenAIModel.GPT_4_1_MINI,
- )
- )
-
- all_calls = mock_client.chat.completions.create.await_args_list
- map_calls = [
- call
- for call in all_calls
- if call.kwargs["response_format"]["json_schema"]["name"] == "evaluation_summary_candidates"
- ]
- reduce_calls = [
- call
- for call in all_calls
- if call.kwargs["response_format"]["json_schema"]["name"] == "evaluation_summary_reduced_candidates"
- ]
-
- assert returned_incomplete_map
- assert len(map_calls) == len({call.kwargs["messages"][1]["content"] for call in map_calls}) + 1
- assert reduce_calls
- for completion_call in all_calls:
- messages = completion_call.kwargs["messages"]
- assert sum(len(message["content"]) for message in messages) <= EVALUATION_SUMMARY_PROMPT_MAX_CHARS
-
- for map_call in map_calls:
- user_prompt = map_call.kwargs["messages"][1]["content"]
- response_schema = map_call.kwargs["response_format"]["json_schema"]["schema"]
- candidate_properties = response_schema["$defs"]["EvaluationPatternCandidate"]["properties"]
-
- assert response_schema["properties"]["patterns"]["maxItems"] == user_prompt.count("- Generation ID:")
- assert candidate_properties["occurrence_count"]["maximum"] == user_prompt.count("- Generation ID:")
- assert "maxLength" in candidate_properties["title"]
- assert "maxLength" in candidate_properties["example_reasoning"]
- assert "maxItems" in candidate_properties["example_generation_ids"]
-
- merge_user_prompt = all_calls[-1].kwargs["messages"][1]["content"]
- assert f'"total_analyzed":{run_count}' in merge_user_prompt
- assert result.statistics.total_analyzed == run_count
- assert result.statistics.pass_count == run_count // 2
- assert result.statistics.fail_count == run_count // 2
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index dad452d43534..edf0e5efc41b 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -82,7 +82,7 @@ export function EvalResultBadges({
)
}
- // The trace-scoped fetch is capped at EVALUATION_SUMMARY_MAX_RUNS most-recent runs, so on a
+ // The trace-scoped fetch is capped at EVALUATION_RUNS_QUERY_LIMIT most-recent runs, so on a
// trace with very heavy eval volume older runs for a given generation can fall out of view.
const summaries = getEvalSummaries(scopeRunsToTarget(generationEvaluationRuns, generationEventId))
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 22a652020ff1..6eea8235e252 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -39,14 +39,15 @@ import { providerKeyStateIssueDescription, providerLabel } from '../settings/pro
import { EvaluationCodeEditor } from './components/EvaluationCodeEditor'
import { EvaluationPromptEditor } from './components/EvaluationPromptEditor'
import { EvaluationReportConfig } from './components/EvaluationReportConfig'
+import { EvaluationReportsCallout } from './components/EvaluationReportsCallout'
import { EvaluationReportsTab } from './components/EvaluationReportsTab'
import { EvaluationRunsTable } from './components/EvaluationRunsTable'
import { EvaluationTriggers } from './components/EvaluationTriggers'
-import { EVALUATION_PASSED_HOGQL, EVALUATION_SUMMARY_MAX_RUNS } from './constants'
+import { EVALUATION_PASSED_HOGQL, EVALUATION_RUNS_QUERY_LIMIT } from './constants'
import {
evaluationOffersSessionTarget,
evaluationSupportsReports,
- evaluationSupportsRunSummary,
+ evaluationSupportsRunOutcomes,
evaluationTypeHasEditableCriteria,
evaluationTypeUsesModelConfiguration,
isBooleanEvaluationOutput,
@@ -128,12 +129,12 @@ export function AIObservabilityEvaluation(): JSX.Element {
const effectiveStrategy: EvaluationSettleStrategy =
evaluation.target_config.strategy ?? (isSessionTarget ? 'inactivity' : 'fixed_window')
const isReportableEvaluation = evaluationSupportsReports(evaluation)
- const supportsRunSummary = evaluationSupportsRunSummary(evaluation)
+ const supportsRunOutcomes = evaluationSupportsRunOutcomes(evaluation)
const isBooleanOutput = isBooleanEvaluationOutput(evaluation.output_type)
const hasEditableCriteria = evaluationTypeHasEditableCriteria(evaluation.evaluation_type)
const trendInsightUrl =
- supportsRunSummary && !isNewEvaluation && evaluation.id
+ supportsRunOutcomes && !isNewEvaluation && evaluation.id
? urls.insightNew({
query: {
kind: NodeKind.InsightVizNode,
@@ -386,12 +387,23 @@ export function AIObservabilityEvaluation(): JSX.Element {
content: (
<div className="max-w-6xl">
<div className="flex justify-between items-center mb-4">
- <p className="text-muted text-sm m-0">
- History of when this evaluation has been executed.
- {runsSummary && runsSummary.total > EVALUATION_SUMMARY_MAX_RUNS && (
- <> The table below shows the latest {EVALUATION_SUMMARY_MAX_RUNS} runs.</>
+ <div className="min-w-0">
+ <p className="text-muted text-sm m-0">
+ History of when this evaluation has been executed.
+ {runsSummary && runsSummary.total > EVALUATION_RUNS_QUERY_LIMIT && (
+ <>
+ {' '}
+ The table below shows the latest {EVALUATION_RUNS_QUERY_LIMIT} runs.
+ </>
+ )}
+ </p>
+ {isReportableEvaluation && (
+ <EvaluationReportsCallout
+ evaluationId={evaluation.id}
+ onReportsClick={() => setActiveTab('reports')}
+ />
)}
- </p>
+ </div>
{runsSummary && (
<div className="flex flex-col items-end gap-1">
<div className="flex gap-4 text-sm">
@@ -399,7 +411,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="font-semibold text-lg">{runsSummary.total}</div>
<div className="text-muted">Total runs</div>
</div>
- {supportsRunSummary && (
+ {supportsRunOutcomes && (
<div className="text-center">
<div className="font-semibold text-lg text-success">
{runsSummary.successRate}%
@@ -407,7 +419,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="text-muted">Success rate</div>
</div>
)}
- {supportsRunSummary && evaluation.output_config.allows_na && (
+ {supportsRunOutcomes && evaluation.output_config.allows_na && (
<div className="text-center">
<div className="font-semibold text-lg">
{runsSummary.applicabilityRate}%
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportsCallout.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsCallout.test.tsx
new file mode 100644
index 000000000000..23c892547e12
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsCallout.test.tsx
@@ -0,0 +1,78 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { evaluationReportLogic } from '../evaluationReportLogic'
+import type { EvaluationReport } from '../types'
+import { EvaluationReportsCallout } from './EvaluationReportsCallout'
+
+const EVALUATION_ID = 'evaluation-123'
+
+function buildReport(enabled: boolean): EvaluationReport {
+ return {
+ id: 'report-123',
+ evaluation: EVALUATION_ID,
+ frequency: 'every_n',
+ rrule: '',
+ starts_at: null,
+ timezone_name: 'UTC',
+ next_delivery_date: null,
+ delivery_targets: [],
+ max_sample_size: 200,
+ enabled,
+ deleted: false,
+ last_delivered_at: null,
+ report_prompt_guidance: '',
+ trigger_threshold: 100,
+ cooldown_minutes: 60,
+ daily_run_cap: 10,
+ created_by: null,
+ created_at: '2026-08-14T00:00:00Z',
+ }
+}
+
+describe('EvaluationReportsCallout', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(cleanup)
+
+ it.each<[name: string, reports: EvaluationReport[], expectedVisible: boolean]>([
+ ['shows when no report is configured', [], true],
+ ['shows for a disabled report configuration', [buildReport(false)], true],
+ ['stays hidden for an enabled report configuration', [buildReport(true)], false],
+ ])('%s', async (_, reports, expectedVisible) => {
+ useMocks({
+ get: {
+ '/api/projects/:teamId/llm_analytics/evaluation_reports/': { results: reports },
+ '/api/projects/:teamId/llm_analytics/evaluation_reports/:id/runs/': { results: [] },
+ },
+ })
+ const logic = evaluationReportLogic({ evaluationId: EVALUATION_ID })
+ logic.mount()
+
+ try {
+ await expectLogic(logic).toDispatchActions(['loadReportsSuccess'])
+ render(
+ <Provider>
+ <EvaluationReportsCallout evaluationId={EVALUATION_ID} onReportsClick={jest.fn()} />
+ </Provider>
+ )
+
+ const callout = screen.queryByText(/Evaluation reports analyze these runs/)
+ if (expectedVisible) {
+ expect(callout).toBeInTheDocument()
+ } else {
+ expect(callout).not.toBeInTheDocument()
+ }
+ } finally {
+ logic.unmount()
+ }
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportsCallout.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsCallout.tsx
new file mode 100644
index 000000000000..61d45b498e94
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsCallout.tsx
@@ -0,0 +1,38 @@
+import { useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { evaluationReportLogic } from '../evaluationReportLogic'
+
+interface EvaluationReportsCalloutProps {
+ evaluationId: string
+ onReportsClick: () => void
+}
+
+export function EvaluationReportsCallout({
+ evaluationId,
+ onReportsClick,
+}: EvaluationReportsCalloutProps): JSX.Element | null {
+ const { activeReport, reportsLoading } = useValues(evaluationReportLogic({ evaluationId }))
+
+ // Hold the banner back until the schedule has resolved so anyone with enabled reports never sees it flash.
+ if (reportsLoading || activeReport?.enabled) {
+ return null
+ }
+
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
+ <span className="text-muted">
+ Evaluation reports analyze these runs and send results by email or Slack.
+ </span>
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ onClick={onReportsClick}
+ data-attr="llma-evaluation-reports-callout-cta"
+ >
+ Go to reports
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
index e054d6bb0ed2..9a687d1450b5 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconInfo } from '@posthog/icons'
-import { LemonButton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
@@ -12,7 +12,7 @@ import { EvaluationReportViewer, summarizeEvaluationReportResults } from './Eval
interface EvaluationReportsTabProps {
evaluationId: string
/** Called when the user clicks the "Set up scheduled reports" CTA in the empty state. */
- onConfigureClick?: () => void
+ onConfigureClick: () => void
}
const STATUS_STYLES: Record<
@@ -42,11 +42,9 @@ export function EvaluationReportsTab({ evaluationId, onConfigureClick }: Evaluat
Scheduled reports deliver AI-generated analysis of this evaluation's results to email or Slack
on a recurring basis.
</p>
- {onConfigureClick && (
- <LemonButton type="primary" onClick={onConfigureClick}>
- Set up scheduled reports
- </LemonButton>
- )}
+ <LemonButton type="primary" onClick={onConfigureClick}>
+ Set up scheduled reports
+ </LemonButton>
</div>
</div>
)
@@ -54,13 +52,14 @@ export function EvaluationReportsTab({ evaluationId, onConfigureClick }: Evaluat
return (
<div className="max-w-6xl">
- <div className="flex items-center justify-between mb-4">
- <p className="text-muted text-sm m-0">
+ <div className="flex items-start justify-between gap-6 mb-4">
+ <p className="min-w-0 text-muted text-sm m-0">
History of AI-generated reports for this evaluation. Click a row to expand the full report. Schedule
- and delivery targets are configured in the Configuration tab.
+ and delivery targets are configured in the <Link onClick={onConfigureClick}>Configuration tab</Link>
+ .
</p>
{activeReport && (
- <div className="flex items-center gap-2">
+ <div className="flex shrink-0 items-center gap-2">
<LemonButton
type="secondary"
size="small"
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
new file mode 100644
index 000000000000..5b1f524113ba
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
@@ -0,0 +1,41 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { llmEvaluationLogic } from '../llmEvaluationLogic'
+import { EvaluationRunsFilter } from '../types'
+
+interface FilterOption {
+ value: EvaluationRunsFilter
+ label: string
+}
+
+const BASE_FILTER_OPTIONS: FilterOption[] = [
+ { value: 'all', label: 'All' },
+ { value: 'pass', label: 'Passing' },
+ { value: 'fail', label: 'Failing' },
+]
+
+const NA_FILTER_OPTION: FilterOption = { value: 'na', label: 'N/A' }
+
+export function EvaluationRunsFilters(): JSX.Element | null {
+ const { evaluation, runsSummary, evaluationRunsFilter } = useValues(llmEvaluationLogic)
+ const { setEvaluationRunsFilter } = useActions(llmEvaluationLogic)
+
+ if (!runsSummary || runsSummary.total === 0) {
+ return null
+ }
+
+ return (
+ <LemonSegmentedButton
+ value={evaluationRunsFilter}
+ onChange={(value) => {
+ setEvaluationRunsFilter(value, evaluationRunsFilter)
+ }}
+ options={[...BASE_FILTER_OPTIONS, ...(evaluation?.output_config?.allows_na ? [NA_FILTER_OPTION] : [])]}
+ size="small"
+ // pinned: autocapture data-attr - existing dashboards depend on it
+ data-attr="llma-evaluation-summary-filter"
+ />
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index b50891fa3e2d..869b08ec5d03 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -8,10 +8,10 @@ import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { EvaluationResultTag, getEvaluationResultSortValue } from '../../components/EvaluationResultTag'
import { EvaluationRunTargetCell } from '../../components/EvaluationRunTargetCell'
-import { evaluationSupportsRunSummary } from '../evaluationCapabilities'
+import { evaluationSupportsRunOutcomes } from '../evaluationCapabilities'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import { EvaluationRun, SentimentEvaluationRunsFilter } from '../types'
-import { EvaluationSummaryControls, EvaluationSummaryPanel } from './EvaluationSummaryPanel'
+import { EvaluationRunsFilters } from './EvaluationRunsFilters'
const SENTIMENT_FILTER_OPTIONS: { value: SentimentEvaluationRunsFilter; label: string }[] = [
{ value: 'negative', label: 'Negative' },
@@ -21,14 +21,14 @@ const SENTIMENT_FILTER_OPTIONS: { value: SentimentEvaluationRunsFilter; label: s
]
function SentimentEvaluationRunsFilters(): JSX.Element {
- const { evaluationSummaryFilter } = useValues(llmEvaluationLogic)
- const { setEvaluationSummaryFilter } = useActions(llmEvaluationLogic)
+ const { evaluationRunsFilter } = useValues(llmEvaluationLogic)
+ const { setEvaluationRunsFilter } = useActions(llmEvaluationLogic)
return (
<LemonSegmentedButton
- value={evaluationSummaryFilter as SentimentEvaluationRunsFilter}
+ value={evaluationRunsFilter as SentimentEvaluationRunsFilter}
onChange={(value) => {
- setEvaluationSummaryFilter(value as SentimentEvaluationRunsFilter, evaluationSummaryFilter)
+ setEvaluationRunsFilter(value as SentimentEvaluationRunsFilter, evaluationRunsFilter)
}}
options={SENTIMENT_FILTER_OPTIONS}
size="small"
@@ -38,9 +38,9 @@ function SentimentEvaluationRunsFilters(): JSX.Element {
}
export function EvaluationRunsTable(): JSX.Element {
- const { filteredEvaluationRuns, evaluation, evaluationRunsLoading, runsLookup } = useValues(llmEvaluationLogic)
+ const { filteredEvaluationRuns, evaluation, evaluationRunsLoading } = useValues(llmEvaluationLogic)
const { refreshEvaluationRuns } = useActions(llmEvaluationLogic)
- const showSummary = evaluationSupportsRunSummary(evaluation)
+ const showOutcomeFilters = evaluationSupportsRunOutcomes(evaluation)
const showSentimentFilters = evaluation?.evaluation_type === 'sentiment'
const columns: LemonTableColumns<EvaluationRun> = [
@@ -92,8 +92,8 @@ export function EvaluationRunsTable(): JSX.Element {
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
- {showSummary ? (
- <EvaluationSummaryControls />
+ {showOutcomeFilters ? (
+ <EvaluationRunsFilters />
) : showSentimentFilters ? (
<SentimentEvaluationRunsFilters />
) : (
@@ -111,8 +111,6 @@ export function EvaluationRunsTable(): JSX.Element {
</LemonButton>
</div>
- {showSummary && <EvaluationSummaryPanel runsLookup={runsLookup} />}
-
<LemonTable
columns={columns}
dataSource={filteredEvaluationRuns}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx
deleted file mode 100644
index 4f52edd23108..000000000000
--- a/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx
+++ /dev/null
@@ -1,363 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconCheck, IconChevronDown, IconMinus, IconX } from '@posthog/icons'
-import { LemonButton, LemonSegmentedButton, Spinner, Tooltip } from '@posthog/lemon-ui'
-
-import { AccessControlAction } from 'lib/components/AccessControlAction'
-
-import { AccessControlLevel, AccessControlResourceType } from '~/types'
-
-import { llmEvaluationLogic } from '../llmEvaluationLogic'
-import {
- EvaluationPattern,
- EvaluationRun,
- EvaluationSummary,
- EvaluationSummaryFilter,
- SentimentEvaluationRunsFilter,
-} from '../types'
-import { PatternCard } from './PatternCard'
-
-type ReportPatternFilter = Exclude<EvaluationSummaryFilter, 'all' | SentimentEvaluationRunsFilter>
-
-const FILTER_LABELS: Record<Exclude<EvaluationSummaryFilter, 'all'>, string> = {
- pass: 'passing ',
- fail: 'failing ',
- na: 'N/A ',
- negative: 'negative ',
- positive: 'positive ',
- neutral: 'neutral ',
-}
-
-function getFilterLabel(filter: EvaluationSummaryFilter): string {
- return filter === 'all' ? '' : FILTER_LABELS[filter]
-}
-
-function getSummarizeTooltip(runsCount: number, filter: EvaluationSummaryFilter, hasSummary: boolean): string {
- if (runsCount === 0) {
- return 'No runs match the current filter'
- }
- const filterLabel = getFilterLabel(filter)
- const action = hasSummary ? 'Regenerate AI summary for' : 'Use AI to analyze patterns in'
- return `${action} ${runsCount} ${filterLabel}evaluation results`
-}
-
-interface FilterOption {
- value: EvaluationSummaryFilter
- label: string
-}
-
-const BASE_FILTER_OPTIONS: FilterOption[] = [
- { value: 'all', label: 'All' },
- { value: 'pass', label: 'Passing' },
- { value: 'fail', label: 'Failing' },
-]
-
-const NA_FILTER_OPTION: FilterOption = { value: 'na', label: 'N/A' }
-
-export function EvaluationSummaryControls(): JSX.Element | null {
- const {
- evaluation,
- runsSummary,
- runsToSummarizeCount,
- evaluationSummary,
- evaluationSummaryLoading,
- evaluationSummaryFilter,
- } = useValues(llmEvaluationLogic)
- const {
- generateEvaluationSummary,
- regenerateEvaluationSummary,
- setEvaluationSummaryFilter,
- trackSummarizeClicked,
- } = useActions(llmEvaluationLogic)
-
- if (!runsSummary || runsSummary.total === 0) {
- return null
- }
-
- return (
- <div className="flex items-center gap-2">
- <Tooltip title={getSummarizeTooltip(runsToSummarizeCount, evaluationSummaryFilter, !!evaluationSummary)}>
- <AccessControlAction
- resourceType={AccessControlResourceType.LlmAnalytics}
- minAccessLevel={AccessControlLevel.Editor}
- >
- <LemonButton
- type="secondary"
- onClick={() => {
- if (evaluationSummary) {
- regenerateEvaluationSummary()
- } else {
- trackSummarizeClicked()
- generateEvaluationSummary({})
- }
- }}
- size="small"
- disabled={runsToSummarizeCount === 0}
- loading={evaluationSummaryLoading}
- data-attr="llma-evaluation-summarize"
- >
- {evaluationSummary ? 'Regenerate' : 'Summarize'}
- </LemonButton>
- </AccessControlAction>
- </Tooltip>
- <LemonSegmentedButton
- value={evaluationSummaryFilter}
- onChange={(value) => {
- setEvaluationSummaryFilter(value as EvaluationSummaryFilter, evaluationSummaryFilter)
- }}
- options={[...BASE_FILTER_OPTIONS, ...(evaluation?.output_config?.allows_na ? [NA_FILTER_OPTION] : [])]}
- size="small"
- data-attr="llma-evaluation-summary-filter"
- />
- </div>
- )
-}
-
-interface EvaluationSummaryPanelProps {
- runsLookup: Record<string, EvaluationRun>
-}
-
-export function EvaluationSummaryPanel({ runsLookup }: EvaluationSummaryPanelProps): JSX.Element | null {
- const {
- runsToSummarizeCount,
- evaluationSummary,
- evaluationSummaryLoading,
- evaluationSummaryError,
- evaluationSummaryFilter,
- summaryExpanded,
- } = useValues(llmEvaluationLogic)
- const { toggleSummaryExpanded } = useActions(llmEvaluationLogic)
-
- if (evaluationSummaryLoading) {
- return (
- <div className="flex items-center justify-center py-6 border rounded-lg bg-bg-light">
- <Spinner className="text-primary" />
- <span className="ml-2 text-muted">Analyzing {runsToSummarizeCount} evaluation results...</span>
- </div>
- )
- }
-
- if (evaluationSummaryError) {
- return (
- <div className="flex items-center justify-center py-6 border rounded-lg bg-bg-light">
- <span className="text-muted text-sm">Failed to generate summary. Try again.</span>
- </div>
- )
- }
-
- if (!evaluationSummary) {
- return null
- }
-
- return (
- <div className="border rounded-lg bg-bg-light">
- <LemonButton
- fullWidth
- onClick={toggleSummaryExpanded}
- data-attr="llma-evaluation-summary-toggle"
- sideIcon={
- <IconChevronDown
- className={`text-muted transition-transform ${summaryExpanded ? '' : '-rotate-90'}`}
- />
- }
- >
- <div className="flex items-center gap-2">
- <span className="font-semibold text-sm">AI Summary</span>
- <span className="text-xs text-muted">
- {evaluationSummary.statistics.total_analyzed} runs analyzed
- </span>
- </div>
- </LemonButton>
-
- {summaryExpanded && (
- <div className="p-4 pt-0 space-y-4">
- <div>
- <p className="text-sm">{evaluationSummary.overall_assessment}</p>
- <SummaryStatistics filter={evaluationSummaryFilter} statistics={evaluationSummary.statistics} />
- </div>
-
- {evaluationSummaryFilter === 'all' && (
- <AllPatternsGrid evaluationSummary={evaluationSummary} runsLookup={runsLookup} />
- )}
-
- <FilteredPatternSection
- filter={evaluationSummaryFilter}
- evaluationSummary={evaluationSummary}
- runsLookup={runsLookup}
- />
-
- {evaluationSummary.recommendations.length > 0 && (
- <div>
- <h4 className="font-semibold mb-2 text-sm">Recommendations</h4>
- <div className="space-y-1 text-sm">
- {evaluationSummary.recommendations.map((rec, i) => (
- <div key={i}>- {rec}</div>
- ))}
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- )
-}
-
-function SummaryStatistics({
- filter,
- statistics,
-}: {
- filter: EvaluationSummaryFilter
- statistics: EvaluationSummary['statistics']
-}): JSX.Element {
- return (
- <div className="mt-1 text-xs text-muted">
- {filter === 'all' && (
- <>
- {statistics.pass_count} passed, {statistics.fail_count} failed
- {statistics.na_count > 0 && <>, {statistics.na_count} N/A</>}
- </>
- )}
- {filter === 'pass' && <>{statistics.pass_count} passing runs analyzed</>}
- {filter === 'fail' && <>{statistics.fail_count} failing runs analyzed</>}
- {filter === 'na' && <>{statistics.na_count} N/A runs analyzed</>}
- </div>
- )
-}
-
-function AllPatternsGrid({
- evaluationSummary,
- runsLookup,
-}: {
- evaluationSummary: EvaluationSummary
- runsLookup: Record<string, EvaluationRun>
-}): JSX.Element | null {
- const hasPass = evaluationSummary.pass_patterns.length > 0
- const hasFail = evaluationSummary.fail_patterns.length > 0
-
- if (!hasPass && !hasFail) {
- return null
- }
-
- return (
- <div className={`grid gap-4 ${hasPass && hasFail ? 'grid-cols-2' : 'grid-cols-1'}`}>
- {hasPass && (
- <PatternList
- patterns={evaluationSummary.pass_patterns}
- type="pass"
- label="Passing patterns"
- icon={<IconCheck className="text-success" />}
- runsLookup={runsLookup}
- />
- )}
- {hasFail && (
- <PatternList
- patterns={evaluationSummary.fail_patterns}
- type="fail"
- label="Failing patterns"
- icon={<IconX className="text-danger" />}
- runsLookup={runsLookup}
- />
- )}
- </div>
- )
-}
-
-function PatternList({
- patterns,
- type,
- label,
- icon,
- runsLookup,
-}: {
- patterns: EvaluationPattern[]
- type: 'pass' | 'fail' | 'na'
- label: string
- icon: JSX.Element
- runsLookup: Record<string, EvaluationRun>
-}): JSX.Element {
- return (
- <div>
- <h4 className="font-semibold mb-2 flex items-center gap-2 text-sm">
- {icon}
- {label}
- </h4>
- <div className="space-y-2">
- {patterns.map((pattern, i) => (
- <PatternCard key={i} pattern={pattern} type={type} runsLookup={runsLookup} />
- ))}
- </div>
- </div>
- )
-}
-
-const FILTER_CONFIG: Record<
- ReportPatternFilter,
- {
- patternsKey: 'pass_patterns' | 'fail_patterns' | 'na_patterns'
- icon: JSX.Element
- label: string
- type: 'pass' | 'fail' | 'na'
- emptyText: string
- }
-> = {
- pass: {
- patternsKey: 'pass_patterns',
- icon: <IconCheck className="text-success" />,
- label: 'Passing patterns',
- type: 'pass',
- emptyText: 'No passing patterns identified',
- },
- fail: {
- patternsKey: 'fail_patterns',
- icon: <IconX className="text-danger" />,
- label: 'Failing patterns',
- type: 'fail',
- emptyText: 'No failing patterns identified',
- },
- na: {
- patternsKey: 'na_patterns',
- icon: <IconMinus className="text-muted" />,
- label: 'N/A patterns',
- type: 'na',
- emptyText: 'No N/A patterns identified',
- },
-}
-
-function isReportPatternFilter(filter: EvaluationSummaryFilter): filter is ReportPatternFilter {
- return filter === 'pass' || filter === 'fail' || filter === 'na'
-}
-
-function FilteredPatternSection({
- filter,
- evaluationSummary,
- runsLookup,
-}: {
- filter: EvaluationSummaryFilter
- evaluationSummary: EvaluationSummary
- runsLookup: Record<string, EvaluationRun>
-}): JSX.Element | null {
- if (filter === 'all' || !isReportPatternFilter(filter)) {
- return null
- }
-
- const section = FILTER_CONFIG[filter]
- const patterns = evaluationSummary[section.patternsKey]
-
- return (
- <div>
- <h4 className="font-semibold mb-2 flex items-center gap-2 text-sm">
- {section.icon}
- {section.label}
- </h4>
- <div className="space-y-2">
- {patterns.length > 0 ? (
- patterns.map((pattern: EvaluationPattern, i: number) => (
- <PatternCard key={i} pattern={pattern} type={section.type} runsLookup={runsLookup} />
- ))
- ) : (
- <p className="text-sm text-muted">{section.emptyText}</p>
- )}
- </div>
- </div>
- )
-}
diff --git a/products/ai_observability/frontend/evaluations/components/PatternCard.tsx b/products/ai_observability/frontend/evaluations/components/PatternCard.tsx
deleted file mode 100644
index cb6593df0ebe..000000000000
--- a/products/ai_observability/frontend/evaluations/components/PatternCard.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
-import posthog from 'posthog-js'
-
-import { IconCheck, IconMinus, IconX } from '@posthog/icons'
-import { Link, Tooltip } from '@posthog/lemon-ui'
-
-import { urls } from 'scenes/urls'
-
-import { sanitizeTraceUrlSearchParams } from '../../utils'
-import { EvaluationPattern, EvaluationRun } from '../types'
-
-export interface PatternCardProps {
- pattern: EvaluationPattern
- type: 'pass' | 'fail' | 'na'
- runsLookup: Record<string, EvaluationRun>
-}
-
-export function PatternCard({ pattern, type, runsLookup }: PatternCardProps): JSX.Element {
- const { searchParams } = useValues(router)
- const traceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
- const borderClass = type === 'pass' ? 'border-success' : type === 'fail' ? 'border-danger' : 'border-muted'
- const iconClass = type === 'pass' ? 'text-success' : type === 'fail' ? 'text-danger' : 'text-muted'
- const Icon = type === 'pass' ? IconCheck : type === 'fail' ? IconX : IconMinus
-
- return (
- <div className={`border rounded-lg p-3 ${borderClass}`}>
- <div className="flex items-center gap-2 mb-2">
- <Icon className={iconClass} />
- <span className="font-semibold">{pattern.title}</span>
- <span className="text-xs text-muted bg-bg-light px-2 py-0.5 rounded">{pattern.frequency}</span>
- </div>
- <p className="text-sm text-default mb-2">{pattern.description}</p>
- {pattern.example_generation_ids.length > 0 && (
- <div className="mt-2 flex items-baseline gap-1.5 flex-wrap">
- <span className="text-xs text-muted">Generations:</span>
- {pattern.example_generation_ids.map((genId) => {
- const run = runsLookup[genId]
- if (run) {
- return (
- <Tooltip key={genId} title={run.reasoning}>
- <Link
- to={
- combineUrl(urls.aiObservabilityTrace(run.trace_id), {
- ...traceSearchParams,
- event: genId,
- tab: 'evals',
- }).url
- }
- className="text-xs font-mono text-primary hover:underline"
- data-attr="llma-evaluation-summary-example-link"
- onClick={() => {
- posthog.capture('llma evaluation summary example clicked', {
- pattern_type: type,
- pattern_title: pattern.title,
- })
- }}
- >
- {genId.slice(0, 8)}
- </Link>
- </Tooltip>
- )
- }
- return (
- <span key={genId} className="text-xs font-mono text-muted">
- {genId.slice(0, 8)}
- </span>
- )
- })}
- </div>
- )}
- </div>
- )
-}
diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.ts
index bb28ea5f0127..37f0d0609b45 100644
--- a/products/ai_observability/frontend/evaluations/constants.ts
+++ b/products/ai_observability/frontend/evaluations/constants.ts
@@ -1,6 +1,5 @@
-// Evaluation summary limits
-// This should match EVALUATION_SUMMARY_MAX_RUNS in backend/summarization/constants.py
-export const EVALUATION_SUMMARY_MAX_RUNS = 250
+// Most-recent runs fetched for an evaluation's runs table and its result badges
+export const EVALUATION_RUNS_QUERY_LIMIT = 250
// Compared against the string 'true', not `= true` or `= 1`: HogQL types $ai_evaluation_result from
// each team's own property definition, so teams that haven't registered it as Boolean extract the
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
index 5c70354423f7..64bc6c70506b 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
@@ -1,13 +1,18 @@
import {
evaluationOffersSessionTarget,
evaluationSupportsReports,
- evaluationSupportsRunSummary,
+ evaluationSupportsRunOutcomes,
} from './evaluationCapabilities'
import type { EvaluationOutputType, EvaluationTarget } from './types'
describe('evaluationCapabilities', () => {
it.each<
- [outputType: EvaluationOutputType, target: EvaluationTarget, supportsReports: boolean, supportsSummary: boolean]
+ [
+ outputType: EvaluationOutputType,
+ target: EvaluationTarget,
+ supportsReports: boolean,
+ supportsRunOutcomes: boolean,
+ ]
>([
['boolean', 'generation', true, true],
['sentiment', 'generation', true, false],
@@ -19,11 +24,11 @@ describe('evaluationCapabilities', () => {
['sentiment', 'session', false, false],
])(
'supports the expected capabilities for %s %s evaluations',
- (outputType, target, supportsReports, supportsSummary) => {
+ (outputType, target, supportsReports, supportsRunOutcomes) => {
const evaluation = { output_type: outputType, target }
expect(evaluationSupportsReports(evaluation)).toBe(supportsReports)
- expect(evaluationSupportsRunSummary(evaluation)).toBe(supportsSummary)
+ expect(evaluationSupportsRunOutcomes(evaluation)).toBe(supportsRunOutcomes)
}
)
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
index 521ac45db68a..14a94184e5ad 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -21,7 +21,7 @@ export function evaluationSupportsReports(
return REPORTABLE_OUTPUT_TYPES_BY_TARGET[evaluation.target]?.has(evaluation.output_type) ?? false
}
-export function evaluationSupportsRunSummary(
+export function evaluationSupportsRunOutcomes(
evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined
): boolean {
return evaluation?.target === 'generation' && isBooleanEvaluationOutput(evaluation.output_type)
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index fe50437e3b6c..0c1dba520d43 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -8,7 +8,6 @@ import { initKeaTests } from '~/test/init'
import type { TestHogResponseApi } from '../generated/api.schemas'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
-import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'
import { evaluationReportLogic } from './evaluationReportLogic'
import { DEFAULT_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
@@ -911,151 +910,36 @@ return result`,
})
})
- describe('evaluation summary', () => {
+ describe('runs filtering', () => {
beforeEach(() => {
logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
logic.mount()
})
- describe('evaluationSummaryFilter', () => {
+ describe('evaluationRunsFilter', () => {
it('defaults to all', async () => {
- expect(logic.values.evaluationSummaryFilter).toBe('all')
+ expect(logic.values.evaluationRunsFilter).toBe('all')
})
- it('updates when setEvaluationSummaryFilter is called', async () => {
- logic.actions.setEvaluationSummaryFilter('pass', 'all')
+ it('updates when setEvaluationRunsFilter is called', async () => {
+ logic.actions.setEvaluationRunsFilter('pass', 'all')
await expectLogic(logic).toMatchValues({
- evaluationSummaryFilter: 'pass',
- })
- })
-
- it('clears evaluationSummary when filter changes', async () => {
- // Simulate having a summary
- logic.actions.generateEvaluationSummarySuccess({
- overall_assessment: 'Test',
- pass_patterns: [],
- fail_patterns: [],
- na_patterns: [],
- recommendations: [],
- statistics: { total_analyzed: 10, pass_count: 5, fail_count: 3, na_count: 2 },
- })
-
- await expectLogic(logic).toMatchValues({
- evaluationSummary: expect.objectContaining({ overall_assessment: 'Test' }),
- })
-
- logic.actions.setEvaluationSummaryFilter('fail', 'all')
-
- await expectLogic(logic).toMatchValues({
- evaluationSummary: null,
+ evaluationRunsFilter: 'pass',
})
})
})
describe('sentiment evaluation filters', () => {
it('defaults to all for boolean evaluations', async () => {
- expect(logic.values.evaluationSummaryFilter).toBe('all')
+ expect(logic.values.evaluationRunsFilter).toBe('all')
})
it('defaults to negative for sentiment evaluations', async () => {
logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
await expectLogic(logic).toMatchValues({
- evaluationSummaryFilter: 'negative',
- })
- })
- })
-
- describe('runsToSummarizeCount', () => {
- it('returns 0 when no runs', async () => {
- expect(logic.values.runsToSummarizeCount).toBe(0)
- })
-
- it('counts all completed runs when filter is all', async () => {
- logic.actions.loadEvaluationRunsSuccess(mockRuns)
-
- await expectLogic(logic).toMatchValues({
- runsToSummarizeCount: 3,
- })
- })
-
- it('counts only passing runs when filter is pass', async () => {
- logic.actions.loadEvaluationRunsSuccess(mockRuns)
- logic.actions.setEvaluationSummaryFilter('pass', 'all')
-
- await expectLogic(logic).toMatchValues({
- runsToSummarizeCount: 1,
- })
- })
-
- it('counts only failing runs when filter is fail', async () => {
- logic.actions.loadEvaluationRunsSuccess(mockRuns)
- logic.actions.setEvaluationSummaryFilter('fail', 'all')
-
- await expectLogic(logic).toMatchValues({
- runsToSummarizeCount: 1,
- })
- })
-
- it('counts only N/A runs when filter is na', async () => {
- logic.actions.loadEvaluationRunsSuccess(mockRuns)
- logic.actions.setEvaluationSummaryFilter('na', 'all')
-
- await expectLogic(logic).toMatchValues({
- runsToSummarizeCount: 1,
- })
- })
-
- it(`caps count at ${EVALUATION_SUMMARY_MAX_RUNS}`, async () => {
- const manyRuns = Array.from({ length: EVALUATION_SUMMARY_MAX_RUNS + 50 }, (_, i) => ({
- ...mockRuns[0],
- id: `run-${i}`,
- generation_id: `gen-${i}`,
- }))
- logic.actions.loadEvaluationRunsSuccess(manyRuns)
-
- await expectLogic(logic).toMatchValues({
- runsToSummarizeCount: EVALUATION_SUMMARY_MAX_RUNS,
- })
- })
- })
-
- describe('summaryExpanded', () => {
- it('defaults to true', async () => {
- expect(logic.values.summaryExpanded).toBe(true)
- })
-
- it('toggles on toggleSummaryExpanded', async () => {
- logic.actions.toggleSummaryExpanded()
-
- await expectLogic(logic).toMatchValues({
- summaryExpanded: false,
- })
-
- logic.actions.toggleSummaryExpanded()
-
- await expectLogic(logic).toMatchValues({
- summaryExpanded: true,
- })
- })
-
- it('expands on generateEvaluationSummarySuccess', async () => {
- logic.actions.toggleSummaryExpanded() // collapse
-
- await expectLogic(logic).toMatchValues({ summaryExpanded: false })
-
- logic.actions.generateEvaluationSummarySuccess({
- overall_assessment: 'Test',
- pass_patterns: [],
- fail_patterns: [],
- na_patterns: [],
- recommendations: [],
- statistics: { total_analyzed: 10, pass_count: 5, fail_count: 3, na_count: 2 },
- })
-
- await expectLogic(logic).toMatchValues({
- summaryExpanded: true,
+ evaluationRunsFilter: 'negative',
})
})
})
@@ -1071,7 +955,7 @@ return result`,
it('returns only passing runs when filter is pass', async () => {
logic.actions.loadEvaluationRunsSuccess(mockRuns)
- logic.actions.setEvaluationSummaryFilter('pass', 'all')
+ logic.actions.setEvaluationRunsFilter('pass', 'all')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-1', result: true })],
@@ -1080,7 +964,7 @@ return result`,
it('returns only failing runs when filter is fail', async () => {
logic.actions.loadEvaluationRunsSuccess(mockRuns)
- logic.actions.setEvaluationSummaryFilter('fail', 'all')
+ logic.actions.setEvaluationRunsFilter('fail', 'all')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-2', result: false })],
@@ -1089,7 +973,7 @@ return result`,
it('returns only N/A runs when filter is na', async () => {
logic.actions.loadEvaluationRunsSuccess(mockRuns)
- logic.actions.setEvaluationSummaryFilter('na', 'all')
+ logic.actions.setEvaluationRunsFilter('na', 'all')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-3', result: null })],
@@ -1107,11 +991,10 @@ return result`,
skipped: true,
}
logic.actions.loadEvaluationRunsSuccess([...mockRuns, skippedRun])
- logic.actions.setEvaluationSummaryFilter('fail', 'all')
+ logic.actions.setEvaluationRunsFilter('fail', 'all')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-2' })],
- runsToSummarizeCount: 1,
})
})
@@ -1131,7 +1014,7 @@ return result`,
},
]
logic.actions.loadEvaluationRunsSuccess(runsWithFailed)
- logic.actions.setEvaluationSummaryFilter('pass', 'all')
+ logic.actions.setEvaluationRunsFilter('pass', 'all')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-1' })],
@@ -1150,7 +1033,7 @@ return result`,
it('returns only completed sentiment runs matching the selected filter', async () => {
logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
logic.actions.loadEvaluationRunsSuccess(mockSentimentRuns)
- logic.actions.setEvaluationSummaryFilter('positive', 'negative')
+ logic.actions.setEvaluationRunsFilter('positive', 'negative')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-positive' })],
@@ -1160,27 +1043,13 @@ return result`,
it('returns all sentiment runs when the all filter is selected', async () => {
logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
logic.actions.loadEvaluationRunsSuccess(mockSentimentRuns)
- logic.actions.setEvaluationSummaryFilter('all', 'negative')
+ logic.actions.setEvaluationRunsFilter('all', 'negative')
await expectLogic(logic).toMatchValues({
filteredEvaluationRuns: mockSentimentRuns,
})
})
})
-
- describe('runsLookup', () => {
- it('creates lookup by generation_id', async () => {
- logic.actions.loadEvaluationRunsSuccess(mockRuns)
-
- await expectLogic(logic).toMatchValues({
- runsLookup: {
- 'gen-1': expect.objectContaining({ id: 'run-1' }),
- 'gen-2': expect.objectContaining({ id: 'run-2' }),
- 'gen-3': expect.objectContaining({ id: 'run-3' }),
- },
- })
- })
- })
})
describe('hog evaluation type', () => {
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 1b44b34d5e4e..5265bd1b5888 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -16,7 +16,6 @@ import {
evaluationsPartialUpdate,
evaluationsRetrieve,
evaluationsTestHogCreate,
- llmAnalyticsEvaluationSummaryCreate,
} from '../generated/api'
import type { TestHogRequestApi, TestHogResultItemApi } from '../generated/api.schemas'
import { parsePlaygroundProviderKeyId } from '../ModelPicker'
@@ -25,11 +24,9 @@ import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmPr
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { EvaluationRunsStats, queryEvaluationRuns, queryEvaluationRunsStats } from '../utils'
import { evaluationErrorMessage } from './apiErrors'
-import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'
import {
evaluationCanResolveModel,
evaluationSupportsReports,
- evaluationSupportsRunSummary,
isBooleanEvaluationOutput,
isLLMJudgeEvaluation,
} from './evaluationCapabilities'
@@ -42,9 +39,8 @@ import type {
EvaluationConditionSet,
EvaluationConfig,
EvaluationRun,
+ EvaluationRunsFilter,
EvaluationSettleStrategy,
- EvaluationSummary,
- EvaluationSummaryFilter,
EvaluationTarget,
EvaluationTargetConfig,
EvaluationType,
@@ -151,7 +147,7 @@ function toSentimentEvaluation(evaluation: EvaluationConfig): SentimentEvaluatio
}
}
-function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationSummaryFilter): EvaluationRun[] {
+function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationRunsFilter): EvaluationRun[] {
if (filter === 'all') {
return runs
}
@@ -232,11 +228,8 @@ export interface llmEvaluationLogicValues {
evaluationLoading: boolean
evaluationProviderKeyIssue: LLMProviderKey | null
evaluationRuns: EvaluationRun[]
+ evaluationRunsFilter: EvaluationRunsFilter
evaluationRunsLoading: boolean
- evaluationSummary: EvaluationSummary | null
- evaluationSummaryError: boolean
- evaluationSummaryFilter: EvaluationSummaryFilter
- evaluationSummaryLoading: boolean
filteredEvaluationRuns: EvaluationRun[]
formValid: boolean
hasUnsavedChanges: boolean
@@ -248,7 +241,6 @@ export interface llmEvaluationLogicValues {
maxContext: MaxContextInput[]
modelSelectionRequired: boolean
originalEvaluation: EvaluationConfig | null
- runsLookup: Record<string, EvaluationRun>
runsStats: EvaluationRunsStats | null
runsStatsLoading: boolean
runsSummary: {
@@ -259,10 +251,8 @@ export interface llmEvaluationLogicValues {
successRate: number
total: number
} | null
- runsToSummarizeCount: number
selectedModel: string
selectedPickerProviderKeyId: string | null
- summaryExpanded: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -278,27 +268,6 @@ export interface llmEvaluationLogicActions {
clearHogTestResults: () => {
value: true
}
- generateEvaluationSummary: ({ forceRefresh }: { forceRefresh?: boolean }) => {
- forceRefresh?: boolean
- }
- generateEvaluationSummaryFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- generateEvaluationSummarySuccess: (
- evaluationSummary: EvaluationSummary | null,
- payload?: {
- forceRefresh?: boolean
- }
- ) => {
- evaluationSummary: EvaluationSummary | null
- payload?: {
- forceRefresh?: boolean
- }
- }
loadEvaluation: () => {
value: true
}
@@ -342,9 +311,6 @@ export interface llmEvaluationLogicActions {
refreshEvaluationRuns: () => {
value: true
}
- regenerateEvaluationSummary: () => {
- value: true
- }
resetEvaluation: () => {
value: true
}
@@ -382,12 +348,12 @@ export interface llmEvaluationLogicActions {
setEvaluationPrompt: (prompt: string) => {
prompt: string
}
- setEvaluationSummaryFilter: (
- filter: EvaluationSummaryFilter,
- previousFilter: EvaluationSummaryFilter
+ setEvaluationRunsFilter: (
+ filter: EvaluationRunsFilter,
+ previousFilter: EvaluationRunsFilter
) => {
- filter: EvaluationSummaryFilter
- previousFilter: EvaluationSummaryFilter
+ filter: EvaluationRunsFilter
+ previousFilter: EvaluationRunsFilter
}
setEvaluationTarget: (target: EvaluationTarget) => {
target: EvaluationTarget
@@ -425,12 +391,6 @@ export interface llmEvaluationLogicActions {
hogTestResults: TestHogResultItemApi[] | null
payload?: void
}
- toggleSummaryExpanded: () => {
- value: true
- }
- trackSummarizeClicked: () => {
- value: true
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -454,7 +414,6 @@ export interface llmEvaluationLogicMeta {
evaluation: EvaluationConfig | null,
providerKeys: LLMProviderKey[]
) => LLMProviderKey | null
- runsLookup: (evaluationRuns: EvaluationRun[]) => Record<string, EvaluationRun>
runsSummary: (runsStats: EvaluationRunsStats | null) => {
applicabilityRate: number
errors: number
@@ -465,12 +424,8 @@ export interface llmEvaluationLogicMeta {
} | null
filteredEvaluationRuns: (
evaluationRuns: EvaluationRun[],
- evaluationSummaryFilter: EvaluationSummaryFilter
+ evaluationRunsFilter: EvaluationRunsFilter
) => EvaluationRun[]
- runsToSummarizeCount: (
- filteredEvaluationRuns: EvaluationRun[],
- evaluationSummaryFilter: EvaluationSummaryFilter
- ) => number
breadcrumbs: (
evaluation: EvaluationConfig | null,
isNewEvaluation: boolean,
@@ -547,14 +502,11 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
clearHogTestResults: true,
setHogTestMessage: (message: string | null) => ({ message }),
- // Evaluation summary actions
- setEvaluationSummaryFilter: (filter: EvaluationSummaryFilter, previousFilter: EvaluationSummaryFilter) => ({
+ // Runs table actions
+ setEvaluationRunsFilter: (filter: EvaluationRunsFilter, previousFilter: EvaluationRunsFilter) => ({
filter,
previousFilter,
}),
- toggleSummaryExpanded: true,
- regenerateEvaluationSummary: true,
- trackSummarizeClicked: true,
}),
loaders(({ props, values, actions }) => ({
@@ -643,45 +595,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
},
},
],
- evaluationSummary: [
- null as EvaluationSummary | null,
- {
- generateEvaluationSummary: async ({ forceRefresh }: { forceRefresh?: boolean }) => {
- const shouldRefresh = forceRefresh ?? false
- const teamId = teamLogic.values.currentTeamId
- if (!teamId || !props.evaluationId || props.evaluationId === 'new') {
- return null
- }
- if (!evaluationSupportsRunSummary(values.evaluation)) {
- return null
- }
-
- const requestFilter = values.evaluationSummaryFilter
- if (
- requestFilter !== 'all' &&
- requestFilter !== 'pass' &&
- requestFilter !== 'fail' &&
- requestFilter !== 'na'
- ) {
- return null
- }
-
- // Backend fetches data server-side by ID - we just pass the filter
- const response = await llmAnalyticsEvaluationSummaryCreate(teamId.toString(), {
- evaluation_id: props.evaluationId,
- filter: requestFilter,
- force_refresh: shouldRefresh,
- })
-
- // Discard if the user changed the filter while the request was in flight
- if (values.evaluationSummaryFilter !== requestFilter) {
- return null
- }
-
- return response as EvaluationSummary
- },
- },
- ],
})),
reducers({
@@ -848,34 +761,14 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
resetEvaluation: () => false,
},
],
- evaluationSummaryFilter: [
- 'all' as EvaluationSummaryFilter,
+ evaluationRunsFilter: [
+ 'all' as EvaluationRunsFilter,
{
- setEvaluationSummaryFilter: (_, { filter }) => filter,
+ setEvaluationRunsFilter: (_, { filter }) => filter,
loadEvaluationSuccess: (_, { evaluation }) =>
evaluation?.evaluation_type === 'sentiment' ? DEFAULT_SENTIMENT_RUNS_FILTER : 'all',
},
],
- // Clear summary when filter changes so stale summary doesn't mismatch current filter
- evaluationSummary: {
- setEvaluationSummaryFilter: () => null,
- },
- evaluationSummaryError: [
- false,
- {
- generateEvaluationSummary: () => false,
- generateEvaluationSummarySuccess: () => false,
- generateEvaluationSummaryFailure: () => true,
- setEvaluationSummaryFilter: () => false,
- },
- ],
- summaryExpanded: [
- true,
- {
- toggleSummaryExpanded: (state) => !state,
- generateEvaluationSummarySuccess: () => true,
- },
- ],
activeTab: [
'configuration' as string,
{
@@ -984,35 +877,14 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
actions.loadRunsStats()
},
- regenerateEvaluationSummary: () => {
- posthog.capture('llma evaluation regenerate clicked', {
- filter: values.evaluationSummaryFilter,
- runs_to_summarize: values.runsToSummarizeCount,
- })
- actions.generateEvaluationSummary({ forceRefresh: true })
- },
-
- trackSummarizeClicked: () => {
- posthog.capture('llma evaluation summarize clicked', {
- filter: values.evaluationSummaryFilter,
- runs_to_summarize: values.runsToSummarizeCount,
- })
- },
-
- setEvaluationSummaryFilter: ({ filter, previousFilter }) => {
+ setEvaluationRunsFilter: ({ filter, previousFilter }) => {
+ // pinned: analytics event name - renaming it breaks existing dashboards
posthog.capture('llma evaluation summary filter changed', {
filter,
previous_filter: previousFilter,
})
},
- toggleSummaryExpanded: () => {
- posthog.capture('llma evaluation summary toggled', {
- expanded: values.summaryExpanded,
- filter: values.evaluationSummaryFilter,
- })
- },
-
resetEvaluation: () => {
// Reset any pending report-config draft alongside the evaluation so
// Cancel/Back clears both forms (the report draft lives in a separate
@@ -1115,9 +987,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
// Piggyback the scheduled-report draft onto the main save so the single
- // "Save changes" button at the top of the page commits both forms. The
- // evaluationReportLogic is only mounted when EvaluationReportConfig is
- // rendered (gated on the reports feature flag), so skip when it isn't —
+ // "Save changes" button at the top of the page commits both forms. Only
+ // the components that render the report config or history mount
+ // evaluationReportLogic, so skip when none of them is on screen —
// reading .values on an unmounted keyed logic would throw.
if (response?.id && evaluationSupportsReports(response) && reportLogic.isMounted()) {
const reportConfigStillLoading =
@@ -1260,19 +1132,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
},
],
- runsLookup: [
- (s) => [s.evaluationRuns],
- (runs: EvaluationRun[]): Record<string, EvaluationRun> => {
- const lookup: Record<string, EvaluationRun> = {}
- for (const run of runs) {
- if (run.generation_id) {
- lookup[run.generation_id] = run
- }
- }
- return lookup
- },
- ],
-
runsSummary: [
(s) => [s.runsStats],
(stats: EvaluationRunsStats | null) => {
@@ -1296,21 +1155,11 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
],
filteredEvaluationRuns: [
- (s) => [s.evaluationRuns, s.evaluationSummaryFilter],
- (runs: EvaluationRun[], filter: EvaluationSummaryFilter): EvaluationRun[] =>
+ (s) => [s.evaluationRuns, s.evaluationRunsFilter],
+ (runs: EvaluationRun[], filter: EvaluationRunsFilter): EvaluationRun[] =>
filterEvaluationRuns(runs, filter),
],
- runsToSummarizeCount: [
- (s) => [s.filteredEvaluationRuns, s.evaluationSummaryFilter],
- (filteredRuns: EvaluationRun[], filter: EvaluationSummaryFilter): number => {
- // When 'all', filteredEvaluationRuns includes non-completed runs, but summarization only uses completed
- const count =
- filter === 'all' ? filteredRuns.filter((r) => r.status === 'completed').length : filteredRuns.length
- return Math.min(count, EVALUATION_SUMMARY_MAX_RUNS)
- },
- ],
-
breadcrumbs: [
(s) => [s.evaluation, s.isNewEvaluation, s.evaluationBackTarget, router.selectors.searchParams],
(
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index e98c1dc0d12b..ec3c2ab6dde3 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -187,27 +187,4 @@ export type EvaluationReportRunContent = EvaluationReportRunContentApi
export type EvaluationReportRun = EvaluationReportRunApi
export type SentimentEvaluationRunsFilter = 'negative' | 'positive' | 'neutral' | 'all'
-export type EvaluationSummaryFilter = 'pass' | 'fail' | 'na' | SentimentEvaluationRunsFilter
-
-export interface EvaluationPattern {
- title: string
- description: string
- frequency: string
- example_generation_ids: string[]
-}
-
-export interface EvaluationSummaryStatistics {
- total_analyzed: number
- pass_count: number
- fail_count: number
- na_count: number
-}
-
-export interface EvaluationSummary {
- overall_assessment: string
- pass_patterns: EvaluationPattern[]
- fail_patterns: EvaluationPattern[]
- na_patterns: EvaluationPattern[]
- recommendations: string[]
- statistics: EvaluationSummaryStatistics
-}
+export type EvaluationRunsFilter = 'pass' | 'fail' | 'na' | SentimentEvaluationRunsFilter
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 5812ec3b66be..846c023732ce 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1785,80 +1785,6 @@ export interface PaginatedEvaluationReportRunListApi {
results: EvaluationReportRunApi[]
}
-/**
- * * `all` - all
- * * `pass` - pass
- * * `fail` - fail
- * * `na` - na
- */
-export type FilterEnumApi = (typeof FilterEnumApi)[keyof typeof FilterEnumApi]
-
-export const FilterEnumApi = {
- All: 'all',
- Pass: 'pass',
- Fail: 'fail',
- Na: 'na',
-} as const
-
-/**
- * Request serializer for evaluation summary - accepts IDs only, fetches data server-side.
- */
-export interface EvaluationSummaryRequestApi {
- /** UUID of the evaluation config to summarize */
- evaluation_id: string
- /** Filter type to apply ('all', 'pass', 'fail', or 'na')
- *
- * * `all` - all
- * * `pass` - pass
- * * `fail` - fail
- * * `na` - na */
- filter?: FilterEnumApi
- /**
- * Optional: specific generation IDs to include in summary (max 250)
- * @maxItems 250
- */
- generation_ids?: string[]
- /** If true, bypass cache and generate a fresh summary */
- force_refresh?: boolean
-}
-
-export interface EvaluationPatternApi {
- title: string
- description: string
- frequency: string
- example_generation_ids: string[]
-}
-
-export interface EvaluationSummaryStatisticsApi {
- total_analyzed: number
- pass_count: number
- fail_count: number
- na_count: number
-}
-
-export interface EvaluationSummaryResponseApi {
- overall_assessment: string
- pass_patterns: EvaluationPatternApi[]
- fail_patterns: EvaluationPatternApi[]
- na_patterns: EvaluationPatternApi[]
- recommendations: string[]
- statistics: EvaluationSummaryStatisticsApi
-}
-
-export interface EvaluationSummaryThrottleResponseApi {
- /** Error category */
- type: string
- /** Machine-readable error code */
- code: string
- /** Why the request was throttled */
- detail: string
- /**
- * Related request field, when applicable
- * @nullable
- */
- attr: string | null
-}
-
export interface LLMModelInfoApi {
/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */
id: string
@@ -3312,14 +3238,6 @@ export type LlmAnalyticsEvaluationReportsRunsListParams = {
offset?: number
}
-export type LlmAnalyticsEvaluationSummaryCreate400 = { [key: string]: unknown }
-
-export type LlmAnalyticsEvaluationSummaryCreate403 = { [key: string]: unknown }
-
-export type LlmAnalyticsEvaluationSummaryCreate404 = { [key: string]: unknown }
-
-export type LlmAnalyticsEvaluationSummaryCreate500 = { [key: string]: unknown }
-
export type LlmAnalyticsModelsRetrieveParams = {
/**
* Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). Must belong to the same provider as the `provider` parameter.
diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.ts
index 0e2a180ace87..3eec1ad28204 100644
--- a/products/ai_observability/frontend/generated/api.ts
+++ b/products/ai_observability/frontend/generated/api.ts
@@ -37,8 +37,6 @@ import type {
EvaluationReportUpdateApi,
EvaluationRunRequestApi,
EvaluationRunsCreate200,
- EvaluationSummaryRequestApi,
- EvaluationSummaryResponseApi,
EvaluationsListParams,
LLMModelsListResponseApi,
LLMPromptApi,
@@ -1213,39 +1211,6 @@ export const llmAnalyticsEvaluationReportsRunsList = async (
)
}
-export const getLlmAnalyticsEvaluationSummaryCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/llm_analytics/evaluation_summary/`
-}
-
-/**
- *
- * Generate an AI-powered summary of evaluation results.
- *
- * This endpoint analyzes evaluation runs and identifies patterns in passing
- * and failing evaluations, providing actionable recommendations.
- *
- * Data is fetched server-side by evaluation ID to ensure data integrity.
- *
- * **Use Cases:**
- * - Understand why evaluations are passing or failing
- * - Identify systematic issues in LLM responses
- * - Get recommendations for improving response quality
- * - Review patterns across many evaluation runs at once
- *
- */
-export const llmAnalyticsEvaluationSummaryCreate = async (
- projectId: string,
- evaluationSummaryRequestApi: EvaluationSummaryRequestApi,
- options?: RequestInit
-): Promise<EvaluationSummaryResponseApi> => {
- return apiMutator<EvaluationSummaryResponseApi>(getLlmAnalyticsEvaluationSummaryCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(evaluationSummaryRequestApi),
- })
-}
-
export const getLlmAnalyticsModelsRetrieveUrl = (projectId: string, params: LlmAnalyticsModelsRetrieveParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index e6cfd6d82e6e..09fa62559d15 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -1294,49 +1294,6 @@ export const LlmAnalyticsEvaluationReportsPartialUpdateBody = /* @__PURE__ */ zo
),
})
-/**
- *
- * Generate an AI-powered summary of evaluation results.
- *
- * This endpoint analyzes evaluation runs and identifies patterns in passing
- * and failing evaluations, providing actionable recommendations.
- *
- * Data is fetched server-side by evaluation ID to ensure data integrity.
- *
- * **Use Cases:**
- * - Understand why evaluations are passing or failing
- * - Identify systematic issues in LLM responses
- * - Get recommendations for improving response quality
- * - Review patterns across many evaluation runs at once
- *
- */
-export const llmAnalyticsEvaluationSummaryCreateBodyFilterDefault = `all`
-export const llmAnalyticsEvaluationSummaryCreateBodyGenerationIdsMax = 250
-
-export const llmAnalyticsEvaluationSummaryCreateBodyForceRefreshDefault = false
-
-export const LlmAnalyticsEvaluationSummaryCreateBody = /* @__PURE__ */ zod
- .object({
- evaluation_id: zod.uuid().describe('UUID of the evaluation config to summarize'),
- filter: zod
- .enum(['all', 'pass', 'fail', 'na'])
- .describe('\* `all` - all\n\* `pass` - pass\n\* `fail` - fail\n\* `na` - na')
- .default(llmAnalyticsEvaluationSummaryCreateBodyFilterDefault)
- .describe(
- "Filter type to apply ('all', 'pass', 'fail', or 'na')\n\n\* `all` - all\n\* `pass` - pass\n\* `fail` - fail\n\* `na` - na"
- ),
- generation_ids: zod
- .array(zod.uuid())
- .max(llmAnalyticsEvaluationSummaryCreateBodyGenerationIdsMax)
- .optional()
- .describe('Optional: specific generation IDs to include in summary (max 250)'),
- force_refresh: zod
- .boolean()
- .default(llmAnalyticsEvaluationSummaryCreateBodyForceRefreshDefault)
- .describe('If true, bypass cache and generate a fresh summary'),
- })
- .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
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index a2684f0b6f1d..e2977061627d 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -11,7 +11,7 @@ import type { SpanAggregation } from './aiObservabilityTraceDataLogic'
import {
EVALUATION_NOT_SKIPPED_HOGQL,
EVALUATION_PASSED_HOGQL,
- EVALUATION_SUMMARY_MAX_RUNS,
+ EVALUATION_RUNS_QUERY_LIMIT,
} from './evaluations/constants'
import type { EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'
import {
@@ -1187,7 +1187,7 @@ export async function queryEvaluationRuns(params: {
AND ${hogql.raw(`properties.${propertyName}`)} = ${propertyValue}
${lookbackDays ? hogql.raw(`AND timestamp >= now() - INTERVAL ${Math.floor(lookbackDays)} DAY`) : hogql.raw('')}
ORDER BY timestamp DESC
- LIMIT ${EVALUATION_SUMMARY_MAX_RUNS}
+ LIMIT ${EVALUATION_RUNS_QUERY_LIMIT}
`
const response = await api.queryHogQL(
@@ -1206,7 +1206,7 @@ export interface EvaluationRunsStats {
}
// Counts every matching run server-side. queryEvaluationRuns caps its fetch at
-// EVALUATION_SUMMARY_MAX_RUNS, so summary stats can't be derived from that list without
+// EVALUATION_RUNS_QUERY_LIMIT, so summary stats can't be derived from that list without
// undercounting. Counting semantics mirror the evaluations list view (evaluationMetricsLogic)
// so both surfaces report the same totals.
export async function queryEvaluationRunsStats(params: {
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index 9effb93f0b11..532b4ca5ccfa 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -753,24 +753,6 @@ tools:
asynchronously executes the evaluation and stores the result as a '$ai_evaluation' event. Returns a
workflow_id and status "started". Pair with execute-sql to query results: SELECT * FROM events WHERE event =
'$ai_evaluation'.
- llma-evaluation-summary-create:
- operation: llm_analytics_evaluation_summary_create
- enabled: true
- scopes:
- - llm_analytics:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: true
- title: Summarize evaluation results
- description: >
- Generate an AI-powered summary of boolean AI observability evaluation results for a given evaluation config.
- Pass an evaluation_id and an optional filter ("all", "pass", "fail", or "na") to scope which runs are
- analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title,
- description, frequency, and example generation IDs), actionable recommendations, and run statistics.
- Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour —
- use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.
- requires_ai_consent: true
llma-evaluation-test-hog:
operation: evaluations_test_hog_create
enabled: true
diff --git a/products/ai_observability/skills/exploring-ai-failures/SKILL.md b/products/ai_observability/skills/exploring-ai-failures/SKILL.md
index 0c7c595427cd..e62786eaa18a 100644
--- a/products/ai_observability/skills/exploring-ai-failures/SKILL.md
+++ b/products/ai_observability/skills/exploring-ai-failures/SKILL.md
@@ -32,14 +32,13 @@ high volume, `exploring-llm-clusters`.
## Tools
-| Tool | Purpose |
-| ---------------------------------------- | ------------------------------------------------------------------------ |
-| `posthog:query-llm-traces-list` | List candidate traces — filter by error, sort by a metric, scope by type |
-| `posthog:query-llm-trace` | Read a trace in full to see what actually went wrong |
-| `posthog:execute-sql` | Find metric outliers, discover the trace taxonomy, count failure modes |
-| `posthog:llma-evaluation-list` | Find existing evals whose failures might reveal a new mode |
-| `posthog:llma-evaluation-summary-create` | Summarize an existing eval's failures into patterns |
-| `posthog:generate-app-url` | Build a region- and project-qualified deep link to a trace or list |
+| Tool | Purpose |
+| ------------------------------- | ------------------------------------------------------------------------ |
+| `posthog:query-llm-traces-list` | List candidate traces — filter by error, sort by a metric, scope by type |
+| `posthog:query-llm-trace` | Read a trace in full to see what actually went wrong |
+| `posthog:execute-sql` | Find metric outliers, discover the trace taxonomy, count failure modes |
+| `posthog:llma-evaluation-list` | Find existing evals whose failures might reveal a new mode |
+| `posthog:generate-app-url` | Build a region- and project-qualified deep link to a trace or list |
Detailed queries for each strategy below are in
[references/finding-traces.md](references/finding-traces.md). The full `$ai_*` event schema (and the
@@ -79,7 +78,7 @@ signals you have, and combine them:
- **Stratified sample** — when you have no specific signal (the common case), pull a mixed batch across
slices and outcomes and read it. This is the default, not the fallback.
- **Existing-eval spikes** — when evals already run, a jump in an eval's failures points you at traces to
- read (`llma-evaluation-list` + `llma-evaluation-summary-create`).
+ read (`llma-evaluation-list` + `execute-sql` over the `$ai_evaluation` events).
- **Clustering** — at high volume, let groupings emerge to pick representative traces to read; see
`exploring-llm-clusters`.
diff --git a/products/ai_observability/skills/exploring-ai-failures/references/finding-traces.md b/products/ai_observability/skills/exploring-ai-failures/references/finding-traces.md
index 4b4db90c0193..ffea1abeacce 100644
--- a/products/ai_observability/skills/exploring-ai-failures/references/finding-traces.md
+++ b/products/ai_observability/skills/exploring-ai-failures/references/finding-traces.md
@@ -68,12 +68,11 @@ Then `query-llm-trace` on each. Reading ~20–30 across a use case usually surfa
## Existing-eval spikes
-A jump in an existing eval's failures often exposes a new problem. Summarize the failures, then confirm
-the spike with a daily count:
+A jump in an existing eval's failures often exposes a new problem. Find the eval, then confirm the spike
+with a daily count and read the failing runs:
```json
posthog:llma-evaluation-list { "enabled": true }
-posthog:llma-evaluation-summary-create { "evaluation_id": "<uuid>", "filter": "fail" }
```
```sql
diff --git a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
index f2d80a53c060..eaef6f08884f 100644
--- a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
@@ -4,11 +4,12 @@ description: >
Investigate AI observability evaluations — `hog` (deterministic code-based),
`llm_judge` (LLM-prompt-based), and `sentiment` (user-message sentiment).
Find existing evaluations, inspect their configuration, run them against
- specific generations, query individual results, and generate AI-powered
- summaries for boolean pass/fail runs. Use when the user asks to debug why an
- evaluation is failing, surface common failure modes, compare results across
- filters, dry-run a Hog evaluator, prototype a new LLM-judge prompt, inspect
- sentiment classifications, or manage the evaluation lifecycle.
+ specific generations, query individual results, and set up scheduled reports
+ on an evaluation.
+ Use when the user asks to debug why an evaluation is failing, surface common
+ failure modes, compare results across filters, dry-run a Hog evaluator,
+ prototype a new LLM-judge prompt, inspect sentiment classifications, or manage
+ the evaluation lifecycle.
---
# Exploring AI observability evaluations
@@ -33,23 +34,25 @@ evaluations (`llm_judge` and `hog`) set `$ai_evaluation_result`; sentiment
evaluations set `$ai_sentiment_*` properties instead.
This skill covers the full lifecycle: list/inspect/manage evaluation configs, run
-them on specific generations, query individual results, and get an AI-generated
-summary of pass/fail/N/A patterns across many boolean runs.
+them on specific generations, query individual results, and configure evaluation
+reports that summarize recent runs on a schedule.
## Tools
-| Tool | Purpose |
-| ---------------------------------------- | -------------------------------------------------------------- |
-| `posthog:llma-evaluation-list` | List/search evaluation configs (filter by name, enabled flag) |
-| `posthog:llma-evaluation-get` | Get a single evaluation config by UUID |
-| `posthog:llma-evaluation-create` | Create a new `llm_judge`, `hog`, or `sentiment` evaluation |
-| `posthog:llma-evaluation-update` | Update an existing evaluation (name, prompt, enabled, …) |
-| `posthog:llma-evaluation-delete` | Soft-delete an evaluation |
-| `posthog:llma-evaluation-run` | Run an evaluation against a specific `$ai_generation` event |
-| `posthog:llma-evaluation-test-hog` | Dry-run Hog source against recent generations (no save) |
-| `posthog:llma-evaluation-summary-create` | AI-powered summary of pass/fail/N/A patterns across runs |
-| `posthog:execute-sql` | Ad-hoc HogQL over `$ai_evaluation` events |
-| `posthog:query-llm-trace` | Drill into the underlying generation that an evaluation scored |
+| Tool | Purpose |
+| ----------------------------------------- | -------------------------------------------------------------- |
+| `posthog:llma-evaluation-list` | List/search evaluation configs (filter by name, enabled flag) |
+| `posthog:llma-evaluation-get` | Get a single evaluation config by UUID |
+| `posthog:llma-evaluation-create` | Create a new `llm_judge`, `hog`, or `sentiment` evaluation |
+| `posthog:llma-evaluation-update` | Update an existing evaluation (name, prompt, enabled, …) |
+| `posthog:llma-evaluation-delete` | Soft-delete an evaluation |
+| `posthog:llma-evaluation-run` | Run an evaluation against a specific `$ai_generation` event |
+| `posthog:llma-evaluation-test-hog` | Dry-run Hog source against recent generations (no save) |
+| `posthog:llma-evaluation-report-list` | List the report configs attached to an evaluation |
+| `posthog:llma-evaluation-report-create` | Schedule an AI report on an evaluation (email or Slack) |
+| `posthog:llma-evaluation-report-run-list` | Past report runs, including the report content that was sent |
+| `posthog:execute-sql` | Ad-hoc HogQL over `$ai_evaluation` events |
+| `posthog:query-llm-trace` | Drill into the underlying generation that an evaluation scored |
All `llma-evaluation-*` tools are defined in `products/ai_observability/mcp/tools.yaml`.
@@ -95,54 +98,36 @@ Look at the returned `id`, `name`, `evaluation_type`, and either:
The Hog source is the ground truth for why a hog evaluator passes or fails — read it
before assuming the failure is in the generation.
-### Step 2 — Get the AI-generated summary
+### Step 2 — Break down pass, fail, and N/A
-```json
-posthog:llma-evaluation-summary-create
-{
- "evaluation_id": "<uuid>",
- "filter": "fail"
-}
-```
-
-Returns:
-
-- `overall_assessment` — natural-language summary
-- `fail_patterns` — grouped patterns with `title`, `description`, `frequency`, and `example_generation_ids`
-- `pass_patterns` and `na_patterns` — same shape, populated when `filter` includes them
-- `recommendations` — actionable next steps
-- `statistics` — `total_analyzed`, `pass_count`, `fail_count`, `na_count`
-
-The endpoint analyses the most recent ~250 runs (`EVALUATION_SUMMARY_MAX_RUNS`).
-Results are cached for one hour per `(evaluation_id, filter, set_of_generation_ids)`.
-Pass `force_refresh: true` to recompute.
-
-**Compare filters in two calls** to spot what's distinctive about failures vs passes:
-
-```json
-posthog:llma-evaluation-summary-create
-{ "evaluation_id": "<uuid>", "filter": "pass" }
+```sql
+posthog:execute-sql
+SELECT
+ countIf(properties.$ai_evaluation_applicable = false) AS na_count,
+ countIf(
+ (properties.$ai_evaluation_applicable IS NULL
+ OR properties.$ai_evaluation_applicable != false)
+ AND properties.$ai_evaluation_result = true
+ ) AS pass_count,
+ countIf(
+ (properties.$ai_evaluation_applicable IS NULL
+ OR properties.$ai_evaluation_applicable != false)
+ AND properties.$ai_evaluation_result = false
+ ) AS fail_count
+FROM events
+WHERE event = '$ai_evaluation'
+ AND properties.$ai_evaluation_id = '<evaluation_uuid>'
+ AND timestamp >= now() - INTERVAL 7 DAY
```
-Then diff the `pass_patterns` against the `fail_patterns` from Step 2.
-
-### Step 3 — Drill into example failing runs
-
-Each pattern surfaces `example_generation_ids`. Pull the underlying trace for the most
-representative example:
+If the evaluation already has report configs, `llma-evaluation-report-list` and
+`llma-evaluation-report-run-list` give you the AI-written reports from earlier
+periods, which is a fast way to see how the picture has moved.
-```json
-posthog:query-llm-trace
-{ "traceId": "<trace_id>", "dateRange": {"date_from": "-30d"} }
-```
-
-(If you only have a generation ID, query for it via `execute-sql` first to find the
-parent trace ID — see below.)
+### Step 3 — Read the failing runs
-### Step 4 — Verify the pattern with raw SQL
-
-The summary is LLM-generated and should be verified. Use `execute-sql` to count and
-spot-check:
+The reasoning text is where the pattern shows up. Pull the recent fails and read
+them:
```sql
posthog:execute-sql
@@ -167,6 +152,18 @@ LIMIT 25
The N/A guard (`IS NULL OR != false`) is important — it matches the same logic the
backend uses to bucket runs.
+### Step 4 — Drill into example failing runs
+
+Take the most representative rows from Step 3 and pull the underlying trace:
+
+```json
+posthog:query-llm-trace
+{ "traceId": "<trace_id>", "dateRange": {"date_from": "-30d"} }
+```
+
+(If you only have a generation ID, query for it via `execute-sql` first to find the
+parent trace ID.)
+
## Workflow: run an evaluation against a specific generation
Use this when the user pastes a trace/generation URL and asks "what would evaluation X
@@ -277,8 +274,7 @@ LLM judges require organisation AI data processing approval. Hog evaluators do n
| Remove | `llma-evaluation-delete` (soft-delete via PATCH `{deleted: true}`) |
`llm_judge` evaluations require AI data processing approval at the org level
-(`is_ai_data_processing_approved`). The same gate applies to
-`llma-evaluation-summary-create`. Hog evaluations do **not** require this gate
+(`is_ai_data_processing_approved`). Hog evaluations do **not** require this gate
— they run as plain code on the ingestion pipeline.
## When to use Hog vs LLM judge
@@ -301,9 +297,9 @@ the Hog gate (via `conditions`).
## Investigation patterns
-The summarisation tool works the same way regardless of whether the evaluator is `hog`
-or `llm_judge` — it analyses the resulting `$ai_evaluation` events, not the evaluator
-itself. The fix path differs (edit Hog source vs. edit prompt) but the diagnosis is
+Diagnosis works the same way regardless of whether the evaluator is `hog` or
+`llm_judge` — you read the resulting `$ai_evaluation` events, not the evaluator itself.
+The fix path differs (edit Hog source vs. edit prompt) but the diagnosis is
identical.
### "Why is evaluation X suddenly failing more?"
@@ -311,8 +307,8 @@ identical.
1. `llma-evaluation-list` — confirm the evaluation is still enabled and unchanged
(compare `evaluation_config.source` or `evaluation_config.prompt` to the version you
expect)
-2. `llma-evaluation-summary-create` with `filter: "fail"` — get the dominant
- failure patterns and example IDs
+2. Read the recent failing runs and their reasoning (Step 3 above) and group them
+ into the dominant failure patterns
3. SQL count of fails per day to confirm the regression window:
```sql
@@ -330,8 +326,9 @@ identical.
### "Are passes and fails caused by the same root content?"
-1. Generate two summaries: one with `filter: "pass"`, one with `filter: "fail"`
-2. If `pass_patterns` and `fail_patterns` describe similar content:
+1. Pull two samples with the Step 3 query, flipping `$ai_evaluation_result` between
+ `true` and `false`
+2. If the passing and failing runs describe similar content:
- For an `llm_judge`: the prompt or rubric is probably ambiguous — reword
`evaluation_config.prompt` and use `llma-evaluation-update`
- For a `hog` evaluator: the rule is probably under- or over-matching — read the
@@ -355,13 +352,24 @@ yield identical outputs. When fail rates jump for a Hog evaluator:
### "What kinds of generations does this evaluator skip as N/A?"
-```json
-posthog:llma-evaluation-summary-create
-{ "evaluation_id": "<uuid>", "filter": "na" }
+```sql
+posthog:execute-sql
+SELECT
+ properties.$ai_target_event_id AS generation_id,
+ properties.$ai_trace_id AS trace_id,
+ properties.$ai_evaluation_reasoning AS reasoning,
+ timestamp
+FROM events
+WHERE event = '$ai_evaluation'
+ AND properties.$ai_evaluation_id = '<evaluation_uuid>'
+ AND properties.$ai_evaluation_applicable = false
+ AND timestamp >= now() - INTERVAL 7 DAY
+ORDER BY timestamp DESC
+LIMIT 25
```
-Inspect `na_patterns` to see whether the N/A logic is doing the right thing. If a
-pattern in `na_patterns` looks like something that should have been scored:
+Read the reasoning on those runs to see whether the N/A logic is doing the right
+thing. If a run looks like something that should have been scored:
- For an `llm_judge`: the applicability instruction in the prompt is too broad — narrow
it
@@ -383,19 +391,21 @@ Always surface the relevant link so the user can verify in the UI.
## Tips
-- The summary tool is **rate-limited** (burst, sustained, daily) and **caches results
- for one hour** — repeated calls with the same `(evaluation_id, filter)` are cheap; use
- `force_refresh: true` only when you genuinely need fresh analysis
-- Pass `generation_ids: [...]` to scope a summary to a specific cohort of runs (max 250)
-- The `statistics` block in the summary response is computed from raw data, not the LLM
- — trust those counts even if a pattern's `frequency` field is qualitative
+- Evaluation reports are configured per evaluation with `llma-evaluation-report-create`:
+ `frequency: "scheduled"` with an `rrule` for a daily or weekly cadence, or
+ `frequency: "every_n"` with a `trigger_threshold` to fire once that many new results
+ have accumulated. Delivery goes to email or Slack via `delivery_targets`
+- `llma-evaluation-report-generate` runs a configured report immediately instead of
+ waiting for the next trigger; `llma-evaluation-report-run-list` returns past runs with
+ the report content they delivered
- For rich filtering not supported by `llma-evaluation-list` (e.g. by author or model
configuration), fall back to `execute-sql` against the `evaluations` Postgres table or
the `$ai_evaluation` ClickHouse events
- When showing failure patterns to the user, always include 1-2 example trace links so
they can validate the pattern visually
- `llma-evaluation-*` tools use `evaluation:read` for read tools and `evaluation:write` for
- mutating tools; `llma-evaluation-summary-create` uses `llm_analytics:write`
+ mutating tools; the `llma-evaluation-report-*` tools use `llm_analytics:read` and
+ `llm_analytics:write`
- Hog evaluators are reproducible — if you suspect a regression, `llma-evaluation-test-hog`
with the suspect source against the failing generations is the fastest way to bisect
whether the change is in the evaluator or in the producer of the generations
diff --git a/products/ai_observability/skills/feature-usage-feed/SKILL.md b/products/ai_observability/skills/feature-usage-feed/SKILL.md
index 21f0458116fb..01578cf7613e 100644
--- a/products/ai_observability/skills/feature-usage-feed/SKILL.md
+++ b/products/ai_observability/skills/feature-usage-feed/SKILL.md
@@ -45,7 +45,7 @@ If the user asks "what are users trying to DO in [ET / replay / SQL / flags / su
| (Pattern B) `agent_mode` property is present on recent `$ai_generation` events | `posthog:execute-sql` group-by `properties.agent_mode` on recent `ai_product='posthog_ai'` events. Null bucket is normal (batch jobs + tool-internal calls) — you want non-null coverage across the modes you care about. |
| `$session_id` is attached to the `$ai_generation` events (links trace to trigger session) | `posthog:execute-sql` for `countIf($session_id IS NOT NULL) / count()` |
| `$session_id` is also attached to the `$ai_evaluation` events (lets the Slack alert link to the session) | Same query but on `$ai_evaluation` events after the eval has run once |
-| User has organisation-level AI data processing approval | Required for `llm_judge` evaluations and the eval summary tool |
+| User has organisation-level AI data processing approval | Required for `llm_judge` evaluations |
If `$session_id` is missing on either event type, file a backend fix before continuing — there is no UI workaround. The session-summary feature has a worked example of the threading pattern in PR #54952. For Pattern B, the agent-mode threading pattern is in PR #55160.
@@ -59,7 +59,7 @@ If `$session_id` is missing on either event type, file a backend fix before cont
| `posthog:llma-evaluation-create` | (**often unexposed** — UI fallback: AI observability → Evaluations → New) Create the LLM-judge eval (disabled at first) |
| `posthog:llma-evaluation-run` | (**often unexposed** — UI fallback: the eval's detail page has a "Run on event" button) Dry-run the eval against specific generations during prompt iteration |
| `posthog:llma-evaluation-update` | (**often unexposed** — UI fallback: edit the eval in AI observability → Evaluations) Tweak the prompt / enable when ready |
-| `posthog:llma-evaluation-summary-create` | (**often unexposed** — UI fallback: the eval detail page has a "Summarize results" button) After the feed is running, get an AI summary of pass/N/A patterns to validate signal quality |
+| `posthog:llma-evaluation-report-create` | (**often unexposed** — UI fallback: the eval detail page has a "Reports" tab) After the feed is running, schedule an AI report on the eval to keep watching signal quality |
| `posthog:workflows-list` / `posthog:workflows-get` | (**often unexposed** — UI: Data pipeline → Workflows) Browse existing workflow configs — useful for cloning an existing feed's structure when setting up a new one. Read-only; no create/update tool is exposed yet, so step 6's Slack workflow setup is UI-only. |
Before starting, **check which of the `posthog:llma-evaluation-*` tools are actually exposed in your agent's MCP tool set.** If they aren't loaded, treat steps 4-5 as UI walkthroughs rather than tool calls.
@@ -405,19 +405,23 @@ Key observation from setup: the `agent_mode` tag reflects the mode at turn-time,
Once the feed has been running for a day or two, sanity-check the eval output at scale.
-**If `posthog:llma-evaluation-summary-create` is exposed:**
+**If `posthog:llma-evaluation-report-create` is exposed:** schedule an AI report on the eval so the pass/fail picture keeps arriving without you asking for it.
```json
-posthog:llma-evaluation-summary-create
+posthog:llma-evaluation-report-create
{
- "evaluation_id": "<uuid>",
- "filter": "fail"
+ "evaluation": "<uuid>",
+ "frequency": "scheduled",
+ "rrule": "FREQ=WEEKLY;BYDAY=MO",
+ "delivery_targets": [{ "type": "email", "value": "[email protected]" }]
}
```
-**UI fallback:** open the eval in AI observability → Evaluations → "Summarize results" button, filter = fail.
+`posthog:llma-evaluation-report-generate` runs a configured report right away, and `posthog:llma-evaluation-report-run-list` returns the content of past runs.
-If the FAIL bucket is large, the classification step is too strict — relax it. If the PASS bucket has lots of generic reasonings, iterate on the prompt to enforce concreteness. The summary tool gives a quick read on this without you having to scroll through individual events.
+**UI fallback:** open the eval in AI observability → Evaluations, then the "Reports" tab.
+
+If the FAIL bucket is large, the classification step is too strict — relax it. If the PASS bucket has lots of generic reasonings, iterate on the prompt to enforce concreteness. The report gives a quick read on this without you having to scroll through individual events.
Spot-check raw events when needed (note: the stored result value is `'True'`, not `'PASS'` — see step 6):
@@ -442,4 +446,4 @@ LIMIT 25
- Keep the eval scoped tightly via the `conditions` property filters on `$ai_trace_id` prefix. Otherwise it fans out to every `$ai_generation` event in the project and burns LLM cost.
- For high-volume features (>10k traces/week), consider sampling — set the eval to run on a percentage of matching events rather than all of them. Slack flooding is a real failure mode.
- The "View Trigger Session" button is the highest-value link in the alert. Without it, the feed is just text — you can't watch what the user was actually doing. Verify it works in step 7 before considering the feed shipped.
-- Once the feed is live, periodically re-run the eval summary tool with `filter: "pass"` to surface the dominant use case clusters. That's how you turn the feed into actual product insights instead of just a notification stream.
+- Once the feed is live, keep reading the passing runs' reasoning (a scheduled report, or the SQL above with `$ai_evaluation_result = 'True'`) to surface the dominant use case clusters. That's how you turn the feed into actual product insights instead of just a notification stream.
diff --git a/products/signals/skills/signals-scout-ai-observability/SKILL.md b/products/signals/skills/signals-scout-ai-observability/SKILL.md
index 7de89d89dffd..dc3543d17343 100644
--- a/products/signals/skills/signals-scout-ai-observability/SKILL.md
+++ b/products/signals/skills/signals-scout-ai-observability/SKILL.md
@@ -73,7 +73,7 @@ The lenses below are the surfaces worth watching. **Do not run all of them every
When a lens flags something, don't report the top-line number — localize and sample:
- **Localize.** Slice the contributing `$ai_generation` / `$ai_trace` events by a dimension (model, `$ai_span_name`, tool, user, `ai_product`, a custom dim) to show _which_ slice drove the move — that's the difference between "cost is up" and a reportable finding.
-- **Sample.** Pull one or two representative traces via `query-llm-trace` (or a failing generation sampled from the raw `$ai_evaluation` rows) and cite concrete trace / generation / evaluation IDs in the evidence. `llma-evaluation-summary-create` groups failures into patterns with example IDs when it's available, but it's billed and can 500 — don't depend on it. A trace you cite links to `/ai-observability/traces/<trace_id>`: use the `_posthogUrl` on the query result. If you only have an id from raw SQL, call `query-llm-trace` with that id and the relevant date range, then use its `_posthogUrl`; if the trace cannot be fetched, cite the bare id. Never build the link by serializing the trace query into `/insights/new#q=…`, which opens an empty insight because `TraceQuery` isn't an insight source.
+- **Sample.** Pull one or two representative traces via `query-llm-trace` (or a failing generation sampled from the raw `$ai_evaluation` rows) and cite concrete trace / generation / evaluation IDs in the evidence. A trace you cite links to `/ai-observability/traces/<trace_id>`: use the `_posthogUrl` on the query result. If you only have an id from raw SQL, call `query-llm-trace` with that id and the relevant date range, then use its `_posthogUrl`; if the trace cannot be fetched, cite the bare id. Never build the link by serializing the trace query into `/insights/new#q=…`, which opens an empty insight because `TraceQuery` isn't an insight source.
- **Group as a pattern** when a trend spans many traces: describe the shared shape (same model + same span, same tool error, same prompt version) rather than listing rows.
### Save memory as you go
@@ -129,7 +129,7 @@ Telemetry & cost:
Evals & enrichment config:
- `llma-evaluation-list` — eval **config** only (name, type, enabled). Pass-rates are NOT here — read the trend from `$ai_evaluation` events via `execute-sql` (the reliable path).
-- `llma-evaluation-summary-create` — optional AI pass/fail/N/A pattern summary (billed, rate-limited, currently prone to 500s — a drill-down, not the spine). Pair with `llma-evaluation-get` / `-test-hog`.
+- `llma-evaluation-report-list` / `-run-list` — the scheduled AI reports configured on an eval, and what past runs said about it (a drill-down, not the spine). Pair with `llma-evaluation-get` / `-test-hog`.
- `llma-tagger-list` / `llma-score-definition-list` — the enrichment config surface (auto-taggers and scorers — LLM/Hog jobs that can silently break).
- `llma-clustering-job-list` / `-get` — semantic clusters over traces/generations.
- `llma-prompt-list` / `-get` — prompt versions, for correlating a change to its cause.
diff --git a/products/signals/skills/signals-scout-ai-observability/references/lenses.md b/products/signals/skills/signals-scout-ai-observability/references/lenses.md
index 402afc5926fe..24d358e4044c 100644
--- a/products/signals/skills/signals-scout-ai-observability/references/lenses.md
+++ b/products/signals/skills/signals-scout-ai-observability/references/lenses.md
@@ -42,8 +42,8 @@ lens**, not on every run:
- `posthog:exploring-llm-traces` — finding traces by filter, the event hierarchy, drilling
a single trace/session, parsing scripts. (Message content lives on the `posthog.ai_events`
table, not `events.properties`.)
-- `posthog:exploring-llm-evaluations` — the real eval-results path: AI pass/fail/N/A
- pattern summaries and raw `$ai_evaluation` SQL, plus config inspection and Hog dry-runs.
+- `posthog:exploring-llm-evaluations` — the real eval-results path: raw `$ai_evaluation`
+ SQL and scheduled eval reports, plus config inspection and Hog dry-runs.
- `posthog:exploring-llm-clusters` — per-cluster cost/latency/error metrics, comparing
clusters across runs.
@@ -100,11 +100,10 @@ lens**, not on every run:
- **How to read it.** `llma-evaluation-list` only gives **config** — the pass-rate lives in
`$ai_evaluation` events. Read the **trend straight from those events** (fails/day with the
N/A guard) following the eval skill's "Why is evaluation X suddenly failing more?"
- workflow — that raw query is the reliable spine. `llma-evaluation-summary-create
-{evaluation_id, filter:"fail"}` is an optional drill-down that groups failures into
- patterns with example IDs, but it's billed, rate-limited, and currently prone to 500s —
- treat it as a bonus, not a dependency, and fall back to sampling the raw failing rows via
- `query-llm-trace` when it's unavailable.
+ workflow — that raw query is the reliable spine. When the eval has report configs,
+ `llma-evaluation-report-list` / `-run-list` give you the AI reports already written about
+ it as an optional drill-down; either way, sample the raw failing rows via
+ `query-llm-trace`.
- **Discipline.** Pass-rate regressions **also auto-flow to the inbox** via the enabled
`llm_analytics:evaluation` signal source — so only report when you've localized something
the auto-flow won't (a specific eval + a specific failure pattern + a cause); otherwise
@@ -117,7 +116,8 @@ LLM/Hog jobs that can silently break.
- **Signal.** A config that's meant to be running but isn't doing its job: an eval / tagger
/ scorer disabled or status-flipped unexpectedly, an N/A-heavy eval (applicability too
- broad — `summary-create {filter:"na"}`), a job pointed at a **deprecated model** or a
+ broad — count the `$ai_evaluation_applicable = false` rows), a job pointed at a
+ **deprecated model** or a
**disabled/revoked provider key**, or a Hog evaluator hitting the 5s execution limit.
- **How to read it.** `llma-evaluation-list` (status/enabled, type), `llma-tagger-list`
(`enabled`, `model_configuration.provider_key_id`, `conditions`),
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 11774afde204..36b163dfb75e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5937,21 +5937,6 @@
"readOnlyHint": false
}
},
- "llma-evaluation-summary-create": {
- "description": "Generate an AI-powered summary of boolean AI observability evaluation results for a given evaluation config. Pass an evaluation_id and an optional filter (\"all\", \"pass\", \"fail\", or \"na\") to scope which runs are analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title, description, frequency, and example generation IDs), actionable recommendations, and run statistics. Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour — use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.",
- "category": "AI observability",
- "feature": "llm_analytics",
- "summary": "Summarize evaluation results",
- "title": "Summarize evaluation results",
- "required_scopes": ["llm_analytics:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "requires_ai_consent": true
- },
"llma-evaluation-test-hog": {
"description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
"category": "AI observability",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e2d39d627f3b..227972b543b9 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6134,21 +6134,6 @@
"readOnlyHint": false
}
},
- "llma-evaluation-summary-create": {
- "description": "Generate an AI-powered summary of boolean AI observability evaluation results for a given evaluation config. Pass an evaluation_id and an optional filter (\"all\", \"pass\", \"fail\", or \"na\") to scope which runs are analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title, description, frequency, and example generation IDs), actionable recommendations, and run statistics. Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour — use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.",
- "category": "AI observability",
- "feature": "llm_analytics",
- "summary": "Summarize evaluation results",
- "title": "Summarize evaluation results",
- "required_scopes": ["llm_analytics:write"],
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "requires_ai_consent": true
- },
"llma-evaluation-test-hog": {
"description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
"category": "AI observability",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a3b5c1b7982e..43653ca9cba3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -30972,13 +30972,6 @@ export namespace Schemas {
readonly evaluation_count: number;
}
- export interface EvaluationPattern {
- title: string;
- description: string;
- frequency: string;
- example_generation_ids: string[];
- }
-
/**
* * `scheduled` - Scheduled
* * `every_n` - Every N
@@ -31282,74 +31275,6 @@ export namespace Schemas {
distinct_id?: string | null;
}
- /**
- * * `all` - all
- * * `pass` - pass
- * * `fail` - fail
- * * `na` - na
- */
- export type FilterEnum = typeof FilterEnum[keyof typeof FilterEnum];
-
-
- export const FilterEnum = {
- All: 'all',
- Pass: 'pass',
- Fail: 'fail',
- Na: 'na',
- } as const;
-
- /**
- * Request serializer for evaluation summary - accepts IDs only, fetches data server-side.
- */
- export interface EvaluationSummaryRequest {
- /** UUID of the evaluation config to summarize */
- evaluation_id: string;
- /** Filter type to apply ('all', 'pass', 'fail', or 'na')
- *
- * * `all` - all
- * * `pass` - pass
- * * `fail` - fail
- * * `na` - na */
- filter?: FilterEnum;
- /**
- * Optional: specific generation IDs to include in summary (max 250)
- * @maxItems 250
- */
- generation_ids?: string[];
- /** If true, bypass cache and generate a fresh summary */
- force_refresh?: boolean;
- }
-
- export interface EvaluationSummaryStatistics {
- total_analyzed: number;
- pass_count: number;
- fail_count: number;
- na_count: number;
- }
-
- export interface EvaluationSummaryResponse {
- overall_assessment: string;
- pass_patterns: EvaluationPattern[];
- fail_patterns: EvaluationPattern[];
- na_patterns: EvaluationPattern[];
- recommendations: string[];
- statistics: EvaluationSummaryStatistics;
- }
-
- export interface EvaluationSummaryThrottleResponse {
- /** Error category */
- type: string;
- /** Machine-readable error code */
- code: string;
- /** Why the request was throttled */
- detail: string;
- /**
- * Related request field, when applicable
- * @nullable
- */
- attr: string | null;
- }
-
export interface EventDefinitionBasic {
id: string;
name: string;
@@ -89777,14 +89702,6 @@ export namespace Schemas {
offset?: number;
};
- export type LlmAnalyticsEvaluationSummaryCreate400 = { [key: string]: unknown };
-
- export type LlmAnalyticsEvaluationSummaryCreate403 = { [key: string]: unknown };
-
- export type LlmAnalyticsEvaluationSummaryCreate404 = { [key: string]: unknown };
-
- export type LlmAnalyticsEvaluationSummaryCreate500 = { [key: string]: unknown };
-
export type LlmAnalyticsModelsRetrieveParams = {
/**
* Optional provider key UUID. When supplied, models reachable with that specific key are returned (useful for Azure OpenAI, where the deployment list depends on the configured endpoint). Must belong to the same provider as the `provider` parameter.
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 46db81dad124..76307355d93a 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 77 enabled ops
+ * PostHog API - MCP 76 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1419,57 +1419,6 @@ export const LlmAnalyticsEvaluationReportsRunsListQueryParams = /* @__PURE__ */
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
-/**
- *
- * Generate an AI-powered summary of evaluation results.
- *
- * This endpoint analyzes evaluation runs and identifies patterns in passing
- * and failing evaluations, providing actionable recommendations.
- *
- * Data is fetched server-side by evaluation ID to ensure data integrity.
- *
- * **Use Cases:**
- * - Understand why evaluations are passing or failing
- * - Identify systematic issues in LLM responses
- * - Get recommendations for improving response quality
- * - Review patterns across many evaluation runs at once
- *
- */
-export const LlmAnalyticsEvaluationSummaryCreateParams = /* @__PURE__ */ zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
- ),
-})
-
-export const llmAnalyticsEvaluationSummaryCreateBodyFilterDefault = `all`
-export const llmAnalyticsEvaluationSummaryCreateBodyGenerationIdsMax = 250
-
-export const llmAnalyticsEvaluationSummaryCreateBodyForceRefreshDefault = false
-
-export const LlmAnalyticsEvaluationSummaryCreateBody = /* @__PURE__ */ zod
- .object({
- evaluation_id: zod.string().describe('UUID of the evaluation config to summarize'),
- filter: zod
- .enum(['all', 'pass', 'fail', 'na'])
- .describe('\* `all` - all\n\* `pass` - pass\n\* `fail` - fail\n\* `na` - na')
- .default(llmAnalyticsEvaluationSummaryCreateBodyFilterDefault)
- .describe(
- "Filter type to apply ('all', 'pass', 'fail', or 'na')\n\n\* `all` - all\n\* `pass` - pass\n\* `fail` - fail\n\* `na` - na"
- ),
- generation_ids: zod
- .array(zod.string())
- .max(llmAnalyticsEvaluationSummaryCreateBodyGenerationIdsMax)
- .optional()
- .describe('Optional: specific generation IDs to include in summary (max 250)'),
- force_refresh: zod
- .boolean()
- .default(llmAnalyticsEvaluationSummaryCreateBodyForceRefreshDefault)
- .describe('If true, bypass cache and generate a fresh summary'),
- })
- .describe('Request serializer for evaluation summary - accepts IDs only, fetches data server-side.')
-
/**
* List available models for a provider.
*/
diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.ts
index 12a0927d3af6..053388696751 100644
--- a/services/mcp/src/tools/generated/ai_observability.ts
+++ b/services/mcp/src/tools/generated/ai_observability.ts
@@ -53,7 +53,6 @@ import {
LlmAnalyticsEvaluationReportsRetrieveParams,
LlmAnalyticsEvaluationReportsRunsListParams,
LlmAnalyticsEvaluationReportsRunsListQueryParams,
- LlmAnalyticsEvaluationSummaryCreateBody,
LlmAnalyticsModelsRetrieveQueryParams,
LlmAnalyticsPersonalSpendListQueryParams,
LlmAnalyticsProviderKeysListQueryParams,
@@ -1215,38 +1214,6 @@ const llmaEvaluationRun = (): ToolBase<typeof LlmaEvaluationRunSchema, unknown>
},
})
-const LlmaEvaluationSummaryCreateSchema = LlmAnalyticsEvaluationSummaryCreateBody
-
-const llmaEvaluationSummaryCreate = (): ToolBase<
- typeof LlmaEvaluationSummaryCreateSchema,
- Schemas.EvaluationSummaryResponse
-> => ({
- name: 'llma-evaluation-summary-create',
- schema: LlmaEvaluationSummaryCreateSchema,
- handler: async (context: Context, params: z.infer<typeof LlmaEvaluationSummaryCreateSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.evaluation_id !== undefined) {
- body['evaluation_id'] = params.evaluation_id
- }
- if (params.filter !== undefined) {
- body['filter'] = params.filter
- }
- if (params.generation_ids !== undefined) {
- body['generation_ids'] = params.generation_ids
- }
- if (params.force_refresh !== undefined) {
- body['force_refresh'] = params.force_refresh
- }
- const result = await context.api.request<Schemas.EvaluationSummaryResponse>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_analytics/evaluation_summary/`,
- body,
- })
- return result
- },
-})
-
const LlmaEvaluationTestHogSchema = EvaluationsTestHogCreateBody
const llmaEvaluationTestHog = (): ToolBase<typeof LlmaEvaluationTestHogSchema, Schemas.TestHogResponse> => ({
@@ -2572,7 +2539,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'llma-evaluation-report-run-list': llmaEvaluationReportRunList,
'llma-evaluation-report-update': llmaEvaluationReportUpdate,
'llma-evaluation-run': llmaEvaluationRun,
- 'llma-evaluation-summary-create': llmaEvaluationSummaryCreate,
'llma-evaluation-test-hog': llmaEvaluationTestHog,
'llma-evaluation-update': llmaEvaluationUpdate,
'llma-personal-spend': llmaPersonalSpend,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-summary-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-summary-create.json
deleted file mode 100644
index 7c5e1739c22b..000000000000
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-summary-create.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "description": "Request serializer for evaluation summary - accepts IDs only, fetches data server-side.",
- "properties": {
- "evaluation_id": {
- "description": "UUID of the evaluation config to summarize",
- "type": "string"
- },
- "filter": {
- "default": "all",
- "description": "Filter type to apply ('all', 'pass', 'fail', or 'na')\n\n* `all` - all\n* `pass` - pass\n* `fail` - fail\n* `na` - na",
- "enum": ["all", "pass", "fail", "na"],
- "type": "string"
- },
- "force_refresh": {
- "default": false,
- "description": "If true, bypass cache and generate a fresh summary",
- "type": "boolean"
- },
- "generation_ids": {
- "description": "Optional: specific generation IDs to include in summary (max 250)",
- "items": {
- "type": "string"
- },
- "maxItems": 250,
- "type": "array"
- }
- },
- "required": ["evaluation_id"],
- "type": "object"
-}