Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(aio): add categorical online evaluation outputs (#107289)

Bernat Torres68ae961e99fa
diff --git a/.github/new-events-schema-targets.txt b/.github/new-events-schema-targets.txt
index 62e6551cd81e..f4b250e59cd3 100644
--- a/.github/new-events-schema-targets.txt
+++ b/.github/new-events-schema-targets.txt
@@ -44,6 +44,7 @@ posthog/models/test/test_deletion_targets.py
posthog/tasks/test/test_ai_observability_usage_report.py
posthog/tasks/test/test_usage_report.py
posthog/temporal/tests/test_clickhouse.py
+posthog/temporal/ai_observability/eval_reports/test/test_activities.py
products/batch_exports/backend/tests/api/test_serializers.py
products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
products/batch_exports/backend/tests/temporal/pipeline/test_internal_stage.py
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.md
index e844d3647a68..7490308afc61 100644
--- a/docs/internal/ai-observability-judge-inputs.md
+++ b/docs/internal/ai-observability-judge-inputs.md
@@ -54,6 +54,7 @@ The playground keeps the provider's explanation so users can correct the setting
Boolean online evaluations write their raw verdict to `$ai_evaluation_result`.
Numeric evaluations write their score to `$ai_evaluation_numeric_result`, with optional `$ai_evaluation_numeric_result_min` and `$ai_evaluation_numeric_result_max` bounds.
`$ai_evaluation_result_type` identifies the output type; events without it are legacy boolean results.
+Categorical evaluations write a list of category keys to `$ai_evaluation_categorical_result`, including for single selection.
Sentiment evaluations keep their `$ai_sentiment_*` properties.
N/A and skipped numeric runs omit the score, while zero remains a graded result.
@@ -62,6 +63,43 @@ The numeric property uses normal numeric inference and can be aggregated in Insi
Numeric queries use `toFloat(properties.$ai_evaluation_numeric_result)` to also handle properties whose metadata has not been registered yet.
No property-definition migration is required before enabling `llm-analytics-numeric-evaluations`.
+## Categorical outputs
+
+Hog and LLM judge evaluations support categorical output for generation, trace, and session targets.
+Creation is gated by `llm-analytics-categorical-evaluations`, disabled by default, in the API and frontend.
+Existing evaluations remain editable and continue running when the flag is off.
+
+The output configuration defines `options` as `{key, label}` pairs, `selection_mode` as `single` or `multiple`, and optional `allows_na`.
+Each evaluation supports 1 to 100 categories, enforced by the API and editor.
+Keys must be unique lowercase identifiers; labels are for display.
+Keep keys stable when changing labels so historical results retain their meaning.
+In the editor, **Categories per result** controls the number of returned categories independently of the passing rule.
+Category errors appear below the category table; passing-rule errors appear below the passing categories.
+
+Hog returns a list of keys, or a single key string for single selection.
+The editor updates the untouched Hog example when its category key changes, is removed, or the draft's output type changes.
+Custom code is preserved.
+The LLM judge returns `categories` and `reasoning`.
+Single selection requires exactly one key; multiple selection accepts `[]` as an applicable result.
+Categorical events always set `$ai_evaluation_applicable`, because native JSON property reads treat empty arrays as absent.
+`null` means N/A only when `allows_na` is enabled.
+Unknown or duplicate keys are invalid results.
+Invalid model responses and Hog results with unknown keys, duplicate keys, or the wrong number of selections skip the run without disabling the evaluation.
+Wrong Hog return types follow the existing return-contract error path.
+
+An optional `passing_rule: {categories: [key]}` marks the passing categories.
+With passing categories selected, a result passes only when it contains at least one category and every returned category is marked as passing.
+Single selection requires at least one passing category when a rule is enabled.
+Multiple selection allows an empty passing-categories list; only `[]` passes that rule.
+N/A and skipped runs are excluded from pass rates.
+Run details, text representations, and report-agent generation details distinguish skipped runs from N/A, even when N/A is disabled.
+Without a rule, results stay ungraded and new reports are unavailable.
+Rule edits reclassify stored results, while each report retains its own configuration snapshot.
+
+The new result property leaves boolean and numeric properties unchanged and needs no property-definition backfill.
+Evaluation clustering excludes numeric and categorical results because its embedding format requires boolean verdicts.
+Deploy all evaluation workers before enabling the flag.
+
## Run history and reports
The evaluation's Runs tab defaults to the last seven days.
@@ -69,9 +107,13 @@ Its date filter applies to both the run list and summary statistics, supports cu
Opening a specific backfill shows all runs from that backfill, regardless of the date filter.
Backfilled results use the original generation's timestamp.
-Removing a numeric evaluation's passing rule stops new report generation and scheduled delivery.
+Removing a numeric or categorical evaluation's passing rule stops new report generation and scheduled delivery.
Existing reports remain accessible through the Reports tab and the report list, detail, and history API endpoints.
+The report agent's `list_all_eval_results` and `sample_eval_results` tools cap each response at 30,000 characters.
+Large results reduce the number of examples returned; each returned example keeps its complete category list.
+The tools indicate when examples are omitted, and aggregate counts and pass rates still cover the full period.
+
## Browser compatibility
The evaluations list keeps supported rows visible if the API returns an output type the browser cannot display.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 64a55de013c0..8ffc4ecc288a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10244,6 +10244,22 @@ snapshots:
hash: v1.k794b7964.16253c58cc7e0f11bd32af653724cced02b42de025ce92acb041a2c7ce6a04d4.qu3iiFJrUI2Hiq-59roGNvGTqUInaL-mUS-u6XFYvJ8
scenes-app-links--new-link--light:
hash: v1.k794b7964.96b374104c35e53400745ac6a24686d195f42222e24d097dd1363983e6f43e8c.t4_adK3iuY98o2Ro0cnQGdfudgzw5wRasCqIsMs2wUc
+ scenes-app-llm-observability-categoricalevaluationconfig--default--dark:
+ hash: v1.k794b7964.5d13f8e4da4472d9afaa7bdaa4684b69e83d718b13ce996057ac181df792afec.QAvBIAMjHaItLYd-Zgj2X088lA-gxJadN8ijiqhGkIo
+ scenes-app-llm-observability-categoricalevaluationconfig--default--light:
+ hash: v1.k794b7964.2f27936e1adef36981db2b3099b05057bc603b40489f7b4dcf6d1696af85ddbe.aFk-vFyGv0uHtYAAEWuW0qN1ktNAOvdOy69XkwjtSxU
+ scenes-app-llm-observability-categoricalevaluationconfig--duplicate-keys--dark:
+ hash: v1.k794b7964.94005aed5ae5353e8d8c2cb9631b683e95408030720ddfcb3e5fb9820e15ee90.TgwkYuTA4wd1Ci2isCxadZ_szsY_kI7my_KQnE0wq-A
+ scenes-app-llm-observability-categoricalevaluationconfig--duplicate-keys--light:
+ hash: v1.k794b7964.ed68af50f92b6e4e398fc257a17ea72d979de6f9de9f6da0d9d2acb9fdf9609c.Lo2e2uFUHe7A_4hglEhLCaqZPRY0638jI0Fcp_BFVj8
+ scenes-app-llm-observability-categoricalevaluationconfig--invalid-passing-rule--dark:
+ hash: v1.k794b7964.a85d83120f135c73b50fb434836988ec2a417bdacda581cb6ad7f741296e3114.pRo6Tp791ruMRMXEFypwDj7u2bbEQ7c-b1CGSjQtdXQ
+ scenes-app-llm-observability-categoricalevaluationconfig--invalid-passing-rule--light:
+ hash: v1.k794b7964.d27e7eb29b2bbf297aac6ed17e32ab9bb4179243955bc524aaa22b8856260a1a.1WZBFuxI-8PXuuTG2u7H1YlOmzpw5nX3IK10XIhWJ4Y
+ scenes-app-llm-observability-categoricalevaluationconfig--narrow--dark:
+ hash: v1.k794b7964.436dcd7ee00a47ccca4d46685c0066615f888983b15844ac3945b8e51a79e508.zpSy36nqAxQSuvSHzElPGHXJZgnJKRjQmxBwDamre9w
+ scenes-app-llm-observability-categoricalevaluationconfig--narrow--light:
+ hash: v1.k794b7964.8489284cc30b609b61e118a4c29d24a2ded7d4bd674c30cc5cba80d1cd97f76b.fbzkOm6zlJje7ju3NPx5a-8JiaQdshwaLbVhRvplR6E
scenes-app-llm-observability-evaluationreportconfig--lemon-ui--dark:
hash: v1.k794b7964.195aa4a5a39e8f947e17fe67f5c23303b7dd0579c278907761be24a08780be92.IkGQtAI95T60kJKVZcmmFBIWNCd4meuJv-bcNDoohwU
scenes-app-llm-observability-evaluationreportconfig--lemon-ui--light:
@@ -10252,6 +10268,10 @@ snapshots:
hash: v1.k794b7964.195aa4a5a39e8f947e17fe67f5c23303b7dd0579c278907761be24a08780be92.t2Zgr2Pj-cL6F6Xx11DpcCyR1L0QQ8fD17WzQNmXbw8
scenes-app-llm-observability-evaluationreportconfig--quill--light:
hash: v1.k794b7964.e6179df07dd55d64e0140d40ac812feb4662e28e5bded7ce2cf9e2575f245626.4iGTruUDV858d17xZIUMJCG2xFeWLagkzakPS2Yw4Ps
+ scenes-app-llm-observability-evaluationresulttag--categorical--dark:
+ hash: v1.k794b7964.c4e312671669532a4bb20c3d59585d8771fb67597fd211d8f6826f66ecf62c11.F1VmFUHyXVK0odHStOtQJBlVZyPmAE8FgkkHva2hbzg
+ scenes-app-llm-observability-evaluationresulttag--categorical--light:
+ hash: v1.k794b7964.45c5f02e9112dedb384783067742d23e6030c168878fed04de5deff678c8bd64.CRIywDuIaYMhwH_2Al4ytrohDpd5WB8e45s10FlVClw
scenes-app-llm-observability-evaluationresulttag--numeric--dark:
hash: v1.k794b7964.1bcae05742f63c4b15b94fa5c6244a87c0dc72844623fd5a33fc72c54c879e3d.yz9CWrxD2rjp0oW_PvO6xOocQQunI1_Y2ymHqgtXPJA
scenes-app-llm-observability-evaluationresulttag--numeric--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b3a0464b6e7d..df13e29cc061 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -362,6 +362,7 @@ export const FEATURE_FLAGS = {
LINKS: 'links', // owner: @marconlp #team-link (team doesn't exist for now, maybe will come back in the future)
LIVE_DEBUGGER: 'live-debugger', // owner: @marcecoll
LIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analytics
+ LLM_ANALYTICS_CATEGORICAL_EVALS: 'llm-analytics-categorical-evaluations', // owner: #team-ai-observability
LLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observability
LLM_ANALYTICS_COMMUNITY_SKILLS: 'llm-analytics-community-skills', // owner: #team-ai-observability
LLM_ANALYTICS_DATASETS: 'llm-analytics-datasets', // owner: #team-ai-observability #team-posthog-ai
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index 297e1991d1be..f517e0d6240f 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -315,6 +315,15 @@
],
"label": "AI Evaluation Applicable (LLM)"
},
+ "$ai_evaluation_categorical_result": {
+ "description": "The category keys returned by an online evaluation. An empty list is an applicable result with no matching categories.",
+ "examples": [
+ "[\"resolved\"]",
+ "[\"fast\", \"reliable\"]",
+ "[]"
+ ],
+ "label": "AI evaluation categorical result"
+ },
"$ai_evaluation_id": {
"description": "The unique identifier of the evaluation configuration used to judge the AI event.",
"examples": [
@@ -5178,6 +5187,15 @@
],
"label": "AI Evaluation Applicable (LLM)"
},
+ "$ai_evaluation_categorical_result": {
+ "description": "The category keys returned by an online evaluation. An empty list is an applicable result with no matching categories.",
+ "examples": [
+ "[\"resolved\"]",
+ "[\"fast\", \"reliable\"]",
+ "[]"
+ ],
+ "label": "AI evaluation categorical result"
+ },
"$ai_evaluation_id": {
"description": "The unique identifier of the evaluation configuration used to judge the AI event.",
"examples": [
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 5146d4b72921..3f167cb6f28b 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2546,6 +2546,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"description": "The boolean verdict of the evaluation (true = pass, false = fail).",
"examples": [True, False],
},
+ "$ai_evaluation_categorical_result": {
+ "label": "AI evaluation categorical result",
+ "description": "The category keys returned by an online evaluation. An empty list is an applicable result with no matching categories.",
+ "examples": ['["resolved"]', '["fast", "reliable"]', "[]"],
+ },
"$ai_evaluation_numeric_result": {
"label": "AI evaluation numeric result",
"description": "The raw numeric score returned by an online evaluation.",
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 57d6f07e4b73..28f245f98b69 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -622,7 +622,7 @@ async def prepare_report_context_activity(
report.save(update_fields=["last_attempted_at", "next_delivery_date"])
# Activity failures remain readable by workflow workers from an older release.
raise ApplicationError(
- "This evaluation no longer supports reports. For numeric evaluations, set a passing rule and generate the report again.",
+ "This evaluation no longer supports reports. For numeric or categorical evaluations, set a passing rule and generate the report again.",
type="ReportNotEligible",
non_retryable=True,
)
@@ -703,12 +703,12 @@ async def run_eval_report_agent_activity(
from posthog.temporal.ai_observability.eval_reports.report_agent import run_eval_report_agent
evaluation_target = _load_evaluation_target(inputs.team_id, inputs.evaluation_id)
- numeric_output_configs = _load_numeric_output_configs(inputs.team_id)
+ evaluation_output_configs = _load_evaluation_output_configs(inputs.team_id)
agent_inputs = inputs
- if inputs.output_type == "numeric" and not inputs.output_config:
+ if inputs.output_type in ("numeric", "categorical") and not inputs.output_config:
# Older workflow payloads omit the rule snapshot.
- output_config = numeric_output_configs.get(inputs.evaluation_id, {})
- if not evaluation_supports_reports("numeric", evaluation_target, output_config):
+ output_config = evaluation_output_configs.get(inputs.evaluation_id, {})
+ if not evaluation_supports_reports(inputs.output_type, evaluation_target, output_config):
raise ApplicationError(
"This evaluation no longer supports reports.", type="ReportNotEligible", non_retryable=True
)
@@ -718,7 +718,7 @@ async def run_eval_report_agent_activity(
agent_inputs,
evaluation_target=evaluation_target,
detector_evaluation_ids=_load_detector_evaluation_ids(inputs.team_id),
- numeric_output_configs=numeric_output_configs,
+ evaluation_output_configs=evaluation_output_configs,
),
evaluation_target,
)
@@ -741,14 +741,14 @@ def _load_evaluation_target(team_id: int, evaluation_id: str) -> str:
return Evaluation.objects.values_list("target", flat=True).get(id=evaluation_id, team_id=team_id)
-def _load_numeric_output_configs(team_id: int) -> dict[str, dict[str, Any]]:
+def _load_evaluation_output_configs(team_id: int) -> dict[str, dict[str, Any]]:
from products.ai_observability.backend.models.evaluations import Evaluation
return {
str(evaluation_id): config
- for evaluation_id, config in Evaluation.objects.filter(team_id=team_id, output_type="numeric").values_list(
- "id", "output_config"
- )
+ for evaluation_id, config in Evaluation.objects.filter(
+ team_id=team_id, output_type__in=("numeric", "categorical")
+ ).values_list("id", "output_config")
}
@@ -839,7 +839,7 @@ async def store_report_run_activity(
"$ai_report_previous_total_runs": parsed_metrics.previous_total_runs,
}
)
- if parsed_metrics is not None and parsed_metrics.output_type in ("boolean", "numeric"):
+ if parsed_metrics is not None and parsed_metrics.output_type in ("boolean", "numeric", "categorical"):
# Preserve the original flat properties for existing boolean-report consumers.
properties.update(
{
diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.py
index b9253363210b..03ac58a98180 100644
--- a/posthog/temporal/ai_observability/eval_reports/delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py
@@ -48,6 +48,7 @@ _EMAIL_TD_STYLE = 'style="border: 1px solid #ddd; padding: 8px 12px;"'
_OUTCOME_LABELS = {
"boolean": (("pass", "Pass"), ("fail", "Fail"), ("na", "N/A")),
"numeric": (("pass", "Pass"), ("fail", "Fail"), ("na", "N/A")),
+ "categorical": (("pass", "Pass"), ("fail", "Fail"), ("na", "N/A")),
"sentiment": (("positive", "Positive"), ("neutral", "Neutral"), ("negative", "Negative")),
}
@@ -189,7 +190,7 @@ def _format_pass_rate(rate: float | None) -> str:
def _format_outcome_value(metrics: EvalReportMetrics, outcome: str) -> str:
count = metrics.result_counts[outcome]
- if metrics.output_type in ("boolean", "numeric"):
+ if metrics.output_type in ("boolean", "numeric", "categorical"):
return str(count)
rate = metrics.result_rates.get(outcome)
@@ -233,7 +234,7 @@ def _render_metrics_block_html(
outcome_labels = _OUTCOME_LABELS[metrics.output_type]
headers = "".join(f"<th>{label}</th>" for _, label in outcome_labels)
values = "".join(f"<td>{_format_outcome_value(metrics, outcome)}</td>" for outcome, _ in outcome_labels)
- if metrics.output_type in ("boolean", "numeric"):
+ if metrics.output_type in ("boolean", "numeric", "categorical"):
headers += "<th>Pass rate</th>"
values += f"<td><strong>{_format_boolean_pass_rate_value(metrics)}</strong></td>"
table = f"<table><tr><th>Total runs</th>{headers}</tr><tr><td>{metrics.total_runs}</td>{values}</tr></table>"
@@ -248,7 +249,7 @@ def _render_metrics_slack_blocks(metrics: EvalReportMetrics | None) -> list[dict
outcome_lines = [
f"{label}: {_format_outcome_value(metrics, outcome)}" for outcome, label in _OUTCOME_LABELS[metrics.output_type]
]
- if metrics.output_type in ("boolean", "numeric"):
+ if metrics.output_type in ("boolean", "numeric", "categorical"):
outcome_lines.append(f"Pass rate: {_format_boolean_pass_rate_value(metrics)}")
code_block = "\n".join([f"Total runs: {metrics.total_runs}", *outcome_lines])
diff --git a/posthog/temporal/ai_observability/eval_reports/output_types.py b/posthog/temporal/ai_observability/eval_reports/output_types.py
index 6bba0a5fa770..6b9cf8f4f307 100644
--- a/posthog/temporal/ai_observability/eval_reports/output_types.py
+++ b/posthog/temporal/ai_observability/eval_reports/output_types.py
@@ -10,7 +10,7 @@ from dataclasses import dataclass
from posthog.hogql import ast
-from products.ai_observability.backend.models.evaluation_configs import NumericOutputConfig
+from products.ai_observability.backend.models.evaluation_configs import CategoricalOutputConfig, NumericOutputConfig
SENTIMENT_LABELS = ("positive", "neutral", "negative")
@@ -26,15 +26,25 @@ class EvaluationReportOutcomeDefinition:
# Which raw boolean is the desirable outcome, or None for an output type that labels itself.
passing_result: bool | None
numeric_config: NumericOutputConfig | None = None
+ categorical_config: CategoricalOutputConfig | None = None
@property
def query_placeholders(self) -> dict[str, ast.Constant]:
+ if self.categorical_config is not None and self.categorical_config.passing_rule is not None:
+ return {"passing_categories": ast.Constant(value=self.categorical_config.passing_rule.categories)}
if self.numeric_config is not None and self.numeric_config.passing_rule is not None:
return {"numeric_threshold": ast.Constant(value=self.numeric_config.passing_rule.threshold)}
return {}
def label_for(self, result: object, applicable: object = None) -> str | None:
"""Map one raw result value to its outcome label, or None when it is not one we report."""
+ if self.categorical_config is not None:
+ if applicable in (False, "false"):
+ return "na"
+ rule = self.categorical_config.passing_rule
+ if rule is None or not isinstance(result, list) or not all(isinstance(value, str) for value in result):
+ return None
+ return "pass" if rule.passes(result) else "fail"
if self.numeric_config is not None:
if applicable in (False, "false"):
return "na"
@@ -105,7 +115,40 @@ _DEFINITION_BUILDERS: Mapping[str, Callable[[bool], EvaluationReportOutcomeDefin
"sentiment": _sentiment_definition,
}
-SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = (*_DEFINITION_BUILDERS, "numeric")
+SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = (*_DEFINITION_BUILDERS, "numeric", "categorical")
+
+
+def _categorical_definition(output_config: dict | None) -> EvaluationReportOutcomeDefinition:
+ config = CategoricalOutputConfig.model_validate(output_config) if output_config else None
+ categories_expression = "JSONExtract(ifNull(properties.$ai_evaluation_categorical_result, '[]'), 'Array(String)')"
+ applicable_predicate = "properties.$ai_evaluation_applicable = 'true'"
+ passed_predicate = "false"
+ failed_predicate = "false"
+
+ if config is not None and config.passing_rule is not None:
+ if config.passing_rule.categories:
+ passing_condition = (
+ f"(notEmpty({categories_expression}) AND hasAll({{passing_categories}}, {categories_expression}))"
+ )
+ else:
+ passing_condition = f"empty({categories_expression})"
+ passed_predicate = f"{passing_condition} AND {applicable_predicate}"
+ failed_predicate = f"NOT {passing_condition} AND {applicable_predicate}"
+
+ return EvaluationReportOutcomeDefinition(
+ outcomes=("pass", "fail", "na"),
+ outcome_predicates={
+ "pass": passed_predicate,
+ "fail": failed_predicate,
+ "na": "properties.$ai_evaluation_applicable = 'false'",
+ },
+ event_predicate=f"properties.$ai_evaluation_result_type = 'categorical' AND {_NOT_SKIPPED_PREDICATE}",
+ result_expression=categories_expression,
+ applicable_expression="properties.$ai_evaluation_applicable",
+ score_expression="NULL",
+ passing_result=None,
+ categorical_config=config,
+ )
def _numeric_definition(output_config: dict | None) -> EvaluationReportOutcomeDefinition:
@@ -133,6 +176,8 @@ def get_outcome_definition(
output_type: str | None, *, true_is_failure: bool = False, output_config: dict | None = None
) -> EvaluationReportOutcomeDefinition:
normalized_output_type = output_type or "boolean"
+ if normalized_output_type == "categorical":
+ return _categorical_definition(output_config)
if normalized_output_type == "numeric":
return _numeric_definition(output_config)
try:
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
index db90717c8e44..8007bc55be0d 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -130,9 +130,11 @@ def _fallback_content(
f"No evaluation runs recorded for **{evaluation_name}** in this period. "
f"Check that the evaluation is enabled and that {ingestion_hint}."
)
- elif metrics.output_type == "numeric" and metrics.pass_rate is None:
- summary = f"No numeric scores were produced across {metrics.total_runs} runs. All results were not applicable."
- elif metrics.output_type in ("boolean", "numeric"):
+ elif metrics.output_type in ("numeric", "categorical") and metrics.pass_rate is None:
+ summary = (
+ f"No applicable results were produced across {metrics.total_runs} runs. All results were not applicable."
+ )
+ elif metrics.output_type in ("boolean", "numeric", "categorical"):
trend = ""
if metrics.pass_rate is not None and metrics.previous_pass_rate is not None:
diff = metrics.pass_rate - metrics.previous_pass_rate
@@ -273,7 +275,7 @@ def run_eval_report_agent(
inputs: RunEvalReportAgentInput,
evaluation_target: str = "generation",
detector_evaluation_ids: Sequence[str] = (),
- numeric_output_configs: dict[str, dict[str, Any]] | None = None,
+ evaluation_output_configs: dict[str, dict[str, Any]] | None = None,
) -> EvalReportContent:
"""Run the evaluation report agent and return the generated content.
@@ -374,7 +376,7 @@ def run_eval_report_agent(
"true_is_failure": inputs.true_is_failure,
"output_config": inputs.output_config,
"detector_evaluation_ids": list(detector_evaluation_ids),
- "numeric_output_configs": {**(numeric_output_configs or {}), inputs.evaluation_id: inputs.output_config},
+ "evaluation_output_configs": {**(evaluation_output_configs or {}), inputs.evaluation_id: inputs.output_config},
"period_start": inputs.period_start,
"period_end": inputs.period_end,
"previous_period_start": inputs.previous_period_start,
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
index fa539af90aed..114e347631af 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
@@ -144,7 +144,7 @@ def build_eval_report_system_prompt(
"- Ground every claim about frustration in the user's own words. Quote or closely paraphrase the actual "
"last user message from real negative generations you cited.\n"
)
- elif output_type in ("boolean", "numeric"):
+ elif output_type in ("boolean", "numeric", "categorical"):
evaluated_unit = get_target_descriptor(evaluation_target).unit_label
if output_type == "numeric":
rule = definition.numeric_config.passing_rule if definition.numeric_config else None
@@ -161,6 +161,15 @@ def build_eval_report_system_prompt(
"Interpret scores using the evaluation criteria, not as normalized percentages. "
f"Score configuration: {output_config}"
)
+ elif output_type == "categorical":
+ result_semantics = (
+ "With passing categories selected, a result passes only if it is non-empty and every category is marked as passing. "
+ "If no passing categories are selected, only an empty selection passes. "
+ "Without a rule, results are ungraded; null is N/A. "
+ "Exclude N/A from pass rates. Use get_summary_metrics() to compare periods under the current rule. "
+ "Historical reports use saved rules; do not compare snapshots with different or unknown rules. "
+ f"Category configuration: {output_config}"
+ )
elif true_is_failure:
result_semantics = (
f"This evaluation looks for a problem. A true result means the {evaluated_unit} matched the "
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
index 2739697ad682..66aebb56f9e5 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
@@ -202,8 +202,10 @@ class EvalReportMetrics:
if outcome in definition.outcomes
}
- if self.output_type in ("boolean", "numeric"):
- self.pass_rate = calculate_pass_rate(self.result_counts, empty_as_none=self.output_type == "numeric")
+ if self.output_type in ("boolean", "numeric", "categorical"):
+ self.pass_rate = calculate_pass_rate(
+ self.result_counts, empty_as_none=self.output_type in ("numeric", "categorical")
+ )
if self.previous_result_counts is not None:
self.previous_pass_rate = calculate_pass_rate(self.previous_result_counts, empty_as_none=True)
else:
@@ -221,14 +223,14 @@ class EvalReportMetrics:
"previous_result_counts": self.previous_result_counts,
"previous_result_rates": self.previous_result_rates,
}
- if self.output_type in ("boolean", "numeric"):
+ if self.output_type in ("boolean", "numeric", "categorical"):
metrics.update(
{
"pass_rate": self.pass_rate,
"previous_pass_rate": self.previous_pass_rate,
}
)
- if self.output_type == "numeric":
+ if self.output_type in ("numeric", "categorical"):
metrics["output_config"] = self.output_config
return metrics
@@ -260,9 +262,9 @@ class EvalReportMetrics:
),
previous_pass_rate=data.get("previous_pass_rate"),
)
- if metrics.output_type in ("boolean", "numeric") and data.get("pass_rate") is not None:
+ if metrics.output_type in ("boolean", "numeric", "categorical") and data.get("pass_rate") is not None:
metrics.pass_rate = float(data["pass_rate"])
- if metrics.output_type in ("boolean", "numeric") and data.get("previous_pass_rate") is not None:
+ if metrics.output_type in ("boolean", "numeric", "categorical") and data.get("previous_pass_rate") is not None:
metrics.previous_pass_rate = float(data["previous_pass_rate"])
return metrics
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
index 8d75faf72d41..0a5618f91b39 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
@@ -35,7 +35,7 @@ class EvalReportAgentState(TypedDict):
true_is_failure: bool
output_config: dict[str, Any]
detector_evaluation_ids: list[str]
- numeric_output_configs: dict[str, dict[str, Any]]
+ evaluation_output_configs: dict[str, dict[str, Any]]
period_start: str
period_end: str
previous_period_start: str
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
index 2a3c23346871..bb3b4a282c51 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py
@@ -19,10 +19,18 @@ from products.ai_observability.backend.models.evaluation_configs import REPORTAB
class TestOutputTypeRegistry(SimpleTestCase):
- def test_numeric_metrics_preserve_passing_rule_and_exclude_na_from_pass_rate(self):
- config = {"min": 0, "max": 10, "passing_rule": {"operator": "gte", "threshold": 7}}
+ @parameterized.expand(
+ [
+ ("numeric", {"min": 0, "max": 10, "passing_rule": {"operator": "gte", "threshold": 7}}),
+ (
+ "categorical",
+ {"options": [{"key": "resolved", "label": "Resolved"}], "passing_rule": {"categories": ["resolved"]}},
+ ),
+ ]
+ )
+ def test_metrics_preserve_passing_rule_and_exclude_na_from_pass_rate(self, output_type, config):
metrics = EvalReportMetrics(
- output_type="numeric",
+ output_type=output_type,
output_config=config,
total_runs=5,
result_counts={"pass": 3, "fail": 1, "na": 1},
@@ -34,7 +42,7 @@ class TestOutputTypeRegistry(SimpleTestCase):
self.assertEqual(stored["output_config"], config)
self.assertEqual(EvalReportMetrics.from_dict(stored).to_dict(), stored)
no_scores = EvalReportMetrics(
- output_type="numeric", output_config=config, total_runs=3, result_counts={"na": 3}
+ output_type=output_type, output_config=config, total_runs=3, result_counts={"na": 3}
)
self.assertIsNone(no_scores.to_dict()["pass_rate"])
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index 0d7670f3accb..56a71cfaafe4 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -35,6 +35,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
)
from posthog.temporal.ai_observability.eval_reports.report_agent.state import REPORT_RUN_HANDLE_KEY
from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
+ _MAX_EVAL_RESULTS_CHARS,
_SESSION_TRACES_SQL,
_UUID_RE,
_ch_ts,
@@ -319,8 +320,8 @@ class TestTargetAwareEvalResults(SimpleTestCase):
generation_state = self._state("generation")
trace_state = self._state("trace")
- generation_result = json.loads(_sample_eval_results_fn(state=generation_state))
- trace_result = json.loads(_sample_eval_results_fn(state=trace_state))
+ generation_result = json.loads(_sample_eval_results_fn(state=generation_state))["results"]
+ trace_result = json.loads(_sample_eval_results_fn(state=trace_state))["results"]
self.assertEqual(generation_result[0]["generation_id"], _VALID_GEN_ID)
self.assertNotIn("trace_id", generation_result[0])
@@ -389,10 +390,73 @@ class TestTargetAwareEvalResults(SimpleTestCase):
self.assertEqual(
result,
- [{"generation_id": _VALID_GEN_ID, "outcome": "negative", "score": 0.91}],
+ {
+ "results": [{"generation_id": _VALID_GEN_ID, "outcome": "negative", "score": 0.91}],
+ "truncated": False,
+ },
)
self.assertIn("ORDER BY score DESC, timestamp DESC", mock_execute_hogql.call_args.args[1])
+ @parameterized.expand(
+ [(tool_name, size) for tool_name in ("list", "sample") for size in ("empty", "small", "large")]
+ )
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_category_results_fit_response_budget_without_partial_categories(
+ self, tool_name: str, size: str, mock_execute_hogql: MagicMock
+ ) -> None:
+ categories = [f"category_{i:03d}_" + "x" * 115 for i in range(100)] if size == "large" else ["ok"]
+ count = {"empty": 0, "small": 3, "large": 500}[size]
+ state = self._state("trace", "categorical")
+ state["output_config"] = {
+ "selection_mode": "multiple",
+ "options": [{"key": key, "label": key} for key in categories],
+ "passing_rule": {"categories": categories},
+ }
+ ids = [f"trace-{i}" for i in range(count)]
+ if tool_name == "list":
+ mock_execute_hogql.side_effect = [
+ [[count]],
+ [[target_id, categories, True, None, ""] for target_id in ids],
+ ]
+ response = _list_all_eval_results_fn(state=state)
+ header, *rows = response.splitlines()
+ self.assertIn(f"Total: {count} results", header)
+ for row in rows:
+ self.assertIn(f"pass ({json.dumps(categories)})", row)
+ self.assertEqual("response size limit" in header, size == "large")
+ else:
+ mock_execute_hogql.return_value = [[target_id, categories, "", True, None] for target_id in ids]
+ response = _sample_eval_results_fn(state=state, limit=500)
+ result = json.loads(response)
+ rows = result["results"]
+ self.assertEqual(result["truncated"], size == "large")
+ for row in rows:
+ self.assertEqual(row["categories"], categories)
+ self.assertEqual(row["outcome"], "pass")
+ if size == "large":
+ self.assertIn("response size limit", result["notice"])
+ self.assertLessEqual(len(response), _MAX_EVAL_RESULTS_CHARS)
+ self.assertEqual(state["trace_id_allowlist"], ids[: len(rows)])
+ if size == "large":
+ self.assertGreater(len(rows), 0)
+ self.assertLess(len(rows), count)
+ else:
+ self.assertEqual(len(rows), count)
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_sample_reports_when_one_result_exceeds_the_budget(self, mock_execute_hogql: MagicMock) -> None:
+ mock_execute_hogql.return_value = [["trace-large", True, "x" * _MAX_EVAL_RESULTS_CHARS, True, None]]
+ state = self._state("trace")
+
+ response = _sample_eval_results_fn(state=state)
+ result = json.loads(response)
+
+ self.assertEqual(result["results"], [])
+ self.assertTrue(result["truncated"])
+ self.assertIn("response size limit", result["notice"])
+ self.assertLessEqual(len(response), _MAX_EVAL_RESULTS_CHARS)
+ self.assertEqual(state["trace_id_allowlist"], [])
+
class TestTraceDetailTools(SimpleTestCase):
def _state(self) -> dict:
@@ -1402,7 +1466,9 @@ class TestToolsCoordinate(SimpleTestCase):
class TestLabelGenerationEvals(SimpleTestCase):
def test_numeric_evaluations_use_their_own_rule_and_keep_unrated_scores(self):
- rows = [[name, "numeric", None, None, None, "reason", True, 7.5] for name in ["high", "low", "unrated"]]
+ rows = [
+ [name, "numeric", None, None, None, "reason", True, 7.5, None, None] for name in ["high", "low", "unrated"]
+ ]
configs = {
"high": {"passing_rule": {"operator": "gte", "threshold": 7}},
"low": {"passing_rule": {"operator": "lte", "threshold": 7}},
@@ -1411,13 +1477,44 @@ class TestLabelGenerationEvals(SimpleTestCase):
self.assertEqual([row["outcome"] for row in labeled], ["pass", "fail", None])
self.assertEqual([row["score"] for row in labeled], [7.5, 7.5, 7.5])
- # (eval_id, result_type, result, sentiment_label, sentiment_score, reasoning, applicable)
+ # (eval_id, result_type, result, sentiment_label, sentiment_score, reasoning, applicable, numeric_score, categories, skipped)
ROWS: list[list[object]] = [
- ["detector-eval", "boolean", True, None, None, "struggled", None],
- ["quality-eval", "boolean", True, None, None, "accurate", None],
- ["sentiment-eval", "sentiment", None, "negative", 0.9, "", None],
+ ["detector-eval", "boolean", True, None, None, "struggled", None, None, None, None],
+ ["quality-eval", "boolean", True, None, None, "accurate", None, None, None, None],
+ ["sentiment-eval", "sentiment", None, "negative", 0.9, "", None, None, None, None],
]
+ @parameterized.expand(
+ [
+ (True, False, "skipped"),
+ ("true", "false", "skipped"),
+ (1, False, "skipped"),
+ (False, False, "na"),
+ ("false", "false", "na"),
+ (None, False, "na"),
+ ("false", True, "pass"),
+ (None, True, "pass"),
+ ]
+ )
+ def test_categorical_skips_are_distinct_from_na(
+ self, skipped: bool | str | int | None, applicable: bool | str, expected_outcome: str
+ ) -> None:
+ categories = ["resolved"] if applicable is True else []
+ rows = [["categorical-eval", "categorical", None, None, None, "reason", applicable, None, categories, skipped]]
+ configs = {
+ "categorical-eval": {
+ "allows_na": False,
+ "options": [{"key": "resolved", "label": "Resolved"}],
+ "passing_rule": {"categories": ["resolved"]},
+ }
+ }
+
+ labeled = _label_generation_evals(rows, set(), configs)
+
+ self.assertEqual(labeled[0]["outcome"], expected_outcome)
+ self.assertEqual(labeled[0]["reasoning"], "reason")
+ self.assertEqual(labeled[0]["categories"], categories)
+
def test_each_evaluation_is_labeled_by_its_own_polarity(self):
labeled = _label_generation_evals(self.ROWS, {"detector-eval"})
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
index 896bf47fc7b1..8dc1be32f425 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools_ai_events_routing.py
@@ -8,6 +8,7 @@ other query sites in `tools.py` deliberately stay on `events` directly via
rationale).
"""
+import json
from typing import cast
from posthog.test.base import BaseTest
@@ -140,9 +141,18 @@ class TestGetGenerationDetailRoutesThroughResolver(BaseTest):
]
)
# Non-resolver path returns eval rows.
- mock_events.return_value = MagicMock(results=[])
+ mock_events.return_value = MagicMock(
+ results=[["eval-1", "categorical", None, None, None, "This run was skipped", False, None, [], True]]
+ )
+
+ result = json.loads(_get_detail_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID))
- _get_detail_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert result["eval_results"][0]["outcome"] == "skipped"
+ eval_query = cast(ast.SelectQuery, mock_events.call_args.kwargs["query"])
+ skipped = cast(ast.Alias, eval_query.select[-1])
+ assert skipped.alias == "skipped"
+ assert isinstance(skipped.expr, ast.Field)
+ assert skipped.expr.chain == ["properties", "$ai_evaluation_skipped"]
# Heavy path went through the resolver.
assert mock_resolver.call_count == 1
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index c7b78b347078..c8896585440b 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -425,9 +425,9 @@ def _period_summary_dict(
"result_counts": result_counts,
"result_rates": result_rates,
}
- if output_type in ("boolean", "numeric"):
+ if output_type in ("boolean", "numeric", "categorical"):
summary["pass_rate"] = calculate_pass_rate(
- result_counts, empty_as_none=empty_rates_as_none or output_type == "numeric"
+ result_counts, empty_as_none=empty_rates_as_none or output_type in ("numeric", "categorical")
)
return summary
@@ -524,6 +524,19 @@ def get_result_distribution_over_time(
_LIST_ALL_MAX_RESULTS = 500
+_MAX_EVAL_RESULTS_CHARS = 30_000
+
+
+def _eval_result_count_within_budget(rendered_rows: Iterable[str]) -> int:
+ # Reserve space for the header or JSON envelope without cutting category lists.
+ remaining_chars = _MAX_EVAL_RESULTS_CHARS - 256
+ count = 0
+ for row in rendered_rows:
+ remaining_chars -= len(row) + 2
+ if remaining_chars < 0:
+ break
+ count += 1
+ return count
@tool
@@ -533,7 +546,8 @@ def list_all_eval_results(
) -> str:
"""Get a compact overview of evaluation results in the period.
- Returns up to 500 results as condensed rows with outcome and target ID.
+ Returns up to 500 results as condensed rows with outcome and target ID,
+ with fewer rows when needed to fit the response size limit.
Boolean results include truncated reasoning, while sentiment results include
scores without classifier reasoning. When there are more than 500 results,
returns a random sample. Use this as your first scan to spot patterns before
@@ -599,8 +613,6 @@ def list_all_eval_results(
""",
placeholders=shared_placeholders,
)
- _remember_returned_target_ids(state, [row[0] for row in rows if row])
-
max_reasoning_length = min(max(20, max_reasoning_length), 200)
lines = []
for row in rows:
@@ -609,6 +621,8 @@ def list_all_eval_results(
score = ""
if isinstance(row[3], int | float):
score = f" ({row[3]})" if output_type == "numeric" else f" ({row[3]:.2f})"
+ if output_type == "categorical":
+ score = f" ({json.dumps(row[1])})"
fields = [f"{outcome}{score}", target_id]
if output_type != "sentiment":
reasoning = (row[4] or "")[:max_reasoning_length]
@@ -617,11 +631,15 @@ def list_all_eval_results(
fields.append(reasoning)
lines.append(" | ".join(fields))
- if is_sampled:
+ result_count = _eval_result_count_within_budget(lines)
+ _remember_returned_target_ids(state, [row[0] for row in rows[:result_count]])
+ if result_count < len(lines):
+ header = f"Total: {total_count} results (showing {result_count}; response size limit)\n"
+ elif is_sampled:
header = f"Total: {total_count} results (showing random sample of {len(lines)})\n"
else:
header = f"Total: {len(lines)} results\n"
- return header + "\n".join(lines)
+ return header + "\n".join(lines[:result_count])
@tool
@@ -635,6 +653,8 @@ def sample_eval_results(
Boolean and numeric results include reasoning. Score ordering returns the worst
numeric scores or the highest-confidence sentiment labels first.
+ Returns JSON with results and a truncated flag. Large rows reduce the sample
+ to fit the response size limit; each returned row retains all its categories.
Args:
outcome: "all" or one of the output type's supported outcomes
@@ -698,8 +718,6 @@ def sample_eval_results(
"limit": ast.Constant(value=limit),
},
)
- _remember_returned_target_ids(state, [row[0] for row in rows if row])
-
target_id_key = _target_id_key(state)
result = []
for row in rows:
@@ -709,11 +727,22 @@ def sample_eval_results(
}
if output_type in ("sentiment", "numeric"):
entry["score"] = row[4]
+ if output_type == "categorical":
+ entry["categories"] = row[1]
if output_type != "sentiment":
entry["reasoning"] = row[2] or ""
result.append(entry)
- return json.dumps(result, indent=2)
+ result_count = _eval_result_count_within_budget(json.dumps(entry) for entry in result)
+ _remember_returned_target_ids(state, [row[0] for row in rows[:result_count]])
+ truncated = result_count < len(result)
+ response: dict[str, object] = {"results": result[:result_count], "truncated": truncated}
+ if truncated:
+ response["notice"] = (
+ f"Showing {result_count} of {len(result)} fetched results due to the response size limit. "
+ "Use get_summary_metrics for aggregate counts and pass rates."
+ )
+ return json.dumps(response)
@tool
@@ -831,7 +860,7 @@ def sample_generation_details(
def _label_generation_evals(
eval_rows: Sequence[Sequence[object]],
detector_evaluation_ids: Container[str],
- numeric_output_configs: dict[str, dict] | None = None,
+ evaluation_output_configs: dict[str, dict] | None = None,
) -> list[dict]:
"""Label every evaluation on one generation, each by its own polarity."""
labeled = []
@@ -842,19 +871,24 @@ def _label_generation_evals(
definition = get_outcome_definition(
output_type,
true_is_failure=evaluation_id in detector_evaluation_ids,
- output_config=(numeric_output_configs or {}).get(evaluation_id),
+ output_config=(evaluation_output_configs or {}).get(evaluation_id),
)
except ValueError:
continue
- raw_result = row[7] if output_type == "numeric" else row[3] if output_type == "sentiment" else row[2]
+ if output_type == "categorical":
+ raw_result = row[8]
+ else:
+ raw_result = row[7] if output_type == "numeric" else row[3] if output_type == "sentiment" else row[2]
entry = {
"evaluation_id": evaluation_id,
"output_type": output_type,
- "outcome": definition.label_for(raw_result, row[6]),
+ "outcome": "skipped" if row[9] in (True, "true") else definition.label_for(raw_result, row[6]),
"reasoning": row[5] or "",
}
if output_type in ("sentiment", "numeric"):
entry["score"] = row[7] if output_type == "numeric" else row[4]
+ if output_type == "categorical":
+ entry["categories"] = raw_result
labeled.append(entry)
return labeled
@@ -959,7 +993,9 @@ def get_generation_detail(
properties.$ai_sentiment_score as sentiment_score,
properties.$ai_evaluation_reasoning as reasoning,
properties.$ai_evaluation_applicable as applicable,
- toFloat(properties.$ai_evaluation_numeric_result) as numeric_score
+ toFloat(properties.$ai_evaluation_numeric_result) as numeric_score,
+ JSONExtract(ifNull(properties.$ai_evaluation_categorical_result, '[]'), 'Array(String)') as categories,
+ properties.$ai_evaluation_skipped as skipped
FROM events
WHERE event = '$ai_evaluation'
AND properties.$ai_target_event_id = {generation_id}
@@ -972,7 +1008,7 @@ def get_generation_detail(
)
evals = _label_generation_evals(
- eval_rows, set(state.get("detector_evaluation_ids") or []), state.get("numeric_output_configs")
+ eval_rows, set(state.get("detector_evaluation_ids") or []), state.get("evaluation_output_configs")
)
result: dict = {
@@ -1405,9 +1441,9 @@ def list_recent_report_runs(
}
if "result_rates" in normalized_metrics:
entry["result_rates"] = normalized_metrics["result_rates"]
- if output_type in ("boolean", "numeric") and "pass_rate" in normalized_metrics:
+ if output_type in ("boolean", "numeric", "categorical") and "pass_rate" in normalized_metrics:
entry["pass_rate"] = normalized_metrics["pass_rate"]
- if output_type == "numeric":
+ if output_type in ("numeric", "categorical"):
config = normalized_metrics.get("output_config") or {}
previous_rule = config.get("passing_rule")
current_rule = (state.get("output_config") or {}).get("passing_rule")
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
index 7ac91fd1dc46..23ed1b90eb5c 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -157,7 +157,7 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
return_value=["detector-id"],
) as load_detectors,
patch(
- "posthog.temporal.ai_observability.eval_reports.activities._load_numeric_output_configs",
+ "posthog.temporal.ai_observability.eval_reports.activities._load_evaluation_output_configs",
return_value={"evaluation-id": {"passing_rule": {"operator": "gte", "threshold": 7}}}
if output_config is not None
else {},
@@ -851,6 +851,62 @@ class TestPeriodForScheduledReport(BaseTest):
class TestEvaluationReportResultMetrics(ClickhouseTestMixin, BaseTest):
+ @parameterized.expand(
+ [
+ ("registered", True, ["resolved"]),
+ ("unregistered", False, ["resolved"]),
+ ("empty_registered", True, []),
+ ("empty_unregistered", False, []),
+ ]
+ )
+ def test_categorical_reports_count_empty_selections_and_exclude_skips(
+ self, _name: str, registered: bool, passing_categories: list[str]
+ ) -> None:
+ if registered:
+ PropertyDefinition.objects.create(
+ team=self.team, name="$ai_evaluation_categorical_result", property_type="String"
+ )
+ PropertyDefinition.objects.create(team=self.team, name="$ai_evaluation_applicable", property_type="Boolean")
+ start = dt.datetime(2026, 7, 1, tzinfo=dt.UTC)
+ results: list[dict[str, object]] = [
+ {"$ai_evaluation_categorical_result": ["resolved"], "$ai_evaluation_applicable": True},
+ {"$ai_evaluation_categorical_result": [], "$ai_evaluation_applicable": True},
+ {"$ai_evaluation_categorical_result": ["resolved", "incorrect"], "$ai_evaluation_applicable": True},
+ {"$ai_evaluation_applicable": False},
+ {"$ai_evaluation_skipped": True},
+ ]
+ for index, properties in enumerate(results):
+ _create_event(
+ team=self.team,
+ event="$ai_evaluation",
+ distinct_id=f"categorical-{index}",
+ timestamp=start,
+ properties={
+ "$ai_evaluation_id": "categorical-eval",
+ "$ai_evaluation_result_type": "categorical",
+ **properties,
+ },
+ )
+ config = {
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "incorrect", "label": "Incorrect"}],
+ "selection_mode": "multiple",
+ "passing_rule": {"categories": passing_categories},
+ }
+ metrics = _compute_metrics(
+ self.team.id,
+ "categorical-eval",
+ start.isoformat(),
+ (start + dt.timedelta(days=1)).isoformat(),
+ (start - dt.timedelta(days=1)).isoformat(),
+ output_type="categorical",
+ output_config=config,
+ )
+ assert metrics is not None
+ self.assertEqual(metrics.total_runs, 4)
+ self.assertEqual(metrics.result_counts, {"pass": 1, "fail": 2, "na": 1})
+ self.assertEqual(metrics.pass_rate, 33.33)
+ self.assertEqual(metrics.output_config, config)
+
@parameterized.expand(
[("registered", True, True), ("unregistered_applicable", False, True), ("unregistered", False, False)]
)
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py b/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py
index c682b2ae3717..c566a54ae56c 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py
@@ -9,6 +9,36 @@ from posthog.temporal.ai_observability.eval_reports.output_types import (
class TestOutcomeDefinitions(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (["resolved"], ["resolved"], "pass"),
+ (["resolved", "incorrect"], ["resolved"], "fail"),
+ (["incorrect"], ["resolved"], "fail"),
+ ([], ["resolved"], "fail"),
+ ([], [], "pass"),
+ (["resolved"], [], "fail"),
+ ([], None, None),
+ (["resolved"], None, None),
+ ]
+ )
+ def test_categorical_passing_categories(
+ self, categories: list[str], passing_categories: list[str] | None, outcome: str | None
+ ) -> None:
+ definition = get_outcome_definition(
+ "categorical",
+ output_config={
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "incorrect", "label": "Incorrect"}],
+ "selection_mode": "multiple",
+ "passing_rule": {"categories": passing_categories} if passing_categories is not None else None,
+ },
+ )
+ self.assertEqual(definition.label_for(categories), outcome)
+ self.assertEqual(definition.label_for(None, applicable=False), "na")
+ self.assertIsNone(definition.label_for(None))
+ self.assertIsNone(definition.label_for("resolved"))
+ if passing_categories is not None:
+ self.assertEqual(definition.query_placeholders["passing_categories"].value, passing_categories)
+
@parameterized.expand(
[
("gte", 6, "fail"),
@@ -73,7 +103,7 @@ class TestOutcomeDefinitions(SimpleTestCase):
self.assertEqual(definition.label_for(0), "fail")
def test_supported_types_are_derived_from_the_builders(self):
- self.assertEqual(set(SUPPORTED_EVAL_REPORT_OUTPUT_TYPES), {"boolean", "sentiment", "numeric"})
+ self.assertEqual(set(SUPPORTED_EVAL_REPORT_OUTPUT_TYPES), {"boolean", "sentiment", "numeric", "categorical"})
for output_type in SUPPORTED_EVAL_REPORT_OUTPUT_TYPES:
self.assertIsNotNone(get_outcome_definition(output_type))
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
index c910384c6cd3..03380ebbfc62 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
@@ -119,6 +119,7 @@ def _sample_and_embed_sync(inputs: SamplerActivityInputs) -> SamplerActivityResu
filter_exprs = [property_to_expr(f, team) for f in inputs.event_filters]
filter_expr = ast.And(exprs=filter_exprs) if len(filter_exprs) > 1 else filter_exprs[0]
+ # The embedding formatter cannot represent numeric or categorical results.
query = parse_select(
"""
SELECT
@@ -131,6 +132,7 @@ def _sample_and_embed_sync(inputs: SamplerActivityInputs) -> SamplerActivityResu
FROM events
WHERE event = '$ai_evaluation'
AND (isNull(properties.$ai_evaluation_result_type) OR properties.$ai_evaluation_result_type != 'numeric')
+ AND (isNull(properties.$ai_evaluation_result_type) OR properties.$ai_evaluation_result_type != 'categorical')
AND timestamp >= {start_dt}
AND timestamp < {end_dt}
AND {filter_expr}
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
index 7e9dbb831e20..07575a867703 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
@@ -231,3 +231,4 @@ class TestSampleAndEmbedForJobActivity:
assert filter_expr.__class__.__name__ != "Constant"
query = replace_placeholders(mock_execute.call_args.kwargs["query"], placeholders).to_hogql()
assert "notEquals(properties.$ai_evaluation_result_type, 'numeric')" in query
+ assert "notEquals(properties.$ai_evaluation_result_type, 'categorical')" in query
diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.py
index afa1b2460d23..a236cd10803a 100644
--- a/posthog/temporal/ai_observability/evaluation_hog.py
+++ b/posthog/temporal/ai_observability/evaluation_hog.py
@@ -18,7 +18,12 @@ from posthog.temporal.ai_observability.evaluation_types import EvaluationActivit
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.metrics import increment_user_errors
-from products.ai_observability.backend.models.evaluation_configs import NumericOutputConfig, NumericScoreOutOfBounds
+from products.ai_observability.backend.models.evaluation_configs import (
+ CategoricalOutputConfig,
+ InvalidEvaluationCategories,
+ NumericOutputConfig,
+ NumericScoreOutOfBounds,
+)
from common.hogvm.python.execute import execute_bytecode
from common.hogvm.python.operation import Operation
@@ -198,6 +203,15 @@ def execute_hog_eval_bytecode(
if response.result is None and allows_na:
return {"verdict": None, "applicable": False, "reasoning": reasoning, "error": None}
+ if output_type == "categorical":
+ try:
+ categories = CategoricalOutputConfig.model_validate(output_config or {}).validate_result(response.result)
+ except InvalidEvaluationCategories as error:
+ return {"verdict": None, "reasoning": reasoning, "error": str(error), "user_input_error": True}
+ except ValueError as error:
+ return {"verdict": None, "reasoning": reasoning, "error": str(error)}
+ return {"categories": categories, "reasoning": reasoning, "error": None, "applicable": True}
+
if output_type == "numeric":
try:
score = NumericOutputConfig.model_validate(output_config or {}).validate_score(response.result)
@@ -299,7 +313,11 @@ def finalize_hog_eval_result(
"reasoning": result["reasoning"],
"allows_na": allows_na,
}
- if evaluation.get("output_type") == "numeric":
+ if evaluation.get("output_type") == "categorical":
+ activity_result["result_type"] = "categorical"
+ if "categories" in result:
+ activity_result["categories"] = result["categories"]
+ elif evaluation.get("output_type") == "numeric":
activity_result["result_type"] = "numeric"
if "score" in result:
config = NumericOutputConfig.model_validate(evaluation.get("output_config") or {})
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 80cb1cc004a7..05fc33cd63dc 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -47,7 +47,11 @@ from products.ai_observability.backend.llm.errors import (
RateLimitError,
StructuredOutputParseError,
)
-from products.ai_observability.backend.models.evaluation_configs import NumericOutputConfig, NumericScoreOutOfBounds
+from products.ai_observability.backend.models.evaluation_configs import (
+ CategoricalOutputConfig,
+ NumericOutputConfig,
+ NumericScoreOutOfBounds,
+)
from products.ai_observability.backend.text_repr.formatters import add_line_numbers, reduce_by_uniform_sampling
logger = structlog.get_logger(__name__)
@@ -139,6 +143,16 @@ class NumericWithNAEvalResult(BaseModel):
return self.score is not None
+class CategoricalEvalResult(BaseModel):
+ reasoning: str
+ categories: list[str]
+
+
+class CategoricalWithNAEvalResult(BaseModel):
+ reasoning: str
+ categories: list[str] | None
+
+
@frozen
class OutputTypeConfig:
"""Configuration for each evaluation output type"""
@@ -148,6 +162,8 @@ class OutputTypeConfig:
| type[BooleanWithNAEvalResult]
| type[NumericEvalResult]
| type[NumericWithNAEvalResult]
+ | type[CategoricalEvalResult]
+ | type[CategoricalWithNAEvalResult]
)
instructions: str
@@ -159,6 +175,21 @@ def get_output_type_config(
output_config: dict[str, Any] | None = None,
) -> OutputTypeConfig:
"""Get the output type configuration based on whether N/A is allowed."""
+ if output_type == "categorical":
+ config = CategoricalOutputConfig.model_validate(output_config or {})
+ options = json.dumps([option.model_dump() for option in config.options])
+ count = (
+ "exactly one category key" if config.selection_mode == "single" else "zero or more distinct category keys"
+ )
+ instructions = f"Provide a brief reasoning (1 sentence) and categories containing {count} from these options: {options}. Return keys, not display labels."
+ if allows_na:
+ instructions += " Return categories=null when the criteria does not apply."
+ if config.selection_mode == "multiple":
+ instructions += " An empty list means no categories apply."
+ return OutputTypeConfig(
+ response_format=CategoricalWithNAEvalResult if allows_na else CategoricalEvalResult,
+ instructions=instructions,
+ )
if output_type == "numeric":
numeric_config = NumericOutputConfig.model_validate(output_config or {})
instructions = "Provide a brief reasoning (1 sentence) and a finite numeric score."
@@ -272,7 +303,7 @@ def _build_context_window_skip_result(
def _build_output_limit_skip_result(
- allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str
+ allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str, output_type: str = "boolean"
) -> EvaluationActivityResult:
"""Per-item skip for a judge reply that hit the model's output limit.
@@ -280,23 +311,13 @@ def _build_output_limit_skip_result(
and the call was billed. The provider reports no usage counts on this path, because the
failure reaches us as an exception.
"""
- result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": "Evaluation model hit its output limit before it finished; evaluation skipped.",
- "input_tokens": 0,
- "output_tokens": 0,
- "total_tokens": 0,
- "is_byok": is_byok,
- "key_id": key_id,
- "allows_na": allows_na,
- "model": model,
- "provider": provider,
- "skipped": True,
- "skip_reason": "output_limit_exceeded",
- }
- if allows_na:
- result["applicable"] = False
+ result = build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Evaluation model hit its output limit before it finished; evaluation skipped.",
+ skip_reason="output_limit_exceeded",
+ )
+ result.update({"is_byok": is_byok, "key_id": key_id, "model": model, "provider": provider})
return result
@@ -363,9 +384,9 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
raise ApplicationError("Missing prompt in evaluation_config", non_retryable=True)
output_type = evaluation["output_type"]
- if output_type not in ("boolean", "numeric"):
+ if output_type not in ("boolean", "numeric", "categorical"):
raise ApplicationError(
- f"Unsupported output type: {output_type}. Supported types: 'boolean', 'numeric'.",
+ f"Unsupported output type: {output_type}. Supported types: 'boolean', 'numeric', 'categorical'.",
non_retryable=True,
)
@@ -580,7 +601,7 @@ def call_llm_judge(
error=str(e),
)
return _build_output_limit_skip_result(
- allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model
+ allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, output_type=output_type
)
except ProviderConnectionError as e:
@@ -628,7 +649,13 @@ def call_llm_judge(
)
assert isinstance(
- parsed_result, BooleanEvalResult | BooleanWithNAEvalResult | NumericEvalResult | NumericWithNAEvalResult
+ parsed_result,
+ BooleanEvalResult
+ | BooleanWithNAEvalResult
+ | NumericEvalResult
+ | NumericWithNAEvalResult
+ | CategoricalEvalResult
+ | CategoricalWithNAEvalResult,
)
usage = response.usage
@@ -655,6 +682,28 @@ def call_llm_judge(
"provider": provider,
}
+ if isinstance(parsed_result, CategoricalEvalResult | CategoricalWithNAEvalResult):
+ result_dict["result_type"] = "categorical"
+ if parsed_result.categories is not None:
+ try:
+ result_dict["categories"] = CategoricalOutputConfig.model_validate(output_config).validate_result(
+ parsed_result.categories
+ )
+ except ValueError as error:
+ increment_errors("parse_error", provider=provider)
+ result_dict.update(
+ build_skipped_evaluation_result(
+ output_type="categorical",
+ allows_na=allows_na,
+ reasoning=f"The judge returned invalid categories: {error}. This run was skipped.",
+ skip_reason="parse_error",
+ )
+ )
+ return result_dict
+ if allows_na:
+ result_dict["applicable"] = parsed_result.categories is not None
+ return result_dict
+
if isinstance(parsed_result, NumericEvalResult | NumericWithNAEvalResult):
result_dict["result_type"] = "numeric"
if parsed_result.score is not None:
diff --git a/posthog/temporal/ai_observability/evaluation_types.py b/posthog/temporal/ai_observability/evaluation_types.py
index d9ab43ae09d1..80ec8c232c07 100644
--- a/posthog/temporal/ai_observability/evaluation_types.py
+++ b/posthog/temporal/ai_observability/evaluation_types.py
@@ -17,7 +17,7 @@ class EvaluationActivityResult(TypedDict, total=False):
`NotRequired`, making the contract honest about which keys every path actually sets:
- `result_type` and `reasoning` are set on every path and are `Required`.
- - `verdict` is set for boolean outputs only; `allows_na` is also set for numeric outputs.
+ - `verdict` is set for boolean outputs only; `allows_na` is also set for numeric and categorical outputs.
- `score` and configured `score_min`/`score_max` are set for applicable numeric outputs.
Skipped and not-applicable numeric outputs omit these fields and never set `verdict`.
- `applicable` is set only when `allows_na=True`.
@@ -31,12 +31,13 @@ class EvaluationActivityResult(TypedDict, total=False):
not treat sentiment as N/A.
"""
- result_type: Required[Literal["boolean", "sentiment", "numeric"]]
+ result_type: Required[Literal["boolean", "sentiment", "numeric", "categorical"]]
reasoning: Required[str]
verdict: NotRequired[bool | None]
score: NotRequired[float]
score_min: NotRequired[float]
score_max: NotRequired[float]
+ categories: NotRequired[list[str]]
allows_na: NotRequired[bool]
input_tokens: NotRequired[int]
output_tokens: NotRequired[int]
@@ -67,13 +68,17 @@ def build_skipped_evaluation_result(
verdict: bool | None = False,
) -> EvaluationActivityResult:
result: EvaluationActivityResult = {
- "result_type": "numeric" if output_type == "numeric" else "boolean",
+ "result_type": "categorical"
+ if output_type == "categorical"
+ else "numeric"
+ if output_type == "numeric"
+ else "boolean",
"reasoning": reasoning,
"allows_na": allows_na,
"skipped": True,
"skip_reason": skip_reason,
}
- if output_type != "numeric":
+ if output_type not in ("numeric", "categorical"):
result["verdict"] = None if allows_na else verdict
if allows_na:
result["applicable"] = False
diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
index 40ece693ef46..6e567fb01f9d 100644
--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py
+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
@@ -303,7 +303,13 @@ def build_evaluation_event_properties(
properties["$ai_evaluation_key_type"] = "byok" if result.get("is_byok") else "posthog"
properties["$ai_evaluation_key_id"] = result.get("key_id")
- if result["result_type"] == "numeric":
+ if result["result_type"] == "categorical":
+ properties["$ai_evaluation_allows_na"] = allows_na
+ # Native JSON property reads turn [] into NULL, so applicability preserves empty results.
+ properties["$ai_evaluation_applicable"] = result.get("applicable", not result.get("skipped", False))
+ if not result.get("skipped") and result.get("applicable", True) and "categories" in result:
+ properties["$ai_evaluation_categorical_result"] = result["categories"]
+ elif result["result_type"] == "numeric":
properties["$ai_evaluation_allows_na"] = allows_na
if allows_na:
properties["$ai_evaluation_applicable"] = result.get("applicable", not result.get("skipped", False))
diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
index 26a97f763d0a..d2c7df5dd606 100644
--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
@@ -602,7 +602,7 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
"evaluation_id": inputs.evaluation_id,
"evaluation_type": evaluation_type,
}
- if evaluation.get("output_type") != "numeric":
+ if evaluation.get("output_type") not in ("numeric", "categorical"):
disabled_result["verdict"] = None
return disabled_result
@@ -720,6 +720,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
workflow_result["verdict"] = result["verdict"]
if "score" in result:
workflow_result["score"] = result["score"]
+ if "categories" in result:
+ workflow_result["categories"] = result["categories"]
if result.get("skipped"):
skip_reason = result.get("skip_reason")
if skip_reason is not None:
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.py
index f354b4e90af1..792e6957cbd7 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -98,6 +98,7 @@ class WorkflowResult(TypedDict, total=False):
skipped: Required[bool]
verdict: NotRequired[bool | None]
score: NotRequired[float]
+ categories: NotRequired[list[str]]
reasoning: NotRequired[str]
is_byok: NotRequired[bool]
skip_reason: NotRequired[str]
@@ -141,7 +142,7 @@ async def handle_llm_judge_activity_error(
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
}
- if evaluation.get("output_type") != "numeric":
+ if evaluation.get("output_type") not in ("numeric", "categorical"):
skip_result["verdict"] = None
return skip_result
@@ -242,7 +243,7 @@ async def handle_terminal_user_error_result(
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
}
- if evaluation.get("output_type") != "numeric":
+ if evaluation.get("output_type") not in ("numeric", "categorical"):
workflow_result["verdict"] = None
return workflow_result
@@ -469,6 +470,8 @@ class RunEvaluationWorkflow(PostHogWorkflow):
}
if "score" in result:
workflow_result["score"] = result["score"]
+ if "categories" in result:
+ workflow_result["categories"] = result["categories"]
if "verdict" in result:
workflow_result["verdict"] = result["verdict"]
if result.get("skipped"):
diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.py
index 6975ef3f88b7..b194cdcd1c13 100644
--- a/posthog/temporal/ai_observability/run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/run_session_evaluation.py
@@ -476,9 +476,9 @@ def execute_session_llm_judge_activity(inputs: ExecuteSessionEvaluationInputs) -
if not prompt:
raise ApplicationError("Missing prompt in evaluation_config", non_retryable=True)
- if evaluation["output_type"] not in ("boolean", "numeric"):
+ if evaluation["output_type"] not in ("boolean", "numeric", "categorical"):
raise ApplicationError(
- f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean', 'numeric'.",
+ f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean', 'numeric', 'categorical'.",
non_retryable=True,
)
@@ -562,6 +562,7 @@ class SessionHogTestResult:
input_preview: str
output_preview: str
score: float | None = None
+ categories: list[str] | None = None
applicable: bool | None = None
@@ -699,6 +700,7 @@ def run_hog_eval_over_recent_sessions(
session_id=session_id,
verdict=hog_result.get("verdict"),
score=hog_result.get("score"),
+ categories=hog_result.get("categories"),
applicable=hog_result.get("applicable"),
reasoning=hog_result.get("reasoning") or "",
error=hog_result.get("error"),
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.py
index 0126eb3c1957..b4251d198c4c 100644
--- a/posthog/temporal/ai_observability/run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py
@@ -349,6 +349,7 @@ class TraceHogTestResult:
input_preview: str
output_preview: str
score: float | None = None
+ categories: list[str] | None = None
applicable: bool | None = None
@@ -509,6 +510,7 @@ def run_hog_eval_over_recent_traces(
trace_id=sample.trace_id,
verdict=result.get("verdict"),
score=result.get("score"),
+ categories=result.get("categories"),
applicable=result.get("applicable"),
reasoning=result["reasoning"],
error=result["error"],
@@ -672,9 +674,9 @@ def execute_trace_llm_judge_activity(inputs: ExecuteTraceEvaluationInputs) -> Ev
if not prompt:
raise ApplicationError("Missing prompt in evaluation_config", non_retryable=True)
- if evaluation["output_type"] not in ("boolean", "numeric"):
+ if evaluation["output_type"] not in ("boolean", "numeric", "categorical"):
raise ApplicationError(
- f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean', 'numeric'.",
+ f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean', 'numeric', 'categorical'.",
non_retryable=True,
)
@@ -871,7 +873,7 @@ class RunTraceEvaluationWorkflow(PostHogWorkflow):
"evaluation_id": inputs.evaluation_id,
"evaluation_type": evaluation_type,
}
- if evaluation.get("output_type") != "numeric":
+ if evaluation.get("output_type") not in ("numeric", "categorical"):
disabled_result["verdict"] = None
return disabled_result
@@ -954,6 +956,8 @@ class RunTraceEvaluationWorkflow(PostHogWorkflow):
workflow_result["verdict"] = result["verdict"]
if "score" in result:
workflow_result["score"] = result["score"]
+ if "categories" in result:
+ workflow_result["categories"] = result["categories"]
if result.get("skipped"):
skip_reason = result.get("skip_reason")
if skip_reason is not None:
diff --git a/posthog/temporal/ai_observability/test_evaluation_hog.py b/posthog/temporal/ai_observability/test_evaluation_hog.py
index 0c91b03f2dbe..24fa9abac0b7 100644
--- a/posthog/temporal/ai_observability/test_evaluation_hog.py
+++ b/posthog/temporal/ai_observability/test_evaluation_hog.py
@@ -105,6 +105,73 @@ def test_numeric_hog_na_omits_score() -> None:
assert result == {"result_type": "numeric", "reasoning": "", "allows_na": True, "applicable": False}
+ "mode,source,categories,applicable",
+ [
+ ("single", "return 'resolved'", ["resolved"], True),
+ ("multiple", "return ['resolved', 'polite']", ["resolved", "polite"], True),
+ ("multiple", "return []", [], True),
+ ("multiple", "return null", None, False),
+ ],
+)
+def test_categorical_hog_preserves_labels_and_applicability(
+ mode: str, source: str, categories: list[str] | None, applicable: bool
+) -> None:
+ config = {
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "polite", "label": "Polite"}],
+ "selection_mode": mode,
+ "allows_na": True,
+ }
+ raw = execute_hog_eval_bytecode(
+ compile_ai_observability_hog(source, "destination"), {}, True, output_type="categorical", output_config=config
+ )
+ result = finalize_hog_eval_result(
+ raw,
+ evaluation={**EVALUATION, "output_type": "categorical", "output_config": config},
+ allows_na=True,
+ unit_label=None,
+ )
+ assert result == {
+ "result_type": "categorical",
+ "reasoning": "",
+ "allows_na": True,
+ "applicable": applicable,
+ **({"categories": categories} if categories is not None else {}),
+ }
+
+
+ "mode,source,terminal",
+ [
+ ("single", "return 'unknown'", False),
+ ("single", "return []", False),
+ ("single", "return ['resolved', 'polite']", False),
+ ("multiple", "return ['resolved', 'resolved']", False),
+ ("single", "return 1", True),
+ ("multiple", "return true", True),
+ ("multiple", "return [1]", True),
+ ],
+)
+def test_invalid_categorical_hog_only_disables_for_wrong_types(mode: str, source: str, terminal: bool) -> None:
+ config = {
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "polite", "label": "Polite"}],
+ "selection_mode": mode,
+ }
+ raw = execute_hog_eval_bytecode(
+ compile_ai_observability_hog(source, "destination"), {}, False, output_type="categorical", output_config=config
+ )
+ result = finalize_hog_eval_result(
+ raw,
+ evaluation={**EVALUATION, "output_type": "categorical", "output_config": config},
+ allows_na=False,
+ unit_label=None,
+ )
+ assert is_terminal_user_error_result(result) is terminal
+ assert result["skipped"] is True
+ assert result["skip_reason"] == ("hog_error" if terminal else "hog_input_error")
+ assert "categories" not in result
+
+
def run_source(source: str, property_value: object = "", *, allows_na: bool = True) -> dict:
bytecode = compile_ai_observability_hog(source, "destination")
return execute_hog_eval_bytecode(bytecode, {"properties": {"$ai_output": property_value}}, allows_na=allows_na)
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 5c0b744e7ba1..c51c185d7ee7 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -478,19 +478,22 @@ class TestRunEvaluationWorkflow:
pytest.param({"allows_na": True}, None, False, id="with_na"),
],
)
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric", "categorical"])
@pytest.mark.django_db(transaction=True)
def test_execute_llm_judge_activity_skips_on_output_limit(
- self, output_config, expected_verdict, expected_applicable, setup_data, active_key_config
+ self, output_config, expected_verdict, expected_applicable, output_type, setup_data, active_key_config
):
team = setup_data["team"]
evaluation_obj = setup_data["evaluation"]
+ if output_type == "categorical":
+ output_config = {**output_config, "options": [{"key": "resolved", "label": "Resolved"}]}
evaluation = {
"id": str(evaluation_obj.id),
"name": "Test Evaluation",
"evaluation_type": "llm_judge",
"evaluation_config": {"prompt": "Is this response factually accurate?"},
- "output_type": "boolean",
+ "output_type": output_type,
"output_config": output_config,
"team_id": team.id,
}
@@ -513,7 +516,11 @@ class TestRunEvaluationWorkflow:
assert result["skipped"] is True
assert result["skip_reason"] == "output_limit_exceeded"
- assert result["verdict"] is expected_verdict
+ assert result["result_type"] == output_type
+ if output_type == "boolean":
+ assert result["verdict"] is expected_verdict
+ else:
+ assert "verdict" not in result
assert result.get("applicable") is expected_applicable
assert result.get("terminal_user_error") is not True
# The model ran and the call was billed, so attribution stays on the result.
@@ -2571,6 +2578,59 @@ class TestExecuteSentimentEvalActivity:
class TestEvalResultModels:
+ @pytest.mark.parametrize(
+ "categories,allows_na",
+ [(["resolved"], True), ([], True), (None, True), (["unknown"], True), ([], False), (["unknown"], False)],
+ )
+ def test_categorical_judge_emits_only_valid_labels(self, categories: list[str] | None, allows_na: bool) -> None:
+ config = {
+ "options": [{"key": "resolved", "label": "Resolved"}],
+ "selection_mode": "multiple",
+ "allows_na": allows_na,
+ }
+ evaluation = {
+ "id": "categorical-eval",
+ "name": "Resolution",
+ "team_id": 1,
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Classify the response"},
+ "output_type": "categorical",
+ "output_config": config,
+ }
+ schema = get_output_type_config(allows_na, output_type="categorical", output_config=config).response_format
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as model_spec,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as client,
+ ):
+ model_spec.return_value.resolve.return_value = MagicMock(
+ provider="openai", model="gpt-4o-mini", provider_key=None, is_byok=False
+ )
+ client.return_value.complete.return_value = MagicMock(
+ parsed=schema.model_validate({"reasoning": "Resolution", "categories": categories}),
+ usage=MagicMock(input_tokens=100, output_tokens=20, total_tokens=120),
+ )
+ result = _execute_llm_judge_activity(
+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=create_mock_event_data(1))
+ )
+ assert result["result_type"] == "categorical"
+ assert "verdict" not in result
+ properties = build_evaluation_event_properties(evaluation, result, datetime(2026, 7, 1, tzinfo=UTC))
+ assert "$ai_evaluation_result" not in properties
+ if categories == ["unknown"]:
+ assert result["skipped"] is True
+ assert "terminal_user_error" not in result
+ assert "$ai_evaluation_categorical_result" not in properties
+ assert properties["$ai_evaluation_applicable"] is False
+ elif categories is None:
+ assert result["applicable"] is False
+ assert "$ai_evaluation_categorical_result" not in properties
+ assert properties["$ai_evaluation_applicable"] is False
+ else:
+ assert result["categories"] == categories
+ assert result.get("applicable", True) is True
+ assert properties["$ai_evaluation_applicable"] is True
+ assert properties["$ai_evaluation_categorical_result"] == categories
+
@pytest.mark.parametrize("score", [0, 0.25, 1, None, -0.1, 1.1])
def test_numeric_judge_validates_bounds_before_returning(self, score: float | None) -> None:
evaluation = {
diff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.py
index fc58a89d296d..d2aaa3ae96cb 100644
--- a/posthog/temporal/ai_observability/test_run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py
@@ -477,8 +477,28 @@ class TestFetchSessionForEvaluation:
class TestExecuteSessionActivities:
@pytest.mark.parametrize("runtime", ["hog", "llm_judge"])
@pytest.mark.parametrize("target", ["generation", "trace", "session"])
- @pytest.mark.parametrize("score", [0.25, None])
- def test_numeric_outputs_across_targets(self, runtime: str, target: str, score: float | None) -> None:
+ @pytest.mark.parametrize(
+ "output_type,score",
+ [
+ ("numeric", 0.25),
+ ("numeric", None),
+ ("categorical", ["resolved"]),
+ ("categorical", []),
+ ("categorical", None),
+ ],
+ )
+ def test_outputs_across_targets(
+ self, runtime: str, target: str, output_type: str, score: float | list[str] | None
+ ) -> None:
+ output_config = {
+ "allows_na": True,
+ **(
+ {"min": 0, "max": 1}
+ if output_type == "numeric"
+ else {"options": [{"key": "resolved", "label": "Resolved"}], "selection_mode": "multiple"}
+ ),
+ }
+ result_key = "score" if output_type == "numeric" else "categories"
trace = _trace("trace-1", cost=0, latency=0)
evaluation = {
"id": "numeric-eval",
@@ -487,14 +507,14 @@ class TestExecuteSessionActivities:
"evaluation_config": {
"prompt": "Rate quality",
"bytecode": compile_ai_observability_hog(
- "return null" if score is None else "return 0.25",
+ "return null" if score is None else f"return {score!r}",
"destination",
),
},
- "output_type": "numeric",
- "output_config": {"min": 0, "max": 1, "allows_na": True},
+ "output_type": output_type,
+ "output_config": output_config,
}
- schema = get_output_type_config(True, output_type="numeric").response_format
+ schema = get_output_type_config(True, output_type=output_type, output_config=output_config).response_format
with (
patch(
"posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
@@ -514,7 +534,7 @@ class TestExecuteSessionActivities:
is_byok=False,
)
client.return_value.complete.return_value = Mock(
- parsed=schema.model_validate({"reasoning": "Quality", "score": score}),
+ parsed=schema.model_validate({"reasoning": "Quality", result_key: score}),
usage=None,
)
if target == "generation":
@@ -544,15 +564,16 @@ class TestExecuteSessionActivities:
if runtime == "hog"
else execute_session_llm_judge_activity(session_inputs)
)
- assert result["result_type"] == "numeric"
+ assert result["result_type"] == output_type
assert "verdict" not in result
assert result["applicable"] is (score is not None)
if score is None:
- assert "score" not in result
+ assert result_key not in result
else:
- assert result["score"] == score
- assert result["score_min"] == 0
- assert result["score_max"] == 1
+ assert result.get(result_key) == score
+ if output_type == "numeric":
+ assert result["score_min"] == 0
+ assert result["score_max"] == 1
@pytest.mark.parametrize(
"skip_reason",
diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
index fad7b07f2aec..fa57004a5a71 100644
--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
@@ -536,7 +536,7 @@ class TestRunHogEvalOverRecentTraces:
assert rewritten_condition.left.chain == ["input"]
@time_machine.travel(FROZEN_NOW, tick=False)
- @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric", "categorical"])
def test_uses_the_sampled_trigger_and_configured_aggregation_window(self, output_type: str):
team = MagicMock(spec=Team)
user = MagicMock()
@@ -550,6 +550,8 @@ class TestRunHogEvalOverRecentTraces:
bytecode = compile_hog(
"return length(evaluation_events) / 4"
if output_type == "numeric"
+ else "return ['resolved']"
+ if output_type == "categorical"
else "return target.type == 'trace' and length(evaluation_events) == 2",
"destination",
)
@@ -574,7 +576,11 @@ class TestRunHogEvalOverRecentTraces:
sample_count=1,
allows_na=False,
output_type=output_type,
- output_config={"min": 0, "max": 1} if output_type == "numeric" else {},
+ output_config={"min": 0, "max": 1}
+ if output_type == "numeric"
+ else {"options": [{"key": "resolved", "label": "Resolved"}]}
+ if output_type == "categorical"
+ else {},
window_seconds=120,
)
@@ -596,6 +602,9 @@ class TestRunHogEvalOverRecentTraces:
if output_type == "numeric":
assert results[0].score == 0.5
assert results[0].verdict is None
+ elif output_type == "categorical":
+ assert results[0].categories == ["resolved"]
+ assert results[0].verdict is None
else:
assert results[0].verdict is True
assert results[0].input_preview == "first"
@@ -702,7 +711,7 @@ class TestExecuteTraceLLMJudgeActivity:
{"outputState": [{"role": "assistant", "parts": [{"type": "text", "content": " \n "}]}]},
],
)
- @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric", "categorical"])
def test_skips_without_llm_call_when_the_trace_has_no_transcript(
self, trace_state: dict[str, Any], output_type: str
) -> None:
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index cf914478c21b..b370330e76ff 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -430,7 +430,7 @@ class EvaluationReportCitationSerializer(serializers.Serializer):
class EvaluationReportMetricsSerializer(serializers.Serializer):
output_config = _OutputConfigField(
required=False,
- help_text="Numeric score configuration and passing rule used for both report periods.",
+ help_text="Output configuration and passing rule used for both report periods.",
)
output_type = serializers.ChoiceField(
choices=OutputType.choices,
@@ -479,12 +479,12 @@ class EvaluationReportMetricsSerializer(serializers.Serializer):
pass_rate = serializers.FloatField(
required=False,
allow_null=True,
- help_text="Boolean or numeric pass percentage, excluding N/A results. Null when no numeric scores were produced.",
+ help_text="Pass percentage excluding N/A. With no applicable results, numeric and categorical reports return null; boolean reports return 0.",
)
previous_pass_rate = serializers.FloatField(
required=False,
allow_null=True,
- help_text="Boolean or numeric pass percentage for the previous period, or null when unavailable.",
+ help_text="Pass percentage for boolean, numeric, or categorical results in the previous period, or null when unavailable.",
)
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index c91632bf53ec..fa05ffbf2fad 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -49,6 +49,7 @@ from ..llm import DEFAULT_MODEL_BY_PROVIDER
from ..models.evaluation_config import EvaluationConfig
from ..models.evaluation_configs import (
EVALUATION_TEST_LOOKBACK_DAYS,
+ MAX_CATEGORICAL_OPTIONS,
SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
SESSION_EVAL_MAX_MAX_AGE_SECONDS,
SESSION_EVAL_MAX_QUIET_PERIOD_SECONDS,
@@ -85,9 +86,10 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
NUMERIC_EVALUATIONS_FEATURE_FLAG = "llm-analytics-numeric-evaluations"
+CATEGORICAL_EVALUATIONS_FEATURE_FLAG = "llm-analytics-categorical-evaluations"
-def _numeric_evaluations_enabled(serializer: serializers.BaseSerializer) -> bool:
+def _evaluation_output_enabled(serializer: serializers.BaseSerializer, flag_key: str) -> bool:
request = serializer.context.get("request")
get_team = serializer.context.get("get_team")
user = getattr(request, "user", None)
@@ -97,7 +99,7 @@ def _numeric_evaluations_enabled(serializer: serializers.BaseSerializer) -> bool
team = get_team()
try:
return posthog_feature_flag_enabled(
- NUMERIC_EVALUATIONS_FEATURE_FLAG,
+ flag_key,
str(user.distinct_id),
organization_id=team.organization_id,
team_id=team.id,
@@ -129,7 +131,7 @@ def _numeric_evaluations_enabled(serializer: serializers.BaseSerializer) -> bool
"properties": {
"source": {
"type": "string",
- "description": "Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.",
+ "description": "Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
}
},
@@ -171,7 +173,7 @@ class _EvaluationConfigField(serializers.JSONField):
},
"true_is_failure": {
"type": "boolean",
- "description": "Boolean output only. Omit for numeric and sentiment "
+ "description": "Boolean output only. Omit for numeric, categorical, and sentiment "
"output. Whether a true result means the evaluation found "
"a problem. False (the default) suits pass/fail "
"evaluations, where a true result satisfied the criteria. "
@@ -195,24 +197,71 @@ class _EvaluationConfigField(serializers.JSONField):
"minimum": 0,
"description": "Optional positive input increment. Does not round evaluation results.",
},
+ "options": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": MAX_CATEGORICAL_OPTIONS,
+ "description": "Categorical output options. Keys identify stored results; labels are displayed to users.",
+ "items": {
+ "type": "object",
+ "required": ["key", "label"],
+ "properties": {
+ "key": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 128,
+ "pattern": "^[a-z0-9]+(?:[_-][a-z0-9]+)*$",
+ "description": "Stable category key.",
+ },
+ "label": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "description": "Category display label.",
+ },
+ },
+ "additionalProperties": False,
+ },
+ },
+ "selection_mode": {
+ "type": "string",
+ "enum": ["single", "multiple"],
+ "description": "Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.",
+ },
"passing_rule": {
- "type": "object",
"nullable": True,
- "required": ["operator", "threshold"],
- "description": "Optional numeric passing rule. Null removes the rule; "
- "historical scores use the current rule.",
- "properties": {
- "operator": {
- "type": "string",
- "enum": ["gte", "lte"],
- "description": "Pass at or above (gte), or at or below (lte), the threshold.",
+ "description": "Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.",
+ "oneOf": [
+ {
+ "type": "object",
+ "required": ["operator", "threshold"],
+ "properties": {
+ "operator": {
+ "type": "string",
+ "enum": ["gte", "lte"],
+ "description": "Pass at or above (gte), or at or below (lte), the threshold.",
+ },
+ "threshold": {
+ "type": "number",
+ "description": "Finite passing threshold within any configured score bounds.",
+ },
+ },
+ "additionalProperties": False,
},
- "threshold": {
- "type": "number",
- "description": "Finite passing threshold within any configured score bounds.",
+ {
+ "type": "object",
+ "required": ["categories"],
+ "properties": {
+ "categories": {
+ "type": "array",
+ "uniqueItems": True,
+ "items": {"type": "string"},
+ "description": "Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.",
+ },
+ },
+ "additionalProperties": False,
},
- },
- "additionalProperties": False,
+ ],
},
},
"additionalProperties": False,
@@ -396,7 +445,7 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and "
"{true_is_failure} to declare that a true result means the evaluation found a problem. "
"For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. "
- "Do not send true_is_failure for numeric output. For 'sentiment': {}."
+ "For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}."
),
)
target_config = _TargetConfigField(
@@ -468,7 +517,7 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
},
"output_type": {
"help_text": (
- "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis."
+ "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis."
)
},
"target": {
@@ -489,19 +538,24 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
def validate(self, data):
evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)
output_type = data.get("output_type") or getattr(self.instance, "output_type", None)
- is_new_numeric_evaluation = output_type == "numeric" and (
- self.instance is None or self.instance.output_type != "numeric"
- )
- if is_new_numeric_evaluation and not _numeric_evaluations_enabled(self):
- raise serializers.ValidationError({"output_type": "Numeric evaluations are not enabled for this project."})
+ flag_key = {
+ "numeric": NUMERIC_EVALUATIONS_FEATURE_FLAG,
+ "categorical": CATEGORICAL_EVALUATIONS_FEATURE_FLAG,
+ }.get(str(output_type))
if (
- self.instance
- and output_type != self.instance.output_type
- and "numeric" in (output_type, self.instance.output_type)
+ flag_key
+ and (self.instance is None or self.instance.output_type != output_type)
+ and not _evaluation_output_enabled(self, flag_key)
):
raise serializers.ValidationError(
- {"output_type": "Create a new evaluation to change between numeric and other output types."}
+ {"output_type": f"{str(output_type).capitalize()} evaluations are not enabled for this project."}
)
+ if (
+ self.instance
+ and output_type != self.instance.output_type
+ and ({output_type, self.instance.output_type} & {"numeric", "categorical"})
+ ):
+ raise serializers.ValidationError({"output_type": "Create a new evaluation to change its output type."})
model_configuration = data.get(
"model_configuration",
getattr(self.instance, "model_configuration", None) if self.instance else None,
@@ -852,6 +906,7 @@ class TestHogTargetConfigSerializer(serializers.Serializer):
class HogEvaluationOutputType(models.TextChoices):
BOOLEAN = OutputType.BOOLEAN.value, OutputType.BOOLEAN.label
NUMERIC = OutputType.NUMERIC.value, OutputType.NUMERIC.label
+ CATEGORICAL = OutputType.CATEGORICAL.value, OutputType.CATEGORICAL.label
class TestHogRequestSerializer(serializers.Serializer):
@@ -859,18 +914,20 @@ class TestHogRequestSerializer(serializers.Serializer):
choices=HogEvaluationOutputType.choices,
required=False,
default=OutputType.BOOLEAN,
- help_text="Expected output: boolean or numeric. Sentiment is not supported by Hog.",
+ help_text="Expected output: boolean, numeric, or categorical. Sentiment is not supported by Hog.",
)
output_config = _OutputConfigField(
required=False,
default=dict,
- help_text="Output settings used to validate the preview, including numeric bounds and allows_na.",
+ help_text="Output settings used to validate the preview, including bounds, categories, and allows_na.",
)
source = serializers.CharField(
required=True,
min_length=1,
help_text=(
- "Hog source code to test. Must return a boolean or a finite number matching output_type, or null for allowed N/A. "
+ "Hog source code to test. Return a boolean, finite number, or category keys matching output_type. "
+ "Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. "
+ "Return null only for allowed N/A. "
"Output settings determine which boolean counts as a failure."
),
) # type: ignore[assignment]
@@ -923,6 +980,12 @@ class TestHogRequestSerializer(serializers.Serializer):
class TestHogResultItemSerializer(serializers.Serializer):
+ categories = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ help_text="Selected category keys. An empty list is an applicable result; null means no categorical result was produced.",
+ )
score = serializers.FloatField(
required=False, allow_null=True, help_text="Raw numeric score, or null when no numeric score was produced."
)
@@ -965,7 +1028,13 @@ def _hog_test_result_counts(
if result["error"]:
counts["error"] += 1
else:
- value = result.get("score") if output_type == "numeric" else result["result"]
+ value = (
+ result.get("categories")
+ if output_type == "categorical"
+ else result.get("score")
+ if output_type == "numeric"
+ else result["result"]
+ )
counts[definition.label_for(value, applicable=value is not None)] += 1
return {f"{outcome}_count": counts[outcome] for outcome in ("pass", "fail", "na", "error")}
@@ -1023,6 +1092,7 @@ def _test_hog_over_sessions(
"output_preview": r.output_preview,
"result": r.verdict,
**({"score": r.score} if output_type == "numeric" else {}),
+ **({"categories": r.categories} if output_type == "categorical" else {}),
"reasoning": r.reasoning,
"error": r.error,
}
@@ -1100,6 +1170,7 @@ def _test_hog_over_traces(
"output_preview": r.output_preview,
"result": r.verdict,
**({"score": r.score} if output_type == "numeric" else {}),
+ **({"categories": r.categories} if output_type == "categorical" else {}),
"reasoning": r.reasoning,
"error": r.error,
}
@@ -1524,6 +1595,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
"output_preview": output_preview,
"result": result.get("verdict"),
**({"score": result.get("score")} if output_type == "numeric" else {}),
+ **({"categories": result.get("categories")} if output_type == "categorical" else {}),
"reasoning": result["reasoning"],
"error": result["error"],
}
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index 7cb41d3fb10b..b73349fe3607 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -79,6 +79,18 @@ class TestNumericEvaluationSerializer(SimpleTestCase):
self.assertEqual(serializer.validated_data["output_type"], "numeric")
self.assertTrue(serializer.validated_data["allows_na"])
+ def test_preview_validates_categorical_config(self):
+ output_config = {
+ "options": [{"key": "resolved", "label": "Resolved"}],
+ "selection_mode": "multiple",
+ "allows_na": True,
+ }
+ serializer = HogRequestSerializer(
+ data={"source": "return [];", "output_type": "categorical", "output_config": output_config}
+ )
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ self.assertEqual(serializer.validated_data["output_config"], output_config)
+
@parameterized.expand([({"min": 10, "max": 0},), ([],), ("invalid",), (1,), (True,), (None,)])
def test_preview_rejects_invalid_numeric_config(self, output_config: object) -> None:
serializer = HogRequestSerializer(
@@ -148,32 +160,42 @@ class TestTargetConfigFieldSchema(SimpleTestCase):
class TestEvaluationConfigsApi(APIBaseTest):
+ @parameterized.expand(
+ [("numeric", {"min": 0, "max": 10}), ("categorical", {"options": [{"key": "resolved", "label": "Resolved"}]})]
+ )
@patch("products.ai_observability.backend.api.evaluations.posthog_feature_flag_enabled", return_value=False)
- def test_numeric_creation_requires_feature_flag(self, _mock_numeric_flag: Mock) -> None:
+ def test_creation_requires_feature_flag(
+ self, output_type: str, output_config: dict, _mock_numeric_flag: Mock
+ ) -> None:
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
{
"name": "Gated score",
"evaluation_type": "hog",
"evaluation_config": {"source": "return 0;"},
- "output_type": "numeric",
- "output_config": {"min": 0, "max": 10},
+ "output_type": output_type,
+ "output_config": output_config,
},
format="json",
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("Numeric evaluations are not enabled", str(response.data))
+ self.assertIn(f"{output_type.capitalize()} evaluations are not enabled", str(response.data))
+ @parameterized.expand(
+ [("numeric", {"min": 0, "max": 10}), ("categorical", {"options": [{"key": "resolved", "label": "Resolved"}]})]
+ )
@patch("products.ai_observability.backend.api.evaluations.posthog_feature_flag_enabled", return_value=False)
- def test_existing_numeric_evaluation_remains_editable_when_flag_is_off(self, _mock_numeric_flag: Mock) -> None:
+ def test_existing_evaluation_remains_editable_when_flag_is_off(
+ self, output_type: str, output_config: dict, _mock_numeric_flag: Mock
+ ) -> None:
evaluation = Evaluation.objects.create(
team=self.team,
name="Existing score",
evaluation_type="hog",
evaluation_config={"source": "return 0;"},
- output_type="numeric",
- output_config={"min": 0, "max": 10},
+ output_type=output_type,
+ output_config=output_config,
)
response = self.client.patch(
@@ -186,19 +208,31 @@ class TestEvaluationConfigsApi(APIBaseTest):
evaluation.refresh_from_db()
self.assertEqual(evaluation.name, "Renamed score")
- @parameterized.expand([(True, "scheduled"), (False, "scheduled"), (True, "every_n")])
+ @parameterized.expand(
+ [
+ (output_type, enabled, frequency)
+ for output_type in ("numeric", "categorical")
+ for enabled, frequency in [(True, "scheduled"), (False, "scheduled"), (True, "every_n")]
+ ]
+ )
@patch("products.ai_observability.backend.api.evaluations.posthog_feature_flag_enabled", return_value=True)
- def test_numeric_passing_rule_controls_report_creation_and_scheduling(
- self, enabled: bool, frequency: str, _mock_numeric_flag: Mock
+ def test_passing_rule_controls_report_creation_and_scheduling(
+ self, output_type: str, enabled: bool, frequency: str, _mock_numeric_flag: Mock
) -> None:
+ output_config = (
+ {"min": 0, "max": 10}
+ if output_type == "numeric"
+ else {"options": [{"key": "resolved", "label": "Resolved"}]}
+ )
+ rule = {"operator": "gte", "threshold": 7} if output_type == "numeric" else {"categories": ["resolved"]}
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
{
"name": "Response score",
"evaluation_type": "hog",
"evaluation_config": {"source": "return 0;"},
- "output_type": "numeric",
- "output_config": {"min": 0, "max": 10},
+ "output_type": output_type,
+ "output_config": output_config,
"enabled": enabled,
},
)
@@ -206,9 +240,9 @@ class TestEvaluationConfigsApi(APIBaseTest):
evaluation = Evaluation.objects.get(id=response.json()["id"])
self.assertFalse(EvaluationReport.objects.filter(evaluation=evaluation).exists())
url = f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/"
- response = self.client.patch(url, {"output_config": {"passing_rule": {"operator": "gte", "threshold": 7}}})
+ response = self.client.patch(url, {"output_config": {"passing_rule": rule}})
self.assertEqual(response.status_code, 200, response.json())
- self.assertEqual(response.json()["output_config"]["min"], 0)
+ self.assertTrue(output_config.items() <= response.json()["output_config"].items())
report = EvaluationReport.objects.get(evaluation=evaluation)
self.assertEqual(EvaluationReport.objects.deliverable().filter(id=report.id).exists(), enabled)
if not enabled:
@@ -227,7 +261,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
next_delivery_date=old_delivery + timedelta(days=1),
)
resumed_at = timezone.now()
- response = self.client.patch(url, {"output_config": {"passing_rule": {"operator": "gte", "threshold": 7}}})
+ response = self.client.patch(url, {"output_config": {"passing_rule": rule}})
self.assertEqual(response.status_code, 200, response.json())
report.refresh_from_db()
self.assertIsNone(report.last_delivered_at)
diff --git a/products/ai_observability/backend/migrations/0059_categorical_evaluation_output.py b/products/ai_observability/backend/migrations/0059_categorical_evaluation_output.py
new file mode 100644
index 000000000000..d04808829eac
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0059_categorical_evaluation_output.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.17 on 2026-09-26 14:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0058_evaluationbackfill_failed_count"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="evaluation",
+ name="output_type",
+ field=models.CharField(
+ choices=[
+ ("boolean", "Boolean (Pass/Fail)"),
+ ("numeric", "Numeric"),
+ ("categorical", "Categorical"),
+ ("sentiment", "Sentiment"),
+ ],
+ max_length=50,
+ ),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index e8e6269c609a..3fab3df7673c 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0058_evaluationbackfill_failed_count
+0059_categorical_evaluation_output
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index a45fd06ec3f4..38a7a64eea30 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -19,6 +19,7 @@ class OutputType(models.TextChoices):
BOOLEAN = "boolean", "Boolean (Pass/Fail)"
NUMERIC = "numeric", "Numeric"
+ CATEGORICAL = "categorical", "Categorical"
SENTIMENT = "sentiment", "Sentiment"
@@ -113,6 +114,75 @@ class NumericOutputConfig(BaseModel):
return score
+# Limit category configuration size to stay within Temporal's activity payload limit.
+MAX_CATEGORICAL_OPTIONS = 100
+
+
+class CategoricalOption(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True, str_strip_whitespace=True)
+
+ key: str = Field(min_length=1, max_length=128, pattern=r"^[a-z0-9]+(?:[_-][a-z0-9]+)*$")
+ label: str = Field(min_length=1, max_length=256)
+
+
+class CategoricalPassingRule(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+
+ categories: list[str]
+
+ @model_validator(mode="after")
+ def validate_categories(self) -> Self:
+ if len(set(self.categories)) != len(self.categories):
+ raise ValueError("Select each passing category only once")
+ self.categories.sort()
+ return self
+
+ def passes(self, categories: list[str]) -> bool:
+ if not categories:
+ return not self.categories
+ return set(categories) <= set(self.categories)
+
+
+class InvalidEvaluationCategories(ValueError):
+ pass
+
+
+class CategoricalOutputConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True)
+
+ options: list[CategoricalOption] = Field(min_length=1, max_length=MAX_CATEGORICAL_OPTIONS)
+ selection_mode: Literal["single", "multiple"] = "single"
+ allows_na: bool = False
+ passing_rule: CategoricalPassingRule | None = None
+
+ @model_validator(mode="after")
+ def validate_options(self) -> Self:
+ keys = {option.key for option in self.options}
+ if len(keys) != len(self.options):
+ raise ValueError("Category keys must be unique")
+ if self.passing_rule is not None:
+ rule = self.passing_rule
+ if self.selection_mode == "single" and not rule.categories:
+ raise ValueError("Choose at least one passing category.")
+ if not set(rule.categories) <= keys:
+ raise ValueError("Passing rules must use configured category keys")
+ return self
+
+ def validate_result(self, value: object) -> list[str]:
+ if self.selection_mode == "single" and isinstance(value, str):
+ value = [value]
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
+ raise ValueError("Return category keys as a list, or one category key for single selection")
+ if self.selection_mode == "single" and len(value) != 1:
+ raise InvalidEvaluationCategories("Single selection must return exactly one category")
+ keys = {option.key for option in self.options}
+ if not set(value) <= keys:
+ raise InvalidEvaluationCategories("Return only configured category keys")
+ if len(value) != len(set(value)):
+ raise InvalidEvaluationCategories("Return each category only once")
+ return value
+
+
class SentimentEvalConfig(BaseModel):
"""Configuration for sentiment evaluations.
@@ -304,6 +374,8 @@ def validate_target_config(target: str, target_config: dict) -> dict:
# Mapping: (evaluation_type, output_type) -> (evaluation_config_model, output_config_model)
EVALUATION_CONFIG_MODELS: dict[tuple[str, str], tuple[type[BaseModel], type[BaseModel]]] = {
+ (EvaluationType.LLM_JUDGE.value, OutputType.CATEGORICAL.value): (LLMJudgeConfig, CategoricalOutputConfig),
+ (EvaluationType.HOG.value, OutputType.CATEGORICAL.value): (HogEvalConfig, CategoricalOutputConfig),
(EvaluationType.LLM_JUDGE.value, OutputType.NUMERIC.value): (LLMJudgeConfig, NumericOutputConfig),
(EvaluationType.HOG.value, OutputType.NUMERIC.value): (HogEvalConfig, NumericOutputConfig),
(EvaluationType.LLM_JUDGE.value, OutputType.BOOLEAN.value): (LLMJudgeConfig, BooleanOutputConfig),
@@ -321,13 +393,14 @@ REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (
OutputType.BOOLEAN.value,
OutputType.SENTIMENT.value,
OutputType.NUMERIC.value,
+ OutputType.CATEGORICAL.value,
)
# Sentiment is generation-only (see the target check in the evaluations API), so the aggregate
-# targets support boolean and numeric results.
+# targets support boolean, numeric, and categorical results.
REPORTABLE_OUTPUT_TYPES_BY_TARGET: dict[str, tuple[str, ...]] = {
"generation": REPORTABLE_OUTPUT_TYPES,
- "trace": (OutputType.BOOLEAN.value, OutputType.NUMERIC.value),
- "session": (OutputType.BOOLEAN.value, OutputType.NUMERIC.value),
+ "trace": (OutputType.BOOLEAN.value, OutputType.NUMERIC.value, OutputType.CATEGORICAL.value),
+ "session": (OutputType.BOOLEAN.value, OutputType.NUMERIC.value, OutputType.CATEGORICAL.value),
}
@@ -336,7 +409,7 @@ def evaluation_uses_model_configuration(evaluation_type: str | None) -> bool:
def evaluation_supports_reports(output_type: str | None, target: str | None, output_config: dict | None = None) -> bool:
- if output_type == OutputType.NUMERIC and not (output_config or {}).get("passing_rule"):
+ if output_type in (OutputType.NUMERIC, OutputType.CATEGORICAL) and not (output_config or {}).get("passing_rule"):
return False
return output_type in REPORTABLE_OUTPUT_TYPES_BY_TARGET.get(target or "", ())
diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.py
index c03366d587d7..963d7c7b9da6 100644
--- a/products/ai_observability/backend/models/evaluation_reports.py
+++ b/products/ai_observability/backend/models/evaluation_reports.py
@@ -24,7 +24,7 @@ class EvaluationReportQuerySet(models.QuerySet):
def reportable(self) -> "EvaluationReportQuerySet":
return self.for_supported_evaluations().exclude(
- models.Q(evaluation__output_type="numeric")
+ models.Q(evaluation__output_type__in=("numeric", "categorical"))
& (
~models.Q(evaluation__output_config__has_key="passing_rule")
| models.Q(evaluation__output_config__passing_rule=None)
diff --git a/products/ai_observability/backend/models/test/test_evaluation_configs.py b/products/ai_observability/backend/models/test/test_evaluation_configs.py
index f780826f31d5..3c8fb5a8cb2a 100644
--- a/products/ai_observability/backend/models/test/test_evaluation_configs.py
+++ b/products/ai_observability/backend/models/test/test_evaluation_configs.py
@@ -3,6 +3,7 @@ import math
import pytest
from products.ai_observability.backend.models.evaluation_configs import (
+ CategoricalOutputConfig,
NumericOutputConfig,
NumericScoreOutOfBounds,
validate_evaluation_configs,
@@ -73,6 +74,60 @@ class TestNumericOutputConfig:
assert output == {"allows_na": True}
+class TestCategoricalOutputConfig:
+ @pytest.mark.parametrize("runtime", ["hog", "llm_judge"])
+ @pytest.mark.parametrize("selection_mode", ["single", "multiple"])
+ @pytest.mark.parametrize("option_count", [2, 100])
+ def test_categorical_configuration(self, runtime: str, selection_mode: str, option_count: int) -> None:
+ evaluation_config = (
+ {"source": "return 'resolved';"} if runtime == "hog" else {"prompt": "Classify the response"}
+ )
+ output_config = {
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "incorrect", "label": "Incorrect"}]
+ + [{"key": f"category_{i}", "label": f"Category {i}"} for i in range(option_count - 2)],
+ "selection_mode": selection_mode,
+ "allows_na": True,
+ "passing_rule": {"categories": ["resolved"]},
+ }
+ _, validated = validate_evaluation_configs(runtime, "categorical", evaluation_config, output_config)
+ assert validated == output_config
+
+ @pytest.mark.parametrize(
+ "mode,value",
+ [
+ ("single", value)
+ for value in [[], ["resolved", "resolved"], ["unknown"], [1], True, None, {"resolved": True}]
+ ]
+ + [("multiple", ["resolved", "resolved"])],
+ )
+ def test_selection_rejects_invalid_results(self, mode: str, value: object) -> None:
+ config = CategoricalOutputConfig.model_validate(
+ {"options": [{"key": "resolved", "label": "Resolved"}], "selection_mode": mode}
+ )
+ with pytest.raises(ValueError):
+ config.validate_result(value)
+
+ @pytest.mark.parametrize(
+ "patch",
+ [
+ {"options": []},
+ {"options": [{"key": f"category_{i}", "label": f"Category {i}"} for i in range(101)]},
+ {"options": [{"key": "a", "label": "A"}, {"key": "a", "label": "B"}]},
+ {"options": [{"key": "A", "label": "A"}]},
+ {"options": [{"key": "a", "label": " "}]},
+ {"passing_rule": {"categories": ["unknown"]}},
+ {"passing_rule": {"categories": []}},
+ {"passing_rule": {"categories": ["resolved", "resolved"]}},
+ {"passing_rule": {"categories": ["resolved"], "operator": "any"}},
+ {"selection_mode": "other"},
+ {"unknown": True},
+ ],
+ )
+ def test_invalid_category_configuration_is_rejected(self, patch: dict) -> None:
+ with pytest.raises(ValueError):
+ CategoricalOutputConfig.model_validate({"options": [{"key": "resolved", "label": "Resolved"}], **patch})
+
+
class TestValidateTargetConfig:
@pytest.mark.parametrize(
"config,expected",
diff --git a/products/ai_observability/backend/text_repr/formatters/event_formatter.py b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
index ad7e1dd1d57a..556573c07929 100644
--- a/products/ai_observability/backend/text_repr/formatters/event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
@@ -203,8 +203,15 @@ def format_evaluation_text_repr(event: dict[str, Any], options: FormatterOptions
model = props.get("$ai_evaluation_model")
# Result line
- if applicable is False or applicable == "false":
+ skipped = props.get("$ai_evaluation_skipped")
+ if skipped is True or skipped == "true":
+ result_str = "Skipped"
+ elif applicable is False or applicable == "false":
result_str = "N/A"
+ elif props.get("$ai_evaluation_result_type") == "categorical" and isinstance(
+ props.get("$ai_evaluation_categorical_result"), list
+ ):
+ result_str = str(props["$ai_evaluation_categorical_result"])
elif (
props.get("$ai_evaluation_result_type") == "numeric" and props.get("$ai_evaluation_numeric_result") is not None
):
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py
index 0685ce74a5cb..727caa140f86 100644
--- a/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py
@@ -203,13 +203,28 @@ class TestErrorFormattingEmbedding:
class TestEvaluationFormatting:
- @parameterized.expand([(0, True, "0"), (7.25, True, "7.25"), (None, False, "N/A")])
- def test_numeric_evaluation(self, score: float | None, applicable: bool, expected: str) -> None:
+ @parameterized.expand(
+ [
+ ("numeric", 0, True, False, "0"),
+ ("numeric", 7.25, True, False, "7.25"),
+ ("numeric", None, False, False, "N/A"),
+ ("categorical", [], True, False, "[]"),
+ ("categorical", ["resolved"], True, False, "['resolved']"),
+ ("categorical", None, False, False, "N/A"),
+ ("categorical", None, False, True, "Skipped"),
+ ("categorical", None, False, "true", "Skipped"),
+ ("numeric", None, False, True, "Skipped"),
+ ]
+ )
+ def test_typed_evaluation(
+ self, output_type: str, score: float | list[str] | None, applicable: bool, skipped: bool | str, expected: str
+ ) -> None:
event = {
"properties": {
- "$ai_evaluation_result_type": "numeric",
- "$ai_evaluation_numeric_result": score,
+ "$ai_evaluation_result_type": output_type,
+ f"$ai_evaluation_{output_type}_result": score,
"$ai_evaluation_applicable": applicable,
+ "$ai_evaluation_skipped": skipped,
}
}
assert f"Result: {expected}" in format_evaluation_text_repr(event)
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
index f744eac56192..7d9d158b0beb 100644
--- a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
@@ -122,11 +122,13 @@ class TestGetEventSummary:
summary = _get_event_summary(event)
assert "ERROR" in summary
- @pytest.mark.parametrize("score", [0, 7.25])
- def test_numeric_evaluation_summary(self, score: float) -> None:
+ @pytest.mark.parametrize(
+ "output_type,score", [("numeric", 0), ("numeric", 7.25), ("categorical", []), ("categorical", ["resolved"])]
+ )
+ def test_typed_evaluation_summary(self, output_type: str, score: float | list[str]) -> None:
event = {
"event": "$ai_evaluation",
- "properties": {"$ai_evaluation_result_type": "numeric", "$ai_evaluation_numeric_result": score},
+ "properties": {"$ai_evaluation_result_type": output_type, f"$ai_evaluation_{output_type}_result": score},
}
assert _get_event_summary(event) == f"evaluation ({score})"
diff --git a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
index 686288efc7aa..ee87482870d7 100644
--- a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
@@ -279,6 +279,10 @@ def _get_event_summary(event: dict[str, Any]) -> str:
parts.append(runtime)
if applicable is False or applicable == "false":
parts.append("N/A")
+ elif props.get("$ai_evaluation_result_type") == "categorical" and isinstance(
+ props.get("$ai_evaluation_categorical_result"), list
+ ):
+ parts.append(str(props["$ai_evaluation_categorical_result"]))
elif (
props.get("$ai_evaluation_result_type") == "numeric"
and props.get("$ai_evaluation_numeric_result") is not None
diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.py
index 99403cba23dd..a419808d2a27 100644
--- a/products/ai_observability/backend/tools/run_hog_eval.py
+++ b/products/ai_observability/backend/tools/run_hog_eval.py
@@ -27,7 +27,7 @@ from ee.hogai.tool import MaxTool
TOOL_DESCRIPTION = f"""Test Hog evaluation code against sample data from the last {EVALUATION_TEST_LOOKBACK_DAYS} days.
-Returns compilation errors if the code is invalid, or raw boolean/numeric/N/A/error results for each sample.
+Returns compilation errors if the code is invalid, or raw boolean/numeric/categorical/N/A/error results for each sample.
Set `target` to match how the evaluation will run: `generation` samples individual generations,
`trace` samples whole traces, and `session` samples whole sessions that have gone quiet. For
@@ -47,7 +47,7 @@ Saved evaluations can still use the generation-only compatibility globals `input
`properties`, and `event`, but do not use them in new source that should also work for traces
or sessions.
-The code must return `true` or `false` for boolean output, or a finite number for numeric output.
+The code must return `true` or `false` for boolean output, a finite number for numeric output, or a list of configured category keys for categorical output. Empty lists are valid for multiple selection; null means N/A when allowed.
Set `output_type` and `output_config` to match the saved evaluation, including bounds and N/A settings. Numeric output disallows N/A by default;
set output_config.allows_na=true to allow null. Boolean previews allow N/A by default.
Use `print()` statements to output reasoning.
@@ -63,9 +63,12 @@ def _format_sample(
output_preview: str,
reasoning: str,
score: float | None = None,
+ categories: list[str] | None = None,
) -> list[str]:
if error:
verdict_str = "ERROR"
+ elif categories is not None:
+ verdict_str = str(categories)
elif score is not None:
verdict_str = str(score)
elif verdict is True:
@@ -90,10 +93,12 @@ def _format_sample(
class RunHogEvalTestArgs(BaseModel):
- output_type: Literal["boolean", "numeric"] = Field(default="boolean", description="The evaluation result type")
+ output_type: Literal["boolean", "numeric", "categorical"] = Field(
+ default="boolean", description="The evaluation result type"
+ )
output_config: dict[str, Any] = Field(
default_factory=dict,
- description="Output settings: allows_na, and for numeric evaluations optional min, max, step and passing_rule",
+ description="Output settings: allows_na, and for numeric evaluations optional min, max, step and passing_rule; categorical settings include options, selection_mode and passing categories",
)
source: str = Field(description="Hog evaluation source code to compile and test")
sample_count: int = Field(
@@ -138,7 +143,7 @@ class RunHogEvalTestTool(MaxTool):
target: Literal["generation", "trace", "session"] = "generation",
window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
quiet_period_seconds: int = SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS,
- output_type: Literal["boolean", "numeric"] = "boolean",
+ output_type: Literal["boolean", "numeric", "categorical"] = "boolean",
output_config: dict[str, Any] | None = None,
) -> tuple[str, Any]:
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
@@ -296,6 +301,7 @@ class RunHogEvalTestTool(MaxTool):
output_preview,
result["reasoning"],
score=result.get("score"),
+ categories=result.get("categories"),
)
)
@@ -341,6 +347,7 @@ class RunHogEvalTestTool(MaxTool):
r.output_preview,
r.reasoning,
score=r.score,
+ categories=r.categories,
)
)
@@ -389,6 +396,7 @@ class RunHogEvalTestTool(MaxTool):
s.output_preview,
s.reasoning,
score=s.score,
+ categories=s.categories,
)
)
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
index e338e68822ac..63c15e6cbed9 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
@@ -65,6 +65,24 @@ describe('EvaluationDisplay', () => {
expect(screen.queryByText('False')).not.toBeInTheDocument()
})
+ test.each([true, 'true'])('renders a skipped categorical run before N/A (%s)', (skipped) => {
+ render(
+ <Provider>
+ <EvaluationDisplay
+ eventProperties={{
+ $ai_evaluation_result_type: 'categorical',
+ $ai_evaluation_applicable: false,
+ $ai_evaluation_allows_na: false,
+ $ai_evaluation_skipped: skipped,
+ }}
+ />
+ </Provider>
+ )
+
+ expect(screen.getByText('Skipped')).toBeInTheDocument()
+ expect(screen.queryByText('N/A')).not.toBeInTheDocument()
+ })
+
it('colors a detector true result as danger, matching the badges elsewhere on the page', () => {
const evaluationsLogic = llmEvaluationsLogic()
evaluationsLogic.mount()
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
index d498a6f248a6..81e4acae3437 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
@@ -20,11 +20,13 @@ export function EvaluationDisplay({ eventProperties }: { eventProperties: EventT
const traceId = eventProperties.$ai_trace_id
const targetEventId = eventProperties.$ai_target_event_id
const evaluationId = eventProperties.$ai_evaluation_id
+ const evaluation = evaluations?.find((evaluation) => evaluation.id === evaluationId)
const resultRun = {
status: 'completed' as const,
skipped: isExplicitEvaluationPass(eventProperties.$ai_evaluation_skipped),
...normalizeEvaluationResultProperties({
rawScore: eventProperties.$ai_evaluation_numeric_result,
+ rawCategories: eventProperties.$ai_evaluation_categorical_result,
rawScoreMin: eventProperties.$ai_evaluation_numeric_result_min,
rawScoreMax: eventProperties.$ai_evaluation_numeric_result_max,
rawResult: eventProperties.$ai_evaluation_result,
@@ -41,9 +43,8 @@ export function EvaluationDisplay({ eventProperties }: { eventProperties: EventT
<div className="flex flex-wrap gap-2">
<EvaluationResultTag
run={resultRun}
- passingRule={
- evaluations?.find((evaluation) => evaluation.id === evaluationId)?.output_config.passing_rule
- }
+ passingRule={evaluation?.output_config.passing_rule}
+ categoryOptions={evaluation?.output_config.options}
trueIsFailure={detectorEvaluationIds.includes(evaluationId)}
/>
{evaluationName && (
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
index b691926cf043..c202f44c936d 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
@@ -63,6 +63,35 @@ describe('EvalResultBadges', () => {
expect(getEvaluationResultDisplay(makeRun({ result_type: 'numeric', score })).label).toBe(label)
})
+ it.each([
+ [[], true, ['resolved'], 'danger', 'No categories'],
+ [['resolved'], true, ['resolved'], 'success', 'Resolved'],
+ [['resolved', 'incorrect'], true, ['resolved'], 'danger', 'Resolved, incorrect'],
+ [[], true, [], 'success', 'No categories'],
+ [['resolved'], true, [], 'danger', 'Resolved'],
+ [[], true, null, 'none', 'No categories'],
+ [null, false, ['resolved'], 'muted', 'N/A'],
+ [null, false, [], 'muted', 'N/A'],
+ ] as const)(
+ 'renders categorical results %s without confusing empty selections and N/A',
+ (categories, applicable, passingCategories, type, label) => {
+ expect(
+ getEvaluationResultDisplay(
+ makeRun({
+ result_type: 'categorical',
+ result: null,
+ categories: categories ? [...categories] : null,
+ applicable,
+ }),
+ {
+ passingRule: passingCategories ? { categories: [...passingCategories] } : null,
+ categoryOptions: [{ key: 'resolved', label: 'Resolved' }],
+ }
+ )
+ ).toMatchObject({ type, label })
+ }
+ )
+
describe('getEvalSummaries', () => {
it('returns empty array for empty input', () => {
expect(getEvalSummaries([])).toEqual([])
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index f09872c6144d..87011ad071a8 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -100,6 +100,9 @@ export function EvalResultBadges({
{summaries.map((summary) => {
const { type, icon, label } = getEvalBadgeProps(summary.latestRun, {
trueIsFailure: detectorEvaluationIds.includes(summary.latestRun.evaluation_id),
+ categoryOptions: evaluations?.find(
+ (evaluation) => evaluation.id === summary.latestRun.evaluation_id
+ )?.output_config.options,
passingRule: evaluations?.find((evaluation) => evaluation.id === summary.latestRun.evaluation_id)
?.output_config.passing_rule,
})
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx
index 49ef4d67f9c4..0bfe1d917215 100644
--- a/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx
@@ -63,3 +63,27 @@ export const Numeric: Story = {
</div>
),
}
+
+export const Categorical: Story = {
+ render: () => (
+ <div className="flex flex-wrap gap-4">
+ {([['resolved'], ['resolved', 'incorrect'], [], null] as const).map((categories, index) => (
+ <EvaluationResultTag
+ key={index}
+ run={{
+ status: 'completed',
+ result: null,
+ result_type: 'categorical',
+ categories: categories ? [...categories] : null,
+ applicable: categories !== null,
+ }}
+ passingRule={{ categories: ['resolved'] }}
+ categoryOptions={[
+ { key: 'resolved', label: 'Resolved' },
+ { key: 'incorrect', label: 'Incorrect information' },
+ ]}
+ />
+ ))}
+ </div>
+ ),
+}
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
index 84664b9f981d..b2f4fec0bcef 100644
--- a/products/ai_observability/frontend/components/EvaluationResultTag.tsx
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
@@ -2,7 +2,7 @@ import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'
import { LemonTag } from '@posthog/lemon-ui'
import type { LemonTagProps } from '@posthog/lemon-ui'
-import { formatNumericEvaluationScore, numericScorePasses } from '../evaluations/constants'
+import { categoricalResultPasses, formatNumericEvaluationScore, numericScorePasses } from '../evaluations/constants'
import type { EvaluationOutputConfig, EvaluationRun } from '../evaluations/types'
import { capitalize } from '../sentimentUtils'
@@ -14,6 +14,7 @@ type EvaluationResultLike = Pick<
| 'evaluation_type'
| 'sentiment_label'
| 'skipped'
+ | 'categories'
| 'score'
| 'score_min'
| 'score_max'
@@ -31,6 +32,7 @@ export interface EvaluationResultDisplayOptions {
/** When true, the evaluation looks for a problem, so a true result is the undesirable one. */
trueIsFailure?: boolean
passingRule?: EvaluationOutputConfig['passing_rule']
+ categoryOptions?: EvaluationOutputConfig['options']
}
const SENTIMENT_DISPLAY: Record<string, Pick<EvaluationResultDisplay, 'type' | 'icon' | 'sortValue'>> = {
@@ -58,6 +60,24 @@ export function getEvaluationResultDisplay(
if (run.skipped) {
return { type: 'muted', icon: <IconMinus />, label: 'Skipped', sortValue: 0.4 }
}
+ if (run.result_type === 'categorical') {
+ if (run.applicable === false) {
+ return { type: 'muted', icon: <IconMinus />, label: 'N/A', sortValue: 0.5 }
+ }
+ if (run.categories == null) {
+ return { type: 'muted', icon: <IconMinus />, label: 'No result', sortValue: -1 }
+ }
+ const passed = categoricalResultPasses(run.categories, options.passingRule)
+ return {
+ type: passed === null ? 'none' : passed ? 'success' : 'danger',
+ icon: passed === null ? <IconMinus /> : passed ? <IconCheck /> : <IconX />,
+ label:
+ run.categories
+ .map((key) => options.categoryOptions?.find((option) => option.key === key)?.label ?? key)
+ .join(', ') || 'No categories',
+ sortValue: 5,
+ }
+ }
if (run.result_type === 'numeric') {
if (run.applicable === false) {
return { type: 'muted', icon: <IconMinus />, label: 'N/A', sortValue: 0.5 }
@@ -111,6 +131,9 @@ export function compareEvaluationResults(
): number {
const aRank = getEvaluationResultSortValue(a, aOptions)
const bRank = getEvaluationResultSortValue(b, bOptions)
+ if (aRank === 5 && bRank === 5) {
+ return (a.categories ?? []).join(',').localeCompare((b.categories ?? []).join(','))
+ }
return aRank === 4 && bRank === 4 ? a.score! - b.score! : aRank - bRank
}
@@ -118,17 +141,25 @@ export function EvaluationResultTag({
run,
trueIsFailure,
passingRule,
+ categoryOptions,
size,
}: {
run: EvaluationResultLike
trueIsFailure?: boolean
passingRule?: EvaluationOutputConfig['passing_rule']
+ categoryOptions?: EvaluationOutputConfig['options']
size?: LemonTagProps['size']
}): JSX.Element {
- const { type, icon, label } = getEvaluationResultDisplay(run, { trueIsFailure, passingRule })
+ const { type, icon, label } = getEvaluationResultDisplay(run, { trueIsFailure, passingRule, categoryOptions })
return (
- <LemonTag type={type} icon={icon} size={size} title={run.score == null ? undefined : String(run.score)}>
- {label}
+ <LemonTag
+ type={type}
+ icon={icon}
+ size={size}
+ className={run.result_type === 'categorical' ? 'max-w-full' : undefined}
+ title={run.result_type === 'categorical' ? label : run.score == null ? undefined : String(run.score)}
+ >
+ {run.result_type === 'categorical' ? <span className="truncate">{label}</span> : label}
</LemonTag>
)
}
diff --git a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
index a5c279f01c74..975a9a2246d1 100644
--- a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
+++ b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
@@ -47,6 +47,9 @@ export function GenerationEvalRunsTable({
render: (_, run) => (
<EvaluationResultTag
run={run}
+ categoryOptions={
+ evaluations?.find((evaluation) => evaluation.id === run.evaluation_id)?.output_config.options
+ }
passingRule={
evaluations?.find((evaluation) => evaluation.id === run.evaluation_id)?.output_config
.passing_rule
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index ca6f19adae4e..3d184fd69783 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -39,6 +39,7 @@ import { ByokModelPickerNotice } from '../ByokModelPickerNotice'
import { getModelPickerFooterLink, ModelPicker } from '../ModelPicker'
import { modelPickerLogic } from '../modelPickerLogic'
import { providerKeyStateIssueDescription, providerLabel } from '../settings/providerKeyStateUtils'
+import { CategoricalEvaluationConfig } from './components/CategoricalEvaluationConfig'
import { EvaluationBackfillsTab } from './components/EvaluationBackfillsTab'
import { EvaluationCodeEditor } from './components/EvaluationCodeEditor'
import { EvaluationPromptEditor } from './components/EvaluationPromptEditor'
@@ -48,7 +49,12 @@ import { EvaluationReportsTab } from './components/EvaluationReportsTab'
import { EvaluationRunsTable } from './components/EvaluationRunsTable'
import { EvaluationTriggers } from './components/EvaluationTriggers'
import { NumericEvaluationConfig } from './components/NumericEvaluationConfig'
-import { EVALUATION_RUNS_QUERY_LIMIT, formatNumericEvaluationScore, numericOutputConfigError } from './constants'
+import {
+ EVALUATION_RUNS_QUERY_LIMIT,
+ formatNumericEvaluationScore,
+ numericOutputConfigError,
+ categoricalOutputConfigError,
+} from './constants'
import {
evaluationOffersSessionTarget,
evaluationSupportsReportHistory,
@@ -118,6 +124,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
patchTargetConfig,
setActiveTab,
} = useActions(llmEvaluationLogic)
+ const categoricalEvaluationsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_CATEGORICAL_EVALS]
const { push } = useActions(router)
const triggersRef = useRef<HTMLDivElement>(null)
const settingsUrl = combineUrl(urls.aiObservabilityEvaluations(), { ...searchParams, tab: 'settings' }).url
@@ -177,9 +184,11 @@ export function AIObservabilityEvaluation(): JSX.Element {
: 'Add an evaluation prompt before saving'
: !hasSelectedJudgeModel
? 'Select a judge model before saving'
- : evaluation.output_type === 'numeric'
- ? (numericOutputConfigError(evaluation.output_config) ?? undefined)
- : undefined
+ : evaluation.output_type === 'categorical'
+ ? (categoricalOutputConfigError(evaluation.output_config) ?? undefined)
+ : evaluation.output_type === 'numeric'
+ ? (numericOutputConfigError(evaluation.output_config) ?? undefined)
+ : undefined
const focusTriggers = (): void => {
setActiveTab('configuration')
@@ -534,7 +543,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
...option,
disabledReason:
!isNewEvaluation &&
- evaluation.output_type === 'numeric' &&
+ ['numeric', 'categorical'].includes(
+ evaluation.output_type
+ ) &&
option.value === 'sentiment'
? 'Create a new evaluation to change its output type.'
: undefined,
@@ -719,6 +730,14 @@ export function AIObservabilityEvaluation(): JSX.Element {
value={evaluation.output_type}
options={[
{ value: 'boolean', label: 'Boolean' },
+ {
+ value: 'categorical',
+ label: 'Categorical',
+ disabledReason:
+ isNewEvaluation && !categoricalEvaluationsEnabled
+ ? 'Categorical evaluations are not enabled for this project.'
+ : undefined,
+ },
{
value: 'numeric',
label: 'Numeric score',
@@ -729,7 +748,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
},
]}
onChange={(value) =>
- setOutputType(value as 'boolean' | 'numeric')
+ setOutputType(
+ value as 'boolean' | 'numeric' | 'categorical'
+ )
}
disabledReason={
!isNewEvaluation
@@ -740,6 +761,12 @@ export function AIObservabilityEvaluation(): JSX.Element {
/>
</LemonField.Pure>
)}
+ {evaluation.output_type === 'categorical' && (
+ <CategoricalEvaluationConfig
+ config={evaluation.output_config}
+ onChange={patchOutputConfig}
+ />
+ )}
{evaluation.output_type === 'numeric' && (
<NumericEvaluationConfig
config={evaluation.output_config}
diff --git a/products/ai_observability/frontend/evaluations/components/CategoricalEvaluationConfig.stories.tsx b/products/ai_observability/frontend/evaluations/components/CategoricalEvaluationConfig.stories.tsx
new file mode 100644
index 000000000000..3863149c97a6
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/CategoricalEvaluationConfig.stories.tsx
@@ -0,0 +1,60 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import type { EvaluationOutputConfig } from '../types'
+import { CategoricalEvaluationConfig } from './CategoricalEvaluationConfig'
+
+const meta: Meta<typeof CategoricalEvaluationConfig> = {
+ title: 'Scenes-App/LLM observability/CategoricalEvaluationConfig',
+ component: CategoricalEvaluationConfig,
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+type Story = StoryObj<typeof CategoricalEvaluationConfig>
+
+function Template({
+ narrow = false,
+ initialConfig,
+}: {
+ narrow?: boolean
+ initialConfig?: EvaluationOutputConfig
+}): JSX.Element {
+ const [config, setConfig] = useState<EvaluationOutputConfig>({
+ options: [
+ { key: 'resolved', label: 'Resolved' },
+ { key: 'needs_follow_up', label: 'Needs follow-up' },
+ ],
+ selection_mode: 'multiple',
+ allows_na: true,
+ passing_rule: { categories: ['resolved'] },
+ ...initialConfig,
+ })
+ return (
+ <div className={narrow ? 'max-w-lg' : 'max-w-4xl'}>
+ <CategoricalEvaluationConfig
+ config={config}
+ onChange={(patch) => setConfig((current) => ({ ...current, ...patch }))}
+ />
+ </div>
+ )
+}
+
+export const Default: Story = { render: () => <Template /> }
+export const Narrow: Story = { render: () => <Template narrow /> }
+export const InvalidPassingRule: Story = {
+ render: () => <Template narrow initialConfig={{ selection_mode: 'single', passing_rule: { categories: [] } }} />,
+}
+export const DuplicateKeys: Story = {
+ render: () => (
+ <Template
+ narrow
+ initialConfig={{
+ options: [
+ { key: 'resolved', label: 'Resolved' },
+ { key: 'resolved', label: 'Needs follow-up' },
+ ],
+ }}
+ />
+ ),
+}
diff --git a/products/ai_observability/frontend/evaluations/components/CategoricalEvaluationConfig.tsx b/products/ai_observability/frontend/evaluations/components/CategoricalEvaluationConfig.tsx
new file mode 100644
index 000000000000..13679ed42102
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/CategoricalEvaluationConfig.tsx
@@ -0,0 +1,200 @@
+import { useId } from 'react'
+
+import { IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonCheckbox, LemonInput, LemonSelect, LemonSwitch, LemonTable } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { MAX_CATEGORICAL_OPTIONS, categoricalOptionsError, categoricalPassingRuleError } from '../constants'
+import type { EvaluationOutputConfig } from '../types'
+
+export function CategoricalEvaluationConfig({
+ config,
+ onChange,
+}: {
+ config: EvaluationOutputConfig
+ onChange: (patch: EvaluationOutputConfig) => void
+}): JSX.Element {
+ const id = useId()
+ const options = config.options ?? []
+ const rule = config.passing_rule && 'categories' in config.passing_rule ? config.passing_rule : null
+ return (
+ <div className="space-y-4">
+ <LemonField.Pure
+ label="Categories per result"
+ htmlFor={`${id}-selection`}
+ help="Choose whether each result can contain one category or several."
+ >
+ <LemonSelect
+ id={`${id}-selection`}
+ data-attr="llma-evaluation-categorical-selection"
+ value={config.selection_mode ?? 'single'}
+ options={[
+ { value: 'single', label: 'One category' },
+ { value: 'multiple', label: 'Multiple categories' },
+ ]}
+ onChange={(selection_mode) => onChange({ selection_mode })}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Categories" error={categoricalOptionsError(config)}>
+ <LemonTable
+ dataSource={options}
+ size="small"
+ embedded
+ stealth
+ inset
+ tableLayout="fixed"
+ uppercaseHeader={false}
+ emptyState="Add a category to define the possible results."
+ columns={[
+ {
+ title: 'Label',
+ key: 'label',
+ render: (_, option, index) => (
+ <LemonInput
+ aria-label={`Category ${index + 1} label`}
+ data-attr="llma-evaluation-categorical-label"
+ placeholder="Resolved"
+ fullWidth
+ value={option.label}
+ maxLength={256}
+ onChange={(label) =>
+ onChange({
+ options: options.map((item, i) =>
+ i === index ? { ...item, label } : item
+ ),
+ })
+ }
+ />
+ ),
+ },
+ {
+ title: 'Key',
+ key: 'key',
+ render: (_, option, index) => (
+ <LemonInput
+ aria-label={`Category ${index + 1} key`}
+ data-attr="llma-evaluation-categorical-key"
+ placeholder="resolved"
+ fullWidth
+ value={option.key}
+ maxLength={128}
+ onChange={(key) =>
+ onChange({
+ options: options.map((item, i) => (i === index ? { ...item, key } : item)),
+ ...(rule
+ ? {
+ passing_rule: {
+ categories: rule.categories.map((value) =>
+ value === option.key ? key : value
+ ),
+ },
+ }
+ : {}),
+ })
+ }
+ />
+ ),
+ },
+ {
+ key: 'actions',
+ width: 48,
+ render: (_, option, index) => (
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ tooltip="Remove category"
+ aria-label={`Remove category ${option.label || index + 1}`}
+ data-attr="llma-evaluation-categorical-remove"
+ onClick={() =>
+ onChange({
+ options: options.filter((_, i) => i !== index),
+ ...(rule
+ ? {
+ passing_rule: {
+ categories: rule.categories.filter(
+ (key) => key !== option.key
+ ),
+ },
+ }
+ : {}),
+ })
+ }
+ />
+ ),
+ },
+ ]}
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ className="self-start"
+ data-attr="llma-evaluation-categorical-add"
+ disabledReason={
+ options.length >= MAX_CATEGORICAL_OPTIONS
+ ? `You can add up to ${MAX_CATEGORICAL_OPTIONS} categories.`
+ : undefined
+ }
+ onClick={() => onChange({ options: [...options, { key: '', label: '' }] })}
+ >
+ Add category
+ </LemonButton>
+ </LemonField.Pure>
+ <p className="text-muted text-sm">
+ Results store category keys. Keep keys unchanged to preserve historical results.
+ </p>
+ <LemonSwitch
+ label="Allow N/A responses"
+ data-attr="llma-evaluation-categorical-allows-na"
+ checked={config.allows_na ?? false}
+ onChange={(allows_na) => onChange({ allows_na })}
+ />
+ <LemonField.Pure error={categoricalPassingRuleError(config)}>
+ <LemonSwitch
+ label="Set a passing rule"
+ data-attr="llma-evaluation-categorical-passing-rule"
+ checked={!!rule}
+ onChange={(enabled) => onChange({ passing_rule: enabled ? { categories: [] } : null })}
+ />
+ {rule && (
+ <LemonField.Pure label="Passing categories" className="mt-2">
+ {options
+ .filter((option) => option.key)
+ .map((option, index) => (
+ <LemonCheckbox
+ key={index}
+ label={option.label || option.key}
+ data-attr="llma-evaluation-categorical-passing-category"
+ checked={rule.categories.includes(option.key)}
+ onChange={(checked) =>
+ onChange({
+ passing_rule: {
+ categories: checked
+ ? [...rule.categories, option.key]
+ : rule.categories.filter((key) => key !== option.key),
+ },
+ })
+ }
+ />
+ ))}
+ </LemonField.Pure>
+ )}
+ </LemonField.Pure>
+ {rule ? (
+ <p className="text-muted text-sm">
+ Every returned category must be marked as passing.
+ {config.selection_mode === 'multiple'
+ ? ' An empty selection passes only when no categories are marked as passing.'
+ : ''}{' '}
+ Changing this rule also updates how historical results count as passes.
+ </p>
+ ) : (
+ <p className="text-muted text-sm">
+ Results show their categories without a pass or fail status. Add a passing rule to enable pass rates
+ and reports.
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
index 5a27a3676734..870ed9bc0cd2 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
@@ -11,7 +11,13 @@ import { urls } from '~/scenes/urls'
import { EvaluationResultTag } from '../../components/EvaluationResultTag'
import type { TestHogResultItemApi } from '../../generated/api.schemas'
-import { evaluationIsDetector, numericOutputConfigError, numericScorePasses } from '../constants'
+import {
+ categoricalOutputConfigError,
+ categoricalResultPasses,
+ evaluationIsDetector,
+ numericOutputConfigError,
+ numericScorePasses,
+} from '../constants'
import { HOG_EVAL_EXAMPLES } from '../hogEvalExamples'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import type { EvaluationTarget } from '../types'
@@ -200,16 +206,28 @@ export function HogTestResultsPanel(): JSX.Element | null {
// Every result here belongs to `evaluation`, so its polarity applies to the whole panel.
const trueIsFailure = !!evaluation && evaluationIsDetector(evaluation)
const numeric = evaluation?.output_type === 'numeric'
+ const categorical = evaluation?.output_type === 'categorical'
const rule = evaluation?.output_config.passing_rule
const passed =
hogTestResults?.filter((r) =>
- numeric ? numericScorePasses(r.score, rule) === true : r.result === !trueIsFailure
+ categorical
+ ? categoricalResultPasses(r.categories, rule) === true
+ : numeric
+ ? numericScorePasses(r.score, rule) === true
+ : r.result === !trueIsFailure
).length ?? 0
const failed =
hogTestResults?.filter((r) =>
- numeric ? numericScorePasses(r.score, rule) === false : r.result === trueIsFailure
+ categorical
+ ? categoricalResultPasses(r.categories, rule) === false
+ : numeric
+ ? numericScorePasses(r.score, rule) === false
+ : r.result === trueIsFailure
+ ).length ?? 0
+ const na =
+ hogTestResults?.filter(
+ (r) => (categorical ? r.categories == null : numeric ? r.score == null : r.result === null) && !r.error
).length ?? 0
- const na = hogTestResults?.filter((r) => (numeric ? r.score == null : r.result === null) && !r.error).length ?? 0
const errors = hogTestResults?.filter((r) => r.error !== null).length ?? 0
return (
@@ -219,7 +237,7 @@ export function HogTestResultsPanel(): JSX.Element | null {
<span className="font-semibold">Test results</span>
{hogTestResults && (
<>
- {(!numeric || rule) && (
+ {(!(numeric || categorical) || rule) && (
<>
<LemonTag type="success" icon={<IconCheck />}>
{passed} passed
@@ -265,17 +283,19 @@ export function HogTestResultsPanel(): JSX.Element | null {
</Tooltip>
)
}
- if (numeric) {
+ if (numeric || categorical) {
return (
<EvaluationResultTag
run={{
status: 'completed',
result: null,
- result_type: 'numeric',
+ result_type: categorical ? 'categorical' : 'numeric',
+ categories: row.categories,
score: row.score,
- applicable: row.score != null,
+ applicable: categorical ? row.categories != null : row.score != null,
}}
passingRule={rule}
+ categoryOptions={evaluation?.output_config.options}
/>
)
}
@@ -398,9 +418,11 @@ export function EvaluationCodeEditor(): JSX.Element {
loading={hogTestResultsLoading}
disabled={!source.trim()}
disabledReason={
- evaluation.output_type === 'numeric'
- ? numericOutputConfigError(evaluation.output_config)
- : null
+ evaluation.output_type === 'categorical'
+ ? categoricalOutputConfigError(evaluation.output_config)
+ : evaluation.output_type === 'numeric'
+ ? numericOutputConfigError(evaluation.output_config)
+ : null
}
onClick={() => testHogOnSample()}
data-attr="llma-evaluation-test-hog"
@@ -431,13 +453,17 @@ export function EvaluationCodeEditor(): JSX.Element {
<div className="flex items-center gap-2">
<span>Expected output:</span>
<LemonTag type="completion">
- {evaluation.output_type === 'numeric'
+ {evaluation.output_type === 'categorical'
? evaluation.output_config.allows_na
- ? 'Number or null'
- : 'Number'
- : evaluation.output_config.allows_na
- ? 'Boolean or null (true/false/null)'
- : 'Boolean (true/false)'}
+ ? 'Category keys or null'
+ : 'Category keys'
+ : evaluation.output_type === 'numeric'
+ ? evaluation.output_config.allows_na
+ ? 'Number or null'
+ : 'Number'
+ : evaluation.output_config.allows_na
+ ? 'Boolean or null (true/false/null)'
+ : 'Boolean (true/false)'}
</LemonTag>
</div>
</div>
@@ -456,12 +482,16 @@ export function EvaluationCodeEditor(): JSX.Element {
</Link>
</div>
<div className="flex flex-wrap gap-1.5 mb-3">
- {(evaluation.output_type === 'numeric'
- ? [
- { label: 'Latency', source: 'return target.total_latency_seconds;' },
- { label: 'Cost', source: 'return target.total_cost_usd;' },
- ]
- : HOG_EVAL_EXAMPLES
+ {(evaluation.output_type === 'categorical'
+ ? (evaluation.output_config.options ?? [])
+ .slice(0, 2)
+ .map(({ key, label }) => ({ label, source: `return ['${key}'];` }))
+ : evaluation.output_type === 'numeric'
+ ? [
+ { label: 'Latency', source: 'return target.total_latency_seconds;' },
+ { label: 'Cost', source: 'return target.total_cost_usd;' },
+ ]
+ : HOG_EVAL_EXAMPLES
).map((example) => (
<LemonButton
key={example.label}
@@ -513,7 +543,12 @@ export function EvaluationCodeEditor(): JSX.Element {
<h4 className="text-sm font-semibold mt-3 mb-2">Tips</h4>
<ul className="text-sm text-muted space-y-1 list-disc list-inside">
<li>
- {evaluation.output_type === 'numeric' ? (
+ {evaluation.output_type === 'categorical' ? (
+ <span>
+ Return configured category keys in a list. An empty list is valid for multiple
+ selection; null means N/A when allowed.
+ </span>
+ ) : evaluation.output_type === 'numeric' ? (
<span>Return a number within the configured bounds.</span>
) : (
<>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
index 889cd10e61d4..8f98f6bd1391 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
@@ -78,8 +78,8 @@ export function EvaluationMetrics(): JSX.Element {
) : (
<div className="flex-1 bg-bg-light border rounded p-8 flex items-center justify-center">
<div className="text-muted text-center">
- No enabled evaluations with pass rates. Enable a boolean evaluation or set a passing
- threshold on a numeric evaluation.
+ No enabled evaluations with pass rates. Enable a boolean evaluation or set a passing rule on
+ a numeric or categorical evaluation.
</div>
</div>
)}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx
index b6a0502ad6da..3142dc3c974d 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx
@@ -25,13 +25,15 @@ export function EvaluationPromptEditor(): JSX.Element {
value={prompt}
onChange={setEvaluationPrompt}
placeholder={
- evaluation.output_type === 'numeric'
- ? 'Describe how to score the response. Return a numeric score within the configured bounds.'
- : allowsNA
- ? `Write a prompt that evaluates the LLM generation and returns true, false, or N/A if the criteria doesn't apply.
+ evaluation.output_type === 'categorical'
+ ? 'Describe when each category applies. Return the matching category keys.'
+ : evaluation.output_type === 'numeric'
+ ? 'Describe how to score the response. Return a numeric score within the configured bounds.'
+ : allowsNA
+ ? `Write a prompt that evaluates the LLM generation and returns true, false, or N/A if the criteria doesn't apply.
Example: Is this response mathematically accurate? Return true if correct, false if incorrect, or N/A if no math is involved.`
- : `Write a prompt that evaluates the LLM generation and returns true or false.
+ : `Write a prompt that evaluates the LLM generation and returns true or false.
Example: Is this response helpful and accurate? Return true if yes, false if no.`
}
@@ -44,13 +46,17 @@ Example: Is this response helpful and accurate? Return true if yes, false if no.
<div className="flex items-center gap-2">
<span>Expected output:</span>
<LemonTag type="completion">
- {evaluation.output_type === 'numeric'
+ {evaluation.output_type === 'categorical'
? allowsNA
- ? 'Number or N/A'
- : 'Number'
- : allowsNA
- ? 'Boolean (true/false/NA)'
- : 'Boolean (true/false)'}
+ ? 'Category keys or N/A'
+ : 'Category keys'
+ : evaluation.output_type === 'numeric'
+ ? allowsNA
+ ? 'Number or N/A'
+ : 'Number'
+ : allowsNA
+ ? 'Boolean (true/false/NA)'
+ : 'Boolean (true/false)'}
</LemonTag>
</div>
</div>
@@ -63,7 +69,9 @@ Example: Is this response helpful and accurate? Return true if yes, false if no.
<ul className="text-sm text-muted space-y-1 list-disc list-inside">
<li>Be specific about what you want to evaluate</li>
<li>
- {evaluation.output_type === 'numeric' ? (
+ {evaluation.output_type === 'categorical' ? (
+ <span>Explain what each category means and when to select it</span>
+ ) : evaluation.output_type === 'numeric' ? (
<span>Describe the scoring scale and what each score means</span>
) : allowsNA ? (
<>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
index 11563c94bb5b..c3ae7774657d 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
@@ -154,6 +154,7 @@ function ReportSectionContent({
const RESULT_ORDER: Record<EvaluationOutputType, string[]> = {
boolean: ['pass', 'fail', 'na'],
numeric: ['pass', 'fail', 'na'],
+ categorical: ['pass', 'fail', 'na'],
sentiment: ['positive', 'neutral', 'negative'],
}
@@ -225,7 +226,7 @@ function getBooleanPassRate(
export function summarizeEvaluationReportResults(metrics: EvaluationReportStoredMetrics): string {
const resultMetrics = getResultMetrics(metrics)
- if (['boolean', 'numeric'].includes(metrics.output_type ?? 'boolean')) {
+ if (['boolean', 'numeric', 'categorical'].includes(metrics.output_type ?? 'boolean')) {
const passRate = getBooleanPassRate(metrics, resultMetrics)
const summaryParts = passRate == null ? [] : [`Pass rate ${formatResultRate(passRate, 1)}`]
summaryParts.push(
@@ -251,7 +252,7 @@ export function summarizeEvaluationReportResults(metrics: EvaluationReportStored
function MetricsCard({ metrics }: { metrics: EvaluationReportStoredMetrics }): JSX.Element {
const resultMetrics = getResultMetrics(metrics)
- const isBooleanMetrics = ['boolean', 'numeric'].includes(metrics.output_type ?? 'boolean')
+ const isBooleanMetrics = ['boolean', 'numeric', 'categorical'].includes(metrics.output_type ?? 'boolean')
const passRate = isBooleanMetrics ? getBooleanPassRate(metrics, resultMetrics) : undefined
const passRateDiff =
passRate == null || metrics.previous_pass_rate == null ? null : passRate - metrics.previous_pass_rate
@@ -262,9 +263,20 @@ function MetricsCard({ metrics }: { metrics: EvaluationReportStoredMetrics }): J
return (
<div className="bg-bg-light border rounded p-3 mb-3">
- {metrics.output_type === 'numeric' && passingRule && (
+ {metrics.output_type === 'numeric' && passingRule && 'threshold' in passingRule && (
<p className="text-sm text-muted">{`Passing rule used for this report: score ${passingRule.operator === 'gte' ? '≥' : '≤'} ${passingRule.threshold}`}</p>
)}
+ {metrics.output_type === 'categorical' && passingRule && 'categories' in passingRule && (
+ <p className="text-sm text-muted">
+ Passing categories used for this report:{' '}
+ {passingRule.categories
+ .map(
+ (key) => metrics.output_config?.options?.find((option) => option.key === key)?.label ?? key
+ )
+ .join(', ') || 'None'}
+ . Every returned category must pass.
+ </p>
+ )}
<div className="flex items-center gap-6 flex-wrap text-sm">
<div>
<div className="text-muted text-xs">Total runs</div>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
index 3a3d2816091b..1193d18dc968 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
@@ -33,7 +33,9 @@ export function EvaluationRunsFilters(): JSX.Element | null {
setEvaluationRunsFilter(value, evaluationRunsFilter)
}}
options={[
- ...(evaluation?.output_type === 'numeric' && !evaluation.output_config.passing_rule
+ ...(evaluation &&
+ ['numeric', 'categorical'].includes(evaluation.output_type) &&
+ !evaluation.output_config.passing_rule
? BASE_FILTER_OPTIONS.filter((option) => option.value === 'all')
: BASE_FILTER_OPTIONS),
...(evaluation?.output_config?.allows_na ? [NA_FILTER_OPTION] : []),
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index 4d622629945e..7a445ec94b17 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -50,7 +50,10 @@ export function EvaluationRunsTable(): JSX.Element {
runsBackfillId,
} = useValues(llmEvaluationLogic)
const { refreshEvaluationRuns, setRunsDates } = useActions(llmEvaluationLogic)
- const showOutcomeFilters = evaluation?.output_type === 'numeric' || evaluationSupportsRunOutcomes(evaluation)
+ const showOutcomeFilters =
+ evaluation?.output_type === 'numeric' ||
+ evaluation?.output_type === 'categorical' ||
+ evaluationSupportsRunOutcomes(evaluation)
const showSentimentFilters = evaluation?.evaluation_type === 'sentiment'
// Every run in this table belongs to `evaluation`, so its polarity applies to the whole column.
const trueIsFailure = !!evaluation && evaluationIsDetector(evaluation)
@@ -113,6 +116,7 @@ export function EvaluationRunsTable(): JSX.Element {
run={run}
trueIsFailure={trueIsFailure}
passingRule={evaluation?.output_config.passing_rule}
+ categoryOptions={evaluation?.output_config.options}
/>
),
sorter: (a, b) => compareEvaluationResults(b, a, { trueIsFailure }),
diff --git a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
index 848d6addc8c6..56bb6cc0f222 100644
--- a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
+++ b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
@@ -15,7 +15,7 @@ export function NumericEvaluationConfig({
onChange: (patch: EvaluationOutputConfig) => void
}): JSX.Element {
const id = useId()
- const rule = config.passing_rule
+ const rule = config.passing_rule && 'threshold' in config.passing_rule ? config.passing_rule : null
const error = numericOutputConfigError(config)
return (
<div className="space-y-4">
diff --git a/products/ai_observability/frontend/evaluations/constants.test.ts b/products/ai_observability/frontend/evaluations/constants.test.ts
new file mode 100644
index 000000000000..76d26bef314d
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/constants.test.ts
@@ -0,0 +1,120 @@
+import {
+ EVALUATION_CATEGORIES_HOGQL,
+ categoricalEvaluationPassedHogQL,
+ categoricalEvaluationsPassedHogQL,
+ categoricalOptionsError,
+ categoricalOutputConfigError,
+ categoricalPassingRuleError,
+ categoricalResultPasses,
+} from './constants'
+import type { EvaluationConfig, EvaluationOutputConfig } from './types'
+
+describe('categorical evaluation rules', () => {
+ test.each<{
+ selection_mode: EvaluationOutputConfig['selection_mode']
+ passing_rule: EvaluationOutputConfig['passing_rule']
+ options?: EvaluationOutputConfig['options']
+ optionsError?: string
+ error: string | null
+ }>([
+ { selection_mode: undefined, passing_rule: { categories: [] }, error: 'Choose at least one passing category.' },
+ { selection_mode: 'single', passing_rule: { categories: [] }, error: 'Choose at least one passing category.' },
+ { selection_mode: 'single', passing_rule: { categories: ['fast'] }, error: null },
+ { selection_mode: 'single', passing_rule: null, error: null },
+ { selection_mode: 'multiple', passing_rule: { categories: [] }, error: null },
+ {
+ selection_mode: 'single',
+ passing_rule: { categories: ['missing'] },
+ error: 'Choose passing categories from the configured categories.',
+ },
+ {
+ selection_mode: 'single',
+ options: [],
+ optionsError: 'Add at least one category.',
+ passing_rule: { categories: [] },
+ error: 'Choose at least one passing category.',
+ },
+ {
+ selection_mode: 'single',
+ options: [
+ { key: 'fast', label: 'Fast' },
+ { key: 'fast', label: 'Slow' },
+ ],
+ optionsError: 'Use a different key for each category.',
+ passing_rule: null,
+ error: null,
+ },
+ ])(
+ 'validates $selection_mode with $passing_rule and $options',
+ ({ selection_mode, passing_rule, options = [{ key: 'fast', label: 'Fast' }], optionsError, error }) => {
+ const config = {
+ options,
+ selection_mode,
+ passing_rule,
+ }
+ expect(categoricalOptionsError(config)).toBe(optionsError ?? null)
+ expect(categoricalPassingRuleError(config)).toBe(error)
+ expect(categoricalOutputConfigError(config)).toBe(optionsError ?? error)
+ }
+ )
+
+ test.each<{
+ rule: EvaluationOutputConfig['passing_rule']
+ categories: string[] | null
+ passed: boolean | null
+ }>([
+ { rule: null, categories: ['fast'], passed: null },
+ { rule: { categories: [] }, categories: [], passed: true },
+ { rule: { categories: [] }, categories: ['fast'], passed: false },
+ { rule: { categories: ['fast'] }, categories: [], passed: false },
+ { rule: { categories: ['fast'] }, categories: ['fast'], passed: true },
+ { rule: { categories: ['fast'] }, categories: ['fast', 'slow'], passed: false },
+ { rule: { categories: ['fast'] }, categories: null, passed: null },
+ ])('grades $categories using $rule as $passed', ({ rule, categories, passed }) => {
+ expect(categoricalResultPasses(categories, rule)).toBe(passed)
+ })
+
+ test.each<{
+ rule: EvaluationOutputConfig['passing_rule']
+ predicate: string
+ }>([
+ { rule: null, predicate: 'false' },
+ { rule: { categories: [] }, predicate: `empty(${EVALUATION_CATEGORIES_HOGQL})` },
+ {
+ rule: { categories: ['fast'] },
+ predicate: `notEmpty(${EVALUATION_CATEGORIES_HOGQL}) AND hasAll(['fast'], ${EVALUATION_CATEGORIES_HOGQL})`,
+ },
+ ])('builds the single-evaluation predicate for $rule', ({ rule, predicate }) => {
+ expect(categoricalEvaluationPassedHogQL({ output_config: { passing_rule: rule } })).toBe(predicate)
+ })
+
+ test.each([false, true])('scopes mixed rules to their evaluation (empty rule first: %s)', (emptyFirst) => {
+ const evaluations: Pick<EvaluationConfig, 'id' | 'output_type' | 'output_config'>[] = [
+ { id: 'empty', output_type: 'categorical', output_config: { passing_rule: { categories: [] } } },
+ { id: 'fast', output_type: 'categorical', output_config: { passing_rule: { categories: ['fast'] } } },
+ ]
+ if (!emptyFirst) {
+ evaluations.reverse()
+ }
+ evaluations.push(
+ { id: 'ungraded', output_type: 'categorical', output_config: {} },
+ {
+ id: 'numeric',
+ output_type: 'numeric',
+ output_config: { passing_rule: { operator: 'lte', threshold: 50 } },
+ }
+ )
+ const ids = emptyFirst ? "'empty', 'fast'" : "'fast', 'empty'"
+ const rules = emptyFirst ? "[], ['fast']" : "['fast'], []"
+ const lookup = `arrayElement([${rules}], transform(properties.$ai_evaluation_id, [${ids}], [1, 2], 0))`
+ expect(categoricalEvaluationsPassedHogQL(evaluations)).toBe(
+ `properties.$ai_evaluation_id IN (${ids}) AND if(empty(${EVALUATION_CATEGORIES_HOGQL}), empty(${lookup}), hasAll(${lookup}, ${EVALUATION_CATEGORIES_HOGQL}))`
+ )
+ })
+
+ it('never counts ungraded evaluations as passing', () => {
+ expect(
+ categoricalEvaluationsPassedHogQL([{ id: 'ungraded', output_type: 'categorical', output_config: {} }])
+ ).toBe('false')
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.ts
index 0498837fbed3..bebbe1633f3f 100644
--- a/products/ai_observability/frontend/evaluations/constants.ts
+++ b/products/ai_observability/frontend/evaluations/constants.ts
@@ -22,7 +22,8 @@ export const EVALUATION_NOT_SKIPPED_HOGQL =
"(isNull(properties.$ai_evaluation_skipped) OR properties.$ai_evaluation_skipped != 'true')"
export function numericOutputConfigError(config: EvaluationOutputConfig): string | null {
- const { min, max, step, passing_rule } = config
+ const { min, max, step } = config
+ const passing_rule = config.passing_rule && 'threshold' in config.passing_rule ? config.passing_rule : null
if ([min, max, step, passing_rule?.threshold].some((value) => value != null && !Number.isFinite(value))) {
return 'Enter finite numbers for the score bounds, step, and threshold.'
}
@@ -47,7 +48,7 @@ export const EVALUATION_NUMERIC_MEAN_HOGQL = `avgIf(toFloat(properties.$ai_evalu
export function numericEvaluationPassedHogQL(evaluation: Pick<EvaluationConfig, 'output_config'>): string {
const rule = evaluation.output_config.passing_rule
- if (!rule || !Number.isFinite(rule.threshold)) {
+ if (!rule || !('threshold' in rule) || !Number.isFinite(rule.threshold)) {
return 'false'
}
return `toFloat(properties.$ai_evaluation_numeric_result) ${rule.operator === 'gte' ? '>=' : '<='} ${rule.threshold}`
@@ -91,8 +92,104 @@ export function numericScorePasses(
score: number | null | undefined,
rule: EvaluationOutputConfig['passing_rule']
): boolean | null {
- if (score == null || !Number.isFinite(score) || !rule || !Number.isFinite(rule.threshold)) {
+ if (
+ score == null ||
+ !Number.isFinite(score) ||
+ !rule ||
+ !('threshold' in rule) ||
+ !Number.isFinite(rule.threshold)
+ ) {
return null
}
return rule.operator === 'gte' ? score >= rule.threshold : score <= rule.threshold
}
+
+export const EVALUATION_CATEGORIES_HOGQL =
+ "JSONExtract(ifNull(properties.$ai_evaluation_categorical_result, '[]'), 'Array(String)')"
+export const EVALUATION_CATEGORICAL_GRADED_HOGQL = `properties.$ai_evaluation_result_type = 'categorical' AND properties.$ai_evaluation_applicable = 'true' AND ${EVALUATION_NOT_SKIPPED_HOGQL}`
+
+export function categoricalResultPasses(
+ categories: string[] | null | undefined,
+ rule: EvaluationOutputConfig['passing_rule']
+): boolean | null {
+ if (categories == null || !rule || !('categories' in rule)) {
+ return null
+ }
+ if (categories.length === 0) {
+ return rule.categories.length === 0
+ }
+ return categories.every((category) => rule.categories.includes(category))
+}
+
+export function categoricalEvaluationPassedHogQL(evaluation: Pick<EvaluationConfig, 'output_config'>): string {
+ const rule = evaluation.output_config.passing_rule
+ if (!rule || !('categories' in rule)) {
+ return 'false'
+ }
+ if (rule.categories.length === 0) {
+ return `empty(${EVALUATION_CATEGORIES_HOGQL})`
+ }
+ const categories = rule.categories.map(escapeHogQLString).join(', ')
+ return `notEmpty(${EVALUATION_CATEGORIES_HOGQL}) AND hasAll([${categories}], ${EVALUATION_CATEGORIES_HOGQL})`
+}
+
+export const MAX_CATEGORICAL_OPTIONS = 100
+
+export function categoricalOptionsError(config: EvaluationOutputConfig): string | null {
+ if (!config.options?.length) {
+ return 'Add at least one category.'
+ }
+ if (config.options.length > MAX_CATEGORICAL_OPTIONS) {
+ return `Use at most ${MAX_CATEGORICAL_OPTIONS} categories.`
+ }
+ if (
+ config.options.some(
+ ({ key, label }) =>
+ !/^[a-z0-9]+(?:[_-][a-z0-9]+)*$/.test(key) || key.length > 128 || !label.trim() || label.length > 256
+ )
+ ) {
+ return 'Give each category a label and a key using lowercase letters, numbers, underscores, or hyphens.'
+ }
+ if (new Set(config.options.map(({ key }) => key)).size !== config.options.length) {
+ return 'Use a different key for each category.'
+ }
+ return null
+}
+
+export function categoricalPassingRuleError(config: EvaluationOutputConfig): string | null {
+ const rule = config.passing_rule
+ if (rule && 'categories' in rule && config.selection_mode !== 'multiple' && rule.categories.length === 0) {
+ return 'Choose at least one passing category.'
+ }
+ if (
+ rule &&
+ (!('categories' in rule) ||
+ rule.categories.some((key) => !config.options?.some((option) => option.key === key)))
+ ) {
+ return 'Choose passing categories from the configured categories.'
+ }
+ return null
+}
+
+export function categoricalOutputConfigError(config: EvaluationOutputConfig): string | null {
+ return categoricalOptionsError(config) ?? categoricalPassingRuleError(config)
+}
+
+export function categoricalEvaluationsPassedHogQL(
+ evaluations: Pick<EvaluationConfig, 'id' | 'output_type' | 'output_config'>[]
+): string {
+ const rules = evaluations.flatMap((evaluation) => {
+ const rule = evaluation.output_config.passing_rule
+ return evaluation.output_type === 'categorical' && rule && 'categories' in rule
+ ? [{ id: evaluation.id, categories: rule.categories }]
+ : []
+ })
+ if (!rules.length) {
+ return 'false'
+ }
+ const ids = rules.map(({ id }) => escapeHogQLString(id)).join(', ')
+ const categories = rules.map(({ categories }) => `[${categories.map(escapeHogQLString).join(', ')}]`).join(', ')
+ const indexes = rules.map((_, index) => index + 1).join(', ')
+ const passingCategories = `arrayElement([${categories}], transform(properties.$ai_evaluation_id, [${ids}], [${indexes}], 0))`
+ return `properties.$ai_evaluation_id IN (${ids}) AND if(empty(${EVALUATION_CATEGORIES_HOGQL}), empty(${passingCategories}), hasAll(${passingCategories}, ${EVALUATION_CATEGORIES_HOGQL}))`
+}
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
index a5e30380ffe9..33c90a8111bb 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -3,9 +3,9 @@ import type { EvaluationConfig, EvaluationOutputType, EvaluationType, LLMJudgeEv
// Mirrors REPORTABLE_OUTPUT_TYPES_BY_TARGET in evaluation_configs.py — keep the two in step.
const REPORTABLE_OUTPUT_TYPES_BY_TARGET: Record<string, ReadonlySet<EvaluationOutputType>> = {
- generation: new Set(['boolean', 'sentiment', 'numeric']),
- trace: new Set(['boolean', 'numeric']),
- session: new Set(['boolean', 'numeric']),
+ generation: new Set(['boolean', 'sentiment', 'numeric', 'categorical']),
+ trace: new Set(['boolean', 'numeric', 'categorical']),
+ session: new Set(['boolean', 'numeric', 'categorical']),
}
export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | null | undefined): boolean {
@@ -26,7 +26,8 @@ export function evaluationSupportsReports(
): boolean {
return (
evaluationSupportsReportHistory(evaluation) &&
- (evaluation?.output_type !== 'numeric' || !!evaluation.output_config?.passing_rule)
+ (!['numeric', 'categorical'].includes(evaluation?.output_type ?? '') ||
+ !!evaluation?.output_config?.passing_rule)
)
}
@@ -36,7 +37,7 @@ export function evaluationSupportsRunOutcomes(
| null
| undefined
): boolean {
- return evaluation?.output_type === 'numeric'
+ return evaluation?.output_type === 'numeric' || evaluation?.output_type === 'categorical'
? !!evaluation.output_config?.passing_rule
: isBooleanEvaluationOutput(evaluation?.output_type)
}
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
index 71eb41b82645..8e6919168a8e 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
@@ -93,6 +93,27 @@ describe('evaluationMetricsLogic', () => {
evaluationsLogic.unmount()
})
+ it('includes categorical pass rates while excluding N/A from their denominator', async () => {
+ evaluationsLogic.actions.loadEvaluationsSuccess([
+ {
+ ...evaluation('categories', null),
+ output_type: 'categorical',
+ output_config: {
+ options: [{ key: 'resolved', label: 'Resolved' }],
+ passing_rule: { categories: ['resolved'] },
+ },
+ },
+ ])
+ queryMock.mockResolvedValueOnce({ results: [['categories', 4, 0, 0, 0, null, 0, 3, 2]] })
+ await expectLogic(metricsLogic, () => metricsLogic.actions.loadStats()).toFinishAllListeners()
+ expect(metricsLogic.values.evaluationsWithMetrics[0].stats).toMatchObject({
+ applicable_count: 3,
+ pass_count: 2,
+ pass_rate: (2 / 3) * 100,
+ })
+ expect(metricsLogic.values.summaryMetrics.overall_pass_rate).toBe(66.7)
+ })
+
it('loads stats once after evaluations finish loading on mount', async () => {
metricsLogic.unmount()
queryMock.mockClear()
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
index 6c2f987d6d94..702865128b8a 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
@@ -15,6 +15,8 @@ import {
EVALUATION_NUMERIC_GRADED_HOGQL,
EVALUATION_NUMERIC_MEAN_HOGQL,
numericEvaluationPassedHogQL,
+ categoricalEvaluationsPassedHogQL,
+ EVALUATION_CATEGORICAL_GRADED_HOGQL,
EVALUATION_RESULT_TRUE_HOGQL,
evaluationIsDetector,
evaluationPassedHogQLForMany,
@@ -35,6 +37,8 @@ export interface EvaluationStatsRow {
applicability_rate: number
score_count?: number
score_mean?: number | null
+ categorical_count?: number
+ categorical_pass_count?: number
numeric_pass_count?: number
}
@@ -58,12 +62,14 @@ type RawStatsRow = [
score_count?: number,
score_mean?: number | null,
numeric_pass_count?: number,
+ categorical_count?: number,
+ categorical_pass_count?: number,
]
function hasPassRate(evaluation: EvaluationConfig): boolean {
return (
evaluation.output_type === 'boolean' ||
- (evaluation.output_type === 'numeric' && !!evaluation.output_config.passing_rule)
+ (['numeric', 'categorical'].includes(evaluation.output_type) && !!evaluation.output_config.passing_rule)
)
}
@@ -231,7 +237,9 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
const rules = values.evaluations.flatMap((evaluation) => {
const rule = evaluation.output_config.passing_rule
return evaluation.output_type === 'numeric' &&
- rule?.operator === operator &&
+ rule &&
+ 'threshold' in rule &&
+ rule.operator === operator &&
Number.isFinite(rule.threshold)
? [{ id: evaluation.id, threshold: rule.threshold }]
: []
@@ -256,7 +264,9 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
countIf(${EVALUATION_RESULT_TRUE_HOGQL} AND ${EVALUATION_BOOLEAN_GRADED_HOGQL}) as true_count,
countIf(${EVALUATION_NUMERIC_GRADED_HOGQL}) as score_count,
${EVALUATION_NUMERIC_MEAN_HOGQL} as score_mean,
- countIf((${numericPass}) AND ${EVALUATION_NUMERIC_GRADED_HOGQL}) as numeric_pass_count
+ countIf((${numericPass}) AND ${EVALUATION_NUMERIC_GRADED_HOGQL}) as numeric_pass_count,
+ countIf(${EVALUATION_CATEGORICAL_GRADED_HOGQL}) as categorical_count,
+ countIf((${categoricalEvaluationsPassedHogQL(values.evaluations)}) AND ${EVALUATION_CATEGORICAL_GRADED_HOGQL}) as categorical_pass_count
FROM events
WHERE event = '$ai_evaluation' AND {filters}
GROUP BY evaluation_id
@@ -284,6 +294,8 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
score_count: row[4] ?? 0,
score_mean: row[4] && row[5] != null && Number.isFinite(row[5]) ? row[5] : null,
numeric_pass_count: row[6] ?? 0,
+ categorical_count: row[7] ?? 0,
+ categorical_pass_count: row[8] ?? 0,
runs_count,
applicable_count,
true_count,
@@ -319,9 +331,13 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
if (!stat) {
return { ...evaluation }
}
- if (evaluation.output_type === 'numeric') {
- const applicable_count = stat.score_count ?? 0
- const pass_count = stat.numeric_pass_count ?? 0
+ if (evaluation.output_type === 'numeric' || evaluation.output_type === 'categorical') {
+ const applicable_count =
+ (evaluation.output_type === 'categorical' ? stat.categorical_count : stat.score_count) ?? 0
+ const pass_count =
+ (evaluation.output_type === 'categorical'
+ ? stat.categorical_pass_count
+ : stat.numeric_pass_count) ?? 0
return {
...evaluation,
stats: {
@@ -422,6 +438,11 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
gradedExpression = `if(properties.$ai_evaluation_id IN (${numericIds}), ${EVALUATION_NUMERIC_GRADED_HOGQL}, ${EVALUATION_BOOLEAN_GRADED_HOGQL})`
}
+ if (enabledEvaluations.some((evaluation) => evaluation.output_type === 'categorical')) {
+ passedExpression = `if(properties.$ai_evaluation_result_type = 'categorical', ${categoricalEvaluationsPassedHogQL(enabledEvaluations)}, ${passedExpression})`
+ gradedExpression = `if(properties.$ai_evaluation_result_type = 'categorical', ${EVALUATION_CATEGORICAL_GRADED_HOGQL}, ${gradedExpression})`
+ }
+
return {
kind: NodeKind.TrendsQuery,
series: [
diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
index 537ff31ac85c..db3d40d803c9 100644
--- a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
@@ -96,7 +96,7 @@ describe('evaluationsApi', () => {
expect(evaluation).toMatchObject({ evaluation_type, output_type: 'numeric', output_config })
})
- it.each(['categorical', 'future_output'])(
+ it.each(['future_output', 'another_output'])(
'keeps supported rows when a page contains a future %s output',
async (output_type) => {
jest.mocked(evaluationsList).mockResolvedValueOnce({
diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.ts
index bd57724e5071..360fbf0b0a7c 100644
--- a/products/ai_observability/frontend/evaluations/evaluationsApi.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.ts
@@ -65,7 +65,9 @@ export function evaluationFromApi(evaluation: EvaluationApi): EvaluationConfig |
if (
evaluation.evaluation_type === 'llm_judge' &&
- (evaluation.output_type === 'boolean' || evaluation.output_type === 'numeric') &&
+ (evaluation.output_type === 'boolean' ||
+ evaluation.output_type === 'numeric' ||
+ evaluation.output_type === 'categorical') &&
evaluation.evaluation_config &&
'prompt' in evaluation.evaluation_config
) {
@@ -79,7 +81,9 @@ export function evaluationFromApi(evaluation: EvaluationApi): EvaluationConfig |
if (
evaluation.evaluation_type === 'hog' &&
- (evaluation.output_type === 'boolean' || evaluation.output_type === 'numeric') &&
+ (evaluation.output_type === 'boolean' ||
+ evaluation.output_type === 'numeric' ||
+ evaluation.output_type === 'categorical') &&
evaluation.evaluation_config &&
'source' in evaluation.evaluation_config &&
typeof evaluation.evaluation_config.source === 'string'
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 9e054c350a46..43b71ee19333 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -310,6 +310,52 @@ describe('llmEvaluationLogic', () => {
expect(logic.values.evaluation?.output_config.max).toBe(20)
})
+ it.each([
+ ['hog', null],
+ ['llm_judge', null],
+ ['hog', 'return [input.category];'],
+ ['llm_judge', 'return [input.category];'],
+ ] as const)(
+ 'keeps category edits and output switches in sync with generated Hog code from %s (custom: %s)',
+ (runtime, customSource) => {
+ logic.actions.setEvaluationType(runtime)
+ logic.actions.setOutputType('categorical')
+ if (runtime === 'llm_judge') {
+ logic.actions.setEvaluationType('hog')
+ }
+ if (customSource) {
+ logic.actions.setHogSource(customSource)
+ }
+
+ logic.actions.patchOutputConfig({
+ options: [
+ { key: 'helpful', label: 'Helpful' },
+ { key: 'unresolved', label: 'Unresolved' },
+ ],
+ })
+ expect(logic.values.evaluation?.evaluation_config).toEqual({
+ source: customSource ?? "return ['helpful'];",
+ })
+
+ logic.actions.patchOutputConfig({ options: [{ key: 'unresolved', label: 'Unresolved' }] })
+ expect(logic.values.evaluation?.evaluation_config).toEqual({
+ source: customSource ?? "return ['unresolved'];",
+ })
+
+ for (const outputType of ['numeric', 'boolean'] as const) {
+ logic.actions.setOutputType(outputType)
+ expect(logic.values.evaluation?.evaluation_config).toEqual({
+ source: customSource ?? (outputType === 'numeric' ? 'return 0;' : DEFAULT_HOG_SOURCE),
+ })
+
+ logic.actions.setOutputType('categorical')
+ expect(logic.values.evaluation?.evaluation_config).toEqual({
+ source: customSource ?? "return ['unresolved'];",
+ })
+ }
+ }
+ )
+
it('preserves numeric output while switching runtimes and locks saved output types', async () => {
const numeric = {
...mockEvaluation,
@@ -1597,23 +1643,35 @@ return result`,
expect(numericScorePasses(7, { operator: 'gte', threshold })).toBeNull()
})
- it('does not request a sample with an invalid numeric config', async () => {
- const testSample = jest.fn(() => ({ results: [] }))
- useMocks({ post: { '/api/projects/:teamId/evaluations/test_hog/': testSample } })
- logic = llmEvaluationLogic({ evaluationId: 'new' })
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
- logic.actions.setEvaluationType('hog')
- logic.actions.setOutputType('numeric')
- logic.actions.patchOutputConfig({ passing_rule: { operator: 'gte', threshold: NaN } })
+ it.each(['numeric', 'categorical'] as const)(
+ 'does not request a sample with an invalid %s config',
+ async (outputType) => {
+ const testSample = jest.fn(() => ({ results: [] }))
+ useMocks({ post: { '/api/projects/:teamId/evaluations/test_hog/': testSample } })
+ logic = llmEvaluationLogic({ evaluationId: 'new' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ logic.actions.setEvaluationType('hog')
+ logic.actions.setOutputType(outputType)
+ logic.actions.patchOutputConfig(
+ outputType === 'numeric'
+ ? { passing_rule: { operator: 'gte', threshold: NaN } }
+ : {
+ options: Array.from({ length: 101 }, (_, i) => ({
+ key: `category_${i}`,
+ label: `Category ${i}`,
+ })),
+ }
+ )
- await expectLogic(logic, () => logic.actions.testHogOnSample()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.testHogOnSample()).toFinishAllListeners()
- expect(testSample).not.toHaveBeenCalled()
- expect(logic.values.hogTestResults).toBeNull()
- })
+ expect(testSample).not.toHaveBeenCalled()
+ expect(logic.values.hogTestResults).toBeNull()
+ }
+ )
- it.each(['boolean', 'numeric'] as const)(
+ it.each(['boolean', 'numeric', 'categorical'] as const)(
'sends %s output config and clears sample results after configuration changes',
async (outputType) => {
let requestBody: Record<string, unknown> | undefined
@@ -1667,7 +1725,16 @@ return result`,
output_config:
outputType === 'numeric'
? { min: 0, max: 10, allows_na: false, passing_rule: { operator: 'gte', threshold: 7 } }
- : { allows_na: false },
+ : outputType === 'categorical'
+ ? {
+ allows_na: false,
+ selection_mode: 'single',
+ options: [
+ { key: 'resolved', label: 'Resolved' },
+ { key: 'unresolved', label: 'Unresolved' },
+ ],
+ }
+ : { allows_na: false },
target_config: { window_seconds: 120 },
})
expect(requestBody).not.toHaveProperty('allows_na')
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index bc11da83705e..8a6cfa26a125 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -40,6 +40,10 @@ import {
evaluationIsDetector,
numericOutputConfigError,
numericScorePasses,
+ categoricalResultPasses,
+ categoricalOutputConfigError,
+ categoricalEvaluationPassedHogQL,
+ EVALUATION_CATEGORICAL_GRADED_HOGQL,
} from './constants'
import {
evaluationCanResolveModel,
@@ -158,22 +162,34 @@ function toLLMJudgeEvaluation(evaluation: EvaluationConfig): LLMJudgeEvaluation
...evaluation,
evaluation_type: 'llm_judge',
evaluation_config: { prompt: '' },
- output_type: evaluation.output_type === 'numeric' ? 'numeric' : 'boolean',
- output_config: evaluation.output_type === 'numeric' ? evaluation.output_config : { allows_na: false },
+ output_type: evaluation.output_type === 'sentiment' ? 'boolean' : evaluation.output_type,
+ output_config: ['numeric', 'categorical'].includes(evaluation.output_type)
+ ? evaluation.output_config
+ : { allows_na: false },
}
}
+function defaultCategoricalHogSource(config: EvaluationOutputConfig): string {
+ return `return ['${config.options?.[0]?.key ?? 'resolved'}'];`
+}
+
function toHogEvaluation(evaluation: EvaluationConfig): HogEvaluation {
return {
...evaluation,
evaluation_type: 'hog',
- evaluation_config: { source: evaluation.output_type === 'numeric' ? 'return 0;' : DEFAULT_HOG_SOURCE },
- output_type: evaluation.output_type === 'numeric' ? 'numeric' : 'boolean',
+ evaluation_config: {
+ source:
+ evaluation.output_type === 'numeric'
+ ? 'return 0;'
+ : evaluation.output_type === 'categorical'
+ ? defaultCategoricalHogSource(evaluation.output_config)
+ : DEFAULT_HOG_SOURCE,
+ },
+ output_type: evaluation.output_type === 'sentiment' ? 'boolean' : evaluation.output_type,
model_configuration: null,
- output_config:
- evaluation.output_type === 'numeric'
- ? evaluation.output_config
- : { ...evaluation.output_config, allows_na: false },
+ output_config: ['numeric', 'categorical'].includes(evaluation.output_type)
+ ? evaluation.output_config
+ : { ...evaluation.output_config, allows_na: false },
}
}
@@ -204,7 +220,7 @@ function filterEvaluationRuns(
// A skipped run carries result=false when the evaluation disallows N/A, so it has to be
// excluded before the outcome is read or it lands in the fail bucket without being graded.
const gradedRuns = completedRuns.filter((r) => !r.skipped)
- if (evaluation?.output_type === 'numeric') {
+ if (evaluation?.output_type === 'numeric' || evaluation?.output_type === 'categorical') {
if (filter === 'na') {
return gradedRuns.filter((run) => run.applicable === false)
}
@@ -213,10 +229,13 @@ function filterEvaluationRuns(
return []
}
return gradedRuns.filter((run) => {
- if (run.applicable === false || run.score == null) {
+ if (run.applicable === false) {
return false
}
- const passed = numericScorePasses(run.score, rule)
+ const passed =
+ evaluation.output_type === 'categorical'
+ ? categoricalResultPasses(run.categories, rule)
+ : numericScorePasses(run.score, rule)
return filter === 'pass' ? passed === true : filter === 'fail' ? passed === false : false
})
}
@@ -315,7 +334,7 @@ export interface llmEvaluationLogicValues {
maxContext: MaxContextInput[]
modelSelectionRequired: boolean
originalEvaluation: EvaluationConfig | null
- outputConfigDrafts: Partial<Record<'boolean' | 'numeric', EvaluationOutputConfig>>
+ outputConfigDrafts: Partial<Record<'boolean' | 'categorical' | 'numeric', EvaluationOutputConfig>>
runsBackfill: EvaluationBackfillApi | null
runsBackfillId: string | null
runsBackfillLoading: boolean
@@ -470,9 +489,9 @@ export interface llmEvaluationLogicActions {
setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => {
modelConfiguration: ModelConfiguration | null
}
- setOutputType: (outputType: 'boolean' | 'numeric') => {
+ setOutputType: (outputType: 'boolean' | 'categorical' | 'numeric') => {
outputConfig: EvaluationApiOutputConfig | undefined
- outputType: 'boolean' | 'numeric'
+ outputType: 'boolean' | 'categorical' | 'numeric'
previousEvaluation: EvaluationConfig | null
}
setRunsBackfillId: (backfillId: string | null) => {
@@ -602,7 +621,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setEvaluationDescription: (description: string) => ({ description }),
setEvaluationPrompt: (prompt: string) => ({ prompt }),
setEvaluationEnabled: (enabled: boolean) => ({ enabled }),
- setOutputType: (outputType: 'boolean' | 'numeric') => ({
+ setOutputType: (outputType: 'boolean' | 'numeric' | 'categorical') => ({
outputType,
previousEvaluation: values.evaluation,
outputConfig: values.outputConfigDrafts[outputType],
@@ -666,7 +685,11 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!isTestableHogEvaluation(evaluation)) {
return null
}
- if (evaluation.output_type === 'numeric' && numericOutputConfigError(evaluation.output_config)) {
+ if (
+ (evaluation.output_type === 'numeric' && numericOutputConfigError(evaluation.output_config)) ||
+ (evaluation.output_type === 'categorical' &&
+ categoricalOutputConfigError(evaluation.output_config))
+ ) {
return null
}
@@ -767,7 +790,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
reducers(({ props }) => ({
outputConfigDrafts: [
- {} as Partial<Record<'boolean' | 'numeric', EvaluationOutputConfig>>,
+ {} as Partial<Record<'boolean' | 'numeric' | 'categorical', EvaluationOutputConfig>>,
{
loadEvaluationSuccess: () => ({}),
setOutputType: (state, { previousEvaluation }) =>
@@ -802,9 +825,23 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
) {
return state
}
- const output_config = outputConfig ?? { allows_na: state.output_config.allows_na ?? false }
+ const output_config = outputConfig ?? {
+ allows_na: state.output_config.allows_na ?? false,
+ ...(outputType === 'categorical'
+ ? {
+ options: [
+ { key: 'resolved', label: 'Resolved' },
+ { key: 'unresolved', label: 'Unresolved' },
+ ],
+ selection_mode: 'single' as const,
+ }
+ : {}),
+ }
if (state.evaluation_type === 'hog') {
const source = state.evaluation_config.source
+ const isDefaultCategoricalSource =
+ state.output_type === 'categorical' &&
+ source === defaultCategoricalHogSource(state.output_config)
return {
...state,
output_type: outputType,
@@ -812,21 +849,48 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
evaluation_config: {
...state.evaluation_config,
source:
- outputType === 'numeric' &&
- (source === DEFAULT_HOG_SOURCE || LEGACY_HOG_DEFAULT_SOURCES.includes(source))
- ? 'return 0;'
- : outputType === 'boolean' && source === 'return 0;'
- ? DEFAULT_HOG_SOURCE
- : source,
+ outputType === 'categorical' &&
+ (source === 'return 0;' ||
+ source === DEFAULT_HOG_SOURCE ||
+ LEGACY_HOG_DEFAULT_SOURCES.includes(source))
+ ? defaultCategoricalHogSource(output_config)
+ : outputType === 'numeric' &&
+ (isDefaultCategoricalSource ||
+ source === DEFAULT_HOG_SOURCE ||
+ LEGACY_HOG_DEFAULT_SOURCES.includes(source))
+ ? 'return 0;'
+ : outputType === 'boolean' &&
+ (isDefaultCategoricalSource || source === 'return 0;')
+ ? DEFAULT_HOG_SOURCE
+ : source,
},
}
}
return { ...state, output_type: outputType, output_config }
},
- patchOutputConfig: (state, { patch }) =>
- state?.output_type === 'numeric'
- ? { ...state, output_config: { ...state.output_config, ...patch } }
- : state,
+ patchOutputConfig: (state, { patch }) => {
+ if (state?.output_type !== 'numeric' && state?.output_type !== 'categorical') {
+ return state
+ }
+ const output_config = { ...state.output_config, ...patch }
+ // Only the untouched example follows category edits; custom code belongs to the user.
+ if (
+ state.output_type === 'categorical' &&
+ state.evaluation_type === 'hog' &&
+ patch.options &&
+ state.evaluation_config.source === defaultCategoricalHogSource(state.output_config)
+ ) {
+ return {
+ ...state,
+ output_config,
+ evaluation_config: {
+ ...state.evaluation_config,
+ source: defaultCategoricalHogSource(output_config),
+ },
+ }
+ }
+ return { ...state, output_config }
+ },
setAllowsNA: (state, { allowsNA }) =>
state && state.output_type !== 'sentiment'
? { ...state, output_config: { ...state.output_config, allows_na: allowsNA } }
@@ -849,7 +913,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return toHogEvaluation(state)
}
if (evaluationType === 'sentiment') {
- if (props.evaluationId !== 'new' && state.output_type === 'numeric') {
+ if (
+ props.evaluationId !== 'new' &&
+ (state.output_type === 'numeric' || state.output_type === 'categorical')
+ ) {
return state
}
return toSentimentEvaluation(state)
@@ -1035,7 +1102,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
previousEvaluation.evaluation_config.source === values.evaluation?.evaluation_config.source
) {
lemonToast.warning(
- `Your code was kept. Update it to return a ${outputType === 'numeric' ? 'number' : 'boolean'} and test it before enabling this evaluation.`
+ `Your code was kept. Update it to return a ${outputType === 'numeric' ? 'number' : outputType === 'categorical' ? 'list of category keys' : 'boolean'} and test it before enabling this evaluation.`
)
}
},
@@ -1356,14 +1423,19 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
custom_name: `${evaluation.name} - ${evaluation.output_type === 'numeric' && !evaluation.output_config.passing_rule ? 'Mean score' : 'Pass rate'}`,
math: HogQLMathType.HogQL,
math_hogql:
- evaluation.output_type === 'numeric'
- ? evaluation.output_config.passing_rule
- ? evaluationPassRateHogQL(
- numericEvaluationPassedHogQL(evaluation),
- EVALUATION_NUMERIC_GRADED_HOGQL
- )
- : EVALUATION_NUMERIC_MEAN_HOGQL
- : evaluationPassRateHogQL(evaluationPassedHogQL(evaluation)),
+ evaluation.output_type === 'categorical'
+ ? evaluationPassRateHogQL(
+ categoricalEvaluationPassedHogQL(evaluation),
+ EVALUATION_CATEGORICAL_GRADED_HOGQL
+ )
+ : evaluation.output_type === 'numeric'
+ ? evaluation.output_config.passing_rule
+ ? evaluationPassRateHogQL(
+ numericEvaluationPassedHogQL(evaluation),
+ EVALUATION_NUMERIC_GRADED_HOGQL
+ )
+ : EVALUATION_NUMERIC_MEAN_HOGQL
+ : evaluationPassRateHogQL(evaluationPassedHogQL(evaluation)),
properties: [
{
key: '$ai_evaluation_id',
@@ -1373,7 +1445,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
},
],
},
- ...(evaluation.output_type !== 'numeric' && evaluation.output_config.allows_na
+ ...(evaluation.output_type === 'boolean' && evaluation.output_config.allows_na
? [
{
kind: NodeKind.EventsNode as const,
@@ -1437,7 +1509,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!evaluation) {
return false
}
- if (evaluation.output_type === 'numeric' && numericOutputConfigError(evaluation.output_config)) {
+ if (
+ (evaluation.output_type === 'numeric' && numericOutputConfigError(evaluation.output_config)) ||
+ (evaluation.output_type === 'categorical' && categoricalOutputConfigError(evaluation.output_config))
+ ) {
return false
}
const hasValidName = (evaluation.name?.length ?? 0) > 0
@@ -1497,13 +1572,20 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
const { total, trueCount } = stats
- const applicable = evaluation?.output_type === 'numeric' ? (stats.scoreCount ?? 0) : stats.applicable
+ const applicable =
+ evaluation?.output_type === 'categorical'
+ ? (stats.categoricalCount ?? 0)
+ : evaluation?.output_type === 'numeric'
+ ? (stats.scoreCount ?? 0)
+ : stats.applicable
const passed =
- evaluation?.output_type === 'numeric'
- ? (stats.numericPassCount ?? 0)
- : evaluation && evaluationIsDetector(evaluation)
- ? applicable - trueCount
- : trueCount
+ evaluation?.output_type === 'categorical'
+ ? (stats.categoricalPassCount ?? 0)
+ : evaluation?.output_type === 'numeric'
+ ? (stats.numericPassCount ?? 0)
+ : evaluation && evaluationIsDetector(evaluation)
+ ? applicable - trueCount
+ : trueCount
// Applicable runs excludes N/A results
const failed = applicable - passed
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index ddc944c0883e..0fe69bd65a88 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -13,7 +13,7 @@ import { LLMProvider } from '../settings/llmProviderKeysLogic'
export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'
export type EvaluationTarget = 'generation' | 'trace' | 'session'
export type EvaluationSettleStrategy = 'fixed_window' | 'inactivity'
-export type EvaluationOutputType = 'boolean' | 'sentiment' | 'numeric'
+export type EvaluationOutputType = 'boolean' | 'sentiment' | 'numeric' | 'categorical'
export type EvaluationStatus = 'active' | 'paused' | 'error'
export type EvaluationStatusReason =
| 'provider_key_required'
@@ -90,13 +90,13 @@ export interface BaseEvaluationConfig {
export interface LLMJudgeEvaluation extends BaseEvaluationConfig {
evaluation_type: 'llm_judge'
- output_type: 'boolean' | 'numeric'
+ output_type: 'boolean' | 'numeric' | 'categorical'
evaluation_config: LLMJudgeEvaluationConfig
}
export interface HogEvaluation extends BaseEvaluationConfig {
evaluation_type: 'hog'
- output_type: 'boolean' | 'numeric'
+ output_type: 'boolean' | 'numeric' | 'categorical'
evaluation_config: HogEvaluationConfig
}
@@ -134,6 +134,7 @@ export interface EvaluationRun {
result: boolean | null
sentiment_label?: string | null
sentiment_score?: number | null
+ categories?: string[] | null
score?: number | null
score_min?: number | null
score_max?: number | null
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index edeacac39eeb..292a04ba47c9 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1734,6 +1734,7 @@ export const EvaluationTypeEnumApi = {
/**
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment
*/
export type OutputTypeEnumApi = (typeof OutputTypeEnumApi)[keyof typeof OutputTypeEnumApi]
@@ -1741,9 +1742,21 @@ export type OutputTypeEnumApi = (typeof OutputTypeEnumApi)[keyof typeof OutputTy
export const OutputTypeEnumApi = {
Boolean: 'boolean',
Numeric: 'numeric',
+ Categorical: 'categorical',
Sentiment: 'sentiment',
} as const
+/**
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
+ */
+export type EvaluationApiOutputConfigSelectionMode =
+ (typeof EvaluationApiOutputConfigSelectionMode)[keyof typeof EvaluationApiOutputConfigSelectionMode]
+
+export const EvaluationApiOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+} as const
+
export type EvaluationConditionApiPropertiesItem = { [key: string]: unknown }
/**
@@ -1834,7 +1847,7 @@ export type EvaluationApiEvaluationConfig =
}
| {
/**
- * Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.
+ * Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string
@@ -1844,24 +1857,45 @@ export type EvaluationApiEvaluationConfig =
source?: 'user_messages'
}
+export type EvaluationApiOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string
+}
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
*/
-export type EvaluationApiOutputConfigPassingRule = {
- /** Pass at or above (gte), or at or below (lte), the threshold. */
- operator: 'gte' | 'lte'
- /** Finite passing threshold within any configured score bounds. */
- threshold: number
-} | null
+export type EvaluationApiOutputConfigPassingRule =
+ | {
+ /** Pass at or above (gte), or at or below (lte), the threshold. */
+ operator: 'gte' | 'lte'
+ /** Finite passing threshold within any configured score bounds. */
+ threshold: number
+ }
+ | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[]
+ }
+ | null
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}.
*/
export type EvaluationApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -1881,9 +1915,14 @@ export type EvaluationApiOutputConfig = {
*/
step?: number | null
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: EvaluationApiOutputConfigOptionsItem[]
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: EvaluationApiOutputConfigSelectionMode
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: EvaluationApiOutputConfigPassingRule
}
@@ -1952,13 +1991,14 @@ export interface EvaluationApi {
evaluation_type: EvaluationTypeEnumApi
/** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: EvaluationApiEvaluationConfig
- /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment */
output_type: OutputTypeEnumApi
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}. */
output_config?: EvaluationApiOutputConfig
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationConditionApi[]
@@ -2117,7 +2157,7 @@ export type PatchedEvaluationApiEvaluationConfig =
}
| {
/**
- * Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.
+ * Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string
@@ -2127,24 +2167,56 @@ export type PatchedEvaluationApiEvaluationConfig =
source?: 'user_messages'
}
+export type PatchedEvaluationApiOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string
+}
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
*/
-export type PatchedEvaluationApiOutputConfigPassingRule = {
- /** Pass at or above (gte), or at or below (lte), the threshold. */
- operator: 'gte' | 'lte'
- /** Finite passing threshold within any configured score bounds. */
- threshold: number
-} | null
+export type PatchedEvaluationApiOutputConfigSelectionMode =
+ (typeof PatchedEvaluationApiOutputConfigSelectionMode)[keyof typeof PatchedEvaluationApiOutputConfigSelectionMode]
+
+export const PatchedEvaluationApiOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+} as const
+
+/**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
+ */
+export type PatchedEvaluationApiOutputConfigPassingRule =
+ | {
+ /** Pass at or above (gte), or at or below (lte), the threshold. */
+ operator: 'gte' | 'lte'
+ /** Finite passing threshold within any configured score bounds. */
+ threshold: number
+ }
+ | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[]
+ }
+ | null
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}.
*/
export type PatchedEvaluationApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -2164,9 +2236,14 @@ export type PatchedEvaluationApiOutputConfig = {
*/
step?: number | null
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: PatchedEvaluationApiOutputConfigOptionsItem[]
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: PatchedEvaluationApiOutputConfigSelectionMode
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: PatchedEvaluationApiOutputConfigPassingRule
}
@@ -2235,13 +2312,14 @@ export interface PatchedEvaluationApi {
evaluation_type?: EvaluationTypeEnumApi
/** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: PatchedEvaluationApiEvaluationConfig
- /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnumApi
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}. */
output_config?: PatchedEvaluationApiOutputConfig
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationConditionApi[]
@@ -2268,24 +2346,56 @@ export interface PatchedEvaluationApi {
readonly user_access_level?: string | null
}
+export type TestHogRequestApiOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string
+}
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
+ */
+export type TestHogRequestApiOutputConfigSelectionMode =
+ (typeof TestHogRequestApiOutputConfigSelectionMode)[keyof typeof TestHogRequestApiOutputConfigSelectionMode]
+
+export const TestHogRequestApiOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+} as const
+
+/**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
*/
-export type TestHogRequestApiOutputConfigPassingRule = {
- /** Pass at or above (gte), or at or below (lte), the threshold. */
- operator: 'gte' | 'lte'
- /** Finite passing threshold within any configured score bounds. */
- threshold: number
-} | null
+export type TestHogRequestApiOutputConfigPassingRule =
+ | {
+ /** Pass at or above (gte), or at or below (lte), the threshold. */
+ operator: 'gte' | 'lte'
+ /** Finite passing threshold within any configured score bounds. */
+ threshold: number
+ }
+ | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[]
+ }
+ | null
/**
- * Output settings used to validate the preview, including numeric bounds and allows_na.
+ * Output settings used to validate the preview, including bounds, categories, and allows_na.
*/
export type TestHogRequestApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -2305,9 +2415,14 @@ export type TestHogRequestApiOutputConfig = {
*/
step?: number | null
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: TestHogRequestApiOutputConfigOptionsItem[]
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: TestHogRequestApiOutputConfigSelectionMode
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: TestHogRequestApiOutputConfigPassingRule
}
@@ -2316,6 +2431,7 @@ export type TestHogRequestApiConditionsItem = { [key: string]: unknown }
/**
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
*/
export type HogEvaluationOutputTypeEnumApi =
(typeof HogEvaluationOutputTypeEnumApi)[keyof typeof HogEvaluationOutputTypeEnumApi]
@@ -2323,6 +2439,7 @@ export type HogEvaluationOutputTypeEnumApi =
export const HogEvaluationOutputTypeEnumApi = {
Boolean: 'boolean',
Numeric: 'numeric',
+ Categorical: 'categorical',
} as const
export interface TestHogTargetConfigApi {
@@ -2341,15 +2458,16 @@ export interface TestHogTargetConfigApi {
}
export interface TestHogRequestApi {
- /** Expected output: boolean or numeric. Sentiment is not supported by Hog.
+ /** Expected output: boolean, numeric, or categorical. Sentiment is not supported by Hog.
*
* * `boolean` - Boolean (Pass/Fail)
- * * `numeric` - Numeric */
+ * * `numeric` - Numeric
+ * * `categorical` - Categorical */
output_type?: HogEvaluationOutputTypeEnumApi
- /** Output settings used to validate the preview, including numeric bounds and allows_na. */
+ /** Output settings used to validate the preview, including bounds, categories, and allows_na. */
output_config?: TestHogRequestApiOutputConfig
/**
- * Hog source code to test. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.
+ * Hog source code to test. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string
@@ -2374,6 +2492,11 @@ export interface TestHogRequestApi {
}
export interface TestHogResultItemApi {
+ /**
+ * Selected category keys. An empty list is an applicable result; null means no categorical result was produced.
+ * @nullable
+ */
+ categories?: string[] | null
/**
* Raw numeric score, or null when no numeric score was produced.
* @nullable
@@ -2946,23 +3069,55 @@ export const GenerationStatusEnumApi = {
} as const
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
*/
-export type EvaluationReportMetricsApiOutputConfigPassingRule = {
- /** Pass at or above (gte), or at or below (lte), the threshold. */
- operator: 'gte' | 'lte'
- /** Finite passing threshold within any configured score bounds. */
- threshold: number
-} | null
+export type EvaluationReportMetricsApiOutputConfigSelectionMode =
+ (typeof EvaluationReportMetricsApiOutputConfigSelectionMode)[keyof typeof EvaluationReportMetricsApiOutputConfigSelectionMode]
+
+export const EvaluationReportMetricsApiOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+} as const
+
+export type EvaluationReportMetricsApiOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string
+}
+
+/**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
+ */
+export type EvaluationReportMetricsApiOutputConfigPassingRule =
+ | {
+ /** Pass at or above (gte), or at or below (lte), the threshold. */
+ operator: 'gte' | 'lte'
+ /** Finite passing threshold within any configured score bounds. */
+ threshold: number
+ }
+ | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[]
+ }
+ | null
/**
- * Numeric score configuration and passing rule used for both report periods.
+ * Output configuration and passing rule used for both report periods.
*/
export type EvaluationReportMetricsApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -2982,9 +3137,14 @@ export type EvaluationReportMetricsApiOutputConfig = {
*/
step?: number | null
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: EvaluationReportMetricsApiOutputConfigOptionsItem[]
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: EvaluationReportMetricsApiOutputConfigSelectionMode
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: EvaluationReportMetricsApiOutputConfigPassingRule
}
@@ -3011,12 +3171,13 @@ export type EvaluationReportMetricsApiPreviousResultCounts = { [key: string]: nu
export type EvaluationReportMetricsApiPreviousResultRates = { [key: string]: number } | null
export interface EvaluationReportMetricsApi {
- /** Numeric score configuration and passing rule used for both report periods. */
+ /** Output configuration and passing rule used for both report periods. */
output_config?: EvaluationReportMetricsApiOutputConfig
/** Evaluation result type. Stored metrics without this field represent boolean evaluations.
*
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnumApi
/** Number of evaluation results in the report period. */
@@ -3045,12 +3206,12 @@ export interface EvaluationReportMetricsApi {
*/
previous_result_rates?: EvaluationReportMetricsApiPreviousResultRates
/**
- * Boolean or numeric pass percentage, excluding N/A results. Null when no numeric scores were produced.
+ * Pass percentage excluding N/A. With no applicable results, numeric and categorical reports return null; boolean reports return 0.
* @nullable
*/
pass_rate?: number | null
/**
- * Boolean or numeric pass percentage for the previous period, or null when unavailable.
+ * Pass percentage for boolean, numeric, or categorical results in the previous period, or null when unavailable.
* @nullable
*/
previous_pass_rate?: number | null
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 6d693aac783b..348848450539 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -515,6 +515,13 @@ export const evaluationsCreateBodyNameMax = 400
export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsCreateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsCreateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsCreateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsCreateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsCreateBodyOutputConfigOptionsMax = 100
+
export const evaluationsCreateBodyConditionsItemIdMax = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -563,7 +570,7 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
}),
zod.object({
@@ -580,10 +587,12 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'numeric', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'categorical', 'sentiment'])
+ .describe(
+ '\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment'
+ )
.describe(
- "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment"
+ "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment"
),
output_config: zod
.object({
@@ -595,7 +604,7 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -604,23 +613,61 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.gt(evaluationsCreateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsCreateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsCreateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsCreateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsCreateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe(
+ 'Categorical output options. Keys identify stored results; labels are displayed to users.'
+ ),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod
- .number()
- .describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
.describe(
- "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}."
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}."
),
conditions: zod
.array(
@@ -842,6 +889,13 @@ export const evaluationsUpdateBodyNameMax = 400
export const evaluationsUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsUpdateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsUpdateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsUpdateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsUpdateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsUpdateBodyOutputConfigOptionsMax = 100
+
export const evaluationsUpdateBodyConditionsItemIdMax = 100
export const evaluationsUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -890,7 +944,7 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
}),
zod.object({
@@ -907,10 +961,12 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'numeric', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'categorical', 'sentiment'])
+ .describe(
+ '\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment'
+ )
.describe(
- "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment"
+ "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment"
),
output_config: zod
.object({
@@ -922,7 +978,7 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -931,23 +987,61 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.gt(evaluationsUpdateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsUpdateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsUpdateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsUpdateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsUpdateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe(
+ 'Categorical output options. Keys identify stored results; labels are displayed to users.'
+ ),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod
- .number()
- .describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
.describe(
- "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}."
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}."
),
conditions: zod
.array(
@@ -1071,6 +1165,13 @@ export const evaluationsPartialUpdateBodyNameMax = 400
export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsPartialUpdateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsPartialUpdateBodyOutputConfigOptionsMax = 100
+
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -1120,7 +1221,7 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
}),
zod.object({
@@ -1137,11 +1238,13 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'numeric', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'categorical', 'sentiment'])
+ .describe(
+ '\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment'
+ )
.optional()
.describe(
- "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment"
+ "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment"
),
output_config: zod
.object({
@@ -1153,7 +1256,7 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -1162,23 +1265,61 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.gt(evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsPartialUpdateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsPartialUpdateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe(
+ 'Categorical output options. Keys identify stored results; labels are displayed to users.'
+ ),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod
- .number()
- .describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
.describe(
- "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}."
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}."
),
conditions: zod
.array(
@@ -1303,6 +1444,13 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
export const evaluationsTestHogCreateBodyOutputTypeDefault = `boolean`
export const evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsTestHogCreateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsTestHogCreateBodyOutputConfigOptionsMax = 100
+
export const evaluationsTestHogCreateBodySampleCountDefault = 5
export const evaluationsTestHogCreateBodySampleCountMax = 10
@@ -1318,11 +1466,11 @@ export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax =
export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
output_type: zod
- .enum(['boolean', 'numeric'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric')
+ .enum(['boolean', 'numeric', 'categorical'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical')
.default(evaluationsTestHogCreateBodyOutputTypeDefault)
.describe(
- 'Expected output: boolean or numeric. Sentiment is not supported by Hog.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric'
+ 'Expected output: boolean, numeric, or categorical. Sentiment is not supported by Hog.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical'
),
output_config: zod
.object({
@@ -1334,7 +1482,7 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -1343,25 +1491,63 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.gt(evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsTestHogCreateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsTestHogCreateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe('Categorical output options. Keys identify stored results; labels are displayed to users.'),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod.number().describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
- .describe('Output settings used to validate the preview, including numeric bounds and allows_na.'),
+ .describe('Output settings used to validate the preview, including bounds, categories, and allows_na.'),
source: zod
.string()
.min(1)
.describe(
- 'Hog source code to test. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code to test. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
sample_count: zod
.number()
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 62d5318fe644..f351414d5d64 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -75,6 +75,28 @@ function makeEvaluationRunRow({
}
describe('mapEvaluationRunRow', () => {
+ it.each([
+ ['["resolved"]', ['resolved']],
+ ['[]', []],
+ [null, []],
+ ['invalid', null],
+ ['[1]', null],
+ ])('preserves categorical JSON %p without confusing empty and absent results', (raw, expected) => {
+ const row = makeEvaluationRunRow({ result: null, resultType: 'categorical' })
+ row[18] = raw
+ expect(mapEvaluationRunRow(row)).toMatchObject({
+ result_type: 'categorical',
+ categories: expected,
+ result: null,
+ })
+ })
+
+ it.each([false, 'false'])('keeps an inapplicable categorical result as N/A (%p)', (applicable) => {
+ const row = makeEvaluationRunRow({ result: null, resultType: 'categorical', applicable })
+ row[18] = null
+ expect(mapEvaluationRunRow(row).categories).toBeNull()
+ })
+
it.each([0, 0.5, -2, '0', '0.5', '-2'])('keeps numeric score %p and its original bounds', (score) => {
const row = makeEvaluationRunRow({ result: null, resultType: 'numeric' })
row[15] = score
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index 7c3924e2241b..e20032609b76 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -13,6 +13,8 @@ import {
EVALUATION_NUMERIC_GRADED_HOGQL,
EVALUATION_NUMERIC_MEAN_HOGQL,
numericEvaluationPassedHogQL,
+ categoricalEvaluationPassedHogQL,
+ EVALUATION_CATEGORICAL_GRADED_HOGQL,
EVALUATION_RESULT_TRUE_HOGQL,
EVALUATION_RUNS_QUERY_LIMIT,
} from './evaluations/constants'
@@ -1133,6 +1135,7 @@ type RawEvaluationRunRow = [
score?: number | string | null,
score_min?: number | string | null,
score_max?: number | string | null,
+ categories?: string[] | string | null,
]
export function normalizeEvaluationType(value: unknown): EvaluationType | undefined {
@@ -1143,7 +1146,7 @@ export function normalizeEvaluationType(value: unknown): EvaluationType | undefi
}
export function normalizeEvaluationOutputType(value: unknown): EvaluationOutputType | undefined {
- if (value === 'boolean' || value === 'sentiment' || value === 'numeric') {
+ if (value === 'boolean' || value === 'sentiment' || value === 'numeric' || value === 'categorical') {
return value
}
return undefined
@@ -1179,6 +1182,7 @@ export interface NormalizedEvaluationResultProperties {
rawResultType?: unknown
rawSentimentLabel?: unknown
rawSentimentScore?: unknown
+ rawCategories?: unknown
rawScore?: unknown
rawScoreMin?: unknown
rawScoreMax?: unknown
@@ -1192,6 +1196,7 @@ export function normalizeEvaluationResultProperties({
rawSentimentLabel,
rawSentimentScore,
rawScore,
+ rawCategories,
rawScoreMin,
rawScoreMax,
}: NormalizedEvaluationResultProperties): Pick<
@@ -1202,6 +1207,7 @@ export function normalizeEvaluationResultProperties({
| 'sentiment_label'
| 'sentiment_score'
| 'applicable'
+ | 'categories'
| 'score'
| 'score_min'
| 'score_max'
@@ -1213,9 +1219,22 @@ export function normalizeEvaluationResultProperties({
normalizeEvaluationOutputType(rawResultType) ??
(evaluationType === 'sentiment' || sentimentLabel ? 'sentiment' : 'boolean')
+ if (resultType === 'categorical') {
+ if (rawCategories == null && isExplicitEvaluationPass(rawApplicable)) {
+ rawCategories = []
+ } else if (typeof rawCategories === 'string') {
+ try {
+ rawCategories = JSON.parse(rawCategories)
+ } catch {
+ rawCategories = null
+ }
+ }
+ }
+
const result =
resultType === 'sentiment' ||
resultType === 'numeric' ||
+ resultType === 'categorical' ||
isExplicitEvaluationNotApplicable(rawApplicable) ||
rawResult === null ||
rawResult === undefined
@@ -1228,6 +1247,16 @@ export function normalizeEvaluationResultProperties({
result,
sentiment_label: sentimentLabel,
sentiment_score: normalizeOptionalNumber(rawSentimentScore),
+ ...(resultType === 'categorical'
+ ? {
+ categories:
+ !isExplicitEvaluationNotApplicable(rawApplicable) &&
+ Array.isArray(rawCategories) &&
+ rawCategories.every((value) => typeof value === 'string')
+ ? rawCategories
+ : null,
+ }
+ : {}),
...(resultType === 'numeric'
? {
score:
@@ -1254,6 +1283,7 @@ export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
rawScore: row[15],
rawScoreMin: row[16],
rawScoreMax: row[17],
+ rawCategories: row[18],
})
return {
@@ -1314,7 +1344,8 @@ export async function queryEvaluationRuns(params: {
properties.$ai_evaluation_skipped as skipped,
properties.$ai_evaluation_numeric_result as score,
properties.$ai_evaluation_numeric_result_min as score_min,
- properties.$ai_evaluation_numeric_result_max as score_max
+ properties.$ai_evaluation_numeric_result_max as score_max,
+ properties.$ai_evaluation_categorical_result as categories
FROM events
WHERE
event = '$ai_evaluation'
@@ -1345,6 +1376,8 @@ export interface EvaluationRunsStats {
scoreCount?: number
scoreMean?: number | null
numericPassCount?: number
+ categoricalCount?: number
+ categoricalPassCount?: number
}
// Counts every matching run server-side. queryEvaluationRuns caps its fetch at
@@ -1376,7 +1409,9 @@ export async function queryEvaluationRunsStats(params: {
countIf(${hogql.raw(EVALUATION_RESULT_TRUE_HOGQL)} AND ${hogql.raw(EVALUATION_BOOLEAN_GRADED_HOGQL)}) as true_count,
countIf(${hogql.raw(EVALUATION_NUMERIC_GRADED_HOGQL)}) as score_count,
${hogql.raw(EVALUATION_NUMERIC_MEAN_HOGQL)} as score_mean,
- countIf(${hogql.raw(evaluation?.output_type === 'numeric' ? numericEvaluationPassedHogQL(evaluation) : 'false')} AND ${hogql.raw(EVALUATION_NUMERIC_GRADED_HOGQL)}) as numeric_pass_count
+ countIf(${hogql.raw(evaluation?.output_type === 'numeric' ? numericEvaluationPassedHogQL(evaluation) : 'false')} AND ${hogql.raw(EVALUATION_NUMERIC_GRADED_HOGQL)}) as numeric_pass_count,
+ countIf(${hogql.raw(EVALUATION_CATEGORICAL_GRADED_HOGQL)}) as categorical_count,
+ countIf(${hogql.raw(evaluation?.output_type === 'categorical' ? categoricalEvaluationPassedHogQL(evaluation) : 'false')} AND ${hogql.raw(EVALUATION_CATEGORICAL_GRADED_HOGQL)}) as categorical_pass_count
FROM events
WHERE
event = '$ai_evaluation'
@@ -1407,5 +1442,7 @@ export async function queryEvaluationRunsStats(params: {
scoreCount: Number(row[3]) || 0,
scoreMean: Number(row[3]) > 0 ? normalizeOptionalNumber(row[4]) : null,
numericPassCount: Number(row[5]) || 0,
+ categoricalCount: Number(row[6]) || 0,
+ categoricalPassCount: Number(row[7]) || 0,
}
}
diff --git a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
index 57be644f0718..40c71211ca07 100644
--- a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
@@ -17,7 +17,7 @@ description: >
PostHog evaluations score `$ai_generation` events. Each evaluation is one of three
types:
-- **`hog`** — deterministic Hog code that returns `true`/`false` (and optionally N/A).
+- **`hog`** — deterministic Hog code that returns a boolean, numeric score, or categories (and optionally N/A).
Best for objective rule-based checks: format validation (JSON parses, schema matches),
length limits, keyword presence/absence, regex patterns, structural assertions, latency
thresholds, cost guards. Cheap, fast, reproducible — no LLM call per run. Prefer this
@@ -39,6 +39,15 @@ Use `output_config.passing_rule` to interpret scores: `gte` means at least the t
Changing the rule reinterprets historical scores. Saved reports retain the rule and metrics used when generated.
Without a passing rule, inspect score means and distributions; pass rates and reports are unavailable.
+Both runtimes also support `output_type: "categorical"` when categorical evaluations are enabled for the project.
+Read `output_config.options` for the configured `{key, label}` pairs and `selection_mode` for `single` or `multiple`.
+Results store keys as a list in `$ai_evaluation_categorical_result`; single selection requires exactly one key, while multiple selection accepts `[]`.
+Hog can also return a single key string in single mode.
+Use `output_config.passing_rule.categories` to grade results: a nonempty result passes only when every returned key is a passing category.
+A nonempty rule fails `[]`; an empty rule passes only `[]` and is allowed only in multiple mode.
+Without a rule, inspect category frequencies instead of pass rates; new reports are unavailable.
+Rule edits reclassify historical results, while saved reports retain their rule snapshot.
+
This skill covers the full lifecycle: list/inspect/manage evaluation configs, run
them on specific generations, query individual results, and configure evaluation
reports that summarize recent runs on a schedule.
@@ -66,21 +75,24 @@ All `llma-evaluation-*` tools are defined in `products/ai_observability/mcp/tool
Every run of an evaluation emits an `$ai_evaluation` event. Key properties:
-| Property | Meaning |
-| ------------------------------- | -------------------------------------------------------------------------------- |
-| `$ai_evaluation_id` | UUID of the evaluation config |
-| `$ai_evaluation_name` | Human-readable name |
-| `$ai_target_event_id` | UUID of the `$ai_generation` event being scored |
-| `$ai_trace_id` | Parent trace ID (for jumping to the trace UI) |
-| `$ai_evaluation_result_type` | Result kind: `boolean`, `numeric`, or `sentiment` |
-| `$ai_evaluation_numeric_result` | Raw numeric score. Use the passing rule to map it to pass or fail |
-| `$ai_evaluation_result` | Raw boolean result. Use the evaluation's output config to map it to pass or fail |
-| `$ai_evaluation_reasoning` | Free-text explanation (set by the LLM judge or Hog code) |
-| `$ai_evaluation_applicable` | `false` when the evaluator decided the generation is N/A |
-| `$ai_sentiment_label` | For sentiment evaluations: `positive`, `neutral`, or `negative` |
-| `$ai_sentiment_score` | Confidence score for the winning sentiment label |
-
-When `$ai_evaluation_applicable = false`, the run counts as N/A regardless of `$ai_evaluation_result`.
+| Property | Meaning |
+| ----------------------------------- | -------------------------------------------------------------------------------- |
+| `$ai_evaluation_id` | UUID of the evaluation config |
+| `$ai_evaluation_name` | Human-readable name |
+| `$ai_target_event_id` | UUID of the `$ai_generation` event being scored |
+| `$ai_trace_id` | Parent trace ID (for jumping to the trace UI) |
+| `$ai_evaluation_result_type` | Result kind: `boolean`, `numeric`, `categorical`, or `sentiment` |
+| `$ai_evaluation_numeric_result` | Raw numeric score. Use the passing rule to map it to pass or fail |
+| `$ai_evaluation_categorical_result` | List of category keys. Use the passing rule to map it to pass or fail |
+| `$ai_evaluation_result` | Raw boolean result. Use the evaluation's output config to map it to pass or fail |
+| `$ai_evaluation_reasoning` | Free-text explanation (set by the LLM judge or Hog code) |
+| `$ai_evaluation_applicable` | `false` when the evaluator decided the generation is N/A |
+| `$ai_evaluation_skipped` | `true` when no result was graded because the run could not be evaluated |
+| `$ai_sentiment_label` | For sentiment evaluations: `positive`, `neutral`, or `negative` |
+| `$ai_sentiment_score` | Confidence score for the winning sentiment label |
+
+Check `$ai_evaluation_skipped` first: skipped runs are excluded from pass rates and are distinct from N/A.
+Otherwise, `$ai_evaluation_applicable = false` means N/A regardless of the result value.
For evaluations that don't support N/A, this property may be `null` — treat null as "applicable".
For boolean evaluations, `output_config.true_is_failure: false` maps `true` to pass and `false` to fail.
Set it to `true` for detector-style evaluations where `true` means the evaluator found a problem.
@@ -91,6 +103,8 @@ Works the same way for boolean `llm_judge` and `hog` evaluations — the differe
only matter when you eventually go to fix the evaluator (edit the prompt vs. edit
the Hog source). Sentiment evaluations should be inspected by sentiment label and
score rather than pass/fail filters.
+The SQL pass/fail examples below use boolean results.
+For numeric and categorical evaluations, read their result property and current passing rule instead of `$ai_evaluation_result`.
### Step 1 — Find the evaluation
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0cdbaa5f2e82..ca99aaea4faa 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38458,7 +38458,7 @@ export namespace Schemas {
prompt: string;
} | {
/**
- * Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.
+ * Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string;
@@ -38467,24 +38467,53 @@ export namespace Schemas {
source?: 'user_messages';
};
+ export type EvaluationOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string;
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string;
+ };
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
+ */
+ export type EvaluationOutputConfigSelectionMode = typeof EvaluationOutputConfigSelectionMode[keyof typeof EvaluationOutputConfigSelectionMode];
+
+
+ export const EvaluationOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+ } as const;
+
+ /**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
*/
export type EvaluationOutputConfigPassingRule = {
/** Pass at or above (gte), or at or below (lte), the threshold. */
operator: 'gte' | 'lte';
/** Finite passing threshold within any configured score bounds. */
threshold: number;
+ } | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[];
} | null;
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}.
*/
export type EvaluationOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -38504,9 +38533,14 @@ export namespace Schemas {
*/
step?: number | null;
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: EvaluationOutputConfigOptionsItem[];
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: EvaluationOutputConfigSelectionMode;
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: EvaluationOutputConfigPassingRule;
};
@@ -38596,6 +38630,7 @@ export namespace Schemas {
/**
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment
*/
export type OutputTypeEnum = typeof OutputTypeEnum[keyof typeof OutputTypeEnum];
@@ -38604,6 +38639,7 @@ export namespace Schemas {
export const OutputTypeEnum = {
Boolean: 'boolean',
Numeric: 'numeric',
+ Categorical: 'categorical',
Sentiment: 'sentiment',
} as const;
@@ -38720,13 +38756,14 @@ export namespace Schemas {
evaluation_type: EvaluationTypeEnum;
/** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: EvaluationEvaluationConfig;
- /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment */
output_type: OutputTypeEnum;
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}. */
output_config?: EvaluationOutputConfig;
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationCondition[];
@@ -39048,24 +39085,53 @@ export namespace Schemas {
reason?: string;
}
+ export type EvaluationReportMetricsOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string;
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string;
+ };
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
+ */
+ export type EvaluationReportMetricsOutputConfigSelectionMode = typeof EvaluationReportMetricsOutputConfigSelectionMode[keyof typeof EvaluationReportMetricsOutputConfigSelectionMode];
+
+
+ export const EvaluationReportMetricsOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+ } as const;
+
+ /**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
*/
export type EvaluationReportMetricsOutputConfigPassingRule = {
/** Pass at or above (gte), or at or below (lte), the threshold. */
operator: 'gte' | 'lte';
/** Finite passing threshold within any configured score bounds. */
threshold: number;
+ } | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[];
} | null;
/**
- * Numeric score configuration and passing rule used for both report periods.
+ * Output configuration and passing rule used for both report periods.
*/
export type EvaluationReportMetricsOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -39085,9 +39151,14 @@ export namespace Schemas {
*/
step?: number | null;
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: EvaluationReportMetricsOutputConfigOptionsItem[];
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: EvaluationReportMetricsOutputConfigSelectionMode;
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: EvaluationReportMetricsOutputConfigPassingRule;
};
@@ -39114,12 +39185,13 @@ export namespace Schemas {
export type EvaluationReportMetricsPreviousResultRates = {[key: string]: number} | null;
export interface EvaluationReportMetrics {
- /** Numeric score configuration and passing rule used for both report periods. */
+ /** Output configuration and passing rule used for both report periods. */
output_config?: EvaluationReportMetricsOutputConfig;
/** Evaluation result type. Stored metrics without this field represent boolean evaluations.
*
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnum;
/** Number of evaluation results in the report period. */
@@ -39148,12 +39220,12 @@ export namespace Schemas {
*/
previous_result_rates?: EvaluationReportMetricsPreviousResultRates;
/**
- * Boolean or numeric pass percentage, excluding N/A results. Null when no numeric scores were produced.
+ * Pass percentage excluding N/A. With no applicable results, numeric and categorical reports return null; boolean reports return 0.
* @nullable
*/
pass_rate?: number | null;
/**
- * Boolean or numeric pass percentage for the previous period, or null when unavailable.
+ * Pass percentage for boolean, numeric, or categorical results in the previous period, or null when unavailable.
* @nullable
*/
previous_pass_rate?: number | null;
@@ -49696,6 +49768,7 @@ export namespace Schemas {
/**
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
*/
export type HogEvaluationOutputTypeEnum = typeof HogEvaluationOutputTypeEnum[keyof typeof HogEvaluationOutputTypeEnum];
@@ -49703,6 +49776,7 @@ export namespace Schemas {
export const HogEvaluationOutputTypeEnum = {
Boolean: 'boolean',
Numeric: 'numeric',
+ Categorical: 'categorical',
} as const;
/**
@@ -73409,7 +73483,7 @@ export namespace Schemas {
prompt: string;
} | {
/**
- * Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.
+ * Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string;
@@ -73418,24 +73492,53 @@ export namespace Schemas {
source?: 'user_messages';
};
+ export type PatchedEvaluationOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string;
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string;
+ };
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
+ */
+ export type PatchedEvaluationOutputConfigSelectionMode = typeof PatchedEvaluationOutputConfigSelectionMode[keyof typeof PatchedEvaluationOutputConfigSelectionMode];
+
+
+ export const PatchedEvaluationOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+ } as const;
+
+ /**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
*/
export type PatchedEvaluationOutputConfigPassingRule = {
/** Pass at or above (gte), or at or below (lte), the threshold. */
operator: 'gte' | 'lte';
/** Finite passing threshold within any configured score bounds. */
threshold: number;
+ } | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[];
} | null;
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}.
*/
export type PatchedEvaluationOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -73455,9 +73558,14 @@ export namespace Schemas {
*/
step?: number | null;
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: PatchedEvaluationOutputConfigOptionsItem[];
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: PatchedEvaluationOutputConfigSelectionMode;
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: PatchedEvaluationOutputConfigPassingRule;
};
@@ -73524,13 +73632,14 @@ export namespace Schemas {
evaluation_type?: EvaluationTypeEnum;
/** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: PatchedEvaluationEvaluationConfig;
- /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
* * `numeric` - Numeric
+ * * `categorical` - Categorical
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnum;
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}. */
output_config?: PatchedEvaluationOutputConfig;
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationCondition[];
@@ -101004,24 +101113,53 @@ export namespace Schemas {
temperature?: number | null;
}
+ export type TestHogRequestOutputConfigOptionsItem = {
+ /**
+ * Stable category key.
+ * @minLength 1
+ * @maxLength 128
+ * @pattern ^[a-z0-9]+(?:[_-][a-z0-9]+)*$
+ */
+ key: string;
+ /**
+ * Category display label.
+ * @minLength 1
+ * @maxLength 256
+ */
+ label: string;
+ };
+
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.
+ */
+ export type TestHogRequestOutputConfigSelectionMode = typeof TestHogRequestOutputConfigSelectionMode[keyof typeof TestHogRequestOutputConfigSelectionMode];
+
+
+ export const TestHogRequestOutputConfigSelectionMode = {
+ Single: 'single',
+ Multiple: 'multiple',
+ } as const;
+
+ /**
+ * Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.
*/
export type TestHogRequestOutputConfigPassingRule = {
/** Pass at or above (gte), or at or below (lte), the threshold. */
operator: 'gte' | 'lte';
/** Finite passing threshold within any configured score bounds. */
threshold: number;
+ } | {
+ /** Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes. */
+ categories: string[];
} | null;
/**
- * Output settings used to validate the preview, including numeric bounds and allows_na.
+ * Output settings used to validate the preview, including bounds, categories, and allows_na.
*/
export type TestHogRequestOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
- /** Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ /** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
* Inclusive minimum numeric score. Omit for no lower bound.
@@ -101041,9 +101179,14 @@ export namespace Schemas {
*/
step?: number | null;
/**
- * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
- * @nullable
+ * Categorical output options. Keys identify stored results; labels are displayed to users.
+ * @minItems 1
+ * @maxItems 100
*/
+ options?: TestHogRequestOutputConfigOptionsItem[];
+ /** Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single. */
+ selection_mode?: TestHogRequestOutputConfigSelectionMode;
+ /** Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule. */
passing_rule?: TestHogRequestOutputConfigPassingRule;
};
@@ -101065,15 +101208,16 @@ export namespace Schemas {
}
export interface TestHogRequest {
- /** Expected output: boolean or numeric. Sentiment is not supported by Hog.
+ /** Expected output: boolean, numeric, or categorical. Sentiment is not supported by Hog.
*
* * `boolean` - Boolean (Pass/Fail)
- * * `numeric` - Numeric */
+ * * `numeric` - Numeric
+ * * `categorical` - Categorical */
output_type?: HogEvaluationOutputTypeEnum;
- /** Output settings used to validate the preview, including numeric bounds and allows_na. */
+ /** Output settings used to validate the preview, including bounds, categories, and allows_na. */
output_config?: TestHogRequestOutputConfig;
/**
- * Hog source code to test. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.
+ * Hog source code to test. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string;
@@ -101098,6 +101242,11 @@ export namespace Schemas {
}
export interface TestHogResultItem {
+ /**
+ * Selected category keys. An empty list is an applicable result; null means no categorical result was produced.
+ * @nullable
+ */
+ categories?: string[] | null;
/**
* Raw numeric score, or null when no numeric score was produced.
* @nullable
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 8bae0b433737..b3fb1af44057 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -563,6 +563,13 @@ export const evaluationsCreateBodyNameMax = 400
export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsCreateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsCreateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsCreateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsCreateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsCreateBodyOutputConfigOptionsMax = 100
+
export const evaluationsCreateBodyConditionsItemIdMax = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -611,7 +618,7 @@ export const EvaluationsCreateBody = () => zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
}),
zod.object({
@@ -628,10 +635,12 @@ export const EvaluationsCreateBody = () => zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'numeric', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'categorical', 'sentiment'])
.describe(
- "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment"
+ '\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment'
+ )
+ .describe(
+ "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment"
),
output_config: zod
.object({
@@ -643,7 +652,7 @@ export const EvaluationsCreateBody = () => zod
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -652,23 +661,61 @@ export const EvaluationsCreateBody = () => zod
.gt(evaluationsCreateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsCreateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsCreateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsCreateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsCreateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe(
+ 'Categorical output options. Keys identify stored results; labels are displayed to users.'
+ ),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod
- .number()
- .describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
.describe(
- "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}."
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}."
),
conditions: zod
.array(
@@ -810,6 +857,13 @@ export const evaluationsPartialUpdateBodyNameMax = 400
export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsPartialUpdateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsPartialUpdateBodyOutputConfigOptionsMax = 100
+
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -859,7 +913,7 @@ export const EvaluationsPartialUpdateBody = () => zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
}),
zod.object({
@@ -876,11 +930,13 @@ export const EvaluationsPartialUpdateBody = () => zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'numeric', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'categorical', 'sentiment'])
+ .describe(
+ '\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment'
+ )
.optional()
.describe(
- "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment"
+ "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical\n\* `sentiment` - Sentiment"
),
output_config: zod
.object({
@@ -892,7 +948,7 @@ export const EvaluationsPartialUpdateBody = () => zod
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -901,23 +957,61 @@ export const EvaluationsPartialUpdateBody = () => zod
.gt(evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsPartialUpdateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsPartialUpdateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsPartialUpdateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe(
+ 'Categorical output options. Keys identify stored results; labels are displayed to users.'
+ ),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod
- .number()
- .describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
.describe(
- "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}."
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min\/max\/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}."
),
conditions: zod
.array(
@@ -1062,6 +1156,13 @@ export const EvaluationsTestHogCreateParams = () => zod.object({
export const evaluationsTestHogCreateBodyOutputTypeDefault = `boolean`
export const evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin = 0
+export const evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyMax = 128
+
+export const evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyRegExp = new RegExp('^[a-z0-9]+(?:[_-][a-z0-9]+)\*$')
+export const evaluationsTestHogCreateBodyOutputConfigOptionsItemLabelMax = 256
+
+export const evaluationsTestHogCreateBodyOutputConfigOptionsMax = 100
+
export const evaluationsTestHogCreateBodySampleCountDefault = 5
export const evaluationsTestHogCreateBodySampleCountMax = 10
@@ -1077,11 +1178,11 @@ export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax =
export const EvaluationsTestHogCreateBody = () => zod.object({
output_type: zod
- .enum(['boolean', 'numeric'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric')
+ .enum(['boolean', 'numeric', 'categorical'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical')
.default(evaluationsTestHogCreateBodyOutputTypeDefault)
.describe(
- 'Expected output: boolean or numeric. Sentiment is not supported by Hog.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric'
+ 'Expected output: boolean, numeric, or categorical. Sentiment is not supported by Hog.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `categorical` - Categorical'
),
output_config: zod
.object({
@@ -1093,7 +1194,7 @@ export const EvaluationsTestHogCreateBody = () => zod.object({
.boolean()
.optional()
.describe(
- 'Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ 'Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
),
min: zod.number().nullish().describe('Inclusive minimum numeric score. Omit for no lower bound.'),
max: zod.number().nullish().describe('Inclusive maximum numeric score. Omit for no upper bound.'),
@@ -1102,25 +1203,63 @@ export const EvaluationsTestHogCreateBody = () => zod.object({
.gt(evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin)
.nullish()
.describe('Optional positive input increment. Does not round evaluation results.'),
+ options: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .min(1)
+ .max(evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyMax)
+ .regex(evaluationsTestHogCreateBodyOutputConfigOptionsItemKeyRegExp)
+ .describe('Stable category key.'),
+ label: zod
+ .string()
+ .min(1)
+ .max(evaluationsTestHogCreateBodyOutputConfigOptionsItemLabelMax)
+ .describe('Category display label.'),
+ })
+ )
+ .min(1)
+ .max(evaluationsTestHogCreateBodyOutputConfigOptionsMax)
+ .optional()
+ .describe('Categorical output options. Keys identify stored results; labels are displayed to users.'),
+ selection_mode: zod
+ .enum(['single', 'multiple'])
+ .optional()
+ .describe(
+ 'Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.'
+ ),
passing_rule: zod
- .object({
- operator: zod
- .enum(['gte', 'lte'])
- .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
- threshold: zod.number().describe('Finite passing threshold within any configured score bounds.'),
- })
- .nullish()
+ .union([
+ zod.object({
+ operator: zod
+ .enum(['gte', 'lte'])
+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),
+ threshold: zod
+ .number()
+ .describe('Finite passing threshold within any configured score bounds.'),
+ }),
+ zod.object({
+ categories: zod
+ .array(zod.string())
+ .describe(
+ 'Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
.describe(
- 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ 'Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule.'
),
})
.optional()
- .describe('Output settings used to validate the preview, including numeric bounds and allows_na.'),
+ .describe('Output settings used to validate the preview, including bounds, categories, and allows_na.'),
source: zod
.string()
.min(1)
.describe(
- 'Hog source code to test. Must return a boolean or a finite number matching output_type, or null for allowed N\/A. Output settings determine which boolean counts as a failure.'
+ 'Hog source code to test. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N\/A. Output settings determine which boolean counts as a failure.'
),
sample_count: zod
.number()
diff --git a/services/mcp/src/lib/trace-property-allowlist.generated.ts b/services/mcp/src/lib/trace-property-allowlist.generated.ts
index c53d58cfdbcd..ef9503aabab8 100644
--- a/services/mcp/src/lib/trace-property-allowlist.generated.ts
+++ b/services/mcp/src/lib/trace-property-allowlist.generated.ts
@@ -31,6 +31,7 @@ export const AI_TAXONOMY_EVENT_PROPERTIES = [
'$ai_eval_source',
'$ai_evaluation_allows_na',
'$ai_evaluation_applicable',
+ '$ai_evaluation_categorical_result',
'$ai_evaluation_id',
'$ai_evaluation_key_id',
'$ai_evaluation_key_type',
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.json
index 6281f5f017ed..5b505bb2955f 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
@@ -75,7 +75,7 @@
{
"properties": {
"source": {
- "description": "Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.",
+ "description": "Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
"type": "string"
}
@@ -164,7 +164,7 @@
"type": "string"
},
"output_config": {
- "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}.",
+ "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}.",
"properties": {
"allows_na": {
"description": "Whether the evaluation can return N/A for non-applicable generations.",
@@ -192,6 +192,31 @@
],
"description": "Inclusive minimum numeric score. Omit for no lower bound."
},
+ "options": {
+ "description": "Categorical output options. Keys identify stored results; labels are displayed to users.",
+ "items": {
+ "properties": {
+ "key": {
+ "description": "Stable category key.",
+ "maxLength": 128,
+ "minLength": 1,
+ "pattern": "^[a-z0-9]+(?:[_-][a-z0-9]+)*$",
+ "type": "string"
+ },
+ "label": {
+ "description": "Category display label.",
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["key", "label"],
+ "type": "object"
+ },
+ "maxItems": 100,
+ "minItems": 1,
+ "type": "array"
+ },
"passing_rule": {
"anyOf": [
{
@@ -209,11 +234,29 @@
"required": ["operator", "threshold"],
"type": "object"
},
+ {
+ "properties": {
+ "categories": {
+ "description": "Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["categories"],
+ "type": "object"
+ },
{
"type": "null"
}
],
- "description": "Optional numeric passing rule. Null removes the rule; historical scores use the current rule."
+ "description": "Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule."
+ },
+ "selection_mode": {
+ "description": "Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.",
+ "enum": ["single", "multiple"],
+ "type": "string"
},
"step": {
"anyOf": [
@@ -228,15 +271,15 @@
"description": "Optional positive input increment. Does not round evaluation results."
},
"true_is_failure": {
- "description": "Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
+ "description": "Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
"type": "boolean"
}
},
"type": "object"
},
"output_type": {
- "description": "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `numeric` - Numeric\n* `sentiment` - Sentiment",
- "enum": ["boolean", "numeric", "sentiment"],
+ "description": "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `numeric` - Numeric\n* `categorical` - Categorical\n* `sentiment` - Sentiment",
+ "enum": ["boolean", "numeric", "categorical", "sentiment"],
"type": "string"
},
"target": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
index 777e7b66f4df..85654a61d5ee 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
@@ -18,7 +18,7 @@
"type": "array"
},
"output_config": {
- "description": "Output settings used to validate the preview, including numeric bounds and allows_na.",
+ "description": "Output settings used to validate the preview, including bounds, categories, and allows_na.",
"properties": {
"allows_na": {
"description": "Whether the evaluation can return N/A for non-applicable generations.",
@@ -46,6 +46,31 @@
],
"description": "Inclusive minimum numeric score. Omit for no lower bound."
},
+ "options": {
+ "description": "Categorical output options. Keys identify stored results; labels are displayed to users.",
+ "items": {
+ "properties": {
+ "key": {
+ "description": "Stable category key.",
+ "maxLength": 128,
+ "minLength": 1,
+ "pattern": "^[a-z0-9]+(?:[_-][a-z0-9]+)*$",
+ "type": "string"
+ },
+ "label": {
+ "description": "Category display label.",
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["key", "label"],
+ "type": "object"
+ },
+ "maxItems": 100,
+ "minItems": 1,
+ "type": "array"
+ },
"passing_rule": {
"anyOf": [
{
@@ -63,11 +88,29 @@
"required": ["operator", "threshold"],
"type": "object"
},
+ {
+ "properties": {
+ "categories": {
+ "description": "Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["categories"],
+ "type": "object"
+ },
{
"type": "null"
}
],
- "description": "Optional numeric passing rule. Null removes the rule; historical scores use the current rule."
+ "description": "Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule."
+ },
+ "selection_mode": {
+ "description": "Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.",
+ "enum": ["single", "multiple"],
+ "type": "string"
},
"step": {
"anyOf": [
@@ -82,7 +125,7 @@
"description": "Optional positive input increment. Does not round evaluation results."
},
"true_is_failure": {
- "description": "Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
+ "description": "Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
"type": "boolean"
}
},
@@ -90,8 +133,8 @@
},
"output_type": {
"default": "boolean",
- "description": "Expected output: boolean or numeric. Sentiment is not supported by Hog.\n\n* `boolean` - Boolean (Pass/Fail)\n* `numeric` - Numeric",
- "enum": ["boolean", "numeric"],
+ "description": "Expected output: boolean, numeric, or categorical. Sentiment is not supported by Hog.\n\n* `boolean` - Boolean (Pass/Fail)\n* `numeric` - Numeric\n* `categorical` - Categorical",
+ "enum": ["boolean", "numeric", "categorical"],
"type": "string"
},
"sample_count": {
@@ -102,7 +145,7 @@
"type": "number"
},
"source": {
- "description": "Hog source code to test. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.",
+ "description": "Hog source code to test. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
"type": "string"
},
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.json
index 89c17e47bf32..ef4126cba5f2 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
@@ -74,7 +74,7 @@
{
"properties": {
"source": {
- "description": "Hog source code. Must return a boolean or a finite number matching output_type, or null for allowed N/A. Output settings determine which boolean counts as a failure.",
+ "description": "Hog source code. Return a boolean, finite number, or category keys matching output_type. Categorical single selection accepts one key or a one-item list; multiple selection accepts a list, including []. Return null only for allowed N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
"type": "string"
}
@@ -167,7 +167,7 @@
"type": "string"
},
"output_config": {
- "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. Do not send true_is_failure for numeric output. For 'sentiment': {}.",
+ "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. For 'numeric': only min/max/step, allows_na, and passing_rule {operator: 'gte'|'lte', threshold}. For 'categorical': options [{key, label}], selection_mode (single or multiple), allows_na, and optional passing_rule {categories: [key]}. Do not send true_is_failure for numeric or categorical output. For 'sentiment': {}.",
"properties": {
"allows_na": {
"description": "Whether the evaluation can return N/A for non-applicable generations.",
@@ -195,6 +195,31 @@
],
"description": "Inclusive minimum numeric score. Omit for no lower bound."
},
+ "options": {
+ "description": "Categorical output options. Keys identify stored results; labels are displayed to users.",
+ "items": {
+ "properties": {
+ "key": {
+ "description": "Stable category key.",
+ "maxLength": 128,
+ "minLength": 1,
+ "pattern": "^[a-z0-9]+(?:[_-][a-z0-9]+)*$",
+ "type": "string"
+ },
+ "label": {
+ "description": "Category display label.",
+ "maxLength": 256,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["key", "label"],
+ "type": "object"
+ },
+ "maxItems": 100,
+ "minItems": 1,
+ "type": "array"
+ },
"passing_rule": {
"anyOf": [
{
@@ -212,11 +237,29 @@
"required": ["operator", "threshold"],
"type": "object"
},
+ {
+ "properties": {
+ "categories": {
+ "description": "Passing category keys. With keys selected, results must be non-empty and contain only these keys. If no passing keys are selected, only an empty result passes.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["categories"],
+ "type": "object"
+ },
{
"type": "null"
}
],
- "description": "Optional numeric passing rule. Null removes the rule; historical scores use the current rule."
+ "description": "Optional numeric or categorical passing rule. Null removes the rule; historical results use the current rule."
+ },
+ "selection_mode": {
+ "description": "Select one category or multiple categories. Multiple selection allows an empty result. Defaults to single.",
+ "enum": ["single", "multiple"],
+ "type": "string"
},
"step": {
"anyOf": [
@@ -231,15 +274,15 @@
"description": "Optional positive input increment. Does not round evaluation results."
},
"true_is_failure": {
- "description": "Boolean output only. Omit for numeric and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
+ "description": "Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
"type": "boolean"
}
},
"type": "object"
},
"output_type": {
- "description": "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `numeric` - Numeric\n* `sentiment` - Sentiment",
- "enum": ["boolean", "numeric", "sentiment"],
+ "description": "Output format: 'boolean', 'numeric' for a finite score, 'categorical' for category keys, or 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `numeric` - Numeric\n* `categorical` - Categorical\n* `sentiment` - Sentiment",
+ "enum": ["boolean", "numeric", "categorical", "sentiment"],
"type": "string"
},
"target": {