:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): add online evaluation directories (#77848)
Radu Raiceafcfafd70ee11
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 3ff3adca66d8..017fed96a62e 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -156,6 +156,7 @@ rules:|ErrorTrackingSuppressionRule|ErrorTrackingSymbolSet|Evaluation+ |EvaluationDirectory|Experiment|ExperimentHoldout|ExperimentMetricsRecalculation@@ -501,6 +502,7 @@ rules:|ErrorTrackingSuppressionRule|ErrorTrackingSymbolSet|Evaluation+ |EvaluationDirectory|Experiment|ExperimentHoldout|ExperimentMetricsRecalculationdiff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 0f10fd5d641c..9957bb26c761 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -1838,6 +1838,68 @@ support_tickets: PostgresTable = PostgresTable(},)+evaluation_directories: PostgresTable = PostgresTable(+ name="evaluation_directories",+ postgres_table_name="llm_analytics_evaluationdirectory",+ access_scope="evaluation",+ description="Directories used to organize online evaluations; one row per directory.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Directory UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "name": StringDatabaseField(name="name", description="Directory name."),+ "created_by_id": IntegerDatabaseField(+ name="created_by_id", nullable=True, description="User who created the directory."+ ),+ "created_at": DateTimeDatabaseField(name="created_at", description="When the directory was created."),+ "updated_at": DateTimeDatabaseField(+ name="updated_at", nullable=True, description="When the directory was last updated."+ ),+ },+)++evaluations: PostgresTable = PostgresTable(+ name="evaluations",+ postgres_table_name="llm_analytics_evaluation",+ access_scope="evaluation",+ description="Online evaluations that score AI generations or traces; one row per evaluation.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Evaluation UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "directory_id": UUIDDatabaseField(+ name="directory_id",+ nullable=True,+ description="Directory containing the evaluation; NULL means the top level.",+ ),+ "name": StringDatabaseField(name="name", description="Evaluation name."),+ "description": StringDatabaseField(name="description", description="Evaluation description."),+ "enabled": BooleanDatabaseField(name="enabled", description="Whether the evaluation is active."),+ "status": StringDatabaseField(name="status", description="Evaluation status."),+ "status_reason": StringDatabaseField(+ name="status_reason", nullable=True, description="Reason for the current status, when available."+ ),+ "evaluation_type": StringDatabaseField(name="evaluation_type", description="Evaluation implementation type."),+ "evaluation_config": StringJSONDatabaseField(+ name="evaluation_config", description="Evaluation-specific configuration."+ ),+ "output_type": StringDatabaseField(name="output_type", description="Evaluation result type."),+ "output_config": StringJSONDatabaseField(name="output_config", description="Evaluation output configuration."),+ "conditions": StringJSONDatabaseField(name="conditions", description="Conditions that select matching input."),+ "target": StringDatabaseField(name="target", description="Unit evaluated, such as a generation or trace."),+ "target_config": StringJSONDatabaseField(name="target_config", description="Target-specific configuration."),+ "model_configuration_id": UUIDDatabaseField(+ name="model_configuration_id",+ nullable=True,+ description="Model configuration used by an LLM judge evaluation.",+ ),+ "created_by_id": IntegerDatabaseField(+ name="created_by_id", nullable=True, description="User who created the evaluation."+ ),+ "created_at": DateTimeDatabaseField(name="created_at", description="When the evaluation was created."),+ "updated_at": DateTimeDatabaseField(name="updated_at", description="When the evaluation was last updated."),+ "deleted": BooleanDatabaseField(name="deleted", description="Whether the evaluation has been deleted."),+ },+)+review_queues: PostgresTable = PostgresTable(name="review_queues",postgres_table_name="llm_analytics_reviewqueue",@@ -2404,6 +2466,8 @@ class SystemTables(TableNode):name="error_tracking_suppression_rules", table=error_tracking_suppression_rules),"early_access_features": TableNode(name="early_access_features", table=early_access_features),+ "evaluation_directories": TableNode(name="evaluation_directories", table=evaluation_directories),+ "evaluations": TableNode(name="evaluations", table=evaluations),"experiments": TableNode(name="experiments", table=experiments),"exports": TableNode(name="exports", table=exports),"feature_flags": TableNode(name="feature_flags", table=feature_flags),diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 970369f71543..9c25e38db801 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -24,6 +24,8 @@ from posthog.persons_db import persons_db_connectionfrom posthog.persons_seed import insert_seed_group, insert_seed_group_type_mappingfrom products.actions.backend.models.action import Action+from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectory+from products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.review_queues import ReviewQueue, ReviewQueueItemfrom products.ai_observability.backend.models.score_definitions import ScoreDefinitionfrom products.ai_observability.backend.models.trace_reviews import TraceReview, TraceReviewScore@@ -481,6 +483,27 @@ def _create_logs_alert(team: Team, label: str) -> LogsAlertConfiguration:)+def _create_evaluation_directory(team: Team, label: str) -> EvaluationDirectory:+ user = _get_or_create_user_for_team(team, label)+ return EvaluationDirectory.objects.for_team(team.id).create(+ team=team,+ name=f"evaluation_directory_{label}",+ created_by=user,+ )+++def _create_evaluation(team: Team, label: str) -> Evaluation:+ user = _get_or_create_user_for_team(team, label)+ return Evaluation.objects.create(+ team=team,+ name=f"evaluation_{label}",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ created_by=user,+ )++def _create_review_queue(team: Team, label: str) -> ReviewQueue:user = _get_or_create_user_for_team(team, label)return ReviewQueue.objects.create(team=team, name=f"review_queue_{label}", created_by=user)@@ -730,6 +753,8 @@ SYSTEM_TABLE_FACTORIES = [("error_tracking_releases", _create_error_tracking_release),("error_tracking_symbol_sets", _create_error_tracking_symbol_set),("error_tracking_suppression_rules", _create_error_tracking_suppression_rule),+ ("evaluation_directories", _create_evaluation_directory),+ ("evaluations", _create_evaluation),("experiments", _create_experiment),("exports", _create_export),("feature_flags", _create_feature_flag),diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 9f9c445296ad..30b2dadb95c3 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -5811,6 +5811,264 @@"row_count": null,"type": "system"},+ "system.evaluation_directories": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "name": {+ "chain": null,+ "fields": null,+ "hogql_value": "name",+ "id": null,+ "name": "name",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "created_by_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_by_id",+ "id": null,+ "name": "created_by_id",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ }+ },+ "id": "system.evaluation_directories",+ "name": "system.evaluation_directories",+ "row_count": null,+ "type": "system"+ },+ "system.evaluations": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "directory_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "directory_id",+ "id": null,+ "name": "directory_id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "name": {+ "chain": null,+ "fields": null,+ "hogql_value": "name",+ "id": null,+ "name": "name",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "description": {+ "chain": null,+ "fields": null,+ "hogql_value": "description",+ "id": null,+ "name": "description",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "enabled": {+ "chain": null,+ "fields": null,+ "hogql_value": "enabled",+ "id": null,+ "name": "enabled",+ "schema_valid": true,+ "table": null,+ "type": "boolean"+ },+ "status": {+ "chain": null,+ "fields": null,+ "hogql_value": "status",+ "id": null,+ "name": "status",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "status_reason": {+ "chain": null,+ "fields": null,+ "hogql_value": "status_reason",+ "id": null,+ "name": "status_reason",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "evaluation_type": {+ "chain": null,+ "fields": null,+ "hogql_value": "evaluation_type",+ "id": null,+ "name": "evaluation_type",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "evaluation_config": {+ "chain": null,+ "fields": null,+ "hogql_value": "evaluation_config",+ "id": null,+ "name": "evaluation_config",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "output_type": {+ "chain": null,+ "fields": null,+ "hogql_value": "output_type",+ "id": null,+ "name": "output_type",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "output_config": {+ "chain": null,+ "fields": null,+ "hogql_value": "output_config",+ "id": null,+ "name": "output_config",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "conditions": {+ "chain": null,+ "fields": null,+ "hogql_value": "conditions",+ "id": null,+ "name": "conditions",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "target": {+ "chain": null,+ "fields": null,+ "hogql_value": "target",+ "id": null,+ "name": "target",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "target_config": {+ "chain": null,+ "fields": null,+ "hogql_value": "target_config",+ "id": null,+ "name": "target_config",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "model_configuration_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "model_configuration_id",+ "id": null,+ "name": "model_configuration_id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "created_by_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_by_id",+ "id": null,+ "name": "created_by_id",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "deleted": {+ "chain": null,+ "fields": null,+ "hogql_value": "deleted",+ "id": null,+ "name": "deleted",+ "schema_valid": true,+ "table": null,+ "type": "boolean"+ }+ },+ "id": "system.evaluations",+ "name": "system.evaluations",+ "row_count": null,+ "type": "system"+ },"system.experiments": {"certification": null,"fields": {@@ -15009,6 +15267,264 @@"row_count": null,"type": "system"},+ "system.evaluation_directories": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "name": {+ "chain": null,+ "fields": null,+ "hogql_value": "name",+ "id": null,+ "name": "name",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "created_by_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_by_id",+ "id": null,+ "name": "created_by_id",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ }+ },+ "id": "system.evaluation_directories",+ "name": "system.evaluation_directories",+ "row_count": null,+ "type": "system"+ },+ "system.evaluations": {+ "certification": null,+ "fields": {+ "id": {+ "chain": null,+ "fields": null,+ "hogql_value": "id",+ "id": null,+ "name": "id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "directory_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "directory_id",+ "id": null,+ "name": "directory_id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "name": {+ "chain": null,+ "fields": null,+ "hogql_value": "name",+ "id": null,+ "name": "name",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "description": {+ "chain": null,+ "fields": null,+ "hogql_value": "description",+ "id": null,+ "name": "description",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "enabled": {+ "chain": null,+ "fields": null,+ "hogql_value": "enabled",+ "id": null,+ "name": "enabled",+ "schema_valid": true,+ "table": null,+ "type": "boolean"+ },+ "status": {+ "chain": null,+ "fields": null,+ "hogql_value": "status",+ "id": null,+ "name": "status",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "status_reason": {+ "chain": null,+ "fields": null,+ "hogql_value": "status_reason",+ "id": null,+ "name": "status_reason",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "evaluation_type": {+ "chain": null,+ "fields": null,+ "hogql_value": "evaluation_type",+ "id": null,+ "name": "evaluation_type",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "evaluation_config": {+ "chain": null,+ "fields": null,+ "hogql_value": "evaluation_config",+ "id": null,+ "name": "evaluation_config",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "output_type": {+ "chain": null,+ "fields": null,+ "hogql_value": "output_type",+ "id": null,+ "name": "output_type",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "output_config": {+ "chain": null,+ "fields": null,+ "hogql_value": "output_config",+ "id": null,+ "name": "output_config",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "conditions": {+ "chain": null,+ "fields": null,+ "hogql_value": "conditions",+ "id": null,+ "name": "conditions",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "target": {+ "chain": null,+ "fields": null,+ "hogql_value": "target",+ "id": null,+ "name": "target",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "target_config": {+ "chain": null,+ "fields": null,+ "hogql_value": "target_config",+ "id": null,+ "name": "target_config",+ "schema_valid": true,+ "table": null,+ "type": "json"+ },+ "model_configuration_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "model_configuration_id",+ "id": null,+ "name": "model_configuration_id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },+ "created_by_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_by_id",+ "id": null,+ "name": "created_by_id",+ "schema_valid": true,+ "table": null,+ "type": "integer"+ },+ "created_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "created_at",+ "id": null,+ "name": "created_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "updated_at": {+ "chain": null,+ "fields": null,+ "hogql_value": "updated_at",+ "id": null,+ "name": "updated_at",+ "schema_valid": true,+ "table": null,+ "type": "datetime"+ },+ "deleted": {+ "chain": null,+ "fields": null,+ "hogql_value": "deleted",+ "id": null,+ "name": "deleted",+ "schema_valid": true,+ "table": null,+ "type": "boolean"+ }+ },+ "id": "system.evaluations",+ "name": "system.evaluations",+ "row_count": null,+ "type": "system"+ },"system.experiments": {"certification": null,"fields": {diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex e61c9931c95a..510228c8aaea 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -80,6 +80,7 @@ ActivityScope = Literal["ExternalDataSource","ExternalDataSchema","Evaluation",+ "EvaluationDirectory","LLMPrompt","LLMPromptLabel","LLMTrace",@@ -775,6 +776,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {"table",],"Evaluation": [+ # The fail-closed relation cannot be resolved outside a team scope; the handler diffs IDs instead.+ "directory",# Reverse relations — auto-managed by FK creates, not user intent."reports",],diff --git a/posthog/permissions.py b/posthog/permissions.pyindex d403871b4732..b578d8d7698c 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -947,6 +947,9 @@ class AccessControlPermission(ScopeBasePermission):has_access = uac.check_access_level_for_resource(scope_object, required_level=required_level)if has_access:return True+ elif getattr(view, "requires_resource_level_access", False):+ self.message = f"You do not have {required_level} access to this resource."+ return Falseelif view.action == "create":# If the user has no access to the resource level, but is trying to create a new object, we should block it# Specific object access isn't relevant here as we are trying to create a new objectdiff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 31cca82409bf..b8b857d7f971 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -28,6 +28,7 @@ from products.ai_observability.backend.llm.errors import (StructuredOutputParseError,)from products.ai_observability.backend.models.evaluation_config import EvaluationConfig+from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectoryfrom products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey@@ -1098,6 +1099,12 @@ class TestRunEvaluationWorkflow:evaluation = setup_data["evaluation"]team = setup_data["team"]+ directory = await sync_to_async(+ lambda: EvaluationDirectory.objects.for_team(team.id).create(team=team, name="Quality")+ )()+ await sync_to_async(lambda: Evaluation.objects.filter(id=evaluation.id).update(directory=directory))()+ await sync_to_async(evaluation.refresh_from_db)()+assert evaluation.enableddisabled = await disable_evaluation_activity(diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 1a3028a3a55b..acc11544cd3b 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -19,6 +19,7 @@ model_activity:posthog.models.activity_logging.signal_handlers.handle_tagged_itemodel_activity:posthog.models.activity_logging.signal_handlers.log_user_change_activitymodel_activity:products.actions.backend.activity_logging.handle_action_changemodel_activity:products.ai_observability.backend.activity_logging.handle_evaluation_change+model_activity:products.ai_observability.backend.activity_logging.handle_evaluation_directory_changemodel_activity:products.ai_observability.backend.activity_logging.handle_llm_prompt_label_changemodel_activity:products.alerts.backend.activity_logging.handle_alert_configuration_changemodel_activity:products.alerts.backend.activity_logging.handle_alert_subscription_changediff --git a/products/ai_observability/backend/activity_logging.py b/products/ai_observability/backend/activity_logging.pyindex a4d154eb1e80..8abef98d0327 100644--- a/products/ai_observability/backend/activity_logging.py+++ b/products/ai_observability/backend/activity_logging.py@@ -7,12 +7,15 @@ from posthog.models.activity_logging.activity_log import (Change,ChangeAction,Detail,+ LogActivityEntry,+ bulk_log_activity,changes_between,log_activity,)from posthog.models.activity_logging.utils import activity_storagefrom posthog.models.signals import model_activity_signal, mutable_receiver+from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectoryfrom products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.llm_prompt import LLMPromptLabel@@ -87,6 +90,30 @@ def _strip_compiled_from_eval_config(config: dict[str, Any] | None) -> dict[str,return {k: v for k, v in config.items() if k not in _COMPILED_KEYS}+def _evaluation_directory_change(before_update: Evaluation | None, after_update: Evaluation | None) -> Change | None:+ if before_update is None or after_update is None:+ return None++ before_directory_id = str(before_update.directory_id) if before_update.directory_id else None+ after_directory_id = str(after_update.directory_id) if after_update.directory_id else None+ if before_directory_id == after_directory_id:+ return None++ action: ChangeAction = "changed"+ if before_directory_id is None:+ action = "created"+ elif after_directory_id is None:+ action = "deleted"++ return Change(+ type="Evaluation",+ action=action,+ field="directory",+ before=before_directory_id,+ after=after_directory_id,+ )++@mutable_receiver(model_activity_signal, sender=Evaluation)def handle_evaluation_change(sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs@@ -107,6 +134,11 @@ def handle_evaluation_change(if before_deleted is not None and after_deleted is not None and before_deleted != after_deleted:activity = "restored" if after_deleted is False else "deleted"+ changes = changes_between(scope, before_log, after_log)+ directory_change = _evaluation_directory_change(before_update, after_update)+ if directory_change is not None:+ changes.append(directory_change)+log_activity(organization_id=after_update.team.organization_id,team_id=after_update.team_id,@@ -116,12 +148,66 @@ def handle_evaluation_change(scope=scope,activity=activity,detail=Detail(- changes=changes_between(scope, previous=before_log, current=after_log),+ changes=changes,name=after_update.name,),)+def log_evaluations_moved_to_top_level(evaluations: list[Evaluation]) -> None:+ user = activity_storage.get_user()+ was_impersonated = activity_storage.get_was_impersonated()+ bulk_log_activity(+ [+ LogActivityEntry(+ organization_id=None,+ team_id=evaluation.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(evaluation.id),+ scope="Evaluation",+ activity="updated",+ detail=Detail(+ name=evaluation.name,+ changes=[+ Change(+ type="Evaluation",+ action="deleted",+ field="directory",+ before=str(evaluation.directory_id),+ after=None,+ )+ ],+ ),+ )+ for evaluation in evaluations+ ]+ )+++@mutable_receiver(model_activity_signal, sender=EvaluationDirectory)+def handle_evaluation_directory_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ directory = after_update or before_update+ if directory is None:+ return++ log_activity(+ organization_id=directory.team.organization_id,+ team_id=directory.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=directory.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ name=directory.name,+ changes=changes_between(scope, before_update, after_update),+ ),+ )++@mutable_receiver(model_activity_signal, sender=LLMPromptLabel)def handle_llm_prompt_label_change(sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargsdiff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.pyindex e4f55ce65a73..58b4e96108f8 100644--- a/products/ai_observability/backend/api/__init__.py+++ b/products/ai_observability/backend/api/__init__.py@@ -4,6 +4,7 @@ from .clustering_config import ClusteringConfigViewSetfrom .clustering_job import ClusteringJobViewSetfrom .datasets import DatasetItemViewSet, DatasetViewSetfrom .evaluation_config import EvaluationConfigViewSet+from .evaluation_directories import EvaluationDirectoryViewSetfrom .evaluation_reports import EvaluationReportViewSetfrom .evaluation_runs import EvaluationRunViewSetfrom .evaluation_summary import LLMEvaluationSummaryViewSet@@ -37,6 +38,7 @@ __all__ = ["DatasetViewSet","DatasetItemViewSet","EvaluationViewSet",+ "EvaluationDirectoryViewSet","EvaluationReportViewSet","EvaluationRunViewSet","EvaluationConfigViewSet",diff --git a/products/ai_observability/backend/api/evaluation_directories.py b/products/ai_observability/backend/api/evaluation_directories.pynew file mode 100644index 000000000000..e907bc0cc37c--- /dev/null+++ b/products/ai_observability/backend/api/evaluation_directories.py@@ -0,0 +1,102 @@+from typing import cast++from django.db import IntegrityError, transaction+from django.db.models import Count, Q, QuerySet+from django.utils import timezone++from rest_framework import serializers, viewsets+from rest_framework.permissions import IsAuthenticated++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.models import User+from posthog.permissions import AccessControlPermission+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin++from products.ai_observability.backend.activity_logging import log_evaluations_moved_to_top_level+from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectory+from products.ai_observability.backend.models.evaluations import Evaluation+++class EvaluationDirectorySerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(+ read_only=True,+ allow_null=True,+ help_text="User who created the directory.",+ )+ evaluation_count = serializers.IntegerField(+ read_only=True,+ help_text="Number of active evaluations in the directory.",+ )++ class Meta:+ model = EvaluationDirectory+ fields = ["id", "name", "created_at", "updated_at", "created_by", "evaluation_count"]+ read_only_fields = ["id", "created_at", "updated_at", "created_by", "evaluation_count"]+ extra_kwargs = {+ "name": {"help_text": "Directory name shown in the online evals list."},+ }++ def validate_name(self, value: str) -> str:+ name = value.strip()+ if not name:+ raise serializers.ValidationError("Enter a directory name.")++ team = self.context["get_team"]()+ directories = EvaluationDirectory.objects.for_team(team.id).filter(name__iexact=name)+ if self.instance is not None:+ directories = directories.exclude(pk=self.instance.pk)+ if directories.exists():+ raise serializers.ValidationError("A directory with this name already exists.")+ return name+++class EvaluationDirectoryViewSet(+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ viewsets.ModelViewSet,+):+ scope_object = "evaluation"+ requires_resource_level_access = True+ permission_classes = [IsAuthenticated, AccessControlPermission]+ serializer_class = EvaluationDirectorySerializer+ queryset = EvaluationDirectory.objects.unscoped()+ pagination_class = None+ http_method_names = ["get", "post", "patch", "delete", "head", "options"]++ def safely_get_queryset(self, queryset: QuerySet[EvaluationDirectory]) -> QuerySet[EvaluationDirectory]:+ return (+ queryset.filter(team_id=self.team_id)+ .select_related("created_by")+ .annotate(evaluation_count=Count("evaluations", filter=Q(evaluations__deleted=False)))+ .order_by("name", "id")+ )++ def perform_create(self, serializer: serializers.BaseSerializer) -> None:+ try:+ with transaction.atomic():+ directory = serializer.save(team=self.team, created_by=cast(User, self.request.user))+ directory.evaluation_count = 0+ except IntegrityError as error:+ raise serializers.ValidationError({"name": "A directory with this name already exists."}) from error++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ try:+ with transaction.atomic():+ serializer.save()+ except IntegrityError as error:+ raise serializers.ValidationError({"name": "A directory with this name already exists."}) from error++ def perform_destroy(self, instance: EvaluationDirectory) -> None:+ with transaction.atomic():+ evaluations = list(+ Evaluation.objects.filter(team_id=self.team_id, directory_id=instance.id).only(+ "id", "name", "team_id", "directory_id", "enabled", "status"+ )+ )+ if evaluations:+ Evaluation.objects.filter(+ team_id=self.team_id, id__in=[evaluation.id for evaluation in evaluations]+ ).update(directory=None, updated_at=timezone.now())+ log_evaluations_moved_to_top_level(evaluations)+ instance.delete()diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 6f84fe9f18b1..14c86ecab6a5 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -19,6 +19,7 @@ from posthog.hogql.property import property_to_exprfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.shared import UserBasicSerializerfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.event_usage import report_user_action@@ -60,6 +61,7 @@ from ..models.evaluation_configs import (validate_evaluation_configs,validate_target_config,)+from ..models.evaluation_directories import EvaluationDirectoryfrom ..models.evaluation_reports import EvaluationReportfrom ..models.evaluations import Evaluation, EvaluationTargetfrom ..models.model_configuration import LLMModelConfiguration@@ -263,7 +265,18 @@ class EvaluationConditionSerializer(serializers.Serializer):class EvaluationSerializer(serializers.ModelSerializer):- created_by = UserBasicSerializer(read_only=True)+ created_by = UserBasicSerializer(+ read_only=True,+ allow_null=True,+ help_text="User who created the evaluation.",+ )+ directory_id = TeamScopedPrimaryKeyRelatedField(+ source="directory",+ queryset=EvaluationDirectory.objects.unscoped(),+ required=False,+ allow_null=True,+ help_text="Directory containing the evaluation. Pass null to move the evaluation to the top level.",+ )model_configuration = ModelConfigurationSerializer(required=False,allow_null=True,@@ -320,6 +333,7 @@ class EvaluationSerializer(serializers.ModelSerializer):"id","name","description",+ "directory_id","enabled","status","status_reason",@@ -641,6 +655,15 @@ class EvaluationSerializer(serializers.ModelSerializer):class EvaluationFilter(django_filters.FilterSet):search = django_filters.CharFilter(method="filter_search", help_text="Search in name or description")+ directory_id = django_filters.UUIDFilter(+ field_name="directory_id",+ help_text="Filter evaluations by directory UUID.",+ )+ directory_id__isnull = django_filters.BooleanFilter(+ field_name="directory_id",+ lookup_expr="isnull",+ help_text="Filter evaluations by whether they are at the top level.",+ )enabled = django_filters.BooleanFilter(help_text="Filter by enabled status")evaluation_type = django_filters.ChoiceFilter(choices=EvaluationType.choices,@@ -1026,6 +1049,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbifor field in ["name","description",+ "directory","enabled","evaluation_type","output_type",diff --git a/products/ai_observability/backend/api/test/test_evaluation_directories.py b/products/ai_observability/backend/api/test/test_evaluation_directories.pynew file mode 100644index 000000000000..cd5d049fb0e5--- /dev/null+++ b/products/ai_observability/backend/api/test/test_evaluation_directories.py@@ -0,0 +1,174 @@+import pytest+from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import Team, User+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.organization import OrganizationMembership++from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectory+from products.ai_observability.backend.models.evaluations import Evaluation++try:+ from ee.models.rbac.access_control import AccessControl+except ImportError:+ pass+++class TestEvaluationDirectoriesApi(APIBaseTest):+ def _create_directory(self, name: str = "Quality") -> EvaluationDirectory:+ return EvaluationDirectory.objects.for_team(self.team.id).create(+ team=self.team,+ name=name,+ created_by=self.user,+ )++ def _create_evaluation(self, name: str = "Correctness") -> Evaluation:+ return Evaluation.objects.create(+ team=self.team,+ name=name,+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "Check correctness"},+ output_type="boolean",+ created_by=self.user,+ )++ def test_names_are_trimmed_and_unique_ignoring_case(self) -> None:+ url = f"/api/projects/{self.team.id}/evaluation_directories/"++ created = self.client.post(url, {"name": " Quality "}, format="json")+ duplicate = self.client.post(url, {"name": "quality"}, format="json")++ self.assertEqual(created.status_code, status.HTTP_201_CREATED)+ self.assertEqual(created.json()["name"], "Quality")+ self.assertEqual(duplicate.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(EvaluationDirectory.objects.for_team(self.team.id).count(), 1)++ def test_evaluation_can_move_into_a_directory_and_back_to_the_top_level(self) -> None:+ directory = self._create_directory()+ evaluation = self._create_evaluation()+ url = f"/api/projects/{self.team.id}/evaluations/{evaluation.id}/"++ moved = self.client.patch(url, {"directory_id": str(directory.id)}, format="json")+ moved_to_top_level = self.client.patch(url, {"directory_id": None}, format="json")++ self.assertEqual(moved.status_code, status.HTTP_200_OK)+ self.assertEqual(moved.json()["directory_id"], str(directory.id))+ self.assertEqual(moved_to_top_level.status_code, status.HTTP_200_OK)+ self.assertIsNone(moved_to_top_level.json()["directory_id"])++ def test_evaluation_cannot_move_to_another_teams_directory(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ other_directory = EvaluationDirectory.objects.for_team(other_team.id).create(+ team=other_team,+ name="Other directory",+ )+ evaluation = self._create_evaluation()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/evaluations/{evaluation.id}/",+ {"directory_id": str(other_directory.id)},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ evaluation.refresh_from_db()+ self.assertIsNone(evaluation.directory_id)++ def test_deleting_a_directory_moves_its_evaluations_to_the_top_level(self) -> None:+ directory = self._create_directory()+ active_evaluation = self._create_evaluation("Active")+ deleted_evaluation = self._create_evaluation("Deleted")+ Evaluation.objects.filter(id__in=[active_evaluation.id, deleted_evaluation.id]).update(directory=directory)+ Evaluation.objects.filter(id=deleted_evaluation.id).update(deleted=True)+ active_evaluation.refresh_from_db()+ previous_updated_at = active_evaluation.updated_at+ ActivityLog.objects.filter(team_id=self.team.id).delete()++ listed = self.client.get(f"/api/projects/{self.team.id}/evaluation_directories/")+ response = self.client.delete(f"/api/projects/{self.team.id}/evaluation_directories/{directory.id}/")++ self.assertEqual(listed.status_code, status.HTTP_200_OK)+ self.assertEqual(listed.json()[0]["evaluation_count"], 1)+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(EvaluationDirectory.objects.for_team(self.team.id).filter(id=directory.id).exists())+ self.assertEqual(+ Evaluation.objects.filter(id__in=[active_evaluation.id, deleted_evaluation.id], directory=None).count(),+ 2,+ )+ active_evaluation.refresh_from_db()+ self.assertGreater(active_evaluation.updated_at, previous_updated_at)+ self.assertTrue(+ ActivityLog.objects.filter(+ team_id=self.team.id,+ scope="Evaluation",+ item_id=str(active_evaluation.id),+ activity="updated",+ detail__changes__contains=[{"field": "directory", "action": "deleted"}],+ ).exists()+ )+ self.assertTrue(+ ActivityLog.objects.filter(+ team_id=self.team.id,+ scope="EvaluationDirectory",+ item_id=str(directory.id),+ activity="deleted",+ ).exists()+ )++ def test_evaluations_can_be_filtered_to_the_top_level(self) -> None:+ directory = self._create_directory()+ top_level_evaluation = self._create_evaluation("Top level")+ directory_evaluation = self._create_evaluation("In directory")+ Evaluation.objects.filter(id=directory_evaluation.id).update(directory=directory)++ response = self.client.get(+ f"/api/projects/{self.team.id}/evaluations/",+ {"directory_id__isnull": "true"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([result["id"] for result in response.json()["results"]], [str(top_level_evaluation.id)])++ @pytest.mark.ee+ def test_specific_evaluation_access_does_not_authorize_directory_changes(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()++ limited_user = User.objects.create_and_join(self.organization, "[email protected]", "testpassword123")+ directory = EvaluationDirectory.objects.for_team(self.team.id).create(+ team=self.team,+ name="Restricted",+ created_by=self.user,+ )+ evaluation = self._create_evaluation()+ membership = OrganizationMembership.objects.get(user=limited_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ access_level="none",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="evaluation",+ resource_id=str(evaluation.id),+ access_level="editor",+ organization_member=membership,+ )+ self.client.force_login(limited_user)++ renamed = self.client.patch(+ f"/api/projects/{self.team.id}/evaluation_directories/{directory.id}/",+ {"name": "Renamed"},+ format="json",+ )+ deleted = self.client.delete(f"/api/projects/{self.team.id}/evaluation_directories/{directory.id}/")++ self.assertEqual(renamed.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(deleted.status_code, status.HTTP_403_FORBIDDEN)diff --git a/products/ai_observability/backend/migrations/0034_evaluationdirectory_evaluation_directory_and_more.py b/products/ai_observability/backend/migrations/0034_evaluationdirectory_evaluation_directory_and_more.pynew file mode 100644index 000000000000..054def149899--- /dev/null+++ b/products/ai_observability/backend/migrations/0034_evaluationdirectory_evaluation_directory_and_more.py@@ -0,0 +1,71 @@+# Generated by Django 5.2.14 on 2026-08-04 17:38++import django.db.models.deletion+import django.db.models.functions.text+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("ai_observability", "0033_evaluation_target_session"),+ ("posthog", "1285_drop_desktop_file_system"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="EvaluationDirectory",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("name", models.CharField(max_length=400)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "db_table": "llm_analytics_evaluationdirectory",+ "ordering": ["name", "id"],+ },+ ),+ migrations.AddField(+ model_name="evaluation",+ name="directory",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="evaluations",+ to="ai_observability.evaluationdirectory",+ ),+ ),+ migrations.AddConstraint(+ model_name="evaluationdirectory",+ constraint=models.UniqueConstraint(+ django.db.models.functions.text.Lower("name"), models.F("team"), name="uniq_llma_eval_dir_team_name_ci"+ ),+ ),+ ]diff --git a/products/ai_observability/backend/migrations/0035_evaluation_directory_index.py b/products/ai_observability/backend/migrations/0035_evaluation_directory_index.pynew file mode 100644index 000000000000..31e79b5a966e--- /dev/null+++ b/products/ai_observability/backend/migrations/0035_evaluation_directory_index.py@@ -0,0 +1,21 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("ai_observability", "0034_evaluationdirectory_evaluation_directory_and_more"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="evaluation",+ index=models.Index(+ fields=["team", "directory", "-created_at", "id"],+ name="llma_eval_team_dir_created_idx",+ ),+ ),+ ]diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txtindex 586c68314890..bf01dfd41cd1 100644--- a/products/ai_observability/backend/migrations/max_migration.txt+++ b/products/ai_observability/backend/migrations/max_migration.txt@@ -1 +1 @@-0033_evaluation_target_session+0035_evaluation_directory_indexdiff --git a/products/ai_observability/backend/models/__init__.py b/products/ai_observability/backend/models/__init__.pyindex 43b104f865cb..8769283b419e 100644--- a/products/ai_observability/backend/models/__init__.py+++ b/products/ai_observability/backend/models/__init__.py@@ -2,6 +2,7 @@ from .clustering_config import ClusteringConfigfrom .clustering_job import ClusteringJobfrom .datasets import Dataset, DatasetItem, DatasetItemVersion, DatasetRevisionfrom .evaluation_config import EvaluationConfig+from .evaluation_directories import EvaluationDirectoryfrom .evaluation_reports import EvaluationReport, EvaluationReportRunfrom .evaluations import Evaluationfrom .llm_prompt import LLMPrompt, LLMPromptLabel@@ -19,6 +20,7 @@ __all__ = ["ClusteringJob","Evaluation","EvaluationConfig",+ "EvaluationDirectory","EvaluationReport","EvaluationReportRun","Dataset",diff --git a/products/ai_observability/backend/models/evaluation_directories.py b/products/ai_observability/backend/models/evaluation_directories.pynew file mode 100644index 000000000000..1cd041cf277c--- /dev/null+++ b/products/ai_observability/backend/models/evaluation_directories.py@@ -0,0 +1,40 @@+from django.db import models+from django.db.models.functions import Lower++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel+++class EvaluationDirectory(ModelActivityMixin, TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):+ activity_logging_on_delete = True++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ name = models.CharField(max_length=400)+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ related_name="+",+ )++ class Meta:+ db_table = "llm_analytics_evaluationdirectory"+ ordering = ["name", "id"]+ constraints = [+ models.UniqueConstraint(+ Lower("name"),+ "team",+ name="uniq_llma_eval_dir_team_name_ci",+ )+ ]++ def __str__(self) -> str:+ return self.name++ def _get_before_update(self, **kwargs: object) -> "EvaluationDirectory | None":+ if not self.pk:+ return None+ return EvaluationDirectory.objects.unscoped().filter(pk=self.pk).first()diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.pyindex 07d4b4d52ab8..3bc34ff8d9e9 100644--- a/products/ai_observability/backend/models/evaluations.py+++ b/products/ai_observability/backend/models/evaluations.py@@ -61,6 +61,10 @@ class Evaluation(ModelActivityMixin, UUIDTModel):models.Index(fields=["team", "-created_at", "id"]),models.Index(fields=["team", "enabled"]),models.Index(fields=["model_configuration"], name="llm_analyti_model_c_idx"),+ models.Index(+ fields=["team", "directory", "-created_at", "id"],+ name="llma_eval_team_dir_created_idx",+ ),]constraints = [models.CheckConstraint(@@ -76,6 +80,15 @@ class Evaluation(ModelActivityMixin, UUIDTModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)name = models.CharField(max_length=400)description = models.TextField(blank=True, default="")+ directory = models.ForeignKey(+ "ai_observability.EvaluationDirectory",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="evaluations",+ db_index=False,+ db_constraint=False,+ )# Lifecycle state. `status` is authoritative; `enabled` is a boolean projection kept in sync by save() for# backwards compatibility with existing API / DB callers. When status is ERROR, status_reason must be set.diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.pyindex d939072fc4d4..8ddd9aaf02fb 100644--- a/products/ai_observability/backend/routes.py+++ b/products/ai_observability/backend/routes.py@@ -13,6 +13,7 @@ from products.ai_observability.backend.api import (DatasetItemViewSet,DatasetViewSet,EvaluationConfigViewSet,+ EvaluationDirectoryViewSet,EvaluationReportViewSet,EvaluationRunViewSet,EvaluationViewSet,@@ -48,6 +49,12 @@ def register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"datasets", DatasetViewSet, "project_datasets", ["team_id"])routers.projects.register(r"dataset_items", DatasetItemViewSet, "project_dataset_items", ["team_id"])routers.projects.register(r"evaluations", EvaluationViewSet, "project_evaluations", ["team_id"])+ routers.projects.register(+ r"evaluation_directories",+ EvaluationDirectoryViewSet,+ "project_evaluation_directories",+ ["team_id"],+ )routers.projects.register(r"taggers", TaggerViewSet, "project_taggers", ["team_id"])routers.projects.register(r"evaluation_runs", EvaluationRunViewSet, "project_evaluation_runs", ["team_id"])routers.projects.register(diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsxindex 1e02323ab8c3..d8328fe5d438 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx@@ -2,12 +2,24 @@ import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'import { combineUrl, router } from 'kea-router'import { useEffect, useRef, useState } from 'react'-import { IconEye, IconHide, IconPencil, IconPlus, IconSearch, IconTrash, IconWarning } from '@posthog/icons'+import {+ IconArrowLeft,+ IconEye,+ IconFolder,+ IconHide,+ IconPencil,+ IconPlus,+ IconSearch,+ IconTrash,+ IconWarning,+} from '@posthog/icons'import {LemonBanner,LemonButton,LemonDialog,LemonInput,+ LemonMenu,+ LemonModal,LemonSwitch,LemonTab,LemonTable,@@ -24,11 +36,10 @@ import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'-import { deleteWithUndo } from 'lib/utils/deleteWithUndo'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { fullName } from 'lib/utils/strings'import { SceneExport } from 'scenes/sceneTypes'-import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'@@ -36,6 +47,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import type { EvaluationDirectoryApi } from '../generated/api.schemas'import { LLMProviderKey } from '../settings/llmProviderKeysLogic'import {getUnhealthyProviderKey,@@ -155,7 +167,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {const metricsLogic = evaluationMetricsLogic()const {evaluations,- filteredEvaluations,+ displayedEvaluations,evaluationsLoading,evaluationsFilter,showDisabledEvaluations,@@ -163,23 +175,44 @@ function AIObservabilityEvaluationsContent(): JSX.Element {providerKeys,unhealthyProviderKeysUsedByEvaluations,canEnableEvaluation,+ evaluationDirectories,+ evaluationDirectoriesLoading,+ selectedDirectory,+ selectedDirectoryId,+ directoryEditor,+ submitDirectoryLoading,+ deletingDirectoryId,+ movingEvaluationId,} = useValues(evaluationsLogic)- const { setEvaluationsFilter, setShowDisabledEvaluations, toggleEvaluationEnabled, loadEvaluations, setDates } =- useActions(evaluationsLogic)+ const {+ setEvaluationsFilter,+ setShowDisabledEvaluations,+ toggleEvaluationEnabled,+ setDates,+ openCreateDirectory,+ openRenameDirectory,+ closeDirectoryEditor,+ setDirectoryEditorName,+ submitDirectory,+ deleteDirectory,+ moveEvaluation,+ selectDirectory,+ deleteEvaluation,+ } = useActions(evaluationsLogic)const { evaluationsWithMetrics } = useValues(metricsLogic)- const { currentTeamId } = useValues(teamLogic)const { push } = useActions(router)const { searchParams } = useValues(router)const evaluationUrl = (id: string): string => combineUrl(urls.aiObservabilityEvaluation(id), searchParams).urlconst settingsUrl = urls.settings('project-ai-observability', 'ai-observability-byok')+ const moveEvaluationDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.LlmAnalytics,+ AccessControlLevel.Editor+ )const filteredEvaluationsWithMetrics = evaluationsWithMetrics.filter((evaluation: EvaluationConfig) =>- filteredEvaluations.some((filtered) => filtered.id === evaluation.id)+ displayedEvaluations.some((filtered) => filtered.id === evaluation.id))-- if (!evaluationsLoading && evaluations.length === 0) {- return <EvaluationTemplatesEmptyState />- }+ const directoryById = new Map(evaluationDirectories.map((directory) => [directory.id, directory]))const columns: LemonTableColumns<EvaluationConfig> = [{@@ -195,6 +228,17 @@ function AIObservabilityEvaluationsContent(): JSX.Element {),sorter: (a, b) => a.name.localeCompare(b.name),},+ {+ title: 'Directory',+ key: 'directory',+ render: (_, evaluation) =>+ evaluation.directory_id ? directoryById.get(evaluation.directory_id)?.name : 'Top level',+ sorter: (a, b) => {+ const directoryName = (evaluation: EvaluationConfig): string =>+ evaluation.directory_id ? directoryById.get(evaluation.directory_id)?.name || '' : ''+ return directoryName(a).localeCompare(directoryName(b))+ },+ },{title: 'Status',key: 'status',@@ -370,6 +414,37 @@ function AIObservabilityEvaluationsContent(): JSX.Element {key: 'actions',render: (_, evaluation) => (<div className="flex gap-1">+ <LemonMenu+ items={[+ {+ icon: <IconFolder />,+ label: 'Top level',+ onClick: () => moveEvaluation(evaluation.id, null),+ disabledReason:+ !evaluation.directory_id || movingEvaluationId === evaluation.id+ ? 'Evaluation is already here'+ : undefined,+ },+ ...evaluationDirectories.map((directory) => ({+ icon: <IconFolder />,+ label: directory.name,+ onClick: () => moveEvaluation(evaluation.id, directory.id),+ disabledReason:+ evaluation.directory_id === directory.id || movingEvaluationId === evaluation.id+ ? 'Evaluation is already here'+ : undefined,+ })),+ ]}+ >+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconFolder />}+ tooltip="Move evaluation"+ loading={movingEvaluationId === evaluation.id}+ disabledReason={moveEvaluationDisabledReason}+ />+ </LemonMenu><AccessControlActionresourceType={AccessControlResourceType.LlmAnalytics}minAccessLevel={AccessControlLevel.Editor}@@ -399,13 +474,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {type: 'primary',status: 'danger','data-attr': 'confirm-delete-evaluation',- onClick: () => {- deleteWithUndo({- endpoint: `environments/${currentTeamId}/evaluations`,- object: evaluation,- callback: () => loadEvaluations(),- })- },+ onClick: () => deleteEvaluation(evaluation.id),},secondaryButton: {children: 'Cancel',@@ -420,9 +489,90 @@ function AIObservabilityEvaluationsContent(): JSX.Element {},]+ const directoryColumns: LemonTableColumns<EvaluationDirectoryApi> = [+ {+ title: 'Name',+ key: 'name',+ render: (_, directory) => (+ <LemonButton+ type="tertiary"+ icon={<IconFolder />}+ onClick={() => selectDirectory(directory.id)}+ data-attr="evaluation-directory-link"+ >+ {directory.name}+ </LemonButton>+ ),+ sorter: (a, b) => a.name.localeCompare(b.name),+ },+ {+ title: 'Evaluations',+ key: 'evaluation_count',+ render: (_, directory) => directory.evaluation_count,+ sorter: (a, b) => a.evaluation_count - b.evaluation_count,+ },+ {+ title: 'Actions',+ key: 'actions',+ align: 'right',+ width: 0,+ render: (_, directory) => (+ <div className="flex justify-end gap-1">+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPencil />}+ tooltip="Rename directory"+ onClick={() => openRenameDirectory(directory)}+ />+ </AccessControlAction>+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="small"+ type="secondary"+ status="danger"+ icon={<IconTrash />}+ tooltip="Delete directory"+ loading={deletingDirectoryId === directory.id}+ onClick={() => {+ LemonDialog.open({+ title: `Delete ${directory.name}?`,+ description: `${directory.evaluation_count} evaluation${+ directory.evaluation_count === 1 ? '' : 's'+ } will move to the top level.`,+ primaryButton: {+ children: 'Delete directory',+ status: 'danger',+ onClick: () => deleteDirectory(directory.id),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ }}+ />+ </AccessControlAction>+ </div>+ ),+ },+ ]++ const showEmptyState =+ !evaluationsLoading &&+ !evaluationDirectoriesLoading &&+ evaluations.length === 0 &&+ evaluationDirectories.length === 0+return (<div className="space-y-4">- {unhealthyProviderKeysUsedByEvaluations.length > 0 && (+ {!showEmptyState && unhealthyProviderKeysUsedByEvaluations.length > 0 && (<LemonBanner type="warning"><div className="space-y-2"><p>Some evaluations are using API keys that need attention.</p>@@ -440,66 +590,146 @@ function AIObservabilityEvaluationsContent(): JSX.Element {</LemonBanner>)}- <div className="flex justify-between items-center">- <div>- <h2 className="text-xl font-semibold">Online evals</h2>+ <div className={showEmptyState ? 'hidden' : 'flex justify-between items-start gap-3'}>+ <div className="min-w-0 flex-1">+ {selectedDirectory ? (+ <div className="flex items-center gap-2">+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconArrowLeft />}+ onClick={() => selectDirectory(null)}+ >+ Online evals+ </LemonButton>+ <span className="text-muted">/</span>+ <h2 className="text-xl font-semibold m-0">{selectedDirectory.name}</h2>+ </div>+ ) : (+ <h2 className="text-xl font-semibold">Online evals</h2>+ )}<p className="text-muted">Configure evaluation prompts and triggers to automatically assess your AI generations. Eachevaluation run is billed as an AI observability event.</p></div>- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- type="primary"- icon={<IconPlus />}- to={combineUrl(urls.aiObservabilityEvaluationTemplates(), searchParams).url}- data-attr="create-evaluation-button"- tooltip="Create evaluation"+ <div className="flex shrink-0 items-center gap-2">+ {!selectedDirectoryId && (+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="secondary"+ icon={<IconFolder />}+ onClick={() => openCreateDirectory()}+ data-attr="create-evaluation-directory-button"+ >+ New directory+ </LemonButton>+ </AccessControlAction>+ )}+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}>- Create evaluation- </LemonButton>- </AccessControlAction>+ <LemonButton+ type="primary"+ icon={<IconPlus />}+ to={combineUrl(urls.aiObservabilityEvaluationTemplates(), searchParams).url}+ data-attr="create-evaluation-button"+ tooltip="Create evaluation"+ >+ Create evaluation+ </LemonButton>+ </AccessControlAction>+ </div></div>- <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />+ {showEmptyState ? (+ <EvaluationTemplatesEmptyState />+ ) : (+ <>+ <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />- <EvaluationMetrics />+ <EvaluationMetrics />++ <div className="flex items-center gap-2">+ <LemonInput+ type="search"+ placeholder="Search online evals..."+ value={evaluationsFilter}+ data-attr="evaluations-search-input"+ onChange={setEvaluationsFilter}+ prefix={<IconSearch />}+ className="max-w-sm"+ />+ <LemonButton+ type="secondary"+ active={!showDisabledEvaluations}+ icon={showDisabledEvaluations ? <IconEye /> : <IconHide />}+ onClick={() => setShowDisabledEvaluations(!showDisabledEvaluations)}+ data-attr="toggle-show-disabled-evaluations"+ tooltip={showDisabledEvaluations ? 'Hide disabled evals' : 'Show disabled evals'}+ >+ {showDisabledEvaluations ? 'Hide disabled' : 'Show disabled'}+ </LemonButton>+ </div>- <div className="flex items-center gap-2">+ {!evaluationsFilter && !selectedDirectoryId && (+ <LemonTable+ columns={directoryColumns}+ dataSource={evaluationDirectories}+ loading={evaluationDirectoriesLoading}+ rowKey="id"+ nouns={['directory', 'directories']}+ />+ )}++ <LemonTable+ columns={columns}+ dataSource={filteredEvaluationsWithMetrics}+ loading={evaluationsLoading || evaluationDirectoriesLoading}+ rowKey="id"+ pagination={{+ pageSize: 50,+ }}+ nouns={['evaluation', 'evaluations']}+ />+ </>+ )}++ <LemonModal+ isOpen={!!directoryEditor}+ onClose={closeDirectoryEditor}+ title={directoryEditor?.mode === 'rename' ? 'Rename directory' : 'New directory'}+ width={480}+ footer={+ <>+ <LemonButton type="secondary" onClick={closeDirectoryEditor} disabled={submitDirectoryLoading}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={() => submitDirectory()}+ loading={submitDirectoryLoading}+ disabledReason={!directoryEditor?.name.trim() ? 'Directory name is required' : undefined}+ data-attr="save-evaluation-directory"+ >+ {directoryEditor?.mode === 'rename' ? 'Save directory' : 'Create directory'}+ </LemonButton>+ </>+ }+ ><LemonInput- type="search"- placeholder="Search online evals..."- value={evaluationsFilter}- data-attr="evaluations-search-input"- onChange={setEvaluationsFilter}- prefix={<IconSearch />}- className="max-w-sm"+ value={directoryEditor?.name || ''}+ onChange={(value) => setDirectoryEditorName(String(value || ''))}+ placeholder="Directory name"+ autoFocus+ fullWidth+ data-attr="evaluation-directory-name-input"/>- <LemonButton- type="secondary"- active={!showDisabledEvaluations}- icon={showDisabledEvaluations ? <IconEye /> : <IconHide />}- onClick={() => setShowDisabledEvaluations(!showDisabledEvaluations)}- data-attr="toggle-show-disabled-evaluations"- tooltip={showDisabledEvaluations ? 'Hide disabled evals' : 'Show disabled evals'}- >- {showDisabledEvaluations ? 'Hide disabled' : 'Show disabled'}- </LemonButton>- </div>-- <LemonTable- columns={columns}- dataSource={filteredEvaluationsWithMetrics}- loading={evaluationsLoading}- rowKey="id"- pagination={{- pageSize: 50,- }}- nouns={['evaluation', 'evaluations']}- />+ </LemonModal></div>)}diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.tsnew file mode 100644index 000000000000..8201136fe491--- /dev/null+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts@@ -0,0 +1,111 @@+import { combineUrl, router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { urls } from 'scenes/urls'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { evaluationMetricsLogic, EvaluationStats } from './evaluationMetricsLogic'+import { llmEvaluationsLogic } from './llmEvaluationsLogic'+import { LLMJudgeEvaluation } from './types'++jest.mock('lib/api', () => {+ const actual = jest.requireActual('lib/api')++ return {+ __esModule: true,+ ...actual,+ default: {+ ...actual.default,+ query: jest.fn().mockResolvedValue({ results: [] }),+ },+ }+})++const evaluation = (id: string, directoryId: string | null): LLMJudgeEvaluation => ({+ id,+ name: `Evaluation ${id}`,+ description: '',+ directory_id: directoryId,+ enabled: true,+ status: 'active',+ status_reason: null,+ status_reason_detail: null,+ evaluation_type: 'llm_judge',+ evaluation_config: { prompt: 'Prompt' },+ output_type: 'boolean',+ output_config: {},+ conditions: [{ id: `condition-${id}`, rollout_percentage: 100, properties: [] }],+ target: 'generation',+ target_config: {},+ model_configuration: null,+ total_runs: 0,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+})++const stats = (evaluationId: string, runsCount: number): EvaluationStats => ({+ evaluation_id: evaluationId,+ runs_count: runsCount,+ applicable_count: runsCount,+ pass_count: runsCount,+ pass_rate: 100,+ applicability_rate: 100,+})++describe('evaluationMetricsLogic', () => {+ let evaluationsLogic: ReturnType<typeof llmEvaluationsLogic.build>+ let metricsLogic: ReturnType<typeof evaluationMetricsLogic.build>++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },+ '/api/environments/:teamId/llm_analytics/evaluation_config/': {+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ },+ '/api/projects/:teamId/evaluations/': { results: [] },+ '/api/projects/:teamId/evaluation_directories/': [],+ },+ })+ initKeaTests()+ evaluationsLogic = llmEvaluationsLogic()+ evaluationsLogic.mount()+ metricsLogic = evaluationMetricsLogic()+ metricsLogic.mount()++ await expectLogic(metricsLogic, () => metricsLogic.actions.loadStats()).toFinishAllListeners()+ })++ afterEach(() => {+ metricsLogic.unmount()+ evaluationsLogic.unmount()+ })++ it('scopes the graph and summary metrics when a directory is selected', () => {+ const rootEvaluation = evaluation('root', null)+ const directoryEvaluation = evaluation('inside', 'directory-a')++ evaluationsLogic.actions.loadEvaluationsSuccess([rootEvaluation, directoryEvaluation])+ metricsLogic.actions.loadStatsSuccess([stats(rootEvaluation.id, 4), stats(directoryEvaluation.id, 2)])++ expect(metricsLogic.values.chartQuery?.series).toEqual([+ expect.objectContaining({ custom_name: rootEvaluation.name }),+ ])+ expect(metricsLogic.values.summaryMetrics.total_runs).toBe(4)++ router.actions.push(+ combineUrl(urls.aiObservabilityEvaluations(), {+ directory: 'directory-a',+ }).url+ )++ expect(metricsLogic.values.chartQuery?.series).toEqual([+ expect.objectContaining({ custom_name: directoryEvaluation.name }),+ ])+ expect(metricsLogic.values.summaryMetrics.total_runs).toBe(2)+ })+})diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.tsindex a21b0eb25c7e..1b2ad208420f 100644--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts@@ -66,7 +66,9 @@ export interface evaluationMetricsLogicValues {dateTo: string | null} // llmEvaluationsLogicevaluations: EvaluationConfig[] // llmEvaluationsLogic+ selectedDirectoryId: string | null // llmEvaluationsLogicchartQuery: TrendsQuery | null+ evaluationsForMetrics: EvaluationConfig[]evaluationsWithMetrics: Array<EvaluationConfig & {stats?: EvaluationStats@@ -123,7 +125,11 @@ export interface evaluationMetricsLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface evaluationMetricsLogicMeta {__keaTypeGenInternalSelectorTypes: {- summaryMetrics: (stats: EvaluationStats[]) => SummaryMetrics+ evaluationsForMetrics: (+ evaluations: EvaluationConfig[],+ selectedDirectoryId: string | null+ ) => EvaluationConfig[]+ summaryMetrics: (stats: EvaluationStats[], evaluationsForMetrics: EvaluationConfig[]) => SummaryMetricsevaluationsWithMetrics: (evaluations: EvaluationConfig[],stats: EvaluationStats[]@@ -133,7 +139,7 @@ export interface evaluationMetricsLogicMeta {}>chartQuery: (- evaluations: EvaluationConfig[],+ evaluationsForMetrics: EvaluationConfig[],dateFilter: {dateFrom: string | nulldateTo: string | null@@ -154,7 +160,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([props({} as EvaluationMetricsLogicProps),connect(() => ({- values: [llmEvaluationsLogic, ['evaluations', 'dateFilter']],+ values: [llmEvaluationsLogic, ['evaluations', 'dateFilter', 'selectedDirectoryId']],actions: [llmEvaluationsLogic, ['setDates']],})),@@ -220,16 +226,23 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([})),selectors({+ evaluationsForMetrics: [+ (s) => [s.evaluations, s.selectedDirectoryId],+ (evaluations: EvaluationConfig[], selectedDirectoryId: string | null): EvaluationConfig[] =>+ evaluations.filter((evaluation) => (evaluation.directory_id ?? null) === selectedDirectoryId),+ ],summaryMetrics: [- (s) => [s.stats],- (stats: EvaluationStats[]): SummaryMetrics => {- const total_runs = stats.reduce((sum: number, stat) => sum + stat.runs_count, 0)- const total_applicable = stats.reduce((sum: number, stat) => sum + stat.applicable_count, 0)- const total_passes = stats.reduce((sum: number, stat) => sum + stat.pass_count, 0)+ (s) => [s.stats, s.evaluationsForMetrics],+ (stats: EvaluationStats[], evaluationsForMetrics: EvaluationConfig[]): SummaryMetrics => {+ const evaluationIds = new Set(evaluationsForMetrics.map((evaluation) => evaluation.id))+ const statsForMetrics = stats.filter((stat) => evaluationIds.has(stat.evaluation_id))+ const total_runs = statsForMetrics.reduce((sum: number, stat) => sum + stat.runs_count, 0)+ const total_applicable = statsForMetrics.reduce((sum: number, stat) => sum + stat.applicable_count, 0)+ const total_passes = statsForMetrics.reduce((sum: number, stat) => sum + stat.pass_count, 0)// Overall pass rate excludes N/A resultsconst overall_pass_rate = total_applicable > 0 ? (total_passes / total_applicable) * 100 : 0- const failing_count = stats.filter((stat) => {+ const failing_count = statsForMetrics.filter((stat) => {// Use applicable_count for minimum runs checkreturn (stat.applicable_count >= MIN_RUNS_FOR_FAILING_STATUS &&@@ -261,12 +274,12 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([],chartQuery: [- (s) => [s.evaluations, s.dateFilter],+ (s) => [s.evaluationsForMetrics, s.dateFilter],(- evaluations: EvaluationConfig[],+ evaluationsForMetrics: EvaluationConfig[],dateFilter: { dateFrom: string | null; dateTo: string | null }): TrendsQuery | null => {- const enabledEvaluations = evaluations.filter((e) => e.enabled && !e.deleted)+ const enabledEvaluations = evaluationsForMetrics.filter((e) => e.enabled && !e.deleted)if (enabledEvaluations.length === 0) {return nulldiff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.test.tsnew file mode 100644index 000000000000..bd300b25322d--- /dev/null+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts@@ -0,0 +1,69 @@+import { evaluationsList } from '../generated/api'+import type { EvaluationApi } from '../generated/api.schemas'+import { listAllEvaluations } from './evaluationsApi'++jest.mock('../generated/api', () => ({+ evaluationsList: jest.fn(),+ evaluationsPartialUpdate: jest.fn(),+}))++const evaluationApi = (id: string): EvaluationApi => ({+ id,+ name: `Evaluation ${id}`,+ description: '',+ directory_id: null,+ enabled: true,+ status: 'active',+ status_reason: null,+ status_reason_detail: null,+ evaluation_type: 'llm_judge',+ evaluation_config: { prompt: 'Check correctness' },+ output_type: 'boolean',+ output_config: {},+ conditions: [],+ target: 'generation',+ model_configuration: {+ provider: 'openai',+ model: 'gpt-5-mini',+ provider_key_id: null,+ provider_key_name: null,+ },+ created_at: `2024-01-0${id}T00:00:00Z`,+ updated_at: `2024-01-0${id}T00:00:00Z`,+ created_by: {+ id: 1,+ uuid: '00000000-0000-0000-0000-000000000001',+ email: '[email protected]',+ hedgehog_config: null,+ },+ deleted: false,+})++describe('evaluationsApi', () => {+ beforeEach(() => {+ jest.mocked(evaluationsList).mockReset()+ })++ it('loads every evaluations page', async () => {+ jest.mocked(evaluationsList)+ .mockResolvedValueOnce({+ count: 2,+ next: '/api/projects/1/evaluations/?limit=100&offset=1',+ previous: null,+ results: [evaluationApi('1')],+ })+ .mockResolvedValueOnce({+ count: 2,+ next: null,+ previous: '/api/projects/1/evaluations/?limit=100',+ results: [evaluationApi('2')],+ })++ await expect(listAllEvaluations('1')).resolves.toEqual([+ expect.objectContaining({ id: '1', evaluation_type: 'llm_judge' }),+ expect.objectContaining({ id: '2', evaluation_type: 'llm_judge' }),+ ])+ expect(evaluationsList).toHaveBeenNthCalledWith(1, '1', { limit: 100, offset: 0 })+ expect(evaluationsList).toHaveBeenNthCalledWith(2, '1', { limit: 100, offset: 1 })+ })+})diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.tsnew file mode 100644index 000000000000..cbcf59f21c80--- /dev/null+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.ts@@ -0,0 +1,125 @@+import type { AnyPropertyFilter } from '~/types'++import { evaluationsList, evaluationsPartialUpdate } from '../generated/api'+import type { EvaluationApi, PatchedEvaluationApi } from '../generated/api.schemas'+import type { EvaluationConfig, ModelConfiguration } from './types'++const EVALUATIONS_PAGE_SIZE = 100++function isPropertyFilter(value: unknown): value is AnyPropertyFilter {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function modelConfigurationFromApi(evaluation: EvaluationApi): ModelConfiguration | null {+ if (!evaluation.model_configuration) {+ return null+ }++ return {+ provider: evaluation.model_configuration.provider,+ model: evaluation.model_configuration.model,+ provider_key_id: evaluation.model_configuration.provider_key_id ?? null,+ provider_key_name: evaluation.model_configuration.provider_key_name,+ }+}++export function evaluationFromApi(evaluation: EvaluationApi): EvaluationConfig {+ const baseEvaluation = {+ id: evaluation.id,+ name: evaluation.name,+ description: evaluation.description,+ directory_id: evaluation.directory_id ?? null,+ enabled: evaluation.enabled ?? false,+ status: evaluation.status,+ status_reason: evaluation.status_reason,+ status_reason_detail: evaluation.status_reason_detail,+ output_config: evaluation.output_config ?? {},+ conditions: (evaluation.conditions ?? []).map((condition) => ({+ id: condition.id,+ rollout_percentage: condition.rollout_percentage,+ properties: (condition.properties ?? []).filter(isPropertyFilter),+ })),+ target: evaluation.target ?? 'generation',+ target_config: evaluation.target_config ?? {},+ model_configuration: modelConfigurationFromApi(evaluation),+ created_at: evaluation.created_at,+ updated_at: evaluation.updated_at,+ created_by: evaluation.created_by+ ? {+ id: evaluation.created_by.id,+ uuid: evaluation.created_by.uuid,+ distinct_id: evaluation.created_by.distinct_id ?? '',+ first_name: evaluation.created_by.first_name ?? '',+ last_name: evaluation.created_by.last_name,+ email: evaluation.created_by.email,+ is_email_verified: evaluation.created_by.is_email_verified,+ role_at_organization: evaluation.created_by.role_at_organization,+ }+ : null,+ deleted: evaluation.deleted,+ }++ if (+ evaluation.evaluation_type === 'llm_judge' &&+ evaluation.output_type === 'boolean' &&+ evaluation.evaluation_config &&+ 'prompt' in evaluation.evaluation_config+ ) {+ return {+ ...baseEvaluation,+ evaluation_type: 'llm_judge',+ output_type: 'boolean',+ evaluation_config: { prompt: evaluation.evaluation_config.prompt },+ }+ }++ if (+ evaluation.evaluation_type === 'hog' &&+ evaluation.output_type === 'boolean' &&+ evaluation.evaluation_config &&+ 'source' in evaluation.evaluation_config &&+ typeof evaluation.evaluation_config.source === 'string'+ ) {+ return {+ ...baseEvaluation,+ evaluation_type: 'hog',+ output_type: 'boolean',+ evaluation_config: { source: evaluation.evaluation_config.source },+ }+ }++ if (evaluation.evaluation_type === 'sentiment' && evaluation.output_type === 'sentiment') {+ return {+ ...baseEvaluation,+ evaluation_type: 'sentiment',+ output_type: 'sentiment',+ evaluation_config: { source: 'user_messages' },+ model_configuration: null,+ }+ }++ throw new Error(`Evaluation ${evaluation.id} has an invalid type or configuration`)+}++export async function listAllEvaluations(projectId: string): Promise<EvaluationConfig[]> {+ const evaluations: EvaluationConfig[] = []+ let offset = 0++ while (true) {+ const response = await evaluationsList(projectId, { limit: EVALUATIONS_PAGE_SIZE, offset })+ evaluations.push(...response.results.map(evaluationFromApi))++ if (!response.next || response.results.length === 0) {+ return evaluations+ }+ offset += response.results.length+ }+}++export async function patchEvaluation(+ projectId: string,+ evaluationId: string,+ update: PatchedEvaluationApi+): Promise<EvaluationConfig> {+ return evaluationFromApi(await evaluationsPartialUpdate(projectId, evaluationId, update))+}diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex cf33dc5f8b80..7dd545897a44 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'import posthog from 'posthog-js'+import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'@@ -912,6 +913,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([id: '',name: template?.name || '',description: template?.description || '',+ directory_id:+ typeof router.values.searchParams.directory === 'string'+ ? router.values.searchParams.directory+ : null,// Starting a keyless draft enabled would 400 on save for teams that require a key.enabled: !values.requiresProviderKey,status: 'active' as const,@@ -1014,6 +1019,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([id: '',name: '',description: '',+ directory_id:+ typeof router.values.searchParams.directory === 'string'+ ? router.values.searchParams.directory+ : null,enabled: !values.requiresProviderKey,status: 'active',status_reason: null,@@ -1086,6 +1095,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([values.evaluation as Parameters<typeof evaluationsPartialUpdate>[2])) as unknown as EvaluationConfigactions.saveEvaluationSuccess(response)+ if (isNew) {+ globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.SetUpLlmEvaluation)+ }// Piggyback the scheduled-report draft onto the main save so the single// "Save changes" button at the top of the page commits both forms. Thediff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.tsindex 6eff6f79fc05..376f3e0665a6 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts@@ -1,5 +1,8 @@+import { combineUrl, router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { urls } from 'scenes/urls'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -49,10 +52,15 @@ const mockProviderKeys: LLMProviderKey[] = [},]-const evaluationWithKey = (id: string, providerKeyId: string | null): LLMJudgeEvaluation => ({+const evaluationWithKey = (+ id: string,+ providerKeyId: string | null,+ directoryId: string | null = null+): LLMJudgeEvaluation => ({id,name: `Evaluation ${id}`,description: '',+ directory_id: directoryId,enabled: true,status: 'active',status_reason: null,@@ -105,7 +113,7 @@ describe('llmEvaluationsLogic', () => {created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',},- '/api/environments/:teamId/evaluations/': {+ '/api/projects/:teamId/evaluations/': {results: [evaluationWithKey('eval-ok', 'key-ok'),evaluationWithKey('eval-invalid', 'key-invalid'),@@ -114,6 +122,16 @@ describe('llmEvaluationsLogic', () => {evaluationWithKey('eval-default', null),],},+ '/api/projects/:teamId/evaluation_directories/': [+ {+ id: 'directory-a',+ name: 'Directory A',+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ created_by: null,+ evaluation_count: 1,+ },+ ],},})@@ -220,7 +238,7 @@ describe('llmEvaluationsLogic', () => {it('dispatches toggleEvaluationEnabledFailure when the API rejects the toggle', async () => {useMocks({patch: {- '/api/environments/:teamId/evaluations/:id/': () => [+ '/api/projects/:teamId/evaluations/:id/': () => [400,{enabled: ['Add a provider API key to enable this evaluation.'],@@ -272,5 +290,56 @@ describe('llmEvaluationsLogic', () => {filteredEvaluations: [enabledEval],})})++ it('scopes the list to a directory but searches across all directories', async () => {+ const rootEvaluation = evaluationWithKey('root', null)+ const directoryEvaluation = evaluationWithKey('inside', null, 'directory-a')++ router.actions.push(+ combineUrl(urls.aiObservabilityEvaluations(), {+ directory: 'directory-a',+ }).url+ )+ logic.actions.loadEvaluationsSuccess([rootEvaluation, directoryEvaluation])++ await expectLogic(logic).toMatchValues({+ selectedDirectoryId: 'directory-a',+ displayedEvaluations: [directoryEvaluation],+ })++ logic.actions.setEvaluationsFilter('root')++ await expectLogic(logic).toMatchValues({+ displayedEvaluations: [rootEvaluation],+ })+ })++ it('does not reload evaluations when the selected directory changes', async () => {+ const evaluation = evaluationWithKey('local-state', null)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadEvaluationsSuccess([evaluation])++ router.actions.push(+ combineUrl(urls.aiObservabilityEvaluations(), {+ directory: 'directory-a',+ }).url+ )+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.evaluations).toEqual([evaluation])+ })++ it('restores an evaluation in server list order', async () => {+ const newerEvaluation = {+ ...evaluationWithKey('newer', null),+ created_at: '2024-02-01T00:00:00Z',+ }+ const olderEvaluation = evaluationWithKey('older', null)+ logic.actions.loadEvaluationsSuccess([newerEvaluation])++ logic.actions.restoreEvaluationSuccess(olderEvaluation)++ expect(logic.values.evaluations).toEqual([newerEvaluation, olderEvaluation])+ })})})diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.tsindex bcf59a70af5e..a847741681ab 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts@@ -1,8 +1,7 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'import { combineUrl, router, urlToAction } from 'kea-router'-import api from 'lib/api'-import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -10,14 +9,19 @@ import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'-import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'-import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'+import {+ evaluationDirectoriesCreate,+ evaluationDirectoriesDestroy,+ evaluationDirectoriesList,+ evaluationDirectoriesPartialUpdate,+} from '../generated/api'+import type { EvaluationDirectoryApi } from '../generated/api.schemas'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'import { evaluationErrorMessage } from './apiErrors'import { evaluationCanResolveModel } from './evaluationCapabilities'+import { listAllEvaluations, patchEvaluation } from './evaluationsApi'import { EvaluationConfig } from './types'const INITIAL_DATE_FROM = '-24h' as string | null@@ -25,6 +29,12 @@ const INITIAL_DATE_TO = null as string | nullexport type LLMEvaluationsLogicProps = Record<string, never>+export interface EvaluationDirectoryEditor {+ mode: 'create' | 'rename'+ directoryId: string | null+ name: string+}+function redirectToOnlineEvaluations(searchParams: Record<string, unknown>): void {router.actions.replace(combineUrl(urls.aiObservabilityEvaluations(), {@@ -42,28 +52,47 @@ export interface llmEvaluationsLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicactiveProviderKey: LLMProviderKey | null | undefined // llmProviderKeysLogicproviderKeys: LLMProviderKey[] // llmProviderKeysLogic+ searchParams: Record<string, any> // routercanEnableEvaluation: (evaluation: EvaluationConfig) => booleandateFilter: {dateFrom: string | nulldateTo: string | null}+ deletingDirectoryId: string | null+ directoryEditor: EvaluationDirectoryEditor | null+ displayedEvaluations: EvaluationConfig[]+ evaluationDirectories: EvaluationDirectoryApi[]+ evaluationDirectoriesLoading: booleanevaluations: EvaluationConfig[]evaluationsFilter: stringevaluationsLoading: booleanfilteredEvaluations: EvaluationConfig[]+ movingEvaluationId: string | null+ selectedDirectory: EvaluationDirectoryApi | null+ selectedDirectoryId: string | nullshowDisabledEvaluations: boolean+ submitDirectoryLoading: booleanunhealthyProviderKeysUsedByEvaluations: LLMProviderKey[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmEvaluationsLogicActions {loadProviderKeys: () => any // llmProviderKeysLogic- addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic- createEvaluation: (evaluation: Partial<EvaluationConfig>) => {- evaluation: Partial<EvaluationConfig>+ closeDirectoryEditor: () => {+ value: true}- createEvaluationSuccess: (evaluation: EvaluationConfig) => {- evaluation: EvaluationConfig+ deleteDirectory: (id: string) => {+ id: string+ }+ deleteDirectoryFailure: (+ id: string,+ error: string+ ) => {+ error: string+ id: string+ }+ deleteDirectorySuccess: (id: string) => {+ id: string}deleteEvaluation: (id: string) => {id: string@@ -71,12 +100,60 @@ export interface llmEvaluationsLogicActions {deleteEvaluationSuccess: (id: string) => {id: string}+ loadEvaluationDirectories: () => any+ loadEvaluationDirectoriesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadEvaluationDirectoriesSuccess: (+ evaluationDirectories: EvaluationDirectoryApi[],+ payload?: any+ ) => {+ evaluationDirectories: EvaluationDirectoryApi[]+ payload?: any+ }loadEvaluations: () => {value: true}loadEvaluationsSuccess: (evaluations: EvaluationConfig[]) => {evaluations: EvaluationConfig[]}+ moveEvaluation: (+ id: string,+ directoryId: string | null+ ) => {+ directoryId: string | null+ id: string+ }+ moveEvaluationFailure: (+ id: string,+ error: string+ ) => {+ error: string+ id: string+ }+ moveEvaluationSuccess: (+ id: string,+ directoryId: string | null+ ) => {+ directoryId: string | null+ id: string+ }+ openCreateDirectory: () => {+ value: true+ }+ openRenameDirectory: (directory: EvaluationDirectoryApi) => {+ directory: EvaluationDirectoryApi+ }+ restoreEvaluationSuccess: (evaluation: EvaluationConfig) => {+ evaluation: EvaluationConfig+ }+ selectDirectory: (directoryId: string | null) => {+ directoryId: string | null+ }setDates: (dateFrom: string | null,dateTo: string | null@@ -84,12 +161,24 @@ export interface llmEvaluationsLogicActions {dateFrom: string | nulldateTo: string | null}+ setDirectoryEditorName: (name: string) => {+ name: string+ }setEvaluationsFilter: (filter: string) => {filter: string}setShowDisabledEvaluations: (show: boolean) => {show: boolean}+ submitDirectory: () => {+ value: true+ }+ submitDirectoryFailure: (error: string) => {+ error: string+ }+ submitDirectorySuccess: () => {+ value: true+ }toggleEvaluationEnabled: (id: string) => {id: string}@@ -103,20 +192,6 @@ export interface llmEvaluationsLogicActions {toggleEvaluationEnabledSuccess: (id: string) => {id: string}- updateEvaluation: (- id: string,- evaluation: Partial<EvaluationConfig>- ) => {- evaluation: Partial<EvaluationConfig>- id: string- }- updateEvaluationSuccess: (- id: string,- evaluation: Partial<EvaluationConfig>- ) => {- evaluation: Partial<EvaluationConfig>- id: string- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -127,6 +202,16 @@ export interface llmEvaluationsLogicMeta {evaluationsFilter: string,showDisabledEvaluations: boolean) => EvaluationConfig[]+ selectedDirectoryId: (searchParams: Record<string, any>) => string | null+ selectedDirectory: (+ evaluationDirectories: EvaluationDirectoryApi[],+ selectedDirectoryId: string | null+ ) => EvaluationDirectoryApi | null+ displayedEvaluations: (+ filteredEvaluations: EvaluationConfig[],+ evaluationsFilter: string,+ selectedDirectoryId: string | null+ ) => EvaluationConfig[]canEnableEvaluation: (activeProviderKey: LLMProviderKey | null | undefined) => (evaluation: EvaluationConfig) => boolean@@ -148,20 +233,38 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([path(['products', 'ai_observability', 'evaluations', 'llmEvaluationsLogic']),props({} as LLMEvaluationsLogicProps),connect(() => ({- values: [featureFlagLogic, ['featureFlags'], llmProviderKeysLogic, ['providerKeys', 'activeProviderKey']],- actions: [teamLogic, ['addProductIntent'], llmProviderKeysLogic, ['loadProviderKeys']],+ values: [+ featureFlagLogic,+ ['featureFlags'],+ llmProviderKeysLogic,+ ['providerKeys', 'activeProviderKey'],+ router,+ ['searchParams'],+ ],+ actions: [llmProviderKeysLogic, ['loadProviderKeys']],})),actions({setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),loadEvaluations: true,loadEvaluationsSuccess: (evaluations: EvaluationConfig[]) => ({ evaluations }),- createEvaluation: (evaluation: Partial<EvaluationConfig>) => ({ evaluation }),- createEvaluationSuccess: (evaluation: EvaluationConfig) => ({ evaluation }),- updateEvaluation: (id: string, evaluation: Partial<EvaluationConfig>) => ({ id, evaluation }),- updateEvaluationSuccess: (id: string, evaluation: Partial<EvaluationConfig>) => ({ id, evaluation }),deleteEvaluation: (id: string) => ({ id }),deleteEvaluationSuccess: (id: string) => ({ id }),+ restoreEvaluationSuccess: (evaluation: EvaluationConfig) => ({ evaluation }),+ openCreateDirectory: true,+ openRenameDirectory: (directory: EvaluationDirectoryApi) => ({ directory }),+ closeDirectoryEditor: true,+ setDirectoryEditorName: (name: string) => ({ name }),+ submitDirectory: true,+ submitDirectorySuccess: true,+ submitDirectoryFailure: (error: string) => ({ error }),+ deleteDirectory: (id: string) => ({ id }),+ deleteDirectorySuccess: (id: string) => ({ id }),+ deleteDirectoryFailure: (id: string, error: string) => ({ id, error }),+ moveEvaluation: (id: string, directoryId: string | null) => ({ id, directoryId }),+ moveEvaluationSuccess: (id: string, directoryId: string | null) => ({ id, directoryId }),+ moveEvaluationFailure: (id: string, error: string) => ({ id, error }),+ selectDirectory: (directoryId: string | null) => ({ directoryId }),toggleEvaluationEnabled: (id: string) => ({ id }),toggleEvaluationEnabledSuccess: (id: string) => ({ id }),toggleEvaluationEnabledFailure: (id: string, error: string) => ({ id, error }),@@ -184,12 +287,20 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([[] as EvaluationConfig[],{loadEvaluationsSuccess: (_, { evaluations }) => evaluations,- createEvaluationSuccess: (state, { evaluation }) => [...state, evaluation],- updateEvaluationSuccess: (state, { id, evaluation }) =>- state.map((e: EvaluationConfig) =>- e.id === id ? ({ ...e, ...evaluation } as EvaluationConfig) : e- ),deleteEvaluationSuccess: (state, { id }) => state.filter((e: EvaluationConfig) => e.id !== id),+ restoreEvaluationSuccess: (state, { evaluation }) =>+ [...state, evaluation].sort(+ (left, right) =>+ right.created_at.localeCompare(left.created_at) || left.id.localeCompare(right.id)+ ),+ deleteDirectorySuccess: (state, { id }) =>+ state.map((evaluation) =>+ evaluation.directory_id === id ? { ...evaluation, directory_id: null } : evaluation+ ),+ moveEvaluationSuccess: (state, { id, directoryId }) =>+ state.map((evaluation) =>+ evaluation.id === id ? { ...evaluation, directory_id: directoryId } : evaluation+ ),toggleEvaluationEnabledSuccess: (state, { id }) =>state.map((e: EvaluationConfig) =>e.id === id@@ -224,9 +335,69 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([setShowDisabledEvaluations: (_, { show }) => show,},],+ directoryEditor: [+ null as EvaluationDirectoryEditor | null,+ {+ openCreateDirectory: () => ({ mode: 'create', directoryId: null, name: '' }),+ openRenameDirectory: (_, { directory }) => ({+ mode: 'rename',+ directoryId: directory.id,+ name: directory.name,+ }),+ closeDirectoryEditor: () => null,+ setDirectoryEditorName: (state, { name }) => (state ? { ...state, name } : state),+ submitDirectorySuccess: () => null,+ },+ ],+ submitDirectoryLoading: [+ false,+ {+ submitDirectory: () => true,+ submitDirectorySuccess: () => false,+ submitDirectoryFailure: () => false,+ closeDirectoryEditor: () => false,+ },+ ],+ deletingDirectoryId: [+ null as string | null,+ {+ deleteDirectory: (_, { id }) => id,+ deleteDirectorySuccess: () => null,+ deleteDirectoryFailure: () => null,+ },+ ],+ movingEvaluationId: [+ null as string | null,+ {+ moveEvaluation: (_, { id }) => id,+ moveEvaluationSuccess: () => null,+ moveEvaluationFailure: () => null,+ },+ ],+ }),++ loaders({+ evaluationDirectories: [+ [] as EvaluationDirectoryApi[],+ {+ loadEvaluationDirectories: async () => {+ const teamId = teamLogic.values.currentTeamId+ return teamId ? await evaluationDirectoriesList(teamId.toString()) : []+ },+ },+ ],}),listeners(({ actions, values }) => ({+ loadEvaluationDirectoriesSuccess: ({ evaluationDirectories }) => {+ if (+ values.selectedDirectoryId &&+ !evaluationDirectories.some((directory) => directory.id === values.selectedDirectoryId)+ ) {+ actions.selectDirectory(null)+ }+ },+loadEvaluations: async () => {try {const teamId = teamLogic.values.currentTeamId@@ -234,88 +405,134 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([return}- // nosemgrep: prefer-codegen-api- const response = await api.get(`/api/environments/${teamId}/evaluations/`)- actions.loadEvaluationsSuccess(response.results)+ actions.loadEvaluationsSuccess(await listAllEvaluations(teamId.toString()))} catch (error) {console.error('Failed to load evaluations:', error)actions.loadEvaluationsSuccess([])}},- createEvaluation: async ({ evaluation }) => {+ deleteEvaluation: async ({ id }) => {try {const teamId = teamLogic.values.currentTeamIdif (!teamId) {return}-- // nosemgrep: prefer-codegen-api- const response = await api.create(`/api/environments/${teamId}/evaluations/`, evaluation)- actions.createEvaluationSuccess(response)-- // Trigger global tracking stuff for quick start + intent- globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.SetUpLlmEvaluation)- void actions.addProductIntent({- product_type: ProductKey.LLM_EVALUATIONS,- intent_context: ProductIntentContext.LLM_EVALUATION_CREATED,+ const evaluation = values.evaluations.find((item) => item.id === id)+ await patchEvaluation(teamId.toString(), id, { deleted: true })+ actions.deleteEvaluationSuccess(id)+ actions.loadEvaluationDirectories()+ lemonToast.info(`${evaluation?.name || 'Evaluation'} has been deleted.`, {+ button: {+ label: 'Undo',+ action: async () => {+ try {+ const restored = await patchEvaluation(teamId.toString(), id, {+ deleted: false,+ })+ actions.restoreEvaluationSuccess(restored)+ actions.loadEvaluationDirectories()+ lemonToast.success(`${evaluation?.name || 'Evaluation'} has been restored.`)+ } catch (error) {+ lemonToast.error(evaluationErrorMessage(error, 'Failed to restore evaluation'))+ }+ },+ },})} catch (error) {- console.error('Failed to create evaluation:', error)+ lemonToast.error(evaluationErrorMessage(error, 'Failed to delete evaluation'))}},- updateEvaluation: async ({ id, evaluation }) => {- try {- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- return- }+ toggleEvaluationEnabled: async ({ id }) => {+ const evaluation = values.evaluations.find((e: EvaluationConfig) => e.id === id)+ if (!evaluation) {+ return+ }++ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }- // nosemgrep: prefer-codegen-api- const response = await api.update(`/api/environments/${teamId}/evaluations/${id}/`, evaluation)- actions.updateEvaluationSuccess(id, response)+ try {+ await patchEvaluation(teamId.toString(), id, {+ enabled: !evaluation.enabled,+ })+ actions.toggleEvaluationEnabledSuccess(id)} catch (error) {- console.error('Failed to update evaluation:', error)+ const action = evaluation.enabled ? 'disable' : 'enable'+ const message = evaluationErrorMessage(error, `Failed to ${action} evaluation`)+ lemonToast.error(message)+ actions.toggleEvaluationEnabledFailure(id, message)}},- deleteEvaluation: async ({ id }) => {+ submitDirectory: async () => {+ const teamId = teamLogic.values.currentTeamId+ const editor = values.directoryEditor+ if (!teamId || !editor) {+ actions.submitDirectoryFailure('Directory details are unavailable.')+ return+ }++ const name = editor.name.trim()+ if (!name) {+ actions.submitDirectoryFailure('Enter a directory name.')+ return+ }+try {- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- return+ if (editor.mode === 'create') {+ await evaluationDirectoriesCreate(teamId.toString(), { name })+ } else if (editor.directoryId) {+ await evaluationDirectoriesPartialUpdate(teamId.toString(), editor.directoryId, { name })}- // nosemgrep: prefer-codegen-api- await api.update(`/api/environments/${teamId}/evaluations/${id}/`, { deleted: true })- actions.deleteEvaluationSuccess(id)+ actions.submitDirectorySuccess()+ actions.loadEvaluationDirectories()} catch (error) {- console.error('Failed to delete evaluation:', error)+ const message = evaluationErrorMessage(error, 'Failed to save directory')+ lemonToast.error(message)+ actions.submitDirectoryFailure(message)}},- toggleEvaluationEnabled: async ({ id }) => {- const evaluation = values.evaluations.find((e: EvaluationConfig) => e.id === id)- if (!evaluation) {+ deleteDirectory: async ({ id }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.deleteDirectoryFailure(id, 'Project details are unavailable.')return}+ try {+ await evaluationDirectoriesDestroy(teamId.toString(), id)+ actions.deleteDirectorySuccess(id)+ actions.loadEvaluationDirectories()+ if (values.selectedDirectoryId === id) {+ actions.selectDirectory(null)+ }+ } catch (error) {+ const message = evaluationErrorMessage(error, 'Failed to delete directory')+ lemonToast.error(message)+ actions.deleteDirectoryFailure(id, message)+ }+ },++ moveEvaluation: async ({ id, directoryId }) => {const teamId = teamLogic.values.currentTeamIdif (!teamId) {+ actions.moveEvaluationFailure(id, 'Project details are unavailable.')return}try {- // nosemgrep: prefer-codegen-api- await api.update(`/api/environments/${teamId}/evaluations/${id}/`, {- enabled: !evaluation.enabled,- })- actions.toggleEvaluationEnabledSuccess(id)+ await patchEvaluation(teamId.toString(), id, { directory_id: directoryId })+ actions.moveEvaluationSuccess(id, directoryId)+ actions.loadEvaluationDirectories()} catch (error) {- const action = evaluation.enabled ? 'disable' : 'enable'- const message = evaluationErrorMessage(error, `Failed to ${action} evaluation`)+ const message = evaluationErrorMessage(error, 'Failed to move evaluation')lemonToast.error(message)- actions.toggleEvaluationEnabledFailure(id, message)+ actions.moveEvaluationFailure(id, message)}},})),@@ -341,6 +558,32 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([)},],+ selectedDirectoryId: [+ (s) => [s.searchParams],+ (searchParams: Record<string, unknown>): string | null =>+ typeof searchParams.directory === 'string' ? searchParams.directory : null,+ ],+ selectedDirectory: [+ (s) => [s.evaluationDirectories, s.selectedDirectoryId],+ (+ directories: EvaluationDirectoryApi[],+ selectedDirectoryId: string | null+ ): EvaluationDirectoryApi | null =>+ directories.find((directory) => directory.id === selectedDirectoryId) ?? null,+ ],+ displayedEvaluations: [+ (s) => [s.filteredEvaluations, s.evaluationsFilter, s.selectedDirectoryId],+ (+ filteredEvaluations: EvaluationConfig[],+ evaluationsFilter: string,+ selectedDirectoryId: string | null+ ): EvaluationConfig[] =>+ evaluationsFilter+ ? filteredEvaluations+ : filteredEvaluations.filter(+ (evaluation) => (evaluation.directory_id ?? null) === selectedDirectoryId+ ),+ ],canEnableEvaluation: [(s) => [s.activeProviderKey],(activeProviderKey: LLMProviderKey | null | undefined) => {@@ -376,7 +619,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([}),urlToAction(({ actions, values }) => ({- [urls.aiObservabilityEvaluations()]: (_, searchParams, __, { method }) => {+ [urls.aiObservabilityEvaluations()]: (_, searchParams) => {const showOfflineEvals = !!values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_OFFLINE_EVALS]if (!showOfflineEvals && (searchParams.tab === 'offline' || searchParams.tab === 'offline-evals')) {@@ -395,10 +638,6 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([if (dateFrom !== values.dateFilter.dateFrom || dateTo !== values.dateFilter.dateTo) {actions.setDates(dateFrom, dateTo)}-- if (method !== 'REPLACE') {- actions.loadEvaluations()- }},[urls.aiObservabilityOfflineEvaluations()]: (_, searchParams) => {const showOfflineEvals = !!values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_OFFLINE_EVALS]@@ -427,10 +666,18 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([date_to: dateTo || undefined,},],+ selectDirectory: ({ directoryId }) => [+ urls.aiObservabilityEvaluations(),+ {+ ...router.values.searchParams,+ directory: directoryId ?? undefined,+ },+ ],})),afterMount(({ actions }) => {actions.loadProviderKeys()actions.loadEvaluations()+ actions.loadEvaluationDirectories()}),])diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.tsindex 377df041429e..e98c1dc0d12b 100644--- a/products/ai_observability/frontend/evaluations/types.ts+++ b/products/ai_observability/frontend/evaluations/types.ts@@ -67,6 +67,7 @@ export interface BaseEvaluationConfig {id: stringname: stringdescription?: string+ directory_id?: string | nullenabled: booleanstatus: EvaluationStatusstatus_reason: EvaluationStatusReason | null@@ -79,7 +80,7 @@ export interface BaseEvaluationConfig {/** Target-specific settings — see EvaluationTargetConfig. Empty for 'generation'. */target_config: EvaluationTargetConfigmodel_configuration: ModelConfiguration | null- total_runs: number+ total_runs?: numberlast_run_at?: stringcreated_at: stringupdated_at: stringdiff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 7d758bed73d2..5b1cd1ea3942 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -516,6 +516,38 @@ export interface PaginatedDatasetRevisionReadListApi {results: DatasetRevisionReadApi[]}+export interface EvaluationDirectoryApi {+ readonly id: string+ /**+ * Directory name shown in the online evals list.+ * @maxLength 400+ */+ name: string+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null+ /** User who created the directory. */+ readonly created_by: UserBasicApi | null+ /** Number of active evaluations in the directory. */+ readonly evaluation_count: number+}++export interface PatchedEvaluationDirectoryApi {+ readonly id?: string+ /**+ * Directory name shown in the online evals list.+ * @maxLength 400+ */+ name?: string+ readonly created_at?: string+ /** @nullable */+ readonly updated_at?: string | null+ /** User who created the directory. */+ readonly created_by?: UserBasicApi | null+ /** Number of active evaluations in the directory. */+ readonly evaluation_count?: number+}+export interface EvaluationRunRequestApi {/** UUID of the evaluation to run. */evaluation_id: string@@ -740,6 +772,11 @@ export interface EvaluationApi {name: string/** Optional description of what this evaluation checks. */description?: string+ /**+ * Directory containing the evaluation. Pass null to move the evaluation to the top level.+ * @nullable+ */+ directory_id?: string | null/** Whether the evaluation runs automatically on new $ai_generation events. */enabled?: booleanreadonly status: EvaluationStatusEnumApi@@ -778,7 +815,8 @@ export interface EvaluationApi {model_configuration?: ModelConfigurationApi | nullreadonly created_at: stringreadonly updated_at: string- readonly created_by: UserBasicApi+ /** User who created the evaluation. */+ readonly created_by: UserBasicApi | null/** Set to true to soft-delete the evaluation. */deleted?: boolean}@@ -863,6 +901,11 @@ export interface PatchedEvaluationApi {name?: string/** Optional description of what this evaluation checks. */description?: string+ /**+ * Directory containing the evaluation. Pass null to move the evaluation to the top level.+ * @nullable+ */+ directory_id?: string | null/** Whether the evaluation runs automatically on new $ai_generation events. */enabled?: booleanreadonly status?: EvaluationStatusEnumApi@@ -901,7 +944,8 @@ export interface PatchedEvaluationApi {model_configuration?: ModelConfigurationApi | nullreadonly created_at?: stringreadonly updated_at?: string- readonly created_by?: UserBasicApi+ /** User who created the evaluation. */+ readonly created_by?: UserBasicApi | null/** Set to true to soft-delete the evaluation. */deleted?: boolean}@@ -3043,6 +3087,14 @@ export type DatasetsRevisionsListParams = {export type EvaluationRunsCreate200 = { [key: string]: unknown }export type EvaluationsListParams = {+ /**+ * Filter evaluations by directory UUID.+ */+ directory_id?: string+ /**+ * Filter evaluations by whether they are at the top level.+ */+ directory_id__isnull?: boolean/*** Filter by enabled status*/diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.tsindex b08a1a63f831..92132148dcec 100644--- a/products/ai_observability/frontend/generated/api.ts+++ b/products/ai_observability/frontend/generated/api.ts@@ -29,6 +29,7 @@ import type {EvaluationApi,EvaluationConfigApi,EvaluationConfigSetActiveKeyRequestApi,+ EvaluationDirectoryApi,EvaluationReportApi,EvaluationReportUpdateApi,EvaluationRunRequestApi,@@ -81,6 +82,7 @@ import type {PatchedClusteringJobApi,PatchedDatasetUpdateApi,PatchedEvaluationApi,+ PatchedEvaluationDirectoryApi,PatchedEvaluationReportUpdateApi,PatchedLLMPromptPublishApi,PatchedLLMProviderKeyApi,@@ -486,6 +488,85 @@ export const datasetsRevisionsList = async (})}+export const getEvaluationDirectoriesListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/evaluation_directories/`+}++export const evaluationDirectoriesList = async (+ projectId: string,+ options?: RequestInit+): Promise<EvaluationDirectoryApi[]> => {+ return apiMutator<EvaluationDirectoryApi[]>(getEvaluationDirectoriesListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getEvaluationDirectoriesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/evaluation_directories/`+}++export const evaluationDirectoriesCreate = async (+ projectId: string,+ evaluationDirectoryApi: NonReadonly<EvaluationDirectoryApi>,+ options?: RequestInit+): Promise<EvaluationDirectoryApi> => {+ return apiMutator<EvaluationDirectoryApi>(getEvaluationDirectoriesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(evaluationDirectoryApi),+ })+}++export const getEvaluationDirectoriesRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/evaluation_directories/${id}/`+}++export const evaluationDirectoriesRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<EvaluationDirectoryApi> => {+ return apiMutator<EvaluationDirectoryApi>(getEvaluationDirectoriesRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getEvaluationDirectoriesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/evaluation_directories/${id}/`+}++export const evaluationDirectoriesPartialUpdate = async (+ projectId: string,+ id: string,+ patchedEvaluationDirectoryApi?: NonReadonly<PatchedEvaluationDirectoryApi>,+ options?: RequestInit+): Promise<EvaluationDirectoryApi> => {+ return apiMutator<EvaluationDirectoryApi>(getEvaluationDirectoriesPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedEvaluationDirectoryApi),+ })+}++export const getEvaluationDirectoriesDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/evaluation_directories/${id}/`+}++export const evaluationDirectoriesDestroy = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getEvaluationDirectoriesDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}+export const getEvaluationRunsCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/evaluation_runs/`}diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex 49e9fe807b19..9c19823d7d0d 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -176,6 +176,25 @@ export const DatasetsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Replacement JSON object for descriptive dataset metadata.'),})+export const evaluationDirectoriesCreateBodyNameMax = 400++export const EvaluationDirectoriesCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(evaluationDirectoriesCreateBodyNameMax)+ .describe('Directory name shown in the online evals list.'),+})++export const evaluationDirectoriesPartialUpdateBodyNameMax = 400++export const EvaluationDirectoriesPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(evaluationDirectoriesPartialUpdateBodyNameMax)+ .optional()+ .describe('Directory name shown in the online evals list.'),+})+/*** Create a new evaluation run.*@@ -221,6 +240,10 @@ export const evaluationsCreateBodyModelConfigurationOneModelMax = 100export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(evaluationsCreateBodyNameMax).describe('Name of the evaluation.'),description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .uuid()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),enabled: zod.boolean().optional()@@ -410,6 +433,10 @@ export const evaluationsUpdateBodyModelConfigurationOneModelMax = 100export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({name: zod.string().max(evaluationsUpdateBodyNameMax).describe('Name of the evaluation.'),description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .uuid()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),enabled: zod.boolean().optional()@@ -599,6 +626,10 @@ export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string().max(evaluationsPartialUpdateBodyNameMax).optional().describe('Name of the evaluation.'),description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .uuid()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),enabled: zod.boolean().optional()diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 8a8dff58444d..276c71aa5171 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -353,10 +353,11 @@ tools:Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider andmodel; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning aboolean). 'sentiment': output_type='sentiment', omit model_configuration, optional- evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session' — a+ evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. Asession target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass`enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it- paused). Results are '$ai_evaluation' events.+ paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit+ `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.llma-evaluation-delete:operation: evaluations_destroyenabled: true@@ -371,6 +372,67 @@ tools:Soft-delete an AI observability evaluation. The evaluation stops running and is hidden from list views.Historical evaluation results ($ai_evaluation events) are preserved.soft_delete: true+ llma-evaluation-directory-create:+ operation: evaluation_directories_create+ enabled: true+ scopes:+ - evaluation:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create evaluation directory+ description: >+ Create a top-level directory for organizing online evaluations. Directory names must be unique within the+ project, ignoring capitalization.+ llma-evaluation-directory-delete:+ operation: evaluation_directories_destroy+ enabled: true+ scopes:+ - evaluation:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete evaluation directory+ description: |+ Delete an evaluation directory. Evaluations in the directory are preserved and moved to the top level.+ llma-evaluation-directory-get:+ operation: evaluation_directories_retrieve+ enabled: true+ scopes:+ - evaluation:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get evaluation directory+ description: |+ Get an evaluation directory by UUID, including its name and active evaluation count.+ llma-evaluation-directory-list:+ operation: evaluation_directories_list+ enabled: true+ scopes:+ - evaluation:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List evaluation directories+ description: |+ List the project's evaluation directories and active evaluation counts.+ llma-evaluation-directory-update:+ operation: evaluation_directories_partial_update+ enabled: true+ scopes:+ - evaluation:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update evaluation directory+ description: |+ Rename an evaluation directory. Directory names must be unique within the project, ignoring capitalization.llma-evaluation-get:operation: evaluations_retrieveenabled: true@@ -413,10 +475,11 @@ tools:title: List evaluationsdescription: >List all AI observability evaluations for the current project. Optionally filter by name/description search- or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety,- sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog'- (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as- '$ai_evaluation' events.+ or enabled status. Pass `directory_id` to list evaluations in a directory, or `directory_id__isnull=true` to+ list only top-level evaluations. Call llma-evaluation-directory-list to find directory UUIDs. Evaluations+ automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria.+ Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and+ 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.llma-evaluation-report-create:operation: llm_analytics_evaluation_reports_createenabled: true@@ -594,14 +657,15 @@ tools:idempotent: truetitle: Update evaluationdescription: >- Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it,+ Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it,call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config,or change the model for an llm_judge. When switching to llm_judge, include model_configuration with providerand model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model orprovide both fields to replace it; null is rejected for configured judges. When switching an llm_judge tohog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remaineditable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or- 'session'.+ 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a+ directory, or pass null to move it to the top level.llma-evaluation-update-full:operation: evaluations_updateenabled: falsediff --git a/products/ai_observability/skills/creating-online-evaluations/SKILL.md b/products/ai_observability/skills/creating-online-evaluations/SKILL.mdindex bab461419321..f2bcb961c5d4 100644--- a/products/ai_observability/skills/creating-online-evaluations/SKILL.md+++ b/products/ai_observability/skills/creating-online-evaluations/SKILL.md@@ -37,17 +37,19 @@ debugging a live eval), defer to `exploring-llm-evaluations`.## Tools-| Tool | Purpose |-| -------------------------------------- | ------------------------------------------------------------- |-| `posthog:llma-evaluation-config-get` | Check the active provider key used by unpinned judges |-| `posthog:llma-provider-key-list` | Find a usable (`ok` state) provider key to pin |-| `posthog:llma-evaluation-judge-models` | List valid provider+model combos |-| `posthog:llma-evaluation-test-hog` | Dry-run Hog source against recent generations before creating |-| `posthog:llma-evaluation-create` | Create the evaluation (always `enabled: false` first) |-| `posthog:llma-evaluation-run` | Spot-run a draft eval against one generation |-| `posthog:llma-evaluation-update` | Iterate config, then flip `enabled: true` |-| `posthog:execute-sql` | Verify a condition matches the events and volume you expect |-| `posthog:generate-app-url` | Build a region- and project-qualified deep link to the eval |+| Tool | Purpose |+| ------------------------------------------ | ------------------------------------------------------------- |+| `posthog:llma-evaluation-config-get` | Check the active provider key used by unpinned judges |+| `posthog:llma-provider-key-list` | Find a usable (`ok` state) provider key to pin |+| `posthog:llma-evaluation-judge-models` | List valid provider+model combos |+| `posthog:llma-evaluation-directory-list` | List directories available for organizing the evaluation |+| `posthog:llma-evaluation-directory-create` | Create a directory when the user asks for a new one |+| `posthog:llma-evaluation-test-hog` | Dry-run Hog source against recent generations before creating |+| `posthog:llma-evaluation-create` | Create the evaluation (always `enabled: false` first) |+| `posthog:llma-evaluation-run` | Spot-run a draft eval against one generation |+| `posthog:llma-evaluation-update` | Iterate config, then flip `enabled: true` |+| `posthog:execute-sql` | Verify a condition matches the events and volume you expect |+| `posthog:generate-app-url` | Build a region- and project-qualified deep link to the eval |The full create payload (every field, the config schemas, the exact `conditions` shape) is in[references/evaluation-payload.md](references/evaluation-payload.md).@@ -234,6 +236,10 @@ enable it. Ask the user to add or validate a key in the UI before continuing.Create with `enabled: false` so nothing fires until the scope is verified. Minimal `hog` example:+Evaluations may be created at the top level or in one directory. If the user names a directory, call+`posthog:llma-evaluation-directory-list` and pass its UUID as `directory_id`. Create a directory only when+the user asks for one. Omit `directory_id` or pass `null` for the top level. Directories cannot be nested.+```jsonposthog:llma-evaluation-create{diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex b6525117b01c..1aa6b279f022 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1019,6 +1019,7 @@ export type ActivityLogListParams = {* * `ExternalDataSource` - ExternalDataSource* * `ExternalDataSchema` - ExternalDataSchema* * `Evaluation` - Evaluation+ * * `EvaluationDirectory` - EvaluationDirectory* * `LLMPrompt` - LLMPrompt* * `LLMPromptLabel` - LLMPromptLabel* * `LLMTrace` - LLMTrace@@ -1110,6 +1111,7 @@ export const ActivityLogListScope = {ExternalDataSource: 'ExternalDataSource',ExternalDataSchema: 'ExternalDataSchema',Evaluation: 'Evaluation',+ EvaluationDirectory: 'EvaluationDirectory',LLMPrompt: 'LLMPrompt',LLMPromptLabel: 'LLMPromptLabel',LLMTrace: 'LLMTrace',@@ -1188,6 +1190,7 @@ export const ActivityLogListScope = {* * `ExternalDataSource` - ExternalDataSource* * `ExternalDataSchema` - ExternalDataSchema* * `Evaluation` - Evaluation+ * * `EvaluationDirectory` - EvaluationDirectory* * `LLMPrompt` - LLMPrompt* * `LLMPromptLabel` - LLMPromptLabel* * `LLMTrace` - LLMTrace@@ -1267,6 +1270,7 @@ export const ActivityLogListScopesItem = {ExternalDataSource: 'ExternalDataSource',ExternalDataSchema: 'ExternalDataSchema',Evaluation: 'Evaluation',+ EvaluationDirectory: 'EvaluationDirectory',LLMPrompt: 'LLMPrompt',LLMPromptLabel: 'LLMPromptLabel',LLMTrace: 'LLMTrace',diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.mdindex 8c626d1563e1..5e18cda70872 100644--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md@@ -67,6 +67,7 @@ Schema reference for PostHog's core system models, organized by domain:- [Hog Functions](./references/models-hog-functions.md)- [Integrations](./references/models-integrations.md)- [AI observability events (`posthog.ai_events`)](./references/models-ai-observability-events.md)+- [AI observability evaluations](./references/models-ai-observability-evaluations.md)- [AI observability reviews](./references/models-ai-observability-reviews.md)- [Logs (`logs` data plane + saved views and alerts)](./references/models-logs.md)- [MCP analytics (`$mcp_tool_call` events)](./references/models-mcp.md)diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-ai-observability-evaluations.md b/products/posthog_ai/skills/querying-posthog-data/references/models-ai-observability-evaluations.mdnew file mode 100644index 000000000000..e8d48a210166--- /dev/null+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-ai-observability-evaluations.md@@ -0,0 +1,77 @@+# AI observability evaluations++## Evaluation directory (`system.evaluation_directories`)++Evaluation directories organize online evaluations. Directories are flat. An evaluation with no directory is at the top level.++### Columns++Column | Type | Nullable | Description+`id` | uuid | NOT NULL | Directory UUID+`team_id` | integer | NOT NULL | Owning team+`name` | varchar(400) | NOT NULL | Directory name+`created_by_id` | integer | NULL | User who created the directory+`created_at` | timestamp with tz | NOT NULL | Creation timestamp+`updated_at` | timestamp with tz | NULL | Last update timestamp++## Evaluation (`system.evaluations`)++Online evaluations score AI generations or traces. Evaluation results are stored as `$ai_evaluation` events, not on this configuration table.++### Columns++Column | Type | Nullable | Description+`id` | uuid | NOT NULL | Evaluation UUID+`team_id` | integer | NOT NULL | Owning team+`directory_id` | uuid | NULL | FK to `system.evaluation_directories.id`; NULL means the top level+`name` | varchar(400) | NOT NULL | Evaluation name+`description` | text | NOT NULL | Evaluation description+`enabled` | boolean | NOT NULL | Whether the evaluation is active+`status` | varchar(20) | NOT NULL | Current evaluation status+`status_reason` | varchar(50) | NULL | Reason for the current status, when available+`evaluation_type` | varchar(50) | NOT NULL | Evaluation implementation type+`evaluation_config` | jsonb | NOT NULL | Evaluation-specific configuration+`output_type` | varchar(50) | NOT NULL | Evaluation result type+`output_config` | jsonb | NOT NULL | Evaluation output configuration+`conditions` | jsonb | NOT NULL | Conditions that select matching input+`target` | varchar(20) | NOT NULL | Unit evaluated, such as a generation or trace+`target_config` | jsonb | NOT NULL | Target-specific configuration+`model_configuration_id` | uuid | NULL | Model configuration used by an LLM judge evaluation+`created_by_id` | integer | NULL | User who created the evaluation+`created_at` | timestamp with tz | NOT NULL | Creation timestamp+`updated_at` | timestamp with tz | NOT NULL | Last update timestamp+`deleted` | boolean | NOT NULL | Whether the evaluation has been deleted++### Important notes++- Filter on `deleted = false` to match the default online evals list.+- Use `directory_id IS NULL` for evaluations at the top level.+- Deleting a directory preserves its evaluations and sets their `directory_id` to NULL.++## Common query patterns++**List directories with active evaluation counts:**++```sql+SELECT+ d.id,+ d.name,+ count(e.id) AS evaluation_count+FROM system.evaluation_directories AS d+LEFT JOIN system.evaluations AS e+ ON e.directory_id = d.id+ AND e.deleted = false+GROUP BY d.id, d.name+ORDER BY d.name ASC+```++**List active evaluations at the top level:**++```sql+SELECT id, name, evaluation_type, status, updated_at+FROM system.evaluations+WHERE deleted = false+ AND directory_id IS NULL+ORDER BY updated_at DESC+LIMIT 100+```diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 620c24918eba..5e2c21b87b41 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5288,7 +5288,7 @@}},"llma-evaluation-create": {- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session' — a session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.",+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.","category": "AI observability","feature": "llm_analytics","summary": "Create evaluation",@@ -5315,6 +5315,76 @@"readOnlyHint": false}},+ "llma-evaluation-directory-create": {+ "description": "Create a top-level directory for organizing online evaluations. Directory names must be unique within the project, ignoring capitalization.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Create evaluation directory",+ "title": "Create evaluation directory",+ "required_scopes": ["evaluation:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "llma-evaluation-directory-delete": {+ "description": "Delete an evaluation directory. Evaluations in the directory are preserved and moved to the top level.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Delete evaluation directory",+ "title": "Delete evaluation directory",+ "required_scopes": ["evaluation:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "llma-evaluation-directory-get": {+ "description": "Get an evaluation directory by UUID, including its name and active evaluation count.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Get evaluation directory",+ "title": "Get evaluation directory",+ "required_scopes": ["evaluation:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "llma-evaluation-directory-list": {+ "description": "List the project's evaluation directories and active evaluation counts.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "List evaluation directories",+ "title": "List evaluation directories",+ "required_scopes": ["evaluation:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "llma-evaluation-directory-update": {+ "description": "Rename an evaluation directory. Directory names must be unique within the project, ignoring capitalization.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Update evaluation directory",+ "title": "Update evaluation directory",+ "required_scopes": ["evaluation:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"llma-evaluation-get": {"description": "Get a specific AI observability evaluation by its UUID. Requires the evaluation `id` (UUID) as a parameter — if you don't have it, call llma-evaluation-list first to look it up by name. Returns the full evaluation configuration including type, config, output type, enabled status, and model configuration.","category": "AI observability",@@ -5344,7 +5414,7 @@}},"llma-evaluation-list": {- "description": "List all AI observability evaluations for the current project. Optionally filter by name/description search or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.",+ "description": "List all AI observability evaluations for the current project. Optionally filter by name/description search or enabled status. Pass `directory_id` to list evaluations in a directory, or `directory_id__isnull=true` to list only top-level evaluations. Call llma-evaluation-directory-list to find directory UUIDs. Evaluations automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.","category": "AI observability","feature": "llm_analytics","summary": "List evaluations",@@ -5485,7 +5555,7 @@}},"llma-evaluation-update": {- "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'.",+ "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or pass null to move it to the top level.","category": "AI observability","feature": "llm_analytics","summary": "Update evaluation",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex bd9960962961..4aeaade6a8c1 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5583,7 +5583,7 @@}},"llma-evaluation-create": {- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session' — a session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). Results are '$ai_evaluation' events.",+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.","category": "AI observability","feature": "llm_analytics","summary": "Create evaluation",@@ -5610,6 +5610,76 @@"readOnlyHint": false}},+ "llma-evaluation-directory-create": {+ "description": "Create a top-level directory for organizing online evaluations. Directory names must be unique within the project, ignoring capitalization.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Create evaluation directory",+ "title": "Create evaluation directory",+ "required_scopes": ["evaluation:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "llma-evaluation-directory-delete": {+ "description": "Delete an evaluation directory. Evaluations in the directory are preserved and moved to the top level.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Delete evaluation directory",+ "title": "Delete evaluation directory",+ "required_scopes": ["evaluation:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "llma-evaluation-directory-get": {+ "description": "Get an evaluation directory by UUID, including its name and active evaluation count.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Get evaluation directory",+ "title": "Get evaluation directory",+ "required_scopes": ["evaluation:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "llma-evaluation-directory-list": {+ "description": "List the project's evaluation directories and active evaluation counts.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "List evaluation directories",+ "title": "List evaluation directories",+ "required_scopes": ["evaluation:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "llma-evaluation-directory-update": {+ "description": "Rename an evaluation directory. Directory names must be unique within the project, ignoring capitalization.",+ "category": "AI observability",+ "feature": "llm_analytics",+ "summary": "Update evaluation directory",+ "title": "Update evaluation directory",+ "required_scopes": ["evaluation:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"llma-evaluation-get": {"description": "Get a specific AI observability evaluation by its UUID. Requires the evaluation `id` (UUID) as a parameter — if you don't have it, call llma-evaluation-list first to look it up by name. Returns the full evaluation configuration including type, config, output type, enabled status, and model configuration.","category": "AI observability",@@ -5639,7 +5709,7 @@}},"llma-evaluation-list": {- "description": "List all AI observability evaluations for the current project. Optionally filter by name/description search or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.",+ "description": "List all AI observability evaluations for the current project. Optionally filter by name/description search or enabled status. Pass `directory_id` to list evaluations in a directory, or `directory_id__isnull=true` to list only top-level evaluations. Call llma-evaluation-directory-list to find directory UUIDs. Evaluations automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.","category": "AI observability","feature": "llm_analytics","summary": "List evaluations",@@ -5780,7 +5850,7 @@}},"llma-evaluation-update": {- "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID) — if you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'.",+ "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or pass null to move it to the top level.","category": "AI observability","feature": "llm_analytics","summary": "Update evaluation",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fc255888962a..fcc245905358 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27258,6 +27258,11 @@ export namespace Schemas {name: string;/** Optional description of what this evaluation checks. */description?: string;+ /**+ * Directory containing the evaluation. Pass null to move the evaluation to the top level.+ * @nullable+ */+ directory_id?: string | null;/** Whether the evaluation runs automatically on new $ai_generation events. */enabled?: boolean;readonly status: EvaluationStatusEnum;@@ -27296,7 +27301,8 @@ export namespace Schemas {model_configuration?: ModelConfiguration | null;readonly created_at: string;readonly updated_at: string;- readonly created_by: UserBasic;+ /** User who created the evaluation. */+ readonly created_by: UserBasic | null;/** Set to true to soft-delete the evaluation. */deleted?: boolean;}@@ -27382,6 +27388,22 @@ export namespace Schemas {hidden_from_suggestions: boolean;}+ export interface EvaluationDirectory {+ readonly id: string;+ /**+ * Directory name shown in the online evals list.+ * @maxLength 400+ */+ name: string;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ /** User who created the directory. */+ readonly created_by: UserBasic | null;+ /** Number of active evaluations in the directory. */+ readonly evaluation_count: number;+ }+export interface EvaluationPattern {title: string;description: string;@@ -52362,6 +52384,11 @@ export namespace Schemas {name?: string;/** Optional description of what this evaluation checks. */description?: string;+ /**+ * Directory containing the evaluation. Pass null to move the evaluation to the top level.+ * @nullable+ */+ directory_id?: string | null;/** Whether the evaluation runs automatically on new $ai_generation events. */enabled?: boolean;readonly status?: EvaluationStatusEnum;@@ -52400,11 +52427,28 @@ export namespace Schemas {model_configuration?: ModelConfiguration | null;readonly created_at?: string;readonly updated_at?: string;- readonly created_by?: UserBasic;+ /** User who created the evaluation. */+ readonly created_by?: UserBasic | null;/** Set to true to soft-delete the evaluation. */deleted?: boolean;}+ export interface PatchedEvaluationDirectory {+ readonly id?: string;+ /**+ * Directory name shown in the online evals list.+ * @maxLength 400+ */+ name?: string;+ readonly created_at?: string;+ /** @nullable */+ readonly updated_at?: string | null;+ /** User who created the directory. */+ readonly created_by?: UserBasic | null;+ /** Number of active evaluations in the directory. */+ readonly evaluation_count?: number;+ }+export interface PatchedEvaluationReportUpdate {readonly id?: string;/** UUID of the evaluation this report config belongs to. */@@ -77955,6 +77999,7 @@ export namespace Schemas {* * `ExternalDataSource` - ExternalDataSource* * `ExternalDataSchema` - ExternalDataSchema* * `Evaluation` - Evaluation+ * * `EvaluationDirectory` - EvaluationDirectory* * `LLMPrompt` - LLMPrompt* * `LLMPromptLabel` - LLMPromptLabel* * `LLMTrace` - LLMTrace@@ -78047,6 +78092,7 @@ export namespace Schemas {ExternalDataSource: 'ExternalDataSource',ExternalDataSchema: 'ExternalDataSchema',Evaluation: 'Evaluation',+ EvaluationDirectory: 'EvaluationDirectory',LLMPrompt: 'LLMPrompt',LLMPromptLabel: 'LLMPromptLabel',LLMTrace: 'LLMTrace',@@ -78125,6 +78171,7 @@ export namespace Schemas {* * `ExternalDataSource` - ExternalDataSource* * `ExternalDataSchema` - ExternalDataSchema* * `Evaluation` - Evaluation+ * * `EvaluationDirectory` - EvaluationDirectory* * `LLMPrompt` - LLMPrompt* * `LLMPromptLabel` - LLMPromptLabel* * `LLMTrace` - LLMTrace@@ -78205,6 +78252,7 @@ export namespace Schemas {ExternalDataSource: 'ExternalDataSource',ExternalDataSchema: 'ExternalDataSchema',Evaluation: 'Evaluation',+ EvaluationDirectory: 'EvaluationDirectory',LLMPrompt: 'LLMPrompt',LLMPromptLabel: 'LLMPromptLabel',LLMTrace: 'LLMTrace',@@ -80516,6 +80564,14 @@ export namespace Schemas {export type EvaluationRunsCreate200 = { [key: string]: unknown };export type EvaluationsListParams = {+ /**+ * Filter evaluations by directory UUID.+ */+ directory_id?: string;+ /**+ * Filter evaluations by whether they are at the top level.+ */+ directory_id__isnull?: boolean;/*** Filter by enabled status*/diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 9b055272e7ed..d96216ed674e 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 66 enabled ops+ * PostHog API - MCP 71 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -304,6 +304,68 @@ export const DatasetsRestoreParams = /* @__PURE__ */ zod.object({),})+export const EvaluationDirectoriesListParams = /* @__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 EvaluationDirectoriesCreateParams = /* @__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 evaluationDirectoriesCreateBodyNameMax = 400++export const EvaluationDirectoriesCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(evaluationDirectoriesCreateBodyNameMax)+ .describe('Directory name shown in the online evals list.'),+})++export const EvaluationDirectoriesRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this evaluation directory.'),+ 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 EvaluationDirectoriesPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this evaluation directory.'),+ 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 evaluationDirectoriesPartialUpdateBodyNameMax = 400++export const EvaluationDirectoriesPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(evaluationDirectoriesPartialUpdateBodyNameMax)+ .optional()+ .describe('Directory name shown in the online evals list.'),+})++export const EvaluationDirectoriesDestroyParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this evaluation directory.'),+ 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\/."+ ),+})+/*** Create a new evaluation run.*@@ -342,6 +404,8 @@ export const EvaluationsListParams = /* @__PURE__ */ zod.object({})export const EvaluationsListQueryParams = /* @__PURE__ */ zod.object({+ directory_id: zod.string().optional().describe('Filter evaluations by directory UUID.'),+ directory_id__isnull: zod.boolean().optional().describe('Filter evaluations by whether they are at the top level.'),enabled: zod.boolean().optional().describe('Filter by enabled status'),evaluation_type: zod.enum(['hog', 'llm_judge', 'sentiment'])@@ -393,6 +457,10 @@ export const evaluationsCreateBodyModelConfigurationOneModelMax = 100export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(evaluationsCreateBodyNameMax).describe('Name of the evaluation.'),description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .string()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),enabled: zod.boolean().optional()@@ -600,6 +668,10 @@ export const evaluationsPartialUpdateBodyModelConfigurationOneModelMax = 100export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string().max(evaluationsPartialUpdateBodyNameMax).optional().describe('Name of the evaluation.'),description: zod.string().optional().describe('Optional description of what this evaluation checks.'),+ directory_id: zod+ .string()+ .nullish()+ .describe('Directory containing the evaluation. Pass null to move the evaluation to the top level.'),enabled: zod.boolean().optional()diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex 135242d13fe0..f05154f7a7da 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -15,6 +15,11 @@ import {DatasetsPartialUpdateBody,DatasetsPartialUpdateParams,DatasetsRestoreParams,+ EvaluationDirectoriesCreateBody,+ EvaluationDirectoriesDestroyParams,+ EvaluationDirectoriesPartialUpdateBody,+ EvaluationDirectoriesPartialUpdateParams,+ EvaluationDirectoriesRetrieveParams,EvaluationRunsCreateBody,EvaluationsCreateBody,EvaluationsDestroyParams,@@ -557,6 +562,9 @@ const llmaEvaluationCreate = (): ToolBase<typeof LlmaEvaluationCreateSchema, Schif (params.description !== undefined) {body['description'] = params.description}+ if (params.directory_id !== undefined) {+ body['directory_id'] = params.directory_id+ }if (params.enabled !== undefined) {body['enabled'] = params.enabled}@@ -612,6 +620,106 @@ const llmaEvaluationDelete = (): ToolBase<typeof LlmaEvaluationDeleteSchema, Sch},})+const LlmaEvaluationDirectoryCreateSchema = EvaluationDirectoriesCreateBody++const llmaEvaluationDirectoryCreate = (): ToolBase<+ typeof LlmaEvaluationDirectoryCreateSchema,+ Schemas.EvaluationDirectory+> => ({+ name: 'llma-evaluation-directory-create',+ schema: LlmaEvaluationDirectoryCreateSchema,+ handler: async (context: Context, params: z.infer<typeof LlmaEvaluationDirectoryCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ const result = await context.api.request<Schemas.EvaluationDirectory>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluation_directories/`,+ body,+ })+ return result+ },+})++const LlmaEvaluationDirectoryDeleteSchema = EvaluationDirectoriesDestroyParams.omit({ project_id: true })++const llmaEvaluationDirectoryDelete = (): ToolBase<typeof LlmaEvaluationDirectoryDeleteSchema, unknown> => ({+ name: 'llma-evaluation-directory-delete',+ schema: LlmaEvaluationDirectoryDeleteSchema,+ handler: async (context: Context, params: z.infer<typeof LlmaEvaluationDirectoryDeleteSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'DELETE',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluation_directories/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const LlmaEvaluationDirectoryGetSchema = EvaluationDirectoriesRetrieveParams.omit({ project_id: true })++const llmaEvaluationDirectoryGet = (): ToolBase<+ typeof LlmaEvaluationDirectoryGetSchema,+ Schemas.EvaluationDirectory+> => ({+ name: 'llma-evaluation-directory-get',+ schema: LlmaEvaluationDirectoryGetSchema,+ handler: async (context: Context, params: z.infer<typeof LlmaEvaluationDirectoryGetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.EvaluationDirectory>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluation_directories/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const LlmaEvaluationDirectoryListSchema = z.object({})++const llmaEvaluationDirectoryList = (): ToolBase<+ typeof LlmaEvaluationDirectoryListSchema,+ Schemas.EvaluationDirectory[]+> => ({+ name: 'llma-evaluation-directory-list',+ schema: LlmaEvaluationDirectoryListSchema,+ // eslint-disable-next-line no-unused-vars+ handler: async (context: Context, params: z.infer<typeof LlmaEvaluationDirectoryListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.EvaluationDirectory[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluation_directories/`,+ })+ return result+ },+})++const LlmaEvaluationDirectoryUpdateSchema = EvaluationDirectoriesPartialUpdateParams.omit({ project_id: true }).extend(+ EvaluationDirectoriesPartialUpdateBody.shape+)++const llmaEvaluationDirectoryUpdate = (): ToolBase<+ typeof LlmaEvaluationDirectoryUpdateSchema,+ Schemas.EvaluationDirectory+> => ({+ name: 'llma-evaluation-directory-update',+ schema: LlmaEvaluationDirectoryUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof LlmaEvaluationDirectoryUpdateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ const result = await context.api.request<Schemas.EvaluationDirectory>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluation_directories/${encodeURIComponent(String(params.id))}/`,+ body,+ })+ return result+ },+})+const LlmaEvaluationGetSchema = EvaluationsRetrieveParams.omit({ project_id: true })const llmaEvaluationGet = (): ToolBase<typeof LlmaEvaluationGetSchema, Schemas.Evaluation> => ({@@ -660,6 +768,8 @@ const llmaEvaluationList = (): ToolBase<typeof LlmaEvaluationListSchema, Schemasmethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluations/`,query: {+ directory_id: params.directory_id,+ directory_id__isnull: params.directory_id__isnull,enabled: params.enabled,evaluation_type: params.evaluation_type,id__in: Array.isArray(params.id__in) ? params.id__in.join(',') || undefined : params.id__in,@@ -961,6 +1071,9 @@ const llmaEvaluationUpdate = (): ToolBase<typeof LlmaEvaluationUpdateSchema, Schif (params.description !== undefined) {body['description'] = params.description}+ if (params.directory_id !== undefined) {+ body['directory_id'] = params.directory_id+ }if (params.enabled !== undefined) {body['enabled'] = params.enabled}@@ -2211,6 +2324,11 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'llma-evaluation-config-set-active-key': llmaEvaluationConfigSetActiveKey,'llma-evaluation-create': llmaEvaluationCreate,'llma-evaluation-delete': llmaEvaluationDelete,+ 'llma-evaluation-directory-create': llmaEvaluationDirectoryCreate,+ 'llma-evaluation-directory-delete': llmaEvaluationDirectoryDelete,+ 'llma-evaluation-directory-get': llmaEvaluationDirectoryGet,+ 'llma-evaluation-directory-list': llmaEvaluationDirectoryList,+ 'llma-evaluation-directory-update': llmaEvaluationDirectoryUpdate,'llma-evaluation-get': llmaEvaluationGet,'llma-evaluation-judge-models': llmaEvaluationJudgeModels,'llma-evaluation-list': llmaEvaluationList,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.jsonindex 5c59fa07d977..acdc036c303e 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json@@ -43,6 +43,17 @@"description": "Optional description of what this evaluation checks.","type": "string"},+ "directory_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Directory containing the evaluation. Pass null to move the evaluation to the top level."+ },"enabled": {"description": "Whether the evaluation runs automatically on new $ai_generation events.","type": "boolean"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-create.jsonnew file mode 100644index 000000000000..2e1e4e3acdd9--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-create.json@@ -0,0 +1,12 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "name": {+ "description": "Directory name shown in the online evals list.",+ "maxLength": 400,+ "type": "string"+ }+ },+ "required": ["name"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-delete.jsonnew file mode 100644index 000000000000..fc2cd57954ee--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-delete.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this evaluation directory.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-get.jsonnew file mode 100644index 000000000000..fc2cd57954ee--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-get.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this evaluation directory.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-list.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-list.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-update.jsonnew file mode 100644index 000000000000..95a638a0e6ca--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-directory-update.json@@ -0,0 +1,16 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this evaluation directory.",+ "type": "string"+ },+ "name": {+ "description": "Directory name shown in the online evals list.",+ "maxLength": 400,+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.jsonindex c52e707df84d..c72dd1f85c4d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.json@@ -1,6 +1,14 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "directory_id": {+ "description": "Filter evaluations by directory UUID.",+ "type": "string"+ },+ "directory_id__isnull": {+ "description": "Filter evaluations by whether they are at the top level.",+ "type": "boolean"+ },"enabled": {"description": "Filter by enabled status","type": "boolean"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.jsonindex 5be10dd479c0..529ceb800f95 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json@@ -43,6 +43,17 @@"description": "Optional description of what this evaluation checks.","type": "string"},+ "directory_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Directory containing the evaluation. Pass null to move the evaluation to the top level."+ },"enabled": {"description": "Whether the evaluation runs automatically on new $ai_generation events.","type": "boolean"