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 numeric evaluation outputs (#103492)

Bernat Torres09030e5e6ef0
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.md
index a781587bbaba..b82963635f73 100644
--- a/docs/internal/ai-observability-judge-inputs.md
+++ b/docs/internal/ai-observability-judge-inputs.md
@@ -44,6 +44,29 @@ Users do not need to include items that already have a result to retry them.
A provider rejection of an invalid token setting does not count as a truncated reply.
The playground keeps the provider's explanation so users can correct the setting before trying again.
+## Result encoding
+
+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.
+Sentiment evaluations keep their `$ai_sentiment_*` properties.
+N/A and skipped numeric runs omit the score, while zero remains a graded result.
+
+Separate properties preserve the existing boolean property's type and saved queries.
+The numeric property uses normal numeric inference and can be aggregated in Insights.
+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`.
+
+## Run history and reports
+
+The evaluation's Runs tab defaults to the last seven days.
+Its date filter applies to both the run list and summary statistics, supports custom ranges and All time, and is preserved in the URL.
+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.
+Existing reports remain accessible through the Reports tab and the report list, detail, and history API endpoints.
+
## 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 5fcaa4e49047..6e275a23fe27 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9892,6 +9892,18 @@ snapshots:
hash: v1.k794b7964.195aa4a5a39e8f947e17fe67f5c23303b7dd0579c278907761be24a08780be92.t2Zgr2Pj-cL6F6Xx11DpcCyR1L0QQ8fD17WzQNmXbw8
scenes-app-llm-observability-evaluationreportconfig--quill--light:
hash: v1.k794b7964.e6179df07dd55d64e0140d40ac812feb4662e28e5bded7ce2cf9e2575f245626.4iGTruUDV858d17xZIUMJCG2xFeWLagkzakPS2Yw4Ps
+ scenes-app-llm-observability-evaluationresulttag--numeric--dark:
+ hash: v1.k794b7964.1bcae05742f63c4b15b94fa5c6244a87c0dc72844623fd5a33fc72c54c879e3d.yz9CWrxD2rjp0oW_PvO6xOocQQunI1_Y2ymHqgtXPJA
+ scenes-app-llm-observability-evaluationresulttag--numeric--light:
+ hash: v1.k794b7964.c23c448b50a0cb74a72e21fb5a16dbd24b90d6a3001710988f3d167ba6600f87.NIuKn2a1mky083oY1i2cHNLI2eHUh1PIRWry-7x0fN8
+ scenes-app-llm-observability-numericevaluationconfig--default--dark:
+ hash: v1.k794b7964.5efa717dee7fd925fe2b84fc86da63e6dfc99814d02dc94211113a6021a43914.ZtWJCtl75IPpnldtyrWooFB2tvg5psXqa0zFqELwMlE
+ scenes-app-llm-observability-numericevaluationconfig--default--light:
+ hash: v1.k794b7964.5d515040769bf8f5d2941b2fcd2a260e0b18c4a604344cc8ce650603d8c29a3d.KgaXSMDFPYGdcIljUTKWKROOTuOu0hjWiDTRiDmb7QY
+ scenes-app-llm-observability-numericevaluationconfig--narrow--dark:
+ hash: v1.k794b7964.5d3ea95400c9bfdf99ad885024bae82b001b3a75157cd1d330c5813507ea5db7.CUqQDU0iH8mhHDv7KNqihe1ORp6qTp44s_JexKlTbJA
+ scenes-app-llm-observability-numericevaluationconfig--narrow--light:
+ hash: v1.k794b7964.06665db1bacabdd45b8bc20b07f151cc931a7d59f014af1ed1bc1b20d76fca39.7AaRhvrE7zgHk7SBS31uAfNcm-JyzHeorWybXzX7Dfg
scenes-app-logs-logsimpactcounts--no-coverage--dark:
hash: v1.k794b7964.fcfa5be29c5721d0db9fa21ecab20f16c04a4074c9af7fb3a58311900e168a48.2eslY8aigbAuKJ2Bsn8AjSOah5Q77FoWONVdG2fb6C4
scenes-app-logs-logsimpactcounts--no-coverage--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 298b17fdbc1d..217db6ff9ddb 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -363,6 +363,7 @@ export const FEATURE_FLAGS = {
LLM_ANALYTICS_DATASETS: 'llm-analytics-datasets', // owner: #team-ai-observability #team-posthog-ai
LLM_ANALYTICS_EVAL_BACKFILLS: 'llm-analytics-eval-backfills', // owner: #team-ai-observability
LLM_ANALYTICS_EVAL_SETTLING_STRATEGY: 'llm-analytics-eval-settling-strategy', // owner: #team-ai-observability
+ LLM_ANALYTICS_NUMERIC_EVALS: 'llm-analytics-numeric-evaluations', // owner: #team-ai-observability
LLM_ANALYTICS_OFFLINE_EVALS: 'llm-analytics-offline-evals', // owner: #team-ai-observability
LLM_ANALYTICS_TAGS: 'llm-analytics-tags', // owner: #team-ai-observability
LLM_ANALYTICS_TRACE_NAVIGATION: 'llm-analytics-trace-navigation', // owner: #team-ai-observability
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index 177ad2535a96..297e1991d1be 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -353,6 +353,26 @@
],
"label": "AI Evaluation Name (LLM)"
},
+ "$ai_evaluation_numeric_result": {
+ "description": "The raw numeric score returned by an online evaluation.",
+ "examples": [
+ 0,
+ 0.75,
+ 10
+ ],
+ "label": "AI evaluation numeric result",
+ "type": "Numeric"
+ },
+ "$ai_evaluation_numeric_result_max": {
+ "description": "The configured maximum score for an online evaluation.",
+ "label": "AI evaluation numeric result maximum",
+ "type": "Numeric"
+ },
+ "$ai_evaluation_numeric_result_min": {
+ "description": "The configured minimum score for an online evaluation.",
+ "label": "AI evaluation numeric result minimum",
+ "type": "Numeric"
+ },
"$ai_evaluation_provider": {
"description": "The LLM provider used as the judge (e.g., openai, anthropic, gemini).",
"examples": [
@@ -5196,6 +5216,26 @@
],
"label": "AI Evaluation Name (LLM)"
},
+ "$ai_evaluation_numeric_result": {
+ "description": "The raw numeric score returned by an online evaluation.",
+ "examples": [
+ 0,
+ 0.75,
+ 10
+ ],
+ "label": "AI evaluation numeric result",
+ "type": "Numeric"
+ },
+ "$ai_evaluation_numeric_result_max": {
+ "description": "The configured maximum score for an online evaluation.",
+ "label": "AI evaluation numeric result maximum",
+ "type": "Numeric"
+ },
+ "$ai_evaluation_numeric_result_min": {
+ "description": "The configured minimum score for an online evaluation.",
+ "label": "AI evaluation numeric result minimum",
+ "type": "Numeric"
+ },
"$ai_evaluation_provider": {
"description": "The LLM provider used as the judge (e.g., openai, anthropic, gemini).",
"examples": [
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index 87224dc602ad..5146d4b72921 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2546,6 +2546,22 @@ 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_numeric_result": {
+ "label": "AI evaluation numeric result",
+ "description": "The raw numeric score returned by an online evaluation.",
+ "examples": [0, 0.75, 10],
+ "type": "Numeric",
+ },
+ "$ai_evaluation_numeric_result_min": {
+ "label": "AI evaluation numeric result minimum",
+ "description": "The configured minimum score for an online evaluation.",
+ "type": "Numeric",
+ },
+ "$ai_evaluation_numeric_result_max": {
+ "label": "AI evaluation numeric result maximum",
+ "description": "The configured maximum score for an online evaluation.",
+ "type": "Numeric",
+ },
"$ai_evaluation_reasoning": {
"label": "AI Evaluation Reasoning (LLM)",
"description": "The LLM's explanation for why the evaluation passed or failed.",
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 60fd07e88b15..801b8d7d6ec5 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -3,8 +3,9 @@
import time
import datetime as dt
from collections import defaultdict
+from dataclasses import replace
from itertools import batched
-from typing import TYPE_CHECKING, NamedTuple
+from typing import TYPE_CHECKING, Any, NamedTuple
from zoneinfo import ZoneInfo
from django.db.models import Q
@@ -12,6 +13,7 @@ from django.db.models import Q
import temporalio.activity
from dateutil.rrule import rrulestr
from structlog import get_logger
+from temporalio.exceptions import ApplicationError
from posthog.hogql import ast
@@ -52,6 +54,8 @@ from posthog.temporal.ai_observability.eval_reports.types import (
)
from posthog.temporal.common.heartbeat import Heartbeater
+from products.ai_observability.backend.models.evaluation_configs import evaluation_supports_reports
+
if TYPE_CHECKING:
from posthog.models import Team
@@ -604,9 +608,24 @@ async def prepare_report_context_activity(
def prepare() -> PrepareReportContextOutput:
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
- report = EvaluationReport.objects.select_related("evaluation").get(id=inputs.report_id)
+ report = EvaluationReport.objects.select_related("evaluation").filter(id=inputs.report_id).first()
+ if report is None:
+ raise ApplicationError(
+ "This evaluation report no longer exists.", type="ReportNotFound", non_retryable=True
+ )
evaluation = report.evaluation
now = dt.datetime.now(tz=dt.UTC)
+ if not evaluation_supports_reports(evaluation.output_type, evaluation.target, evaluation.output_config):
+ if not inputs.manual:
+ report.last_attempted_at = now
+ report.set_next_delivery_date()
+ 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.",
+ type="ReportNotEligible",
+ non_retryable=True,
+ )
period_end = now
@@ -654,6 +673,7 @@ async def prepare_report_context_activity(
evaluation_type=evaluation.evaluation_type,
output_type=evaluation.output_type,
true_is_failure=bool(evaluation.output_config.get("true_is_failure")),
+ output_config=evaluation.output_config,
period_start=period_start.isoformat(),
period_end=period_end.isoformat(),
previous_period_start=previous_period_start.isoformat(),
@@ -681,11 +701,22 @@ 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)
+ agent_inputs = inputs
+ if inputs.output_type == "numeric" 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):
+ raise ApplicationError(
+ "This evaluation no longer supports reports.", type="ReportNotEligible", non_retryable=True
+ )
+ agent_inputs = replace(inputs, output_config=output_config)
return (
run_eval_report_agent(
- inputs,
+ agent_inputs,
evaluation_target=evaluation_target,
detector_evaluation_ids=_load_detector_evaluation_ids(inputs.team_id),
+ numeric_output_configs=numeric_output_configs,
),
evaluation_target,
)
@@ -703,20 +734,27 @@ async def run_eval_report_agent_activity(
def _load_evaluation_target(team_id: int, evaluation_id: str) -> str:
- from products.ai_observability.backend.models.evaluations import ( # noqa: PLC0415 -- keep Django model loading inside activity execution
- Evaluation,
- )
+ from products.ai_observability.backend.models.evaluations import Evaluation
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]]:
+ 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"
+ )
+ }
+
+
def _load_detector_evaluation_ids(team_id: int) -> list[str]:
"""The generation detail tool lists every evaluation on a generation, not just this report's,
so it needs each one's polarity to label it. Read here rather than in the context activity,
which would carry the whole team's list through two Temporal payloads to reach this one."""
- from products.ai_observability.backend.models.evaluations import ( # noqa: PLC0415 -- keep Django model loading inside activity execution
- Evaluation,
- )
+ from products.ai_observability.backend.models.evaluations import Evaluation
return [
str(evaluation_id)
@@ -799,7 +837,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 == "boolean":
+ if parsed_metrics is not None and parsed_metrics.output_type in ("boolean", "numeric"):
# 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 df742bd34401..3071da3d6fa9 100644
--- a/posthog/temporal/ai_observability/eval_reports/delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py
@@ -46,6 +46,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")),
"sentiment": (("positive", "Positive"), ("neutral", "Neutral"), ("negative", "Negative")),
}
@@ -187,7 +188,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 == "boolean":
+ if metrics.output_type in ("boolean", "numeric"):
return str(count)
rate = metrics.result_rates.get(outcome)
@@ -204,7 +205,7 @@ def _format_outcome_value(metrics: EvalReportMetrics, outcome: str) -> str:
def _format_boolean_pass_rate_value(metrics: EvalReportMetrics) -> str:
value = _format_pass_rate(metrics.pass_rate)
- if metrics.previous_pass_rate is None:
+ if metrics.pass_rate is None or metrics.previous_pass_rate is None:
return value
diff = metrics.pass_rate - metrics.previous_pass_rate
@@ -231,7 +232,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 == "boolean":
+ if metrics.output_type in ("boolean", "numeric"):
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>"
@@ -246,7 +247,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 == "boolean":
+ if metrics.output_type in ("boolean", "numeric"):
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 8726bc46fa90..6bba0a5fa770 100644
--- a/posthog/temporal/ai_observability/eval_reports/output_types.py
+++ b/posthog/temporal/ai_observability/eval_reports/output_types.py
@@ -1,13 +1,17 @@
"""Trusted query definitions for evaluation report outcomes.
-Only `outcome_predicates` and `label_for` depend on the evaluation's polarity. `event_predicate`,
+Only `outcome_predicates` and `label_for` depend on the evaluation's passing rule. `event_predicate`,
`outcomes`, `result_expression`, `applicable_expression` and `score_expression` do not, so a caller
-that reads only those is correct without passing `true_is_failure`.
+that reads only those is correct without passing `true_is_failure` or `output_config`.
"""
from collections.abc import Callable, Mapping
from dataclasses import dataclass
+from posthog.hogql import ast
+
+from products.ai_observability.backend.models.evaluation_configs import NumericOutputConfig
+
SENTIMENT_LABELS = ("positive", "neutral", "negative")
@@ -21,9 +25,26 @@ class EvaluationReportOutcomeDefinition:
score_expression: str
# 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
+
+ @property
+ def query_placeholders(self) -> dict[str, ast.Constant]:
+ 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.numeric_config is not None:
+ if applicable in (False, "false"):
+ return "na"
+ if self.numeric_config.passing_rule is None:
+ return None
+ try:
+ score = NumericOutputConfig().validate_score(result)
+ except ValueError:
+ return None
+ return "pass" if self.numeric_config.passing_rule.passes(score) else "fail"
if self.passing_result is None:
return result if isinstance(result, str) and result in self.outcomes else None
if applicable is False:
@@ -84,13 +105,36 @@ _DEFINITION_BUILDERS: Mapping[str, Callable[[bool], EvaluationReportOutcomeDefin
"sentiment": _sentiment_definition,
}
-SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = tuple(_DEFINITION_BUILDERS)
+SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = (*_DEFINITION_BUILDERS, "numeric")
+
+
+def _numeric_definition(output_config: dict | None) -> EvaluationReportOutcomeDefinition:
+ config = NumericOutputConfig.model_validate(output_config or {})
+ score = "toFloat(properties.$ai_evaluation_numeric_result)"
+ applicable = "(isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != 'false')"
+ passed = failed = "false"
+ if config.passing_rule is not None:
+ passed_op, failed_op = (">=", "<") if config.passing_rule.operator == "gte" else ("<=", ">")
+ passed = f"{score} {passed_op} {{numeric_threshold}} AND {applicable}"
+ failed = f"{score} {failed_op} {{numeric_threshold}} AND {applicable}"
+ return EvaluationReportOutcomeDefinition(
+ outcomes=("pass", "fail", "na"),
+ outcome_predicates={"pass": passed, "fail": failed, "na": "properties.$ai_evaluation_applicable = 'false'"},
+ event_predicate=f"properties.$ai_evaluation_result_type = 'numeric' AND {_NOT_SKIPPED_PREDICATE}",
+ result_expression=score,
+ applicable_expression="properties.$ai_evaluation_applicable",
+ score_expression=score,
+ passing_result=None,
+ numeric_config=config,
+ )
def get_outcome_definition(
- output_type: str | None, *, true_is_failure: bool = False
+ 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 == "numeric":
+ return _numeric_definition(output_config)
try:
builder = _DEFINITION_BUILDERS[normalized_output_type]
except KeyError as error:
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 2f79275c92fe..db90717c8e44 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -56,6 +56,7 @@ def _compute_metrics(
output_type: str = "boolean",
true_is_failure: bool = False,
evaluation_target: str = GENERATION_TARGET,
+ output_config: dict[str, Any] | None = None,
) -> EvalReportMetrics | None:
"""Compute report metrics directly via HogQL (independent of agent state).
@@ -67,7 +68,7 @@ def _compute_metrics(
ts_start = _ch_ts(period_start)
ts_end = _ch_ts(period_end)
ts_prev_start = _ch_ts(previous_period_start)
- definition = get_outcome_definition(output_type, true_is_failure=true_is_failure)
+ definition = get_outcome_definition(output_type, true_is_failure=true_is_failure, output_config=output_config)
result_counts, total = _fetch_period_summary(
team_id, evaluation_id, ts_start, ts_end, definition, evaluation_target
@@ -78,6 +79,7 @@ def _compute_metrics(
return EvalReportMetrics(
output_type=output_type,
+ output_config=output_config or {},
total_runs=total,
result_counts=result_counts,
period_start=period_start,
@@ -128,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 == "boolean":
+ 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"):
trend = ""
- if metrics.previous_pass_rate is not None:
+ if metrics.pass_rate is not None and metrics.previous_pass_rate is not None:
diff = metrics.pass_rate - metrics.previous_pass_rate
if diff > 1:
trend = f" (up from {metrics.previous_pass_rate}%)"
@@ -269,6 +273,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,
) -> EvalReportContent:
"""Run the evaluation report agent and return the generated content.
@@ -292,6 +297,7 @@ def run_eval_report_agent(
inputs.previous_period_start,
output_type=inputs.output_type,
true_is_failure=inputs.true_is_failure,
+ output_config=inputs.output_config,
evaluation_target=evaluation_target,
)
@@ -342,6 +348,7 @@ def run_eval_report_agent(
period_end=inputs.period_end,
report_prompt_guidance=inputs.report_prompt_guidance,
true_is_failure=inputs.true_is_failure,
+ output_config=inputs.output_config,
)
agent = create_react_agent(
@@ -365,7 +372,9 @@ def run_eval_report_agent(
"evaluation_target": evaluation_target,
"output_type": inputs.output_type,
"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},
"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 bfd5dbeaed6c..2777419650e3 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
@@ -87,8 +87,9 @@ def build_eval_report_system_prompt(
evaluation_target: str = "generation",
report_prompt_guidance: str = "",
true_is_failure: bool = False,
+ output_config: dict | None = None,
) -> str:
- definition = get_outcome_definition(output_type, true_is_failure=true_is_failure)
+ definition = get_outcome_definition(output_type, true_is_failure=true_is_failure, output_config=output_config)
description_section = f"Description: {evaluation_description}\n" if evaluation_description else ""
prompt_section = f"Evaluation prompt/criteria:\n```\n{evaluation_prompt}\n```\n" if evaluation_prompt else ""
guidance_section = ""
@@ -134,9 +135,20 @@ 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 == "boolean":
+ elif output_type in ("boolean", "numeric"):
evaluated_unit = get_target_descriptor(evaluation_target).unit_label
- if true_is_failure:
+ if output_type == "numeric":
+ rule = definition.numeric_config.passing_rule if definition.numeric_config else None
+ if rule is None:
+ raise ValueError("Numeric reports require a passing rule")
+ operator = ">=" if rule.operator == "gte" else "<="
+ result_semantics = (
+ f"The evaluation returns a numeric score. Scores {operator} {rule.threshold} pass; other scores fail. "
+ "Both periods use this same passing rule. N/A results do not count toward the pass rate. "
+ "Interpret the raw score using the evaluation criteria; it is not a normalized percentage. "
+ f"Score 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 "
"condition it looks for, so it is reported as a fail, and a false result is reported as a pass. "
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 041e5256e003..2739697ad682 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
@@ -58,18 +58,18 @@ def calculate_result_rates(
@overload
-def calculate_boolean_pass_rate(counts: dict[str, int], *, empty_as_none: Literal[False] = False) -> float: ...
+def calculate_pass_rate(counts: dict[str, int], *, empty_as_none: Literal[False] = False) -> float: ...
@overload
-def calculate_boolean_pass_rate(counts: dict[str, int], *, empty_as_none: Literal[True]) -> float | None: ...
+def calculate_pass_rate(counts: dict[str, int], *, empty_as_none: Literal[True]) -> float | None: ...
@overload
-def calculate_boolean_pass_rate(counts: dict[str, int], *, empty_as_none: bool) -> float | None: ...
+def calculate_pass_rate(counts: dict[str, int], *, empty_as_none: bool) -> float | None: ...
-def calculate_boolean_pass_rate(counts: dict[str, int], *, empty_as_none: bool = False) -> float | None:
+def calculate_pass_rate(counts: dict[str, int], *, empty_as_none: bool = False) -> float | None:
pass_count = counts.get("pass", 0)
applicable_count = pass_count + counts.get("fail", 0)
if applicable_count == 0:
@@ -147,7 +147,7 @@ class ReportSection:
)
-@dataclass
+@dataclass(frozen=False)
class EvalReportMetrics:
"""Structured metrics computed mechanically from ClickHouse.
@@ -157,6 +157,7 @@ class EvalReportMetrics:
"""
output_type: str = "boolean"
+ output_config: dict = field(default_factory=dict)
total_runs: int = 0
result_counts: dict[str, int] = field(default_factory=dict)
result_rates: dict[str, float] = field(default_factory=dict)
@@ -165,7 +166,7 @@ class EvalReportMetrics:
previous_total_runs: int | None = None
previous_result_counts: dict[str, int] | None = None
previous_result_rates: dict[str, float] | None = None
- pass_rate: float = field(init=False, default=0.0)
+ pass_rate: float | None = field(init=False, default=0.0)
previous_pass_rate: float | None = None
def __post_init__(self) -> None:
@@ -201,10 +202,10 @@ class EvalReportMetrics:
if outcome in definition.outcomes
}
- if self.output_type == "boolean":
- self.pass_rate = calculate_boolean_pass_rate(self.result_counts)
+ 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.previous_result_counts is not None:
- self.previous_pass_rate = calculate_boolean_pass_rate(self.previous_result_counts, empty_as_none=True)
+ self.previous_pass_rate = calculate_pass_rate(self.previous_result_counts, empty_as_none=True)
else:
self.previous_pass_rate = None
@@ -220,13 +221,15 @@ class EvalReportMetrics:
"previous_result_counts": self.previous_result_counts,
"previous_result_rates": self.previous_result_rates,
}
- if self.output_type == "boolean":
+ if self.output_type in ("boolean", "numeric"):
metrics.update(
{
"pass_rate": self.pass_rate,
"previous_pass_rate": self.previous_pass_rate,
}
)
+ if self.output_type == "numeric":
+ metrics["output_config"] = self.output_config
return metrics
@staticmethod
@@ -242,6 +245,7 @@ class EvalReportMetrics:
metrics = EvalReportMetrics(
output_type=output_type,
+ output_config=dict(data.get("output_config") or {}),
total_runs=data.get("total_runs", 0),
result_counts=result_counts,
result_rates=dict(data.get("result_rates") or {}),
@@ -256,9 +260,9 @@ class EvalReportMetrics:
),
previous_pass_rate=data.get("previous_pass_rate"),
)
- if metrics.output_type == "boolean" and data.get("pass_rate") is not None:
+ if metrics.output_type in ("boolean", "numeric") and data.get("pass_rate") is not None:
metrics.pass_rate = float(data["pass_rate"])
- if metrics.output_type == "boolean" and data.get("previous_pass_rate") is not None:
+ if metrics.output_type in ("boolean", "numeric") and data.get("previous_pass_rate") is not None:
metrics.previous_pass_rate = float(data["previous_pass_rate"])
return metrics
@@ -267,6 +271,7 @@ _LEGACY_BOOLEAN_COUNT_FIELDS = frozenset({"pass_count", "fail_count", "na_count"
_KNOWN_METRIC_FIELDS = {
+ "output_config",
"output_type",
"total_runs",
"result_counts",
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 bf2fc9e5ef7f..8d75faf72d41 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
@@ -1,6 +1,6 @@
"""State definitions for the evaluation report agent."""
-from typing import Annotated, TypedDict
+from typing import Annotated, Any, TypedDict
from langgraph.graph.message import add_messages
from langgraph.managed import RemainingSteps
@@ -33,7 +33,9 @@ class EvalReportAgentState(TypedDict):
evaluation_target: str
output_type: str
true_is_failure: bool
+ output_config: dict[str, Any]
detector_evaluation_ids: list[str]
+ numeric_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 d6610745b1a7..2a3c23346871 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,6 +19,25 @@ 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}}
+ metrics = EvalReportMetrics(
+ output_type="numeric",
+ output_config=config,
+ total_runs=5,
+ result_counts={"pass": 3, "fail": 1, "na": 1},
+ previous_result_counts={"pass": 1, "fail": 1, "na": 2},
+ )
+ stored = metrics.to_dict()
+ self.assertEqual(stored["pass_rate"], 75)
+ self.assertEqual(stored["previous_pass_rate"], 50)
+ 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}
+ )
+ self.assertIsNone(no_scores.to_dict()["pass_rate"])
+
def test_backend_reportability_matches_report_adapters(self):
self.assertSetEqual(set(REPORTABLE_OUTPUT_TYPES), set(SUPPORTED_EVAL_REPORT_OUTPUT_TYPES))
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 7b565c8d4e38..a42f0082316a 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
@@ -357,7 +357,7 @@ class TestTargetAwareEvalResults(SimpleTestCase):
def test_sentiment_list_omits_classifier_reasoning(self, mock_execute_hogql):
mock_execute_hogql.side_effect = [
[[1]],
- [[_VALID_GEN_ID, "negative", None, 0.91, "identical classifier reasoning"]],
+ [[_VALID_GEN_ID, "negative", None, 0.9123456789, "identical classifier reasoning"]],
]
result = _list_all_eval_results_fn(state=self._state("generation", "sentiment"))
@@ -365,6 +365,16 @@ class TestTargetAwareEvalResults(SimpleTestCase):
self.assertIn(f"negative (0.91) | {_VALID_GEN_ID}", result)
self.assertNotIn("classifier reasoning", result)
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_numeric_list_preserves_small_scores(self, mock_execute_hogql):
+ mock_execute_hogql.side_effect = [[[1]], [[_VALID_GEN_ID, 0.00014, True, 0.00014, "cost"]]]
+ state = self._state("generation", "numeric")
+ state["output_config"] = {"passing_rule": {"operator": "lte", "threshold": 0.001}}
+
+ result = _list_all_eval_results_fn(state=state)
+
+ self.assertIn(f"pass (0.00014) | {_VALID_GEN_ID}", result)
+
@patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
def test_sentiment_sample_orders_by_score_and_omits_reasoning(self, mock_execute_hogql):
mock_execute_hogql.return_value = [[_VALID_GEN_ID, "negative", "identical classifier reasoning", None, 0.91]]
@@ -1369,6 +1379,16 @@ 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"]]
+ configs = {
+ "high": {"passing_rule": {"operator": "gte", "threshold": 7}},
+ "low": {"passing_rule": {"operator": "lte", "threshold": 7}},
+ }
+ labeled = _label_generation_evals(rows, set(), configs)
+ 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)
ROWS: list[list[object]] = [
["detector-eval", "boolean", True, None, None, "struggled", None],
@@ -1389,6 +1409,6 @@ class TestLabelGenerationEvals(SimpleTestCase):
self.assertEqual(outcomes, {"detector-eval": "pass", "quality-eval": "pass", "sentiment-eval": "negative"})
def test_unsupported_output_type_is_dropped(self):
- labeled = _label_generation_evals([["numeric-eval", "numeric", 1, None, None, "", None]], set())
+ labeled = _label_generation_evals([["unknown-eval", "unknown", 1, None, None, "", None]], set())
self.assertEqual(labeled, [])
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 d118fa716182..070c5dd149cb 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -35,7 +35,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
Citation,
EvalReportGenerationStatus,
ReportSection,
- calculate_boolean_pass_rate,
+ calculate_pass_rate,
calculate_result_rates,
citation_wrappers,
normalize_metrics_payload,
@@ -210,7 +210,9 @@ _TARGET_LOOKUP_TS_END_SENTINEL = "2099-01-01T00:00:00+00:00"
def _definition_from_state(state: dict) -> tuple[str, EvaluationReportOutcomeDefinition]:
"""Resolve the report's output type and outcome definition. The only reader of the state's polarity."""
output_type = state.get("output_type") or "boolean"
- return output_type, get_outcome_definition(output_type, true_is_failure=bool(state.get("true_is_failure")))
+ return output_type, get_outcome_definition(
+ output_type, true_is_failure=bool(state.get("true_is_failure")), output_config=state.get("output_config")
+ )
def _summary_select_sql(definition: EvaluationReportOutcomeDefinition) -> str:
@@ -401,6 +403,7 @@ def _fetch_period_summary(
AND timestamp < {{ts_end}}
""",
placeholders={
+ **definition.query_placeholders,
"evaluation_id": ast.Constant(value=evaluation_id),
"ts_start": ast.Constant(value=ts_start),
"ts_end": ast.Constant(value=ts_end),
@@ -422,8 +425,10 @@ def _period_summary_dict(
"result_counts": result_counts,
"result_rates": result_rates,
}
- if output_type == "boolean":
- summary["pass_rate"] = calculate_boolean_pass_rate(result_counts, empty_as_none=empty_rates_as_none)
+ if output_type in ("boolean", "numeric"):
+ summary["pass_rate"] = calculate_pass_rate(
+ result_counts, empty_as_none=empty_rates_as_none or output_type == "numeric"
+ )
return summary
@@ -503,6 +508,7 @@ def get_result_distribution_over_time(
ORDER BY bucket
""",
placeholders={
+ **definition.query_placeholders,
"evaluation_id": ast.Constant(value=evaluation_id),
"ts_start": ast.Constant(value=ts_start),
"ts_end": ast.Constant(value=ts_end),
@@ -544,6 +550,7 @@ def list_all_eval_results(
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
shared_placeholders = {
+ **definition.query_placeholders,
"evaluation_id": ast.Constant(value=evaluation_id),
"ts_start": ast.Constant(value=ts_start),
"ts_end": ast.Constant(value=ts_end),
@@ -599,7 +606,9 @@ def list_all_eval_results(
for row in rows:
target_id = str(row[0]) if row[0] else "?"
outcome = definition.label_for(row[1], row[2]) or "?"
- score = f" ({row[3]:.2f})" if isinstance(row[3], int | float) else ""
+ score = ""
+ if isinstance(row[3], int | float):
+ score = f" ({row[3]})" if output_type == "numeric" else f" ({row[3]:.2f})"
fields = [f"{outcome}{score}", target_id]
if output_type != "sentiment":
reasoning = (row[4] or "")[:max_reasoning_length]
@@ -624,13 +633,13 @@ def sample_eval_results(
) -> str:
"""Sample evaluation runs with target ID and outcome.
- Boolean results include reasoning. Sentiment results include scores without
- classifier reasoning and can be ordered by score.
+ Boolean and numeric results include reasoning. Score ordering returns the worst
+ numeric scores or the highest-confidence sentiment labels first.
Args:
outcome: "all" or one of the output type's supported outcomes
limit: Maximum number of results to return (default 50)
- order_by: "recent" or "score"; score ordering is only available for sentiment
+ order_by: "recent" or "score"; score ordering supports numeric and sentiment results
"""
limit = min(max(1, limit), 500)
team_id = state["team_id"]
@@ -639,9 +648,18 @@ def sample_eval_results(
ts_end = _ch_ts(state["period_end"])
output_type, definition = _definition_from_state(state)
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
- if order_by == "score" and output_type != "sentiment":
- return json.dumps({"error": "Score ordering is only available for sentiment results"})
- order_clause = "ORDER BY score DESC, timestamp DESC" if order_by == "score" else "ORDER BY timestamp DESC"
+ if order_by == "score" and output_type not in ("sentiment", "numeric"):
+ return json.dumps({"error": "Score ordering is only available for sentiment and numeric results"})
+ score_direction = (
+ "ASC"
+ if definition.numeric_config
+ and definition.numeric_config.passing_rule
+ and definition.numeric_config.passing_rule.operator == "gte"
+ else "DESC"
+ )
+ order_clause = (
+ f"ORDER BY score {score_direction}, timestamp DESC" if order_by == "score" else "ORDER BY timestamp DESC"
+ )
# Whitelisted filter fragment: outcome predicates come only from the trusted
# outcome definition, never directly from the LLM-controlled argument.
@@ -673,6 +691,7 @@ def sample_eval_results(
LIMIT {{limit}}
""",
placeholders={
+ **definition.query_placeholders,
"evaluation_id": ast.Constant(value=evaluation_id),
"ts_start": ast.Constant(value=ts_start),
"ts_end": ast.Constant(value=ts_end),
@@ -688,9 +707,9 @@ def sample_eval_results(
target_id_key: str(row[0]) if row[0] else "",
"outcome": definition.label_for(row[1], row[3]),
}
- if output_type == "sentiment":
+ if output_type in ("sentiment", "numeric"):
entry["score"] = row[4]
- else:
+ if output_type != "sentiment":
entry["reasoning"] = row[2] or ""
result.append(entry)
@@ -810,7 +829,9 @@ def sample_generation_details(
def _label_generation_evals(
- eval_rows: Sequence[Sequence[object]], detector_evaluation_ids: Container[str]
+ eval_rows: Sequence[Sequence[object]],
+ detector_evaluation_ids: Container[str],
+ numeric_output_configs: dict[str, dict] | None = None,
) -> list[dict]:
"""Label every evaluation on one generation, each by its own polarity."""
labeled = []
@@ -818,18 +839,22 @@ def _label_generation_evals(
output_type = str(row[1]) if row[1] else "boolean"
evaluation_id = str(row[0]) if row[0] else ""
try:
- definition = get_outcome_definition(output_type, true_is_failure=evaluation_id in detector_evaluation_ids)
+ definition = get_outcome_definition(
+ output_type,
+ true_is_failure=evaluation_id in detector_evaluation_ids,
+ output_config=(numeric_output_configs or {}).get(evaluation_id),
+ )
except ValueError:
continue
- raw_result = row[3] if output_type == "sentiment" else row[2]
+ 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]),
"reasoning": row[5] or "",
}
- if output_type == "sentiment":
- entry["score"] = row[4]
+ if output_type in ("sentiment", "numeric"):
+ entry["score"] = row[7] if output_type == "numeric" else row[4]
labeled.append(entry)
return labeled
@@ -933,7 +958,8 @@ def get_generation_detail(
properties.$ai_sentiment_label as sentiment_label,
properties.$ai_sentiment_score as sentiment_score,
properties.$ai_evaluation_reasoning as reasoning,
- properties.$ai_evaluation_applicable as applicable
+ properties.$ai_evaluation_applicable as applicable,
+ toFloat(properties.$ai_evaluation_numeric_result) as numeric_score
FROM events
WHERE event = '$ai_evaluation'
AND properties.$ai_target_event_id = {generation_id}
@@ -945,7 +971,9 @@ def get_generation_detail(
placeholders=shared_placeholders,
)
- evals = _label_generation_evals(eval_rows, set(state.get("detector_evaluation_ids") or []))
+ evals = _label_generation_evals(
+ eval_rows, set(state.get("detector_evaluation_ids") or []), state.get("numeric_output_configs")
+ )
result: dict = {
"generation_id": str(row[0]) if row[0] else "",
@@ -1377,7 +1405,7 @@ def list_recent_report_runs(
}
if "result_rates" in normalized_metrics:
entry["result_rates"] = normalized_metrics["result_rates"]
- if output_type == "boolean" and "pass_rate" in normalized_metrics:
+ if output_type in ("boolean", "numeric") and "pass_rate" in normalized_metrics:
entry["pass_rate"] = normalized_metrics["pass_rate"]
result.append(entry)
@@ -1475,6 +1503,7 @@ def get_top_outcome_reasons(
LIMIT {{limit}}
""",
placeholders={
+ **definition.query_placeholders,
"evaluation_id": ast.Constant(value=evaluation_id),
"ts_start": ast.Constant(value=ts_start),
"ts_end": ast.Constant(value=ts_end),
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 e63bc139423b..4c4104eaf234 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -9,13 +9,14 @@ from django.utils import timezone
from asgiref.sync import sync_to_async
from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.visitor import TraversingVisitor
from posthog.exceptions import ClickHouseQueryTimeOut
-from posthog.models import Team
+from posthog.models import PropertyDefinition, Team
from posthog.temporal.ai_observability.eval_reports.activities import (
_check_count_triggered_eval_report_sync,
_check_count_triggered_eval_reports_batch,
@@ -36,6 +37,7 @@ from posthog.temporal.ai_observability.eval_reports.constants import (
COUNT_TRIGGER_QUERY_RETRY_MAX_EXECUTION_TIME_SECONDS,
COUNT_TRIGGER_QUERY_TOTAL_BUDGET_SECONDS,
)
+from posthog.temporal.ai_observability.eval_reports.report_agent.graph import _compute_metrics
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
from posthog.temporal.ai_observability.eval_reports.types import (
PrepareReportContextInput,
@@ -102,12 +104,18 @@ class TestEvaluationTargetLoading(BaseTest):
@pytest.mark.parametrize(
- ("output_type", "evaluation_target"),
- [("sentiment", "generation"), ("boolean", "trace")],
+ ("output_type", "evaluation_target", "output_config"),
+ [
+ ("sentiment", "generation", {}),
+ ("boolean", "trace", {}),
+ ("numeric", "generation", {}),
+ ("numeric", "generation", None),
+ ("numeric", "generation", {"passing_rule": {"operator": "gte", "threshold": 8}}),
+ ],
)
@pytest.mark.asyncio
async def test_run_agent_activity_loads_target_and_forwards_output_type(
- output_type: str, evaluation_target: str
+ output_type: str, evaluation_target: str, output_config: dict | None
) -> None:
@asynccontextmanager
async def noop_heartbeater():
@@ -123,6 +131,7 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
evaluation_prompt="",
evaluation_type="sentiment",
output_type=output_type,
+ output_config=output_config or {},
period_start="2026-07-01T00:00:00+00:00",
period_end="2026-07-02T00:00:00+00:00",
previous_period_start="2026-06-30T00:00:00+00:00",
@@ -147,13 +156,31 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
"posthog.temporal.ai_observability.eval_reports.activities._load_detector_evaluation_ids",
return_value=["detector-id"],
) as load_detectors,
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.activities._load_numeric_output_configs",
+ return_value={"evaluation-id": {"passing_rule": {"operator": "gte", "threshold": 7}}}
+ if output_config is not None
+ else {},
+ ),
):
+ if output_config is None:
+ with pytest.raises(ApplicationError) as error:
+ await run_eval_report_agent_activity(inputs)
+ assert error.value.type == "ReportNotEligible"
+ assert error.value.non_retryable
+ run_agent.assert_not_called()
+ return
result = await run_eval_report_agent_activity(inputs)
assert result.content["metrics"]["output_type"] == output_type
assert result.content["evaluation_target"] == evaluation_target
assert result.generation_status == "completed"
- assert run_agent.call_args.args[0] is inputs
+ if output_type == "numeric":
+ assert run_agent.call_args.args[0].output_config == (
+ output_config or {"passing_rule": {"operator": "gte", "threshold": 7}}
+ )
+ else:
+ assert run_agent.call_args.args[0] is inputs
assert run_agent.call_args.kwargs["evaluation_target"] == evaluation_target
assert run_agent.call_args.kwargs["detector_evaluation_ids"] == ["detector-id"]
load_target.assert_called_once_with(inputs.team_id, inputs.evaluation_id)
@@ -428,15 +455,20 @@ class TestPrepareReportContext(BaseTest):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_prepare_activity_reads_detector_polarity_from_evaluation(team, user) -> None:
[email protected]("remove_passing_rule,manual", [(False, False), (True, False), (True, True)])
+async def test_prepare_activity_reads_current_reportability_and_polarity(
+ team, user, remove_passing_rule, manual
+) -> None:
def _create_report() -> EvaluationReport:
evaluation = Evaluation.objects.create(
team=team,
name="Detector Eval",
evaluation_type="llm_judge",
evaluation_config={"prompt": "test prompt"},
- output_type="boolean",
- output_config={"true_is_failure": True},
+ output_type="numeric" if remove_passing_rule else "boolean",
+ output_config={"passing_rule": {"operator": "gte", "threshold": 7}}
+ if remove_passing_rule
+ else {"true_is_failure": True},
enabled=True,
created_by=user,
conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
@@ -452,9 +484,29 @@ async def test_prepare_activity_reads_detector_polarity_from_evaluation(team, us
report = await sync_to_async(_create_report)()
- context = await prepare_report_context_activity(PrepareReportContextInput(report_id=str(report.id)))
-
- assert context.true_is_failure is True
+ if remove_passing_rule:
+ await sync_to_async(Evaluation.objects.filter(id=report.evaluation_id).update)(
+ output_config={"passing_rule": None}
+ )
+ inputs = PrepareReportContextInput(report_id=str(report.id), manual=manual)
+ if remove_passing_rule:
+ next_delivery_date = report.next_delivery_date
+ with pytest.raises(ApplicationError, match="set a passing rule") as error:
+ await prepare_report_context_activity(inputs)
+ assert error.value.non_retryable
+ assert error.value.type == "ReportNotEligible"
+ await sync_to_async(report.refresh_from_db)()
+ assert report.last_delivered_at is None
+ if manual:
+ assert report.next_delivery_date == next_delivery_date
+ assert report.last_attempted_at is None
+ else:
+ assert report.next_delivery_date is not None
+ assert report.next_delivery_date > timezone.now()
+ assert report.last_attempted_at is not None
+ else:
+ context = await prepare_report_context_activity(inputs)
+ assert context.true_is_failure is True
class TestCountTriggeredReportChecks(BaseTest):
@@ -792,6 +844,57 @@ class TestPeriodForScheduledReport(BaseTest):
self.assertEqual(period, dt.timedelta(hours=23))
+class TestEvaluationReportResultMetrics(ClickhouseTestMixin, BaseTest):
+ @parameterized.expand(
+ [("registered", True, True), ("unregistered_applicable", False, True), ("unregistered", False, False)]
+ )
+ def test_numeric_reports_classify_real_scores_and_exclude_skips(
+ self, _name: str, registered: bool, score_registered: bool
+ ) -> None:
+ if score_registered:
+ PropertyDefinition.objects.create(
+ team=self.team, name="$ai_evaluation_numeric_result", property_type="Numeric", is_numerical=True
+ )
+ if registered:
+ PropertyDefinition.objects.create(team=self.team, name="$ai_evaluation_applicable", property_type="Boolean")
+ start = dt.datetime(2026, 7, 1, tzinfo=dt.UTC)
+ rows: list[dict[str, object]] = [
+ {"$ai_evaluation_numeric_result": 0},
+ {"$ai_evaluation_numeric_result": 7},
+ {"$ai_evaluation_numeric_result": 7.5},
+ {"$ai_evaluation_numeric_result": 8},
+ {"$ai_evaluation_applicable": False},
+ {"$ai_evaluation_skipped": True},
+ ]
+ for index, properties in enumerate(rows):
+ _create_event(
+ team=self.team,
+ event="$ai_evaluation",
+ distinct_id=f"numeric-{index}",
+ timestamp=start,
+ properties={
+ "$ai_evaluation_id": "numeric-eval",
+ "$ai_evaluation_result_type": "numeric",
+ **properties,
+ },
+ )
+ for operator, expected in [("gte", {"pass": 3, "fail": 1, "na": 1}), ("lte", {"pass": 2, "fail": 2, "na": 1})]:
+ config = {"passing_rule": {"operator": operator, "threshold": 7}}
+ metrics = _compute_metrics(
+ self.team.id,
+ "numeric-eval",
+ start.isoformat(),
+ (start + dt.timedelta(days=1)).isoformat(),
+ (start - dt.timedelta(days=1)).isoformat(),
+ output_type="numeric",
+ output_config=config,
+ )
+ assert metrics is not None
+ self.assertEqual(metrics.total_runs, 5)
+ self.assertEqual(metrics.result_counts, expected)
+ self.assertEqual(metrics.output_config, config)
+
+
class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
"""Exercises the batched count check against real ClickHouse events — no query mocking —
so it guards the properties Carlos cares about: each report's count is identical to the
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
index 4589cfb95bd5..4b74346136c4 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
@@ -11,6 +11,7 @@ from posthog.temporal.ai_observability.eval_reports.delivery import (
_inline_email_styles,
_linkify_citations,
_render_metrics_block_html,
+ _render_metrics_slack_blocks,
_render_section_html,
_render_section_mrkdwn,
_strip_redundant_leading_heading,
@@ -306,8 +307,10 @@ class TestInlineEmailStyles(SimpleTestCase):
class TestMetricsBlockHtml(SimpleTestCase):
- def test_renders_all_counts(self):
+ @parameterized.expand(["boolean", "numeric"])
+ def test_renders_all_counts(self, output_type: str) -> None:
metrics = EvalReportMetrics(
+ output_type=output_type,
total_runs=100,
result_counts={"pass": 80, "fail": 18, "na": 2},
period_start="2026-04-08T14:00:00+00:00",
@@ -320,6 +323,11 @@ class TestMetricsBlockHtml(SimpleTestCase):
self.assertIn("2", html) # na_count
self.assertIn("81.63%", html)
self.assertIn("Apr 08, 2026 14:00 UTC", html)
+ slack_text = _render_metrics_slack_blocks(metrics)[0]["text"]["text"]
+ self.assertIn("Pass: 80", slack_text)
+ self.assertIn("Fail: 18", slack_text)
+ self.assertIn("N/A: 2", slack_text)
+ self.assertIn("Pass rate: 81.63%", slack_text)
def test_renders_delta_up(self):
metrics = EvalReportMetrics(
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 e0aa860e0da4..c682b2ae3717 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,31 @@ from posthog.temporal.ai_observability.eval_reports.output_types import (
class TestOutcomeDefinitions(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("gte", 6, "fail"),
+ ("gte", 7, "pass"),
+ ("gte", 8, "pass"),
+ ("lte", 6, "pass"),
+ ("lte", 7, "pass"),
+ ("lte", 8, "fail"),
+ ]
+ )
+ def test_numeric_passing_rule(self, operator, score, outcome):
+ definition = get_outcome_definition(
+ "numeric", output_config={"passing_rule": {"operator": operator, "threshold": 7}}
+ )
+ self.assertEqual(definition.label_for(score), outcome)
+ self.assertEqual(definition.label_for(None, applicable=False), "na")
+ self.assertIsNone(definition.label_for(True))
+ self.assertIsNone(definition.label_for(float("nan")))
+ self.assertIn("{numeric_threshold}", definition.outcome_predicates["pass"])
+ self.assertEqual(definition.query_placeholders["numeric_threshold"].value, 7)
+
+ def test_numeric_without_rule_has_no_pass_fail(self):
+ definition = get_outcome_definition("numeric")
+ self.assertIsNone(definition.label_for(0))
+
def test_absent_polarity_keeps_true_as_the_pass(self):
definition = get_outcome_definition("boolean")
self.assertIn("properties.$ai_evaluation_result = true", definition.outcome_predicates["pass"])
@@ -48,13 +73,13 @@ 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"})
+ self.assertEqual(set(SUPPORTED_EVAL_REPORT_OUTPUT_TYPES), {"boolean", "sentiment", "numeric"})
for output_type in SUPPORTED_EVAL_REPORT_OUTPUT_TYPES:
self.assertIsNotNone(get_outcome_definition(output_type))
def test_unsupported_type_raises(self):
with self.assertRaises(ValueError):
- get_outcome_definition("numeric")
+ get_outcome_definition("unsupported")
class TestReportPromptPolarity(SimpleTestCase):
diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.py
index 288da7844fe7..517337b438b8 100644
--- a/posthog/temporal/ai_observability/eval_reports/types.py
+++ b/posthog/temporal/ai_observability/eval_reports/types.py
@@ -68,6 +68,7 @@ class PrepareReportContextOutput:
report_prompt_guidance: str = ""
output_type: str = "boolean"
true_is_failure: bool = False
+ output_config: dict[str, Any] = dataclasses.field(default_factory=dict)
@frozen
@@ -85,6 +86,7 @@ class RunEvalReportAgentInput:
report_prompt_guidance: str = ""
output_type: str = "boolean"
true_is_failure: bool = False
+ output_config: dict[str, Any] = dataclasses.field(default_factory=dict)
trace_id: str = ""
session_id: str = ""
diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.py
index ba38e91b317e..5711cdfed9c8 100644
--- a/posthog/temporal/ai_observability/eval_reports/workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py
@@ -316,6 +316,7 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
evaluation_type=context.evaluation_type,
output_type=context.output_type,
true_is_failure=context.true_is_failure,
+ output_config=context.output_config,
period_start=context.period_start,
period_end=context.period_end,
previous_period_start=context.previous_period_start,
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
index 910979388036..c910384c6cd3 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
@@ -130,6 +130,7 @@ def _sample_and_embed_sync(inputs: SamplerActivityInputs) -> SamplerActivityResu
properties.$ai_evaluation_id as eval_id
FROM events
WHERE event = '$ai_evaluation'
+ AND (isNull(properties.$ai_evaluation_result_type) OR properties.$ai_evaluation_result_type != 'numeric')
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 344fd5b67f15..7e9dbb831e20 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from posthog.hogql.placeholders import replace_placeholders
+
from posthog.temporal.ai_observability.evaluation_clustering.constants import (
AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,
AI_OBSERVABILITY_EVALUATION_RENDERING,
@@ -227,3 +229,5 @@ class TestSampleAndEmbedForJobActivity:
# filter_expr is a real HogQL expr (not the pass-through True literal) when filters are provided
filter_expr = placeholders["filter_expr"]
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
diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.py
index e70f20aa24a3..6b70bf5182c7 100644
--- a/posthog/temporal/ai_observability/evaluation_errors.py
+++ b/posthog/temporal/ai_observability/evaluation_errors.py
@@ -11,7 +11,7 @@ from typing import Literal
from temporalio.exceptions import ApplicationError
-from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult, build_skipped_evaluation_result
from products.ai_observability.backend.models.evaluations import EvaluationStatusReason
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
@@ -105,7 +105,7 @@ USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
status_reason=EvaluationStatusReason.HOG_ERROR,
disables_evaluation=True,
),
- # The one user-actionable spec that neither disables the evaluation nor sets a status reason:
+ # A user-actionable spec that neither disables the evaluation nor sets a status reason:
# a single unit carried data the Hog source could not handle, which says nothing about whether
# the evaluation works on the next one. What keeps the workflow off `disable_evaluation_activity`
# is the result omitting `terminal_user_error` (see `is_terminal_user_error_result`); the unset
@@ -115,6 +115,11 @@ USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
owner="user",
safe_message="The evaluation code could not handle the data for this run, so it was skipped.",
),
+ "score_out_of_bounds": EvaluationErrorSpec(
+ error_type="score_out_of_bounds",
+ owner="user",
+ safe_message="The score was outside the configured bounds, so this run was skipped. Check the score limits.",
+ ),
}
@@ -172,23 +177,25 @@ def terminal_user_error_result(
spec: EvaluationErrorSpec,
message: str | None,
allows_na: bool,
+ output_type: str = "boolean",
provider: str | None = None,
model: str | None = None,
key_id: str | None = None,
is_byok: bool = False,
) -> EvaluationActivityResult:
result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None,
- "reasoning": spec.safe_message if not message else message,
+ **build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning=spec.safe_message if not message else message,
+ skip_reason=spec.error_type,
+ verdict=None,
+ ),
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"is_byok": is_byok,
"key_id": key_id,
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": spec.error_type,
"terminal_user_error": True,
"status_reason": spec.status_reason,
}
@@ -198,8 +205,6 @@ def terminal_user_error_result(
result["model"] = model
if spec.provider_key_state:
result["provider_key_state"] = spec.provider_key_state
- if allows_na:
- result["applicable"] = False
return result
@@ -207,6 +212,7 @@ def terminal_user_error_result_from_application_error(
error: ApplicationError,
*,
allows_na: bool,
+ output_type: str = "boolean",
provider: str | None = None,
model: str | None = None,
key_id: str | None = None,
@@ -226,6 +232,7 @@ def terminal_user_error_result_from_application_error(
spec=spec,
message=error.message,
allows_na=allows_na,
+ output_type=output_type,
provider=str(detail_provider) if detail_provider else provider,
model=str(detail_model) if detail_model else model,
key_id=str(detail_key_id) if detail_key_id else key_id,
diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.py
index 0feb23848ef1..afa1b2460d23 100644
--- a/posthog/temporal/ai_observability/evaluation_hog.py
+++ b/posthog/temporal/ai_observability/evaluation_hog.py
@@ -14,10 +14,12 @@ from posthog.temporal.ai_observability.evaluation_errors import (
truncate_error_detail,
)
from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
-from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult, build_skipped_evaluation_result
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 common.hogvm.python.execute import execute_bytecode
from common.hogvm.python.operation import Operation
from common.hogvm.python.utils import HogVMException, HogVMMemoryExceededException, HogVMRuntimeExceededException
@@ -145,14 +147,22 @@ def build_hog_event_global(
return event_global
-def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], allows_na: bool) -> dict[str, Any]:
- """Run compiled Hog eval bytecode against pre-built globals and shape the verdict.
+def execute_hog_eval_bytecode(
+ bytecode: list,
+ globals_dict: dict[str, Any],
+ allows_na: bool,
+ *,
+ output_type: str = "boolean",
+ output_config: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Run compiled Hog eval bytecode against pre-built globals and shape the output.
Shared by the single-event and trace-level Hog activities — only the globals differ.
Returns {"verdict": bool | None, "reasoning": str, "error": str | None}, plus "applicable"
when allows_na and a `return null` is treated as N/A, "user_input_error": True when this unit's
data defeated the user's Hog source, and "unexpected": True when the failure was a bug in our
code rather than in the user's Hog source or its input.
+ Numeric success replaces `verdict` with a validated `score`.
"""
try:
response = execute_bytecode(
@@ -188,6 +198,24 @@ def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], allo
if response.result is None and allows_na:
return {"verdict": None, "applicable": False, "reasoning": reasoning, "error": None}
+ if output_type == "numeric":
+ try:
+ score = NumericOutputConfig.model_validate(output_config or {}).validate_score(response.result)
+ except NumericScoreOutOfBounds as error:
+ return {
+ "verdict": None,
+ "reasoning": reasoning,
+ "error": str(error),
+ "user_input_error": True,
+ "skip_reason": "score_out_of_bounds",
+ }
+ except ValueError as error:
+ return {"verdict": None, "reasoning": reasoning, "error": str(error)}
+ numeric_result: dict[str, Any] = {"score": score, "reasoning": reasoning, "error": None}
+ if allows_na:
+ numeric_result["applicable"] = True
+ return numeric_result
+
if not isinstance(response.result, bool):
hint = " (or null if N/A is enabled)" if allows_na else ""
return {
@@ -229,7 +257,7 @@ def finalize_hog_eval_result(
# terminal: the same evaluation usually reads the next unit fine, so disabling it over
# one malformed payload would cost the user every later result. Skipping keeps the
# evaluation running and leaves the run visible as skipped rather than failed.
- input_error_spec = require_user_error_spec("hog_input_error")
+ input_error_spec = require_user_error_spec(result.get("skip_reason", "hog_input_error"))
increment_user_errors(input_error_spec.error_type)
# This path raises nothing and emails nobody, and the counter can't carry ids at this
# cardinality, so without these fields there is no way to find the offending evaluation.
@@ -241,19 +269,13 @@ def finalize_hog_eval_result(
error=result["error"],
)
detail = truncate_error_detail(result["error"])
- skipped_result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- # Leads with the safe message: `detail` is a Python exception repr, which is not a
- # Hog concept, and `reasoning` is the only text the run shows the user.
- "reasoning": f"{input_error_spec.safe_message} ({detail})" if detail else input_error_spec.safe_message,
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": input_error_spec.error_type,
- }
- if allows_na:
- skipped_result["applicable"] = False
- return skipped_result
+ # Lead with the user-facing message; detail may contain a Python exception.
+ return build_skipped_evaluation_result(
+ output_type=evaluation.get("output_type", "boolean"),
+ allows_na=allows_na,
+ reasoning=f"{input_error_spec.safe_message} ({detail})" if detail else input_error_spec.safe_message,
+ skip_reason=input_error_spec.error_type,
+ )
# The user's Hog source itself errored — an expected outcome of running customer-authored
# code, recorded as a skipped evaluation rather than raised (which would flood error
@@ -261,36 +283,51 @@ def finalize_hog_eval_result(
# eval instead of re-running it against every matching unit (mirrors the generation path).
spec = require_user_error_spec("hog_error")
error_detail = status_reason_detail_for_terminal_user_error(spec, result["error"]) or spec.safe_message
- errored_result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": error_detail,
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": "hog_error",
+ return {
+ **build_skipped_evaluation_result(
+ output_type=evaluation.get("output_type", "boolean"),
+ allows_na=allows_na,
+ reasoning=error_detail,
+ skip_reason="hog_error",
+ ),
"terminal_user_error": True,
"status_reason": spec.status_reason,
}
- if allows_na:
- errored_result["applicable"] = False
- return errored_result
activity_result: EvaluationActivityResult = {
"result_type": "boolean",
- "verdict": result["verdict"],
"reasoning": result["reasoning"],
"allows_na": allows_na,
}
+ if evaluation.get("output_type") == "numeric":
+ activity_result["result_type"] = "numeric"
+ if "score" in result:
+ config = NumericOutputConfig.model_validate(evaluation.get("output_config") or {})
+ activity_result["score"] = config.validate_score(result["score"])
+ if config.min is not None:
+ activity_result["score_min"] = config.min
+ if config.max is not None:
+ activity_result["score_max"] = config.max
+ else:
+ activity_result["verdict"] = result["verdict"]
if allows_na:
activity_result["applicable"] = result.get("applicable", True)
return activity_result
-def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = False) -> dict[str, Any]:
+def run_hog_eval(
+ bytecode: list,
+ event_data: dict[str, Any],
+ allows_na: bool = False,
+ *,
+ output_type: str = "boolean",
+ output_config: dict[str, Any] | None = None,
+) -> dict[str, Any]:
"""Run compiled Hog bytecode against a single event.
Used by both the Temporal activity and the test endpoint.
Returns {"verdict": bool | None, "reasoning": str, "error": str | None}.
+ Numeric success replaces `verdict` with a validated `score`.
When allows_na=True, a `return null` is treated as N/A (not an error).
Sets "user_input_error": True when this event's data defeated the user's Hog source, and
"unexpected": True only when the bytecode raised something other than a HogVM error or one of
@@ -332,7 +369,9 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = F
)
]
- return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)
+ return execute_hog_eval_bytecode(
+ bytecode, globals_dict, allows_na=allows_na, output_type=output_type, output_config=output_config
+ )
async def run_hog_eval_for_event(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:
@@ -352,7 +391,13 @@ async def run_hog_eval_for_event(evaluation: dict[str, Any], event_data: dict[st
allows_na = output_config.get("allows_na", False)
def _execute() -> dict[str, Any]:
- return run_hog_eval(bytecode, event_data, allows_na=allows_na)
+ return run_hog_eval(
+ bytecode,
+ event_data,
+ allows_na=allows_na,
+ output_type=evaluation.get("output_type", "boolean"),
+ output_config=output_config,
+ )
result = await database_sync_to_async(_execute, thread_sensitive=False)()
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index cdeb4c156e7c..80cb1cc004a7 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -6,11 +6,12 @@ from typing import Annotated, Any, Literal
import structlog
import temporalio
import posthoganalytics
-from pydantic import BaseModel, BeforeValidator
+from pydantic import BaseModel, BeforeValidator, Field
from structlog.contextvars import bind_contextvars
from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError
+from posthog.dataclasses import frozen
from posthog.temporal.ai_observability.evaluation_errors import (
require_user_error_spec,
terminal_user_error_result,
@@ -21,7 +22,7 @@ from posthog.temporal.ai_observability.evaluation_event_io import (
extract_event_tools,
hydrate_event_reference,
)
-from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult, build_skipped_evaluation_result
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitions
from posthog.temporal.ai_observability.metrics import (
increment_errors,
@@ -46,6 +47,7 @@ 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.text_repr.formatters import add_line_numbers, reduce_by_uniform_sampling
logger = structlog.get_logger(__name__)
@@ -123,16 +125,54 @@ class BooleanWithNAEvalResult(BaseModel):
return self.outcome == "pass"
-@dataclass
+class NumericEvalResult(BaseModel):
+ reasoning: str
+ score: float = Field(strict=True, allow_inf_nan=False)
+
+
+class NumericWithNAEvalResult(BaseModel):
+ reasoning: str
+ score: float | None = Field(strict=True, allow_inf_nan=False)
+
+ @property
+ def applicable(self) -> bool:
+ return self.score is not None
+
+
+@frozen
class OutputTypeConfig:
"""Configuration for each evaluation output type"""
- response_format: type[BooleanEvalResult] | type[BooleanWithNAEvalResult]
+ response_format: (
+ type[BooleanEvalResult]
+ | type[BooleanWithNAEvalResult]
+ | type[NumericEvalResult]
+ | type[NumericWithNAEvalResult]
+ )
instructions: str
-def get_output_type_config(allows_na: bool) -> OutputTypeConfig:
+def get_output_type_config(
+ allows_na: bool,
+ *,
+ output_type: str = "boolean",
+ output_config: dict[str, Any] | None = None,
+) -> OutputTypeConfig:
"""Get the output type configuration based on whether N/A is allowed."""
+ if output_type == "numeric":
+ numeric_config = NumericOutputConfig.model_validate(output_config or {})
+ instructions = "Provide a brief reasoning (1 sentence) and a finite numeric score."
+ if numeric_config.min is not None:
+ instructions += f" The score must be at least {numeric_config.min}."
+ if numeric_config.max is not None:
+ instructions += f" The score must be at most {numeric_config.max}."
+ if numeric_config.step is not None:
+ instructions += f" Suggested score increment: {numeric_config.step}; do not round an otherwise valid score."
+ if allows_na:
+ instructions += " Return score=null when the criteria does not apply."
+ return OutputTypeConfig(
+ response_format=NumericWithNAEvalResult if allows_na else NumericEvalResult, instructions=instructions
+ )
if allows_na:
return OutputTypeConfig(
response_format=BooleanWithNAEvalResult,
@@ -150,9 +190,11 @@ Return:
)
-def build_system_prompt(prompt: str, allows_na: bool) -> str:
+def build_system_prompt(
+ prompt: str, allows_na: bool, *, output_type: str = "boolean", output_config: dict[str, Any] | None = None
+) -> str:
"""Build the system prompt for the LLM judge."""
- config = get_output_type_config(allows_na)
+ config = get_output_type_config(allows_na, output_type=output_type, output_config=output_config)
return f"""You are an evaluator. Evaluate the following generation according to this criteria:
{prompt}
@@ -187,53 +229,45 @@ def _is_errored_trace(properties: dict[str, Any]) -> bool:
return False
-def _build_errored_trace_result(allows_na: bool) -> EvaluationActivityResult:
+def _build_errored_trace_result(allows_na: bool, *, output_type: str = "boolean") -> EvaluationActivityResult:
"""Result returned when the source trace errored — skips the LLM call entirely.
- `model` and `provider` are deliberately omitted so the `.get(..., DEFAULT_JUDGE_MODEL)`
- defaults in downstream activities don't silently attribute phantom calls to a model that
- was never invoked — the emit activity instead detects the `skipped` flag and drops cost
- and model attribution entirely. The `EvaluationActivityResult` TypedDict expresses the shape
- contract previously enforced by convention.
+ Omit `model` and `provider` so the emitted event does not attribute a call that never ran.
"""
reasoning = "Source trace errored before producing output; evaluation skipped."
result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": reasoning,
+ **build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning=reasoning,
+ skip_reason="trace_errored",
+ ),
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"is_byok": False,
"key_id": None,
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": "trace_errored",
}
- if allows_na:
- result["applicable"] = False
return result
def _build_context_window_skip_result(
- allows_na: bool, *, is_byok: bool, key_id: str | None
+ allows_na: bool, *, is_byok: bool, key_id: str | None, output_type: str = "boolean"
) -> EvaluationActivityResult:
"""Per-item skip, not a terminal user error that disables the eval."""
result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": "Evaluation input exceeded the model's context window; evaluation skipped.",
+ **build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Evaluation input exceeded the model's context window; evaluation skipped.",
+ skip_reason="context_window_exceeded",
+ ),
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"is_byok": is_byok,
"key_id": key_id,
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": "context_window_exceeded",
}
- if allows_na:
- result["applicable"] = False
return result
@@ -267,7 +301,14 @@ def _build_output_limit_skip_result(
def _build_unparsable_response_skip_result(
- allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str, usage: Usage | None
+ allows_na: bool,
+ *,
+ is_byok: bool,
+ key_id: str | None,
+ provider: str,
+ model: str,
+ usage: Usage | None,
+ output_type: str = "boolean",
) -> EvaluationActivityResult:
"""Per-item skip for a judge response that does not match the requested schema.
@@ -276,22 +317,20 @@ def _build_unparsable_response_skip_result(
the counts the provider reported.
"""
result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": "Evaluation model returned an unreadable response; evaluation skipped.",
+ **build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Evaluation model returned an unreadable response; evaluation skipped.",
+ skip_reason="unparsable_response",
+ ),
"input_tokens": usage.input_tokens if usage else 0,
"output_tokens": usage.output_tokens if usage else 0,
"total_tokens": usage.total_tokens if usage else 0,
"is_byok": is_byok,
"key_id": key_id,
- "allows_na": allows_na,
"model": model,
"provider": provider,
- "skipped": True,
- "skip_reason": "unparsable_response",
}
- if allows_na:
- result["applicable"] = False
return result
@@ -324,9 +363,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 != "boolean":
+ if output_type not in ("boolean", "numeric"):
raise ApplicationError(
- f"Unsupported output type: {output_type}. Supported types: 'boolean'.",
+ f"Unsupported output type: {output_type}. Supported types: 'boolean', 'numeric'.",
non_retryable=True,
)
@@ -339,7 +378,7 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
properties = json.loads(properties)
if _is_errored_trace(properties):
- return _build_errored_trace_result(allows_na)
+ return _build_errored_trace_result(allows_na, output_type=output_type)
io = extract_event_io(event_type, properties)
tools_raw = extract_event_tools(properties)
@@ -348,7 +387,7 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
output_data = extract_text_from_messages(io.output_raw)
tools_data = format_tool_definitions(tools_raw)
- system_prompt = build_system_prompt(prompt, allows_na)
+ system_prompt = build_system_prompt(prompt, allows_na, output_type=output_type, output_config=output_config)
sections = [f"Input: {input_data}"]
if tools_data:
@@ -384,10 +423,14 @@ def call_llm_judge(
user prompt is assembled differs.
"""
team_id = evaluation["team_id"]
+ output_type = evaluation.get("output_type", "boolean")
+ output_config = evaluation.get("output_config") or {}
try:
resolved = model_spec(evaluation.get("model_configuration")).resolve(team_id)
except ApplicationError as e:
- terminal_result = terminal_user_error_result_from_application_error(e, allows_na=allows_na)
+ terminal_result = terminal_user_error_result_from_application_error(
+ e, allows_na=allows_na, output_type=output_type
+ )
if terminal_result is not None:
increment_user_errors(terminal_result["skip_reason"], provider=terminal_result.get("provider"))
return terminal_result
@@ -399,7 +442,7 @@ def call_llm_judge(
is_byok = resolved.is_byok
key_id = str(provider_key.id) if provider_key else None
- type_config = get_output_type_config(allows_na)
+ type_config = get_output_type_config(allows_na, output_type=output_type, output_config=output_config)
response_format = type_config.response_format
config = None
@@ -427,6 +470,7 @@ def call_llm_judge(
spec=require_user_error_spec("auth_error", is_byok=True),
message="API key is invalid or has been deleted.",
allows_na=allows_na,
+ output_type=output_type,
provider=provider,
model=model,
key_id=key_id,
@@ -441,6 +485,7 @@ def call_llm_judge(
spec=require_user_error_spec("permission_error", is_byok=True),
message="API key doesn't have access to this model.",
allows_na=allows_na,
+ output_type=output_type,
provider=provider,
model=model,
key_id=key_id,
@@ -455,6 +500,7 @@ def call_llm_judge(
spec=require_user_error_spec("quota_error", is_byok=True),
message="API key has exceeded its quota.",
allows_na=allows_na,
+ output_type=output_type,
provider=provider,
model=model,
key_id=key_id,
@@ -469,6 +515,7 @@ def call_llm_judge(
spec=require_user_error_spec("rate_limit", is_byok=True),
message="API key is being rate limited.",
allows_na=allows_na,
+ output_type=output_type,
provider=provider,
model=model,
key_id=key_id,
@@ -483,6 +530,7 @@ def call_llm_judge(
spec=require_user_error_spec("model_not_found", is_byok=True),
message=f"Model '{model}' not found.",
allows_na=allows_na,
+ output_type=output_type,
provider=provider,
model=model,
key_id=key_id,
@@ -506,13 +554,19 @@ def call_llm_judge(
error=str(e),
)
return _build_unparsable_response_skip_result(
- allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, usage=None
+ allows_na,
+ is_byok=is_byok,
+ key_id=key_id,
+ provider=provider,
+ model=model,
+ usage=None,
+ output_type=output_type,
)
except ContextWindowExceededError:
# Skip rather than raise: retrying can't fix an over-window prompt and just spams error tracking.
increment_errors("context_window_exceeded", provider=provider)
- return _build_context_window_skip_result(allows_na, is_byok=is_byok, key_id=key_id)
+ return _build_context_window_skip_result(allows_na, is_byok=is_byok, key_id=key_id, output_type=output_type)
except OutputTokenLimitError as e:
# Avoid automatic retries of a billed generation; a later backfill can retry it.
@@ -564,10 +618,18 @@ def call_llm_judge(
model=model,
)
return _build_unparsable_response_skip_result(
- allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, usage=response.usage
+ allows_na,
+ is_byok=is_byok,
+ key_id=key_id,
+ provider=provider,
+ model=model,
+ usage=response.usage,
+ output_type=output_type,
)
- assert isinstance(parsed_result, BooleanEvalResult | BooleanWithNAEvalResult)
+ assert isinstance(
+ parsed_result, BooleanEvalResult | BooleanWithNAEvalResult | NumericEvalResult | NumericWithNAEvalResult
+ )
usage = response.usage
@@ -582,7 +644,6 @@ def call_llm_judge(
result_dict: EvaluationActivityResult = {
"result_type": "boolean",
- "verdict": parsed_result.verdict,
"reasoning": parsed_result.reasoning,
"input_tokens": usage.input_tokens if usage else 0,
"output_tokens": usage.output_tokens if usage else 0,
@@ -594,6 +655,32 @@ def call_llm_judge(
"provider": provider,
}
+ if isinstance(parsed_result, NumericEvalResult | NumericWithNAEvalResult):
+ result_dict["result_type"] = "numeric"
+ if parsed_result.score is not None:
+ numeric_config = NumericOutputConfig.model_validate(output_config)
+ try:
+ result_dict["score"] = numeric_config.validate_score(parsed_result.score)
+ except NumericScoreOutOfBounds as error:
+ increment_user_errors("score_out_of_bounds", provider=provider)
+ result_dict.update(
+ build_skipped_evaluation_result(
+ output_type="numeric",
+ allows_na=allows_na,
+ reasoning=f"{parsed_result.reasoning}\n\nThe judge returned a score outside the configured bounds: {error}. This run was skipped.",
+ skip_reason="score_out_of_bounds",
+ )
+ )
+ return result_dict
+ if numeric_config.min is not None:
+ result_dict["score_min"] = numeric_config.min
+ if numeric_config.max is not None:
+ result_dict["score_max"] = numeric_config.max
+ if isinstance(parsed_result, NumericWithNAEvalResult):
+ result_dict["applicable"] = parsed_result.applicable
+ return result_dict
+
+ result_dict["verdict"] = parsed_result.verdict
if allows_na and isinstance(parsed_result, BooleanWithNAEvalResult):
result_dict["applicable"] = parsed_result.applicable
elif isinstance(parsed_result, BooleanEvalResult):
diff --git a/posthog/temporal/ai_observability/evaluation_types.py b/posthog/temporal/ai_observability/evaluation_types.py
index 5a35886967cb..d9ab43ae09d1 100644
--- a/posthog/temporal/ai_observability/evaluation_types.py
+++ b/posthog/temporal/ai_observability/evaluation_types.py
@@ -17,22 +17,26 @@ 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` and `allows_na` are set for boolean outputs only.
+ - `verdict` is set for boolean outputs only; `allows_na` is also set for numeric 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`.
- `skipped` and `skip_reason` are set only on the skip path (e.g. errored source trace).
- `model`, `provider`, `key_id`, `is_byok`, and the `*_tokens` fields come from the LLM
judge success path. The skip path omits `model`/`provider` so downstream cost
attribution doesn't credit phantom calls, and `execute_hog_eval_activity` (whose
- output also flows into `emit_evaluation_event_activity`) emits only `verdict`,
- `reasoning`, `allows_na`, and optionally `applicable`.
+ output also flows into `emit_evaluation_event_activity`) omits model and token fields.
- `sentiment_*` fields are set for successful sentiment evaluations (the skip path
omits them) and deliberately omit `verdict` so report and pass/fail metrics do
not treat sentiment as N/A.
"""
- result_type: Required[Literal["boolean", "sentiment"]]
+ result_type: Required[Literal["boolean", "sentiment", "numeric"]]
reasoning: Required[str]
verdict: NotRequired[bool | None]
+ score: NotRequired[float]
+ score_min: NotRequired[float]
+ score_max: NotRequired[float]
allows_na: NotRequired[bool]
input_tokens: NotRequired[int]
output_tokens: NotRequired[int]
@@ -52,3 +56,25 @@ class EvaluationActivityResult(TypedDict, total=False):
sentiment_scores: NotRequired[dict[str, float]]
sentiment_messages: NotRequired[dict[str, dict[str, Any]]]
sentiment_message_count: NotRequired[int]
+
+
+def build_skipped_evaluation_result(
+ *,
+ output_type: str,
+ allows_na: bool,
+ reasoning: str,
+ skip_reason: str,
+ verdict: bool | None = False,
+) -> EvaluationActivityResult:
+ result: EvaluationActivityResult = {
+ "result_type": "numeric" if output_type == "numeric" else "boolean",
+ "reasoning": reasoning,
+ "allows_na": allows_na,
+ "skipped": True,
+ "skip_reason": skip_reason,
+ }
+ if output_type != "numeric":
+ result["verdict"] = None if allows_na else verdict
+ if allows_na:
+ result["applicable"] = False
+ return result
diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
index 0e95de2a5cb2..e3c6bcd99ac6 100644
--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py
+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
@@ -289,7 +289,18 @@ 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"] == "sentiment":
+ if 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))
+ if not result.get("skipped") and result.get("applicable", True):
+ if "score" in result:
+ properties["$ai_evaluation_numeric_result"] = result["score"]
+ if "score_min" in result:
+ properties["$ai_evaluation_numeric_result_min"] = result["score_min"]
+ if "score_max" in result:
+ properties["$ai_evaluation_numeric_result_max"] = result["score_max"]
+ elif result["result_type"] == "sentiment":
if not result.get("skipped"):
properties["$ai_sentiment_label"] = result.get("sentiment_label")
properties["$ai_sentiment_score"] = result.get("sentiment_score")
@@ -436,7 +447,8 @@ async def emit_internal_telemetry_activity(inputs: EmitInternalTelemetryInputs)
"input_tokens": result.get("input_tokens", 0),
"output_tokens": result.get("output_tokens", 0),
"total_tokens": result.get("total_tokens", 0),
- "verdict": result["verdict"],
+ **({"verdict": result["verdict"]} if "verdict" in result else {}),
+ "result_type": result["result_type"],
},
groups={"organization": organization_id, "instance": settings.SITE_URL},
)
diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
index 98b9ef585dfc..26a97f763d0a 100644
--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
@@ -597,12 +597,13 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
# bail out instead of running against config the user just turned off.
if evaluation["deleted"] or not evaluation["enabled"]:
disabled_result: WorkflowResult = {
- "verdict": None,
"skipped": True,
"skip_reason": "evaluation_deleted" if evaluation["deleted"] else "evaluation_disabled",
"evaluation_id": inputs.evaluation_id,
"evaluation_type": evaluation_type,
}
+ if evaluation.get("output_type") != "numeric":
+ disabled_result["verdict"] = None
return disabled_result
if is_session and inputs.ai_session_id is not None:
@@ -709,13 +710,16 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
)
workflow_result: WorkflowResult = {
- "verdict": result["verdict"],
"reasoning": result["reasoning"],
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
"is_byok": result.get("is_byok", False),
"skipped": result.get("skipped", False),
}
+ if "verdict" in result:
+ workflow_result["verdict"] = result["verdict"]
+ if "score" in result:
+ workflow_result["score"] = result["score"]
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 0c5b62a003ff..f354b4e90af1 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -97,6 +97,7 @@ class WorkflowResult(TypedDict, total=False):
evaluation_type: Required[str]
skipped: Required[bool]
verdict: NotRequired[bool | None]
+ score: NotRequired[float]
reasoning: NotRequired[str]
is_byok: NotRequired[bool]
skip_reason: NotRequired[str]
@@ -123,6 +124,7 @@ async def handle_llm_judge_activity_error(
terminal_result = terminal_user_error_result_from_application_error(
e.cause,
allows_na=(evaluation.get("output_config") or {}).get("allows_na", False),
+ output_type=evaluation.get("output_type", "boolean"),
)
if terminal_result is not None:
return await handle_terminal_user_error_result(
@@ -133,13 +135,14 @@ async def handle_llm_judge_activity_error(
if error_type == "parse_error":
skip_result: WorkflowResult = {
- "verdict": None,
"skipped": True,
"skip_reason": error_type,
"message": e.cause.message,
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
}
+ if evaluation.get("output_type") != "numeric":
+ skip_result["verdict"] = None
return skip_result
key_id = details.get("key_id")
@@ -233,13 +236,14 @@ async def handle_terminal_user_error_result(
)
workflow_result: WorkflowResult = {
- "verdict": None,
"skipped": True,
"skip_reason": skip_reason,
"message": result["reasoning"],
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
}
+ if evaluation.get("output_type") != "numeric":
+ workflow_result["verdict"] = None
return workflow_result
@@ -463,6 +467,8 @@ class RunEvaluationWorkflow(PostHogWorkflow):
"is_byok": result.get("is_byok", False),
"skipped": result.get("skipped", False),
}
+ if "score" in result:
+ workflow_result["score"] = result["score"]
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 892c526bc718..6975ef3f88b7 100644
--- a/posthog/temporal/ai_observability/run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/run_session_evaluation.py
@@ -40,7 +40,7 @@ from posthog.temporal.ai_observability.evaluation_payload import (
payload_budget_bytes,
should_skip_for_payload,
)
-from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult, build_skipped_evaluation_result
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.run_trace_evaluation import TRACE_EVENTS_LOOKBACK
from posthog.temporal.common.utils import close_db_connections
@@ -354,10 +354,12 @@ def build_session_hog_globals(
return globals_dict
-def build_session_system_prompt(prompt: str, allows_na: bool) -> str:
+def build_session_system_prompt(
+ prompt: str, allows_na: bool, *, output_type: str = "boolean", output_config: dict[str, Any] | None = None
+) -> str:
"""Session-level variant of `build_trace_system_prompt` — frames the unit under evaluation as
a multi-trace conversation rather than one execution."""
- config = get_output_type_config(allows_na)
+ config = get_output_type_config(allows_na, output_type=output_type, output_config=output_config)
return f"""You are an evaluator. Evaluate the following AI session — every trace in one \
user's conversation, in order — according to this criteria:
@@ -415,20 +417,17 @@ def format_session_for_judge(traces: list[LLMTrace]) -> str | None:
return None
-def build_session_skip_result(allows_na: bool, skip_reason: str) -> EvaluationActivityResult:
+def build_session_skip_result(
+ allows_na: bool, skip_reason: str, *, output_type: str = "boolean"
+) -> EvaluationActivityResult:
"""Session mirror of `_build_trace_skip_result` — no LLM call is made, so model/provider are
omitted and downstream cost attribution stays clean."""
- result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": _SESSION_SKIP_REASONING.get(skip_reason, "Evaluation skipped."),
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": skip_reason,
- }
- if allows_na:
- result["applicable"] = False
- return result
+ return build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning=_SESSION_SKIP_REASONING.get(skip_reason, "Evaluation skipped."),
+ skip_reason=skip_reason,
+ )
@frozen
@@ -477,13 +476,15 @@ 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"] != "boolean":
+ if evaluation["output_type"] not in ("boolean", "numeric"):
raise ApplicationError(
- f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean'.",
+ f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean', 'numeric'.",
non_retryable=True,
)
- allows_na = evaluation.get("output_config", {}).get("allows_na", False)
+ output_type = evaluation.get("output_type", "boolean")
+ output_config = evaluation.get("output_config") or {}
+ allows_na = output_config.get("allows_na", False)
outcome = fetch_session_for_evaluation(
inputs.team_id,
@@ -492,15 +493,17 @@ def execute_session_llm_judge_activity(inputs: ExecuteSessionEvaluationInputs) -
inputs.window_end_datetime,
)
if outcome.skip_reason or outcome.traces is None:
- return build_session_skip_result(allows_na, outcome.skip_reason or "session_not_found")
+ return build_session_skip_result(allows_na, outcome.skip_reason or "session_not_found", output_type=output_type)
transcript = format_session_for_judge(outcome.traces)
if transcript is None:
- return build_session_skip_result(allows_na, "session_too_long_to_judge")
+ return build_session_skip_result(allows_na, "session_too_long_to_judge", output_type=output_type)
return call_llm_judge(
evaluation=evaluation,
- system_prompt=build_session_system_prompt(prompt, allows_na),
+ system_prompt=build_session_system_prompt(
+ prompt, allows_na, output_type=output_type, output_config=output_config
+ ),
user_prompt=transcript,
allows_na=allows_na,
)
@@ -521,7 +524,9 @@ async def execute_session_hog_eval_activity(inputs: ExecuteSessionEvaluationInpu
if not bytecode:
raise ApplicationError("Missing bytecode in evaluation_config", non_retryable=True)
- allows_na = evaluation.get("output_config", {}).get("allows_na", False)
+ output_type = evaluation.get("output_type", "boolean")
+ output_config = evaluation.get("output_config") or {}
+ allows_na = output_config.get("allows_na", False)
def _execute() -> tuple[dict[str, Any] | None, str | None]:
outcome = fetch_session_for_evaluation(
@@ -533,17 +538,19 @@ async def execute_session_hog_eval_activity(inputs: ExecuteSessionEvaluationInpu
if outcome.skip_reason or outcome.traces is None:
return None, outcome.skip_reason or "session_not_found"
globals_dict = build_session_hog_globals(outcome.traces, inputs.session_id, bytecode=bytecode)
- return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na), None
+ return execute_hog_eval_bytecode(
+ bytecode, globals_dict, allows_na=allows_na, output_type=output_type, output_config=output_config
+ ), None
result, skip_reason = await database_sync_to_async(_execute, thread_sensitive=False)()
if skip_reason or result is None:
- return build_session_skip_result(allows_na, skip_reason or "session_not_found")
+ return build_session_skip_result(allows_na, skip_reason or "session_not_found", output_type=output_type)
return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label="session")
-@dataclass
+@frozen
class SessionHogTestResult:
"""One session's outcome from `run_hog_eval_over_recent_sessions`, shaped for the editor test
endpoint rather than for online emission."""
@@ -554,6 +561,8 @@ class SessionHogTestResult:
error: str | None
input_preview: str
output_preview: str
+ score: float | None = None
+ applicable: bool | None = None
# Sessions whose structural activity has been quiet for the configured period, restricted to those
@@ -646,6 +655,8 @@ def run_hog_eval_over_recent_sessions(
allows_na: bool,
quiet_period_seconds: int,
lookback_days: int = EVALUATION_TEST_LOOKBACK_DAYS,
+ output_type: str = "boolean",
+ output_config: dict[str, Any] | None = None,
user: "User | None" = None,
) -> list[SessionHogTestResult]:
"""Sample sessions that have gone quiet and run session-level Hog bytecode against each.
@@ -679,12 +690,16 @@ def run_hog_eval_over_recent_sessions(
continue
globals_dict = build_session_hog_globals(outcome.traces, session_id, bytecode=bytecode)
- hog_result = execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)
+ hog_result = execute_hog_eval_bytecode(
+ bytecode, globals_dict, allows_na=allows_na, output_type=output_type, output_config=output_config
+ )
input_preview, output_preview = _session_io_preview(outcome.traces)
results.append(
SessionHogTestResult(
session_id=session_id,
verdict=hog_result.get("verdict"),
+ score=hog_result.get("score"),
+ applicable=hog_result.get("applicable"),
reasoning=hog_result.get("reasoning") or "",
error=hog_result.get("error"),
input_preview=input_preview,
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.py
index 2133985578d6..cafa2f1d8a8f 100644
--- a/posthog/temporal/ai_observability/run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py
@@ -53,7 +53,7 @@ from posthog.temporal.ai_observability.evaluation_payload import (
payload_budget_bytes,
should_skip_for_payload,
)
-from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult, build_skipped_evaluation_result
from posthog.temporal.ai_observability.evaluation_workflow_activities import (
EmitInternalTelemetryInputs,
RunEvaluationInputs,
@@ -303,7 +303,7 @@ def fetch_trace_for_evaluation(
return _fetch_trace(team, trace_id, date_from, date_to, bound_to_date_to=window_end is not None)
-@dataclass
+@frozen
class TraceHogTestResult:
"""One trace's outcome from `run_hog_eval_over_recent_traces`, shaped for the editor test
endpoint and Max's authoring tool rather than for online emission."""
@@ -314,6 +314,8 @@ class TraceHogTestResult:
error: str | None
input_preview: str
output_preview: str
+ score: float | None = None
+ applicable: bool | None = None
@dataclass(frozen=True)
@@ -421,6 +423,8 @@ def run_hog_eval_over_recent_traces(
allows_na: bool,
window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
lookback_days: int = EVALUATION_TEST_LOOKBACK_DAYS,
+ output_type: str = "boolean",
+ output_config: dict[str, Any] | None = None,
user: "User | None" = None,
) -> list[TraceHogTestResult]:
"""Sample recent traces matching the conditions and run trace-level Hog bytecode against each.
@@ -462,12 +466,16 @@ def run_hog_eval_over_recent_traces(
continue
globals_dict = build_trace_hog_globals(outcome.trace, sample.trace_id, bytecode=bytecode)
- result = execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)
+ result = execute_hog_eval_bytecode(
+ bytecode, globals_dict, allows_na=allows_na, output_type=output_type, output_config=output_config
+ )
input_preview, output_preview = _trace_io_preview(outcome.trace)
results.append(
TraceHogTestResult(
trace_id=sample.trace_id,
- verdict=result["verdict"],
+ verdict=result.get("verdict"),
+ score=result.get("score"),
+ applicable=result.get("applicable"),
reasoning=result["reasoning"],
error=result["error"],
input_preview=input_preview,
@@ -477,26 +485,25 @@ def run_hog_eval_over_recent_traces(
return results
-def _build_trace_skip_result(allows_na: bool, skip_reason: str) -> EvaluationActivityResult:
+def _build_trace_skip_result(
+ allows_na: bool, skip_reason: str, *, output_type: str = "boolean"
+) -> EvaluationActivityResult:
"""Mirror of `_build_errored_trace_result` for trace-level skips — no LLM call is made,
so model/provider are omitted and downstream cost attribution stays clean."""
- result: EvaluationActivityResult = {
- "result_type": "boolean",
- "verdict": None if allows_na else False,
- "reasoning": _SKIP_REASONING.get(skip_reason, "Evaluation skipped."),
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": skip_reason,
- }
- if allows_na:
- result["applicable"] = False
- return result
+ return build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning=_SKIP_REASONING.get(skip_reason, "Evaluation skipped."),
+ skip_reason=skip_reason,
+ )
-def build_trace_system_prompt(prompt: str, allows_na: bool) -> str:
+def build_trace_system_prompt(
+ prompt: str, allows_na: bool, *, output_type: str = "boolean", output_config: dict[str, Any] | None = None
+) -> str:
"""Trace-level variant of `build_system_prompt` — frames the unit under evaluation as the
whole trace rather than a single generation."""
- config = get_output_type_config(allows_na)
+ config = get_output_type_config(allows_na, output_type=output_type, output_config=output_config)
return f"""You are an evaluator. Evaluate the following AI trace — the full sequence of LLM calls and operations from one execution — according to this criteria:
{prompt}
@@ -608,23 +615,27 @@ 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"] != "boolean":
+ if evaluation["output_type"] not in ("boolean", "numeric"):
raise ApplicationError(
- f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean'.",
+ f"Unsupported output type: {evaluation['output_type']}. Supported types: 'boolean', 'numeric'.",
non_retryable=True,
)
- allows_na = evaluation.get("output_config", {}).get("allows_na", False)
+ output_type = evaluation.get("output_type", "boolean")
+ output_config = evaluation.get("output_config") or {}
+ allows_na = output_config.get("allows_na", False)
outcome = fetch_trace_for_evaluation(
inputs.team_id, inputs.trace_id, datetime.fromisoformat(inputs.window_start), inputs.window_end_datetime
)
if outcome.skip_reason or outcome.trace is None:
- return _build_trace_skip_result(allows_na, outcome.skip_reason or "trace_not_found")
+ return _build_trace_skip_result(allows_na, outcome.skip_reason or "trace_not_found", output_type=output_type)
return call_llm_judge(
evaluation=evaluation,
- system_prompt=build_trace_system_prompt(prompt, allows_na),
+ system_prompt=build_trace_system_prompt(
+ prompt, allows_na, output_type=output_type, output_config=output_config
+ ),
user_prompt=format_trace_for_judge(outcome.trace),
allows_na=allows_na,
)
@@ -645,7 +656,9 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs)
if not bytecode:
raise ApplicationError("Missing bytecode in evaluation_config", non_retryable=True)
- allows_na = evaluation.get("output_config", {}).get("allows_na", False)
+ output_type = evaluation.get("output_type", "boolean")
+ output_config = evaluation.get("output_config") or {}
+ allows_na = output_config.get("allows_na", False)
def _execute() -> tuple[dict[str, Any] | None, str | None]:
outcome = fetch_trace_for_evaluation(
@@ -654,12 +667,14 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs)
if outcome.skip_reason or outcome.trace is None:
return None, outcome.skip_reason or "trace_not_found"
globals_dict = build_trace_hog_globals(outcome.trace, inputs.trace_id, bytecode=bytecode)
- return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na), None
+ return execute_hog_eval_bytecode(
+ bytecode, globals_dict, allows_na=allows_na, output_type=output_type, output_config=output_config
+ ), None
result, skip_reason = await database_sync_to_async(_execute, thread_sensitive=False)()
if skip_reason or result is None:
- return _build_trace_skip_result(allows_na, skip_reason or "trace_not_found")
+ return _build_trace_skip_result(allows_na, skip_reason or "trace_not_found", output_type=output_type)
return finalize_hog_eval_result(result, evaluation=evaluation, allows_na=allows_na, unit_label="trace")
@@ -792,12 +807,13 @@ class RunTraceEvaluationWorkflow(PostHogWorkflow):
# bail out instead of running against config the user just turned off.
if evaluation["deleted"] or not evaluation["enabled"]:
disabled_result: WorkflowResult = {
- "verdict": None,
"skipped": True,
"skip_reason": "evaluation_deleted" if evaluation["deleted"] else "evaluation_disabled",
"evaluation_id": inputs.evaluation_id,
"evaluation_type": evaluation_type,
}
+ if evaluation.get("output_type") != "numeric":
+ disabled_result["verdict"] = None
return disabled_result
execute_inputs = ExecuteTraceEvaluationInputs(
@@ -869,13 +885,16 @@ class RunTraceEvaluationWorkflow(PostHogWorkflow):
)
workflow_result: WorkflowResult = {
- "verdict": result["verdict"],
"reasoning": result["reasoning"],
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
"is_byok": result.get("is_byok", False),
"skipped": result.get("skipped", False),
}
+ if "verdict" in result:
+ workflow_result["verdict"] = result["verdict"]
+ if "score" in result:
+ workflow_result["score"] = result["score"]
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 d00172613f74..0c91b03f2dbe 100644
--- a/posthog/temporal/ai_observability/test_evaluation_hog.py
+++ b/posthog/temporal/ai_observability/test_evaluation_hog.py
@@ -36,6 +36,75 @@ return jsonParse()
EVALUATION = {"id": "01890000-0000-0000-0000-000000000000", "team_id": 1}
[email protected]("source,score", [("return 0", 0), ("return 0.25", 0.25), ("return 1", 1)])
+def test_numeric_hog_preserves_scores_and_bounds(source: str, score: float) -> None:
+ config = {"min": 0, "max": 1, "step": 0.5}
+ raw = execute_hog_eval_bytecode(
+ compile_ai_observability_hog(source, "destination"),
+ {},
+ False,
+ output_type="numeric",
+ output_config=config,
+ )
+ result = finalize_hog_eval_result(
+ raw,
+ evaluation={**EVALUATION, "output_type": "numeric", "output_config": config},
+ allows_na=False,
+ unit_label=None,
+ )
+ assert result == {
+ "result_type": "numeric",
+ "score": score,
+ "score_min": 0,
+ "score_max": 1,
+ "reasoning": "",
+ "allows_na": False,
+ }
+
+
+ "source,terminal",
+ [("return true", True), ("return '0.5'", True), ("return -1", False), ("return 2", False), ("return null", True)],
+)
+def test_invalid_numeric_hog_only_skips_bounds_errors(source: str, terminal: bool) -> None:
+ config = {"min": 0, "max": 1}
+ raw = execute_hog_eval_bytecode(
+ compile_ai_observability_hog(source, "destination"),
+ {},
+ False,
+ output_type="numeric",
+ output_config=config,
+ )
+ result = finalize_hog_eval_result(
+ raw,
+ evaluation={**EVALUATION, "output_type": "numeric", "output_config": config},
+ allows_na=False,
+ unit_label=None,
+ )
+ assert result["result_type"] == "numeric"
+ assert is_terminal_user_error_result(result) is terminal
+ assert result["skipped"] is True
+ assert result["skip_reason"] == ("hog_error" if terminal else "score_out_of_bounds")
+ assert "score" not in result
+ assert "verdict" not in result
+
+
+def test_numeric_hog_na_omits_score() -> None:
+ raw = execute_hog_eval_bytecode(
+ compile_ai_observability_hog("return null", "destination"),
+ {},
+ True,
+ output_type="numeric",
+ )
+ result = finalize_hog_eval_result(
+ raw,
+ evaluation={**EVALUATION, "output_type": "numeric"},
+ allows_na=True,
+ unit_label=None,
+ )
+ assert result == {"result_type": "numeric", "reasoning": "", "allows_na": True, "applicable": False}
+
+
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_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
index 7cf69df1a0f1..163f8029c920 100644
--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
@@ -217,7 +217,7 @@ class TestSettleErrorTypesAreNotReportedAsDefects:
assert "session_runaway" not in EXPECTED_CONTROL_FLOW_ERROR_TYPES
-def _mock_activities(calls: list[str], exclude: set[str] | None = None) -> list[Any]:
+def _mock_activities(calls: list[str], exclude: set[str] | None = None, *, output_type: str = "boolean") -> list[Any]:
exclude = exclude or set()
@activity.defn(name="fetch_evaluation_activity")
@@ -228,7 +228,7 @@ def _mock_activities(calls: list[str], exclude: set[str] | None = None) -> list[
"name": "Hog eval",
"evaluation_type": "hog",
"evaluation_config": {},
- "output_type": "boolean",
+ "output_type": output_type,
"output_config": {},
"team_id": 1,
"enabled": True,
@@ -238,6 +238,8 @@ def _mock_activities(calls: list[str], exclude: set[str] | None = None) -> list[
@activity.defn(name="execute_trace_hog_eval_activity")
async def mock_execute_trace_hog(inputs: ExecuteTraceEvaluationInputs) -> EvaluationActivityResult:
calls.append("execute")
+ if output_type == "numeric":
+ return {"result_type": "numeric", "score": 0.25, "reasoning": "ok", "allows_na": False}
return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}
@activity.defn(name="emit_trace_evaluation_event_activity")
@@ -256,11 +258,15 @@ def _mock_activities(calls: list[str], exclude: set[str] | None = None) -> list[
@activity.defn(name="execute_session_hog_eval_activity")
async def mock_execute_session_hog(inputs: ExecuteSessionEvaluationInputs) -> EvaluationActivityResult:
calls.append("execute_session")
+ if output_type == "numeric":
+ return {"result_type": "numeric", "score": 0.25, "reasoning": "ok", "allows_na": False}
return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}
@activity.defn(name="execute_session_llm_judge_activity")
async def mock_execute_session_judge(inputs: ExecuteSessionEvaluationInputs) -> EvaluationActivityResult:
calls.append("execute_session")
+ if output_type == "numeric":
+ return {"result_type": "numeric", "score": 0.25, "reasoning": "ok", "allows_na": False}
return {"result_type": "boolean", "verdict": True, "reasoning": "ok", "allows_na": False}
@activity.defn(name="find_evaluation_quiet_point_activity")
@@ -325,7 +331,10 @@ class TestQuietPoint:
class TestRunAggregateEvaluationWorkflow:
@pytest.mark.asyncio
- async def test_fixed_window_sleeps_then_evaluates(self):
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
+ async def test_fixed_window_sleeps_then_evaluates(self, output_type: str, caplog: pytest.LogCaptureFixture):
+ caplog.set_level("INFO", logger="temporalio.workflow")
+ caplog.set_level("INFO", logger="temporalio.activity")
calls: list[str] = []
task_queue = str(uuid.uuid4())
async with await WorkflowEnvironment.start_time_skipping() as env:
@@ -333,7 +342,7 @@ class TestRunAggregateEvaluationWorkflow:
env.client,
task_queue=task_queue,
workflows=[RunAggregateEvaluationWorkflow],
- activities=_mock_activities(calls),
+ activities=_mock_activities(calls, output_type=output_type),
workflow_runner=UnsandboxedWorkflowRunner(),
):
start = await env.get_current_time()
@@ -342,10 +351,15 @@ class TestRunAggregateEvaluationWorkflow:
_workflow_inputs({"strategy": "fixed_window", "window_seconds": 600}),
id=str(uuid.uuid4()),
task_queue=task_queue,
+ execution_timeout=timedelta(minutes=20),
)
elapsed = (await env.get_current_time()) - start
assert calls == ["fetch", "execute", "emit", "telemetry"]
- assert result["verdict"] is True
+ if output_type == "numeric":
+ assert result["score"] == 0.25
+ assert "verdict" not in result
+ else:
+ assert result["verdict"] is True
assert elapsed >= timedelta(seconds=600)
assert elapsed < timedelta(seconds=900)
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index e2063a6b0bc2..292850ffccc3 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -1,7 +1,7 @@
import json
import uuid
from datetime import UTC, datetime
-from typing import Any
+from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -44,8 +44,19 @@ from .evaluation_errors import (
status_reason_detail_for_terminal_user_error,
terminal_user_error_result_from_application_error,
)
-from .evaluation_llm_judge import JUDGE_EVENT_MAX_CHARS, TransientJudgeError, _execute_llm_judge_activity
-from .evaluation_workflow_activities import LocalEvaluationOutcome, backfill_verdict_timestamp
+from .evaluation_llm_judge import (
+ JUDGE_EVENT_MAX_CHARS,
+ NumericWithNAEvalResult,
+ TransientJudgeError,
+ _execute_llm_judge_activity,
+ get_output_type_config,
+)
+from .evaluation_workflow_activities import (
+ LocalEvaluationOutcome,
+ backfill_verdict_timestamp,
+ build_evaluation_event_properties,
+ emit_internal_telemetry_activity,
+)
from .run_evaluation import (
BooleanEvalResult,
BooleanWithNAEvalResult,
@@ -508,6 +519,29 @@ class TestRunEvaluationWorkflow:
assert result["provider"]
mock_client.complete.assert_called_once()
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_numeric_telemetry_omits_customer_score(self, setup_data: dict[str, Any]) -> None:
+ evaluation = {"id": str(setup_data["evaluation"].id), "name": "Quality", "evaluation_type": "hog"}
+ result: EvaluationActivityResult = {
+ "result_type": "numeric",
+ "score": 123.45,
+ "reasoning": "Customer content",
+ "allows_na": False,
+ }
+ with patch("posthog.tasks.usage_report.get_ph_client") as get_client:
+ await emit_internal_telemetry_activity(
+ EmitInternalTelemetryInputs(evaluation=evaluation, team_id=setup_data["team"].id, result=result)
+ )
+
+ get_client.return_value.capture.assert_called_once()
+ properties = get_client.return_value.capture.call_args.kwargs["properties"]
+ assert properties["result_type"] == "numeric"
+ assert "score" not in properties
+ assert "reasoning" not in properties
+ event_properties = build_evaluation_event_properties(evaluation, result, datetime(2026, 7, 1, tzinfo=UTC))
+ assert event_properties["$ai_evaluation_numeric_result"] == 123.45
+
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
async def test_emit_evaluation_event_activity(self, setup_data):
@@ -1716,15 +1750,16 @@ class TestRunEvaluationWorkflow:
pytest.param({"allows_na": True}, None, False, id="allows_na_true"),
],
)
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
def test_execute_llm_judge_activity_parse_error_skips_item(
- self, output_config, expected_verdict, expected_applicable
+ self, output_config, expected_verdict, expected_applicable, output_type
):
evaluation = {
"id": "eval-123",
"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": 1,
}
@@ -1756,19 +1791,24 @@ class TestRunEvaluationWorkflow:
mock_increment_errors.assert_called_once_with("parse_error", provider="openai")
assert result["skipped"] is True
assert result["skip_reason"] == "unparsable_response"
- assert result["verdict"] is expected_verdict
+ assert result["result_type"] == output_type
+ if output_type == "numeric":
+ assert "verdict" not in result
+ else:
+ assert result["verdict"] is expected_verdict
assert result.get("applicable") is expected_applicable
# The exception drops the provider's counts, but the call still happened on a known model.
assert result["provider"] == "openai"
assert result["input_tokens"] == 0
- def test_execute_llm_judge_activity_empty_structured_response_skips_item(self):
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
+ def test_execute_llm_judge_activity_empty_structured_response_skips_item(self, output_type):
evaluation = {
"id": "eval-123",
"name": "Test Evaluation",
"evaluation_type": "llm_judge",
"evaluation_config": {"prompt": "Is this response factually accurate?"},
- "output_type": "boolean",
+ "output_type": output_type,
"output_config": {},
"team_id": 1,
}
@@ -1799,6 +1839,9 @@ class TestRunEvaluationWorkflow:
result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
mock_increment_errors.assert_called_once_with("empty_structured_response", provider="openai")
+ assert result["result_type"] == output_type
+ if output_type == "numeric":
+ assert "verdict" not in result
assert result["skipped"] is True
assert result["skip_reason"] == "unparsable_response"
assert result["provider"] == "openai"
@@ -2545,6 +2588,125 @@ class TestExecuteSentimentEvalActivity:
class TestEvalResultModels:
+ @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 = {
+ "id": "numeric-eval",
+ "name": "Quality",
+ "team_id": 1,
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Rate quality"},
+ "output_type": "numeric",
+ "output_config": {"min": 0, "max": 1, "allows_na": True},
+ }
+ schema = get_output_type_config(True, output_type="numeric").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,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as increment_errors,
+ ):
+ 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": "Quality", "score": score}),
+ usage=MagicMock(input_tokens=100, output_tokens=20, total_tokens=120),
+ )
+ inputs = ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=create_mock_event_data(1))
+ result = _execute_llm_judge_activity(inputs)
+ increment_errors.assert_not_called()
+ assert result["result_type"] == "numeric"
+ assert "verdict" not in result
+ if score is not None and not 0 <= score <= 1:
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "score_out_of_bounds"
+ assert "terminal_user_error" not in result
+ assert "score" not in result
+ properties = build_evaluation_event_properties(evaluation, result, datetime(2026, 7, 1, tzinfo=UTC))
+ assert properties["$ai_evaluation_skipped"] is True
+ assert properties["$ai_evaluation_skip_reason"] == "score_out_of_bounds"
+ assert properties["$ai_evaluation_reasoning"].startswith("Quality\n\n")
+ assert "$ai_evaluation_numeric_result" not in properties
+ assert properties["$ai_input_tokens"] == 100
+ assert properties["$ai_output_tokens"] == 20
+ assert properties["$ai_model"] == "gpt-4o-mini"
+ assert properties["$ai_provider"] == "openai"
+ return
+ assert result["applicable"] is (score is not None)
+ if score is None:
+ assert "score" not in result
+ assert "score_min" not in result
+ else:
+ assert result["score"] == score
+ assert result["score_min"] == 0
+ assert result["score_max"] == 1
+
+ @pytest.mark.parametrize("allows_na", [False, True])
+ @pytest.mark.parametrize("value", [True, "0.5", float("nan"), float("inf")])
+ def test_numeric_schema_rejects_invalid_scores(self, value: object, allows_na: bool) -> None:
+ schema = get_output_type_config(allows_na, output_type="numeric").response_format
+ with pytest.raises(ValueError):
+ schema.model_validate({"reasoning": "Quality", "score": value})
+
+ @pytest.mark.parametrize("score", [0, 0.5, None])
+ def test_numeric_na_is_derived_from_score(self, score: float | None) -> None:
+ schema = get_output_type_config(True, output_type="numeric").response_format
+ result = schema.model_validate({"reasoning": "Quality", "score": score})
+ assert isinstance(result, NumericWithNAEvalResult)
+ assert result.model_dump() == {"reasoning": "Quality", "score": score}
+ assert result.applicable is (score is not None)
+ with pytest.raises(ValueError):
+ schema.model_validate({"reasoning": "Quality"})
+
+ @pytest.mark.parametrize(
+ "extra,expected",
+ [
+ (
+ {"score": 0, "score_min": 0, "score_max": 1},
+ {
+ "$ai_evaluation_numeric_result": 0,
+ "$ai_evaluation_numeric_result_min": 0,
+ "$ai_evaluation_numeric_result_max": 1,
+ },
+ ),
+ ({"applicable": False}, {}),
+ ({"skipped": True, "skip_reason": "trace_not_found"}, {}),
+ ],
+ )
+ def test_numeric_event_properties(self, extra: dict[str, Any], expected: dict[str, Any]) -> None:
+ result = cast(
+ EvaluationActivityResult,
+ {
+ "result_type": "numeric",
+ "reasoning": "Quality",
+ "allows_na": True,
+ **extra,
+ },
+ )
+ properties = build_evaluation_event_properties(
+ {"id": "eval", "name": "Quality", "evaluation_type": "hog"},
+ result,
+ datetime(2026, 7, 1, tzinfo=UTC),
+ )
+ assert properties["$ai_evaluation_result_type"] == "numeric"
+ assert "$ai_evaluation_result" not in properties
+ assert "$ai_score" not in properties
+ assert "$ai_score_min" not in properties
+ assert "$ai_score_max" not in properties
+ assert {
+ key: value
+ for key, value in properties.items()
+ if key
+ in (
+ "$ai_evaluation_numeric_result",
+ "$ai_evaluation_numeric_result_min",
+ "$ai_evaluation_numeric_result_max",
+ )
+ } == expected
+
def test_boolean_eval_result(self):
"""Test BooleanEvalResult model"""
result = BooleanEvalResult(reasoning="Test reasoning", verdict=True)
diff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.py
index 37a403ae37ea..fc58a89d296d 100644
--- a/posthog/temporal/ai_observability/test_run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py
@@ -14,6 +14,12 @@ from posthog.schema import LLMTrace, LLMTraceEvent
from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT
from posthog.cdp.validation import compile_hog
+from posthog.temporal.ai_observability.evaluation_hog import run_hog_eval_for_event
+from posthog.temporal.ai_observability.evaluation_llm_judge import (
+ ExecuteLLMJudgeInputs,
+ _execute_llm_judge_activity,
+ get_output_type_config,
+)
from posthog.temporal.ai_observability.evaluation_payload import payload_budget_bytes
from posthog.temporal.ai_observability.run_session_evaluation import (
_SESSION_EVENT_COUNT_SQL,
@@ -31,6 +37,14 @@ from posthog.temporal.ai_observability.run_session_evaluation import (
run_hog_eval_over_recent_sessions,
session_fetch_lookback,
)
+from posthog.temporal.ai_observability.run_trace_evaluation import (
+ ExecuteTraceEvaluationInputs,
+ TraceFetchOutcome,
+ execute_trace_hog_eval_activity,
+ execute_trace_llm_judge_activity,
+)
+
+from products.ai_observability.backend.hog import compile_ai_observability_hog
FROZEN_NOW = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)
@@ -461,6 +475,85 @@ 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:
+ trace = _trace("trace-1", cost=0, latency=0)
+ evaluation = {
+ "id": "numeric-eval",
+ "team_id": 1,
+ "evaluation_type": runtime,
+ "evaluation_config": {
+ "prompt": "Rate quality",
+ "bytecode": compile_ai_observability_hog(
+ "return null" if score is None else "return 0.25",
+ "destination",
+ ),
+ },
+ "output_type": "numeric",
+ "output_config": {"min": 0, "max": 1, "allows_na": True},
+ }
+ schema = get_output_type_config(True, output_type="numeric").response_format
+ with (
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
+ return_value=SessionFetchOutcome(traces=[trace], skip_reason=None, event_count=1),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",
+ return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=1),
+ ),
+ 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 = Mock(
+ provider="openai",
+ model="gpt-4o-mini",
+ provider_key=None,
+ is_byok=False,
+ )
+ client.return_value.complete.return_value = Mock(
+ parsed=schema.model_validate({"reasoning": "Quality", "score": score}),
+ usage=None,
+ )
+ if target == "generation":
+ event_data = {"event": "$ai_generation", "properties": trace.events[0].properties}
+ result = (
+ async_to_sync(run_hog_eval_for_event)(evaluation, event_data)
+ if runtime == "hog"
+ else _execute_llm_judge_activity(
+ ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data)
+ )
+ )
+ elif target == "trace":
+ trace_inputs = ExecuteTraceEvaluationInputs(
+ evaluation=evaluation, team_id=1, trace_id="trace-1", window_start=FROZEN_NOW.isoformat()
+ )
+ result = (
+ async_to_sync(execute_trace_hog_eval_activity)(trace_inputs)
+ if runtime == "hog"
+ else execute_trace_llm_judge_activity(trace_inputs)
+ )
+ else:
+ session_inputs = ExecuteSessionEvaluationInputs(
+ evaluation=evaluation, team_id=1, session_id="session-1", window_start=FROZEN_NOW.isoformat()
+ )
+ result = (
+ async_to_sync(execute_session_hog_eval_activity)(session_inputs)
+ if runtime == "hog"
+ else execute_session_llm_judge_activity(session_inputs)
+ )
+ assert result["result_type"] == "numeric"
+ assert "verdict" not in result
+ assert result["applicable"] is (score is not None)
+ if score is None:
+ assert "score" not in result
+ else:
+ assert result["score"] == score
+ assert result["score_min"] == 0
+ assert result["score_max"] == 1
+
@pytest.mark.parametrize(
"skip_reason",
[
@@ -471,7 +564,8 @@ class TestExecuteSessionActivities:
"property_access_restricted",
],
)
- def test_hog_skips_carry_a_session_specific_reason(self, skip_reason):
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
+ def test_hog_skips_carry_a_session_specific_reason(self, skip_reason, output_type):
with patch(
"posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
return_value=SessionFetchOutcome(traces=None, skip_reason=skip_reason, event_count=0),
@@ -482,6 +576,7 @@ class TestExecuteSessionActivities:
"evaluation_type": "hog",
"evaluation_config": {"bytecode": ["_H", 1, 32, True]},
"output_config": {"allows_na": False},
+ "output_type": output_type,
},
team_id=1,
session_id="s-1",
@@ -491,6 +586,10 @@ class TestExecuteSessionActivities:
assert result["skipped"] is True
assert result["skip_reason"] == skip_reason
assert "session" in result["reasoning"].lower()
+ assert result["result_type"] == output_type
+ assert "score" not in result
+ if output_type == "numeric":
+ assert "verdict" not in result
def test_judge_rejects_a_non_judge_evaluation(self):
with pytest.raises(ApplicationError, match="Unsupported evaluation type"):
@@ -503,8 +602,9 @@ class TestExecuteSessionActivities:
)
)
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
@pytest.mark.parametrize("skip_reason", ["session_truncated", "property_access_restricted"])
- def test_judge_skips_without_judging(self, skip_reason: str) -> None:
+ def test_judge_skips_without_judging(self, output_type: str, skip_reason: str) -> None:
with (
patch(
"posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
@@ -517,7 +617,7 @@ class TestExecuteSessionActivities:
evaluation={
"evaluation_type": "llm_judge",
"evaluation_config": {"prompt": "Did the user accomplish their goal?"},
- "output_type": "boolean",
+ "output_type": output_type,
"output_config": {"allows_na": False},
},
team_id=1,
@@ -527,6 +627,10 @@ class TestExecuteSessionActivities:
)
assert result["skipped"] is True
assert result["skip_reason"] == skip_reason
+ assert result["result_type"] == output_type
+ assert "score" not in result
+ if output_type == "numeric":
+ assert "verdict" not in result
if skip_reason == "property_access_restricted":
assert "property access rules" in result["reasoning"]
# The whole point of the truncation-as-skip choice: never grade a partial transcript.
diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
index 592b73d744d7..4bf4dcba2b73 100644
--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
@@ -507,7 +507,8 @@ class TestRunHogEvalOverRecentTraces:
assert rewritten_condition.left.chain == ["input"]
@time_machine.travel(FROZEN_NOW, tick=False)
- def test_uses_the_sampled_trigger_and_configured_aggregation_window(self):
+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])
+ def test_uses_the_sampled_trigger_and_configured_aggregation_window(self, output_type: str):
team = MagicMock(spec=Team)
user = MagicMock()
trigger_timestamp = FROZEN_NOW - timedelta(hours=2)
@@ -518,7 +519,9 @@ class TestRunHogEvalOverRecentTraces:
]
)
bytecode = compile_hog(
- "return target.type == 'trace' and length(evaluation_events) == 2",
+ "return length(evaluation_events) / 4"
+ if output_type == "numeric"
+ else "return target.type == 'trace' and length(evaluation_events) == 2",
"destination",
)
@@ -541,6 +544,8 @@ class TestRunHogEvalOverRecentTraces:
condition_filter=None,
sample_count=1,
allows_na=False,
+ output_type=output_type,
+ output_config={"min": 0, "max": 1} if output_type == "numeric" else {},
window_seconds=120,
)
@@ -559,7 +564,11 @@ class TestRunHogEvalOverRecentTraces:
assert runner_kwargs["query"].traceId == "trace-123"
assert runner_kwargs["query"].dateRange.date_from == (trigger_timestamp - TRACE_EVENTS_LOOKBACK).isoformat()
assert runner_kwargs["query"].dateRange.date_to == (trigger_timestamp + timedelta(seconds=120)).isoformat()
- assert results[0].verdict is True
+ if output_type == "numeric":
+ assert results[0].score == 0.5
+ assert results[0].verdict is None
+ else:
+ assert results[0].verdict is True
assert results[0].input_preview == "first"
assert results[0].output_preview == "two"
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index ce34b3a7b16e..cf914478c21b 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -36,6 +36,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
normalize_report_content_payload,
)
+from products.ai_observability.backend.api.evaluations import _OutputConfigField
from products.ai_observability.backend.api.metrics import llma_track_latency
from products.ai_observability.backend.models.evaluation_configs import OutputType, evaluation_supports_reports
from products.ai_observability.backend.models.evaluation_reports import (
@@ -235,7 +236,7 @@ class EvaluationReportSerializer(serializers.ModelSerializer):
team = self.context["get_team"]()
if value.team_id != team.id:
raise serializers.ValidationError("Evaluation does not belong to this team.")
- if not evaluation_supports_reports(value.output_type, value.target):
+ if not evaluation_supports_reports(value.output_type, value.target, value.output_config):
raise serializers.ValidationError(REPORT_NOT_SUPPORTED_ERROR)
return value
@@ -427,6 +428,10 @@ 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.",
+ )
output_type = serializers.ChoiceField(
choices=OutputType.choices,
required=False,
@@ -473,12 +478,13 @@ class EvaluationReportMetricsSerializer(serializers.Serializer):
)
pass_rate = serializers.FloatField(
required=False,
- help_text="Boolean pass percentage, excluding results marked not applicable.",
+ allow_null=True,
+ help_text="Boolean or numeric pass percentage, excluding N/A results. Null when no numeric scores were produced.",
)
previous_pass_rate = serializers.FloatField(
required=False,
allow_null=True,
- help_text="Boolean pass percentage for the previous period, or null when unavailable.",
+ help_text="Boolean or numeric pass percentage for the previous period, or null when unavailable.",
)
@@ -652,7 +658,8 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse
report_queryset = report_queryset.filter(evaluation_id__in=visible_evaluation_ids)
# Generate validates eligibility explicitly so unsupported legacy rows return a useful 400.
if self.action != "generate":
- report_queryset = report_queryset.reportable()
+ # Reading stored reports must not depend on the current passing rule.
+ report_queryset = report_queryset.for_supported_evaluations()
if self.action not in ("update", "partial_update"):
report_queryset = report_queryset.filter(deleted=False)
@@ -786,7 +793,9 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse
def generate(self, request: Request, **kwargs) -> Response:
"""Trigger immediate report generation."""
report = self.get_object()
- if not evaluation_supports_reports(report.evaluation.output_type, report.evaluation.target):
+ if not evaluation_supports_reports(
+ report.evaluation.output_type, report.evaluation.target, report.evaluation.output_config
+ ):
raise serializers.ValidationError({"evaluation": REPORT_NOT_SUPPORTED_ERROR})
try:
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index d1e33f607d09..c91632bf53ec 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -1,6 +1,8 @@
+from collections import Counter
+from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Any, cast
-from django.db import transaction
+from django.db import models, transaction
from django.db.models import Q, QuerySet
from django.http import Http404
@@ -28,7 +30,8 @@ from posthog.event_usage import report_user_action
from posthog.hogql_queries.ai.ai_table_resolver import AIEventsUnavailableError, query_ai_events
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_properties
from posthog.models.team import Team
-from posthog.permissions import AccessControlPermission
+from posthog.permissions import AccessControlPermission, posthog_feature_flag_enabled
+from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.model_resolution import active_key_fallback
from posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_eval
@@ -62,6 +65,7 @@ from ..models.evaluation_configs import (
TRACE_EVAL_MIN_QUIET_PERIOD_SECONDS,
TRACE_EVAL_MIN_WINDOW_SECONDS,
EvaluationType,
+ OutputType,
evaluation_supports_reports,
evaluation_uses_model_configuration,
get_evaluation_config_content_key,
@@ -80,6 +84,27 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
+NUMERIC_EVALUATIONS_FEATURE_FLAG = "llm-analytics-numeric-evaluations"
+
+
+def _numeric_evaluations_enabled(serializer: serializers.BaseSerializer) -> bool:
+ request = serializer.context.get("request")
+ get_team = serializer.context.get("get_team")
+ user = getattr(request, "user", None)
+ if user is None or not getattr(user, "is_authenticated", False) or not callable(get_team):
+ return False
+
+ team = get_team()
+ try:
+ return posthog_feature_flag_enabled(
+ NUMERIC_EVALUATIONS_FEATURE_FLAG,
+ str(user.distinct_id),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ )
+ except Exception:
+ return False
+
@extend_schema_field(
{
@@ -104,7 +129,7 @@ logger = structlog.get_logger(__name__)
"properties": {
"source": {
"type": "string",
- "description": "Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
+ "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.",
"minLength": 1,
}
},
@@ -146,18 +171,55 @@ class _EvaluationConfigField(serializers.JSONField):
},
"true_is_failure": {
"type": "boolean",
- "description": (
- "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 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": {
+ "type": "number",
+ "nullable": True,
+ "description": "Inclusive minimum numeric score. Omit for no lower bound.",
+ },
+ "max": {
+ "type": "number",
+ "nullable": True,
+ "description": "Inclusive maximum numeric score. Omit for no upper bound.",
+ },
+ "step": {
+ "type": "number",
+ "nullable": True,
+ "exclusiveMinimum": True,
+ "minimum": 0,
+ "description": "Optional positive input increment. Does not round evaluation results.",
+ },
+ "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.",
+ },
+ "threshold": {
+ "type": "number",
+ "description": "Finite passing threshold within any configured score bounds.",
+ },
+ },
+ "additionalProperties": False,
},
},
"additionalProperties": False,
}
)
-class _OutputConfigField(serializers.JSONField):
- pass
+class _OutputConfigField(serializers.DictField):
+ child = serializers.JSONField(allow_null=True)
@extend_schema_field(
@@ -332,7 +394,9 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
required=False,
help_text=(
"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."
+ "{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': {}."
),
)
target_config = _TargetConfigField(
@@ -404,7 +468,7 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
},
"output_type": {
"help_text": (
- "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis."
+ "Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis."
)
},
"target": {
@@ -425,6 +489,19 @@ 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."})
+ if (
+ self.instance
+ and output_type != self.instance.output_type
+ and "numeric" in (output_type, self.instance.output_type)
+ ):
+ raise serializers.ValidationError(
+ {"output_type": "Create a new evaluation to change between numeric and other output types."}
+ )
model_configuration = data.get(
"model_configuration",
getattr(self.instance, "model_configuration", None) if self.instance else None,
@@ -772,12 +849,28 @@ class TestHogTargetConfigSerializer(serializers.Serializer):
)
+class HogEvaluationOutputType(models.TextChoices):
+ BOOLEAN = OutputType.BOOLEAN.value, OutputType.BOOLEAN.label
+ NUMERIC = OutputType.NUMERIC.value, OutputType.NUMERIC.label
+
+
class TestHogRequestSerializer(serializers.Serializer):
+ output_type = serializers.ChoiceField(
+ choices=HogEvaluationOutputType.choices,
+ required=False,
+ default=OutputType.BOOLEAN,
+ help_text="Expected output: boolean or numeric. 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.",
+ )
source = serializers.CharField(
required=True,
min_length=1,
help_text=(
- "Hog source code to test. Must return true or false, or null for N/A. "
+ "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."
),
) # type: ignore[assignment]
@@ -816,8 +909,23 @@ class TestHogRequestSerializer(serializers.Serializer):
),
)
+ def validate(self, data: dict) -> dict:
+ output_config = {"allows_na": data["allows_na"], **data["output_config"]}
+ try:
+ _, output_config = validate_evaluation_configs(
+ "hog", data["output_type"], {"source": data["source"]}, output_config
+ )
+ except ValueError as error:
+ raise serializers.ValidationError({"output_config": str(error)}) from error
+ data["output_config"] = output_config
+ data["allows_na"] = output_config.get("allows_na", False)
+ return data
+
class TestHogResultItemSerializer(serializers.Serializer):
+ score = serializers.FloatField(
+ required=False, allow_null=True, help_text="Raw numeric score, or null when no numeric score was produced."
+ )
sample_id = serializers.CharField(help_text="Stable identifier for the sampled generation, trace, or session.")
sample_type = serializers.ChoiceField(
choices=EvaluationTarget.choices,
@@ -844,6 +952,24 @@ class TestHogResponseSerializer(serializers.Serializer):
)
+def _hog_test_result_counts(
+ results: Sequence[Mapping[str, object]], output_type: str, output_config: dict[str, object] | None
+) -> dict[str, int]:
+ config = output_config or {}
+ # Preview telemetry and reports must agree on polarity and thresholds.
+ definition = get_outcome_definition(
+ output_type, true_is_failure=config.get("true_is_failure") is True, output_config=config
+ )
+ counts: Counter[str | None] = Counter()
+ for result in results:
+ if result["error"]:
+ counts["error"] += 1
+ else:
+ value = 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")}
+
+
def _humanize_seconds(seconds: int) -> str:
"""Whole units only: this reads back the quiet period the user just set, so "24 hours" beats
"1440 minutes"."""
@@ -866,6 +992,8 @@ def _test_hog_over_sessions(
allows_na: bool,
conditions: list[dict[str, Any]],
quiet_period_seconds: int,
+ output_type: str = "boolean",
+ output_config: dict | None = None,
) -> Response:
"""Session-target variant of `test_hog`: sample sessions that have gone quiet and run the code
against session-level globals, so the editor preview matches how a session eval runs online."""
@@ -878,6 +1006,8 @@ def _test_hog_over_sessions(
condition_filter=condition_filter,
sample_count=sample_count,
allows_na=allows_na,
+ output_type=output_type,
+ output_config=output_config,
quiet_period_seconds=quiet_period_seconds,
)
except AIEventsUnavailableError:
@@ -892,6 +1022,7 @@ def _test_hog_over_sessions(
"input_preview": r.input_preview,
"output_preview": r.output_preview,
"result": r.verdict,
+ **({"score": r.score} if output_type == "numeric" else {}),
"reasoning": r.reasoning,
"error": r.error,
}
@@ -904,6 +1035,7 @@ def _test_hog_over_sessions(
{
"sample_count": sample_count,
"results_count": len(results),
+ **_hog_test_result_counts(results, output_type, output_config),
"target": EvaluationTarget.SESSION.value,
"condition_count": len(conditions),
},
@@ -937,6 +1069,8 @@ def _test_hog_over_traces(
allows_na: bool,
conditions: list[dict[str, Any]],
window_seconds: int,
+ output_type: str = "boolean",
+ output_config: dict | None = None,
) -> Response:
"""Trace-target variant of the `test_hog` action: sample recent whole traces and run the code
against trace-level globals, so the editor preview matches how a trace eval runs online."""
@@ -949,6 +1083,8 @@ def _test_hog_over_traces(
condition_filter=condition_filter,
sample_count=sample_count,
allows_na=allows_na,
+ output_type=output_type,
+ output_config=output_config,
window_seconds=window_seconds,
)
except AIEventsUnavailableError:
@@ -963,6 +1099,7 @@ def _test_hog_over_traces(
"input_preview": r.input_preview,
"output_preview": r.output_preview,
"result": r.verdict,
+ **({"score": r.score} if output_type == "numeric" else {}),
"reasoning": r.reasoning,
"error": r.error,
}
@@ -977,10 +1114,7 @@ def _test_hog_over_traces(
"allows_na": allows_na,
"condition_count": len(conditions),
"result_count": len(results),
- "pass_count": sum(1 for r in results if r["result"] is True),
- "fail_count": sum(1 for r in results if r["result"] is False),
- "error_count": sum(1 for r in results if r["error"]),
- "na_count": sum(1 for r in results if r["result"] is None and not r["error"]),
+ **_hog_test_result_counts(results, output_type, output_config),
"no_events": not results,
"target": EvaluationTarget.TRACE.value,
},
@@ -1053,7 +1187,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
with transaction.atomic():
instance = serializer.save()
- if evaluation_supports_reports(instance.output_type, instance.target):
+ if evaluation_supports_reports(instance.output_type, instance.target, instance.output_config):
# Auto-create a default report config so reports are generated from the start.
# Defaults to count-triggered (frequency=every_n), so rrule/starts_at stay empty
# and users add email/Slack delivery targets later if they want notifications.
@@ -1086,6 +1220,9 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
)
def perform_update(self, serializer):
+ previously_supported_reports = evaluation_supports_reports(
+ serializer.instance.output_type, serializer.instance.target, serializer.instance.output_config
+ )
# Check if this is a deletion (soft delete)
is_deletion = serializer.validated_data.get("deleted") is True and not serializer.instance.deleted
@@ -1138,7 +1275,16 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
if old_content != new_content:
config_content_changed = True
- instance = serializer.save()
+ with transaction.atomic():
+ instance = serializer.save()
+ if (
+ not previously_supported_reports
+ and not instance.deleted
+ and evaluation_supports_reports(instance.output_type, instance.target, instance.output_config)
+ ):
+ report, created = EvaluationReport.objects.get_or_create(evaluation=instance, team_id=self.team_id)
+ if not created:
+ report.restart_reporting()
# Track appropriate event
if is_deletion:
@@ -1215,6 +1361,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
source = serializer.validated_data["source"]
sample_count = serializer.validated_data["sample_count"]
allows_na = serializer.validated_data["allows_na"]
+ output_type = serializer.validated_data["output_type"]
+ output_config = serializer.validated_data["output_config"]
conditions = serializer.validated_data.get("conditions", [])
target = serializer.validated_data["target"]
target_config = serializer.validated_data["target_config"]
@@ -1240,6 +1388,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
condition_filter=condition_filter,
sample_count=min(sample_count, SESSION_TEST_HOG_MAX_SAMPLES),
allows_na=allows_na,
+ output_type=output_type,
+ output_config=output_config,
conditions=conditions,
quiet_period_seconds=target_config.get(
"quiet_period_seconds", SESSION_EVAL_DEFAULT_QUIET_PERIOD_SECONDS
@@ -1254,6 +1404,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
condition_filter=condition_filter,
sample_count=sample_count,
allows_na=allows_na,
+ output_type=output_type,
+ output_config=output_config,
conditions=conditions,
window_seconds=target_config.get("window_seconds", TRACE_EVAL_DEFAULT_WINDOW_SECONDS),
)
@@ -1354,7 +1506,9 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
"timestamp": timestamp,
}
- result = run_hog_eval(bytecode, event_data, allows_na=allows_na)
+ result = run_hog_eval(
+ bytecode, event_data, allows_na=allows_na, output_type=output_type, output_config=output_config
+ )
io = extract_event_io(event_type, properties)
input_preview = extract_text_from_messages(io.input_raw)[:200]
@@ -1368,7 +1522,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
"trace_id": properties.get("$ai_trace_id"),
"input_preview": input_preview,
"output_preview": output_preview,
- "result": result["verdict"],
+ "result": result.get("verdict"),
+ **({"score": result.get("score")} if output_type == "numeric" else {}),
"reasoning": result["reasoning"],
"error": result["error"],
}
@@ -1382,10 +1537,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
"allows_na": allows_na,
"condition_count": len(conditions),
"result_count": len(results),
- "pass_count": sum(1 for r in results if r["result"] is True),
- "fail_count": sum(1 for r in results if r["result"] is False),
- "error_count": sum(1 for r in results if r["error"]),
- "na_count": sum(1 for r in results if r["result"] is None and not r["error"]),
+ **_hog_test_result_counts(results, output_type, output_config),
"no_events": False,
"target": target,
},
diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.py
index 14bc557a9266..b302ebcd992f 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py
@@ -802,7 +802,14 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertFalse(report.deleted)
self.assertEqual(EvaluationReport.objects.filter(deleted=False).count(), 1)
- def test_runs_action_returns_paginated_shape(self):
+ @parameterized.expand(
+ [
+ ("boolean", None),
+ ("numeric_rule_removed", {}),
+ ("numeric_rule_cleared", {"passing_rule": None}),
+ ]
+ )
+ def test_runs_action_returns_paginated_shape(self, _name: str, output_config: dict[str, object] | None) -> None:
report = self._create_report()
EvaluationReportRun.objects.create(
report=report,
@@ -811,6 +818,9 @@ class TestEvaluationReportApi(APIBaseTest):
period_start=timezone.now() - dt.timedelta(hours=1),
period_end=timezone.now(),
)
+ if output_config is not None:
+ Evaluation.objects.filter(id=self.evaluation.id).update(output_type="numeric", output_config=output_config)
+
response = self.client.get(f"{self.base_url}{report.id}/runs/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
body = response.json()
@@ -818,6 +828,13 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertIn("count", body)
self.assertEqual(body["count"], 1)
self.assertEqual(len(body["results"]), 1)
+ self.assertEqual(self.client.get(f"{self.base_url}{report.id}/").status_code, status.HTTP_200_OK)
+ self.assertIn(str(report.id), {item["id"] for item in self.client.get(self.base_url).json()["results"]})
+ if output_config is not None:
+ self.assertFalse(EvaluationReport.objects.deliverable().filter(id=report.id).exists())
+ self.assertEqual(
+ self.client.post(f"{self.base_url}{report.id}/generate/").status_code, status.HTTP_400_BAD_REQUEST
+ )
# The /runs/ and /generate/ custom @actions have to declare required_scopes explicitly;
# without them the default scope resolver returns None for non-CRUD action names and PAK
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index e22ae279f6c9..7cb41d3fb10b 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -1,8 +1,9 @@
import json
+from datetime import timedelta
from uuid import UUID, uuid4
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import Mock, patch
from django.db import IntegrityError, connection, transaction
from django.test import SimpleTestCase
@@ -11,13 +12,19 @@ from django.utils import timezone
from drf_spectacular.plumbing import get_override
from parameterized import parameterized
from rest_framework import status
+from rest_framework.exceptions import ValidationError
from posthog.constants import AvailableFeature
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTY
from posthog.models import Organization, OrganizationMembership, Project, Team, User
from products.access_control.backend.models.access_control import AccessControl
-from products.ai_observability.backend.api.evaluations import ModelConfigurationSerializer, _TargetConfigField
+from products.ai_observability.backend.api.evaluations import (
+ EvaluationSerializer,
+ ModelConfigurationSerializer,
+ TestHogRequestSerializer as HogRequestSerializer,
+ _TargetConfigField,
+)
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.evaluation_configs import validate_target_config
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
@@ -54,6 +61,52 @@ def _setup_team():
return team
+class TestNumericEvaluationSerializer(SimpleTestCase):
+ @parameterized.expand([("min", 0), ("passing_rule", {"operator": "gte", "threshold": 7})])
+ def test_boolean_patch_rejects_numeric_settings(self, key: str, value: object) -> None:
+ evaluation = Evaluation(
+ evaluation_type="hog", evaluation_config={"source": "return true;"}, output_type="boolean", output_config={}
+ )
+ serializer = EvaluationSerializer(instance=evaluation, data={"output_config": {key: value}}, partial=True)
+ self.assertFalse(serializer.is_valid())
+ self.assertIn(key, str(serializer.errors))
+
+ def test_preview_validates_numeric_config(self):
+ serializer = HogRequestSerializer(
+ data={"source": "return 0;", "output_type": "numeric", "output_config": {"min": 0, "allows_na": True}}
+ )
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ self.assertEqual(serializer.validated_data["output_type"], "numeric")
+ self.assertTrue(serializer.validated_data["allows_na"])
+
+ @parameterized.expand([({"min": 10, "max": 0},), ([],), ("invalid",), (1,), (True,), (None,)])
+ def test_preview_rejects_invalid_numeric_config(self, output_config: object) -> None:
+ serializer = HogRequestSerializer(
+ data={"source": "return 0;", "output_type": "numeric", "output_config": output_config}
+ )
+ self.assertFalse(serializer.is_valid())
+ self.assertIn("output_config", serializer.errors)
+
+ def test_patch_can_clear_rule_without_clearing_bounds(self):
+ evaluation = Evaluation(
+ evaluation_type="hog",
+ evaluation_config={"source": "return 0;"},
+ output_type="numeric",
+ output_config={"min": 0, "max": 10, "passing_rule": {"operator": "gte", "threshold": 7}},
+ )
+ serializer = EvaluationSerializer(instance=evaluation, partial=True)
+ data = serializer.validate({"output_config": {"passing_rule": None}})
+ self.assertEqual(data["output_config"], {"min": 0, "max": 10, "allows_na": False})
+
+ def test_existing_boolean_cannot_change_to_numeric(self):
+ evaluation = Evaluation(
+ evaluation_type="hog", evaluation_config={"source": "return true;"}, output_type="boolean", output_config={}
+ )
+ serializer = EvaluationSerializer(instance=evaluation, partial=True)
+ with self.assertRaises(ValidationError):
+ serializer.validate({"output_type": "numeric"})
+
+
class TestModelConfigurationSerializer(SimpleTestCase):
@parameterized.expand(
[
@@ -95,6 +148,114 @@ class TestTargetConfigFieldSchema(SimpleTestCase):
class TestEvaluationConfigsApi(APIBaseTest):
+ @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:
+ 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},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("Numeric evaluations are not enabled", str(response.data))
+
+ @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:
+ 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},
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",
+ {"name": "Renamed score"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ evaluation.refresh_from_db()
+ self.assertEqual(evaluation.name, "Renamed score")
+
+ @parameterized.expand([(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
+ ) -> None:
+ 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},
+ "enabled": enabled,
+ },
+ )
+ self.assertEqual(response.status_code, 201, response.json())
+ 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}}})
+ self.assertEqual(response.status_code, 200, response.json())
+ self.assertEqual(response.json()["output_config"]["min"], 0)
+ report = EvaluationReport.objects.get(evaluation=evaluation)
+ self.assertEqual(EvaluationReport.objects.deliverable().filter(id=report.id).exists(), enabled)
+ if not enabled:
+ response = self.client.patch(url, {"enabled": True})
+ self.assertEqual(response.status_code, 200, response.json())
+ self.assertTrue(EvaluationReport.objects.deliverable().filter(id=report.id).exists())
+ response = self.client.patch(url, {"output_config": {"passing_rule": None}})
+ self.assertEqual(response.status_code, 200, response.json())
+ self.assertFalse(EvaluationReport.objects.reportable().filter(id=report.id).exists())
+ old_delivery = timezone.now() - timedelta(days=90)
+ EvaluationReport.objects.filter(id=report.id).update(
+ frequency=frequency,
+ rrule="FREQ=DAILY",
+ starts_at=old_delivery,
+ last_delivered_at=old_delivery,
+ 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}}})
+ self.assertEqual(response.status_code, 200, response.json())
+ report.refresh_from_db()
+ self.assertIsNone(report.last_delivered_at)
+ if frequency == "scheduled":
+ assert report.next_delivery_date is not None
+ self.assertGreater(report.next_delivery_date, resumed_at)
+ self.assertEqual(report.starts_at, old_delivery)
+ else:
+ assert report.starts_at is not None
+ self.assertGreaterEqual(report.starts_at, resumed_at)
+ self.assertIsNone(report.next_delivery_date)
+ response = self.client.patch(url, {"output_type": "boolean"})
+ self.assertEqual(response.status_code, 400)
+
+ @parameterized.expand([({"name": "Renamed"},), ({"enabled": False},), ({"deleted": True},)])
+ def test_edit_does_not_create_report_for_existing_evaluation(self, patch: dict) -> None:
+ evaluation = Evaluation.objects.create(
+ team=self.team,
+ name="Existing evaluation",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true;"},
+ output_type="boolean",
+ enabled=True,
+ )
+ response = self.client.patch(f"/api/projects/{self.team.id}/evaluations/{evaluation.id}/", patch)
+ self.assertEqual(response.status_code, 200, response.json())
+ self.assertFalse(EvaluationReport.objects.filter(evaluation=evaluation).exists())
+
def _create_configured_llm_judge(self) -> tuple[Evaluation, LLMModelConfiguration]:
model_configuration = LLMModelConfiguration.objects.create(
team=self.team, provider="openai", model="gpt-5-mini"
@@ -1268,6 +1429,38 @@ class TestEvaluationConfigsApi(APIBaseTest):
class TestTestHogEndpoint(APIBaseTest):
+ @parameterized.expand(
+ [
+ (None, 0, 0),
+ ({"operator": "gte", "threshold": 0}, 1, 0),
+ ({"operator": "gte", "threshold": 1}, 0, 1),
+ ({"operator": "lte", "threshold": 1}, 1, 0),
+ ]
+ )
+ @patch("products.ai_observability.backend.api.evaluations.report_user_action")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
+ def test_numeric_preview_does_not_coerce_score_to_boolean(
+ self, rule: dict[str, str | int] | None, passed: int, failed: int, mock_query: Mock, mock_report: Mock
+ ) -> None:
+ mock_query.return_value = self._mock_hogql_response()
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/test_hog/",
+ {
+ "source": "return 0;",
+ "output_type": "numeric",
+ "output_config": {"min": 0, "passing_rule": rule},
+ },
+ )
+ self.assertEqual(response.status_code, 200, response.json())
+ result = response.json()["results"][0]
+ self.assertEqual(result["score"], 0)
+ self.assertIsNone(result["result"])
+ self.assertIsNone(result["error"])
+ counts = mock_report.call_args.args[2]
+ self.assertEqual(counts["pass_count"], passed)
+ self.assertEqual(counts["fail_count"], failed)
+ self.assertEqual(counts["na_count"], 0)
+
EVENT_TIMESTAMP = "2026-07-20T12:34:56Z"
def _mock_hogql_response(self, count=1):
@@ -1341,10 +1534,11 @@ class TestTestHogEndpoint(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("Compilation error", response.json()["error"])
- def test_test_hog_empty_source_rejected(self):
+ @parameterized.expand([({"source": ""},), ({"source": "return 0;", "output_config": []},)])
+ def test_test_hog_invalid_request_rejected(self, payload: dict) -> None:
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/test_hog/",
- {"source": ""},
+ payload,
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/ai_observability/backend/migrations/0051_numeric_evaluation_output.py b/products/ai_observability/backend/migrations/0051_numeric_evaluation_output.py
new file mode 100644
index 000000000000..aca4cf5fc305
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0051_numeric_evaluation_output.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.17 on 2026-09-17 19:38
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0050_alter_evaluationreportrun_options"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="evaluation",
+ name="output_type",
+ field=models.CharField(
+ choices=[
+ ("boolean", "Boolean (Pass/Fail)"),
+ ("numeric", "Numeric"),
+ ("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 f7b364cf86ad..0b4742d9834a 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0050_alter_evaluationreportrun_options
+0051_numeric_evaluation_output
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index 699deaf7eda3..a45fd06ec3f4 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -1,4 +1,5 @@
-from typing import Annotated, Any, Literal
+import math
+from typing import Annotated, Any, Literal, Self
from django.db import models
@@ -17,6 +18,7 @@ class OutputType(models.TextChoices):
"""What type of result is expected"""
BOOLEAN = "boolean", "Boolean (Pass/Fail)"
+ NUMERIC = "numeric", "Numeric"
SENTIMENT = "sentiment", "Sentiment"
@@ -50,6 +52,8 @@ class HogEvalConfig(BaseModel):
class BooleanOutputConfig(BaseModel):
"""Configuration for boolean output type"""
+ model_config = ConfigDict(extra="forbid")
+
allows_na: bool = False
# Detector-style evaluations look for a problem, so their true result is the undesirable one and
# must be reported as a fail. Defaulting to False keeps stored configs written before this field
@@ -57,6 +61,58 @@ class BooleanOutputConfig(BaseModel):
true_is_failure: bool = False
+class NumericPassingRule(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False)
+
+ operator: Literal["gte", "lte"]
+ threshold: float
+
+ def passes(self, score: float) -> bool:
+ return score >= self.threshold if self.operator == "gte" else score <= self.threshold
+
+
+class NumericScoreOutOfBounds(ValueError):
+ pass
+
+
+class NumericOutputConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False)
+
+ min: float | None = None
+ max: float | None = None
+ step: float | None = Field(default=None, gt=0)
+ allows_na: bool = False
+ passing_rule: NumericPassingRule | None = None
+
+ @model_validator(mode="after")
+ def validate_bounds(self) -> Self:
+ if self.min is not None and self.max is not None and self.min > self.max:
+ raise ValueError("Minimum score cannot exceed maximum score")
+ if self.passing_rule is not None:
+ self.passing_rule.threshold = self.validate_score(self.passing_rule.threshold)
+ return self
+
+ def validate_score(self, value: object) -> float:
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ raise ValueError("Numeric evaluations must return a finite number")
+ try:
+ score = float(value)
+ except OverflowError as error:
+ raise ValueError("Numeric evaluations must return a finite number") from error
+ if not math.isfinite(score):
+ raise ValueError("Numeric evaluations must return a finite number")
+ # One representable step absorbs arithmetic roundoff without rounding genuine outliers.
+ if self.min is not None and score < self.min:
+ if score < math.nextafter(self.min, -math.inf):
+ raise NumericScoreOutOfBounds(f"Score must be at least {self.min}")
+ score = self.min
+ if self.max is not None and score > self.max:
+ if score > math.nextafter(self.max, math.inf):
+ raise NumericScoreOutOfBounds(f"Score must be at most {self.max}")
+ score = self.max
+ return score
+
+
class SentimentEvalConfig(BaseModel):
"""Configuration for sentiment evaluations.
@@ -248,6 +304,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.NUMERIC.value): (LLMJudgeConfig, NumericOutputConfig),
+ (EvaluationType.HOG.value, OutputType.NUMERIC.value): (HogEvalConfig, NumericOutputConfig),
(EvaluationType.LLM_JUDGE.value, OutputType.BOOLEAN.value): (LLMJudgeConfig, BooleanOutputConfig),
(EvaluationType.HOG.value, OutputType.BOOLEAN.value): (HogEvalConfig, BooleanOutputConfig),
(EvaluationType.SENTIMENT.value, OutputType.SENTIMENT.value): (SentimentEvalConfig, SentimentOutputConfig),
@@ -259,13 +317,17 @@ EVALUATION_CONFIG_CONTENT_KEYS: dict[str, str] = {
EvaluationType.SENTIMENT.value: "source",
}
-REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (OutputType.BOOLEAN.value, OutputType.SENTIMENT.value)
+REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (
+ OutputType.BOOLEAN.value,
+ OutputType.SENTIMENT.value,
+ OutputType.NUMERIC.value,
+)
# Sentiment is generation-only (see the target check in the evaluations API), so the aggregate
-# targets report on boolean results alone.
+# targets support boolean and numeric results.
REPORTABLE_OUTPUT_TYPES_BY_TARGET: dict[str, tuple[str, ...]] = {
"generation": REPORTABLE_OUTPUT_TYPES,
- "trace": (OutputType.BOOLEAN.value,),
- "session": (OutputType.BOOLEAN.value,),
+ "trace": (OutputType.BOOLEAN.value, OutputType.NUMERIC.value),
+ "session": (OutputType.BOOLEAN.value, OutputType.NUMERIC.value),
}
@@ -273,7 +335,9 @@ def evaluation_uses_model_configuration(evaluation_type: str | None) -> bool:
return evaluation_type == EvaluationType.LLM_JUDGE.value
-def evaluation_supports_reports(output_type: str | None, target: 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"):
+ 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 def7cfb7f99b..c03366d587d7 100644
--- a/products/ai_observability/backend/models/evaluation_reports.py
+++ b/products/ai_observability/backend/models/evaluation_reports.py
@@ -13,7 +13,7 @@ from .evaluation_configs import REPORTABLE_OUTPUT_TYPES_BY_TARGET
class EvaluationReportQuerySet(models.QuerySet):
- def reportable(self) -> "EvaluationReportQuerySet":
+ def for_supported_evaluations(self) -> "EvaluationReportQuerySet":
reportable_filter = models.Q()
for target, output_types in REPORTABLE_OUTPUT_TYPES_BY_TARGET.items():
reportable_filter |= models.Q(
@@ -22,6 +22,15 @@ class EvaluationReportQuerySet(models.QuerySet):
)
return self.filter(reportable_filter)
+ def reportable(self) -> "EvaluationReportQuerySet":
+ return self.for_supported_evaluations().exclude(
+ models.Q(evaluation__output_type="numeric")
+ & (
+ ~models.Q(evaluation__output_config__has_key="passing_rule")
+ | models.Q(evaluation__output_config__passing_rule=None)
+ )
+ )
+
def deliverable(self) -> "EvaluationReportQuerySet":
return self.reportable().filter(
enabled=True,
@@ -146,6 +155,13 @@ class EvaluationReport(UUIDTModel):
)
self.next_delivery_date = occurrences[0] if occurrences else None
+ def restart_reporting(self) -> None:
+ self.last_delivered_at = None
+ if self.is_count_triggered:
+ self.starts_at = timezone.now()
+ self.set_next_delivery_date()
+ self.save(update_fields=["last_delivered_at", "starts_at", "next_delivery_date"])
+
def save(self, *args, **kwargs):
recalc = not self.id or not self.next_delivery_date
old = 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 34c666c75da1..f780826f31d5 100644
--- a/products/ai_observability/backend/models/test/test_evaluation_configs.py
+++ b/products/ai_observability/backend/models/test/test_evaluation_configs.py
@@ -1,6 +1,76 @@
+import math
+
import pytest
-from products.ai_observability.backend.models.evaluation_configs import validate_target_config
+from products.ai_observability.backend.models.evaluation_configs import (
+ NumericOutputConfig,
+ NumericScoreOutOfBounds,
+ validate_evaluation_configs,
+ validate_target_config,
+)
+
+
+class TestNumericOutputConfig:
+ @pytest.mark.parametrize(
+ "bounds,score,expected",
+ [
+ ({"max": 0.7}, 7 * 0.1, 0.7),
+ ({"min": -0.7}, -7 * 0.1, -0.7),
+ ({"min": 0.7}, math.nextafter(0.7, -math.inf), 0.7),
+ ({"max": -0.7}, math.nextafter(-0.7, math.inf), -0.7),
+ ({"min": 0, "max": 1}, 0.123456789, 0.123456789),
+ ({"max": 0.7}, math.nextafter(0.7, math.inf, steps=2), None),
+ ({"min": -0.7}, math.nextafter(-0.7, -math.inf, steps=2), None),
+ ({"max": 0.7}, 0.700001, None),
+ ({"max": 1e12}, 1e12 + 1, None),
+ ],
+ )
+ def test_score_boundary_roundoff(self, bounds, score, expected):
+ config = NumericOutputConfig.model_validate(bounds)
+ if expected is None:
+ with pytest.raises(NumericScoreOutOfBounds):
+ config.validate_score(score)
+ else:
+ assert config.validate_score(score) == expected
+
+ @pytest.mark.parametrize(
+ "runtime,config", [("llm_judge", {"prompt": "Score completeness"}), ("hog", {"source": "return 0;"})]
+ )
+ def test_numeric_configuration(self, runtime, config):
+ _, output = validate_evaluation_configs(
+ runtime, "numeric", config, {"min": 0, "max": 10, "passing_rule": {"operator": "gte", "threshold": 7}}
+ )
+ assert output == {"min": 0, "max": 10, "allows_na": False, "passing_rule": {"operator": "gte", "threshold": 7}}
+
+ @pytest.mark.parametrize(
+ "output",
+ [
+ {"min": 2, "max": 1},
+ {"min": True},
+ {"max": "10"},
+ {"max": float("inf")},
+ {"step": 0},
+ {"step": -1},
+ {"typo": 1},
+ {"passing_rule": {"operator": "gt", "threshold": 0}},
+ {"passing_rule": {"operator": "gte"}},
+ {"passing_rule": {"operator": "gte", "threshold": True}},
+ {"passing_rule": {"operator": "gte", "threshold": float("nan")}},
+ {"min": 0, "passing_rule": {"operator": "gte", "threshold": -1}},
+ ],
+ )
+ def test_invalid_numeric_configuration(self, output):
+ with pytest.raises(ValueError):
+ validate_evaluation_configs("hog", "numeric", {"source": "return 0;"}, output)
+
+ def test_unbounded_and_nullable_configuration(self):
+ _, output = validate_evaluation_configs(
+ "hog",
+ "numeric",
+ {"source": "return 0;"},
+ {"min": None, "max": None, "step": None, "passing_rule": None, "allows_na": True},
+ )
+ assert output == {"allows_na": True}
class TestValidateTargetConfig:
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 9ec2c3c8b939..ad7e1dd1d57a 100644
--- a/products/ai_observability/backend/text_repr/formatters/event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
@@ -205,6 +205,10 @@ def format_evaluation_text_repr(event: dict[str, Any], options: FormatterOptions
# Result line
if applicable is False or applicable == "false":
result_str = "N/A"
+ elif (
+ props.get("$ai_evaluation_result_type") == "numeric" and props.get("$ai_evaluation_numeric_result") is not None
+ ):
+ result_str = str(props["$ai_evaluation_numeric_result"])
elif result is True or result == "true":
result_str = "true"
elif result is False or result == "false":
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 78af4c91f15d..0685ce74a5cb 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,6 +203,17 @@ 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:
+ event = {
+ "properties": {
+ "$ai_evaluation_result_type": "numeric",
+ "$ai_evaluation_numeric_result": score,
+ "$ai_evaluation_applicable": applicable,
+ }
+ }
+ assert f"Result: {expected}" in format_evaluation_text_repr(event)
+
def test_evaluation_pass_with_reasoning(self):
event = {
"properties": {
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 270c62ea1800..f744eac56192 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,6 +122,14 @@ 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:
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {"$ai_evaluation_result_type": "numeric", "$ai_evaluation_numeric_result": score},
+ }
+ assert _get_event_summary(event) == f"evaluation ({score})"
+
def test_evaluation_summary_pass(self):
event = {
"event": "$ai_evaluation",
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 fc178568f0ec..686288efc7aa 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,11 @@ 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") == "numeric"
+ and props.get("$ai_evaluation_numeric_result") is not None
+ ):
+ parts.append(str(props["$ai_evaluation_numeric_result"]))
elif result is True or result == "true":
parts.append("true")
elif result is False or result == "false":
diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.py
index 3ec893de0557..99403cba23dd 100644
--- a/products/ai_observability/backend/tools/run_hog_eval.py
+++ b/products/ai_observability/backend/tools/run_hog_eval.py
@@ -20,13 +20,14 @@ from products.ai_observability.backend.models.evaluation_configs import (
TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
TRACE_EVAL_MAX_WINDOW_SECONDS,
TRACE_EVAL_MIN_WINDOW_SECONDS,
+ validate_evaluation_configs,
)
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 true/false/N/A/error results for each sample.
+Returns compilation errors if the code is invalid, or raw boolean/numeric/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
@@ -46,7 +47,9 @@ 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`. Evaluation output settings determine which value counts as a failure.
+The code must return `true` or `false` for boolean output, or a finite number for numeric output.
+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.
"""
@@ -59,9 +62,12 @@ def _format_sample(
input_preview: str,
output_preview: str,
reasoning: str,
+ score: float | None = None,
) -> list[str]:
if error:
verdict_str = "ERROR"
+ elif score is not None:
+ verdict_str = str(score)
elif verdict is True:
verdict_str = "true"
elif verdict is False:
@@ -84,6 +90,11 @@ def _format_sample(
class RunHogEvalTestArgs(BaseModel):
+ output_type: Literal["boolean", "numeric"] = 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",
+ )
source: str = Field(description="Hog evaluation source code to compile and test")
sample_count: int = Field(
default=3,
@@ -127,10 +138,19 @@ 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_config: dict[str, Any] | None = None,
) -> tuple[str, Any]:
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.run_evaluation import run_hog_eval
+ try:
+ _, output_config = validate_evaluation_configs(
+ "hog", output_type, {"source": source}, {"allows_na": output_type == "boolean", **(output_config or {})}
+ )
+ except ValueError as error:
+ return (f"Invalid output configuration: {error}", None)
+
try:
bytecode = compile_ai_observability_hog(source, "destination")
except Exception as e:
@@ -139,10 +159,12 @@ class RunHogEvalTestTool(MaxTool):
team = self._team
if target == "trace":
- return await self._run_over_traces(bytecode, sample_count, window_seconds)
+ return await self._run_over_traces(bytecode, sample_count, window_seconds, output_type, output_config)
if target == "session":
- return await self._run_over_sessions(bytecode, sample_count, quiet_period_seconds)
+ return await self._run_over_sessions(
+ bytecode, sample_count, quiet_period_seconds, output_type, output_config
+ )
# Read from ai_events with native heavy columns so the Hog body still
# sees `event.properties.$ai_input` etc. Falls back to the events table
@@ -242,7 +264,13 @@ class RunHogEvalTestTool(MaxTool):
properties = event_data["properties"]
event_type = event_data["event"]
- result = run_hog_eval(bytecode, event_data, allows_na=True)
+ result = run_hog_eval(
+ bytecode,
+ event_data,
+ allows_na=output_config["allows_na"],
+ output_type=output_type,
+ output_config=output_config,
+ )
if event_type == "$ai_generation":
input_raw = properties.get("$ai_input") or properties.get("$ai_input_state", "")
@@ -258,29 +286,29 @@ class RunHogEvalTestTool(MaxTool):
input_preview = extract_text_from_messages(input_raw)[:200]
output_preview = extract_text_from_messages(output_raw)[:200]
- verdict = result["verdict"]
- if result["error"]:
- verdict_str = "ERROR"
- elif verdict is True:
- verdict_str = "true"
- elif verdict is False:
- verdict_str = "false"
- else:
- verdict_str = "N/A"
-
- lines.append(f"Event {event_data['uuid']} ({event_type}):")
- lines.append(f" Input: {input_preview}")
- lines.append(f" Output: {output_preview}")
- lines.append(f" Result: {verdict_str}")
- if result["reasoning"]:
- lines.append(f" Reasoning: {result['reasoning']}")
- if result["error"]:
- lines.append(f" Error: {result['error']}")
- lines.append("")
+ lines.extend(
+ _format_sample(
+ "Event",
+ f"{event_data['uuid']} ({event_type})",
+ result.get("verdict"),
+ result["error"],
+ input_preview,
+ output_preview,
+ result["reasoning"],
+ score=result.get("score"),
+ )
+ )
return ("\n".join(lines), None)
- async def _run_over_traces(self, bytecode: list[Any], sample_count: int, window_seconds: int) -> tuple[str, Any]:
+ async def _run_over_traces(
+ self,
+ bytecode: list[Any],
+ sample_count: int,
+ window_seconds: int,
+ output_type: str,
+ output_config: dict[str, Any],
+ ) -> tuple[str, Any]:
from posthog.temporal.ai_observability.run_trace_evaluation import run_hog_eval_over_recent_traces
trace_results = await database_sync_to_async(run_hog_eval_over_recent_traces)(
@@ -289,7 +317,9 @@ class RunHogEvalTestTool(MaxTool):
bytecode=bytecode,
condition_filter=None,
sample_count=sample_count,
- allows_na=True,
+ allows_na=output_config["allows_na"],
+ output_type=output_type,
+ output_config=output_config,
window_seconds=window_seconds,
)
if not trace_results:
@@ -302,13 +332,27 @@ class RunHogEvalTestTool(MaxTool):
lines: list[str] = [f"Sampled {len(trace_results)} trace(s). Ran against trace-level globals.", ""]
for r in trace_results:
lines.extend(
- _format_sample("Trace", r.trace_id, r.verdict, r.error, r.input_preview, r.output_preview, r.reasoning)
+ _format_sample(
+ "Trace",
+ r.trace_id,
+ r.verdict,
+ r.error,
+ r.input_preview,
+ r.output_preview,
+ r.reasoning,
+ score=r.score,
+ )
)
return ("\n".join(lines), None)
async def _run_over_sessions(
- self, bytecode: list[Any], sample_count: int, quiet_period_seconds: int
+ self,
+ bytecode: list[Any],
+ sample_count: int,
+ quiet_period_seconds: int,
+ output_type: str,
+ output_config: dict[str, Any],
) -> tuple[str, Any]:
from posthog.temporal.ai_observability.run_session_evaluation import run_hog_eval_over_recent_sessions
@@ -320,7 +364,9 @@ class RunHogEvalTestTool(MaxTool):
# Same bound the editor endpoint applies: each sampled session is fetched in full, so
# the generic sample_count ceiling is far too high for whole conversations.
sample_count=min(sample_count, SESSION_TEST_HOG_MAX_SAMPLES),
- allows_na=True,
+ allows_na=output_config["allows_na"],
+ output_type=output_type,
+ output_config=output_config,
quiet_period_seconds=quiet_period_seconds,
)
if not session_results:
@@ -335,7 +381,14 @@ class RunHogEvalTestTool(MaxTool):
for s in session_results:
lines.extend(
_format_sample(
- "Session", s.session_id, s.verdict, s.error, s.input_preview, s.output_preview, s.reasoning
+ "Session",
+ s.session_id,
+ s.verdict,
+ s.error,
+ s.input_preview,
+ s.output_preview,
+ s.reasoning,
+ score=s.score,
)
)
diff --git a/products/ai_observability/backend/tools/test_run_hog_eval.py b/products/ai_observability/backend/tools/test_run_hog_eval.py
index f46e413d2ca9..9d27d0962a71 100644
--- a/products/ai_observability/backend/tools/test_run_hog_eval.py
+++ b/products/ai_observability/backend/tools/test_run_hog_eval.py
@@ -53,6 +53,20 @@ def test_run_hog_eval_args_reject_unknown_target():
class TestRunHogEvalTestTool(BaseTest):
+ @patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
+ def test_numeric_preview_preserves_zero_and_enforces_bounds(self, mock_query):
+ mock_query.return_value = MagicMock(results=[_make_event()])
+ tool = self._make_tool()
+ result, _ = _run_tool(tool, source="return 0;", output_type="numeric", output_config={"min": 0, "max": 10})
+ self.assertIn("Result: 0.0", result)
+ result, _ = _run_tool(tool, source="return 11;", output_type="numeric", output_config={"min": 0, "max": 10})
+ self.assertIn("Result: ERROR", result)
+ for allows_na, expected in [(False, "ERROR"), (True, "N/A")]:
+ result, _ = _run_tool(
+ tool, source="return null;", output_type="numeric", output_config={"allows_na": allows_na}
+ )
+ self.assertIn(f"Result: {expected}", result)
+
def _make_tool(self):
return RunHogEvalTestTool(team=self.team, user=self.user)
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
index 702ac702c1e5..d498a6f248a6 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
@@ -10,10 +10,10 @@ import { EventType } from '~/types'
import { EvaluationResultTag } from '../components/EvaluationResultTag'
import { MetadataTag } from '../components/MetadataTag'
import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
-import { normalizeEvaluationResultProperties } from '../utils'
+import { isExplicitEvaluationPass, normalizeEvaluationResultProperties } from '../utils'
export function EvaluationDisplay({ eventProperties }: { eventProperties: EventType['properties'] }): JSX.Element {
- const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
+ const { detectorEvaluationIds, evaluations } = useValues(llmEvaluationsLogic)
const reasoning = eventProperties.$ai_evaluation_reasoning
const evaluationName = eventProperties.$ai_evaluation_name
const model = eventProperties.$ai_model ?? eventProperties.$ai_evaluation_model
@@ -22,8 +22,11 @@ export function EvaluationDisplay({ eventProperties }: { eventProperties: EventT
const evaluationId = eventProperties.$ai_evaluation_id
const resultRun = {
status: 'completed' as const,
- skipped: eventProperties.$ai_evaluation_skipped === true || eventProperties.$ai_evaluation_skipped === 'true',
+ skipped: isExplicitEvaluationPass(eventProperties.$ai_evaluation_skipped),
...normalizeEvaluationResultProperties({
+ rawScore: eventProperties.$ai_evaluation_numeric_result,
+ rawScoreMin: eventProperties.$ai_evaluation_numeric_result_min,
+ rawScoreMax: eventProperties.$ai_evaluation_numeric_result_max,
rawResult: eventProperties.$ai_evaluation_result,
rawApplicable: eventProperties.$ai_evaluation_applicable,
rawEvaluationType: eventProperties.$ai_evaluation_runtime,
@@ -36,7 +39,13 @@ export function EvaluationDisplay({ eventProperties }: { eventProperties: EventT
return (
<div className="space-y-4">
<div className="flex flex-wrap gap-2">
- <EvaluationResultTag run={resultRun} trueIsFailure={detectorEvaluationIds.includes(evaluationId)} />
+ <EvaluationResultTag
+ run={resultRun}
+ passingRule={
+ evaluations?.find((evaluation) => evaluation.id === evaluationId)?.output_config.passing_rule
+ }
+ trueIsFailure={detectorEvaluationIds.includes(evaluationId)}
+ />
{evaluationName && (
<MetadataTag label="Evaluation" textToCopy={evaluationName}>
{evaluationName}
diff --git a/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx b/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
index d421d46df956..3af6cf7d1bdb 100644
--- a/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
+++ b/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
@@ -12,7 +12,7 @@ interface LLMASessionEvaluationsDisplayProps {
export function LLMASessionEvaluationsDisplay({ sessionId }: LLMASessionEvaluationsDisplayProps): JSX.Element | null {
const { sessionEvaluations } = useValues(aiObservabilitySessionEvaluationsLogic({ sessionId }))
- const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
+ const { detectorEvaluationIds, evaluations } = useValues(llmEvaluationsLogic)
// A session that resumes after being evaluated can be graded again; collapse to the newest
// verdict per evaluation so a stale tag never sits beside a fresh one. Same helper the trace
@@ -28,6 +28,8 @@ export function LLMASessionEvaluationsDisplay({ sessionId }: LLMASessionEvaluati
{summaries.map((summary) => {
const { type, icon, label } = getEvalBadgeProps(summary.latestRun, {
trueIsFailure: detectorEvaluationIds.includes(summary.latestRun.evaluation_id),
+ passingRule: evaluations?.find((evaluation) => evaluation.id === summary.latestRun.evaluation_id)
+ ?.output_config.passing_rule,
})
return (
<Tooltip key={summary.latestRun.evaluation_id} title={<EvalTooltipContent {...summary} />}>
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
index c1e2ff921c0f..b691926cf043 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
@@ -9,7 +9,12 @@ import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
import { EvaluationConfig, EvaluationRun } from '../evaluations/types'
import { generationEvaluationRunsLogic } from '../generationEvaluationRunsLogic'
import { EvalResultBadges, getEvalBadgeProps, getEvalSummaries, scopeRunsToTarget } from './EvalResultBadges'
-import { getEvaluationResultDisplay, getEvaluationResultSortValue, isSentimentRun } from './EvaluationResultTag'
+import {
+ compareEvaluationResults,
+ getEvaluationResultDisplay,
+ getEvaluationResultSortValue,
+ isSentimentRun,
+} from './EvaluationResultTag'
function makeRun(overrides: Partial<EvaluationRun> = {}): EvaluationRun {
return {
@@ -27,6 +32,37 @@ function makeRun(overrides: Partial<EvaluationRun> = {}): EvaluationRun {
}
describe('EvalResultBadges', () => {
+ it('sorts numeric scores together without colliding with status ranks', () => {
+ const rows = [
+ makeRun({ id: 'negative', result_type: 'numeric', score: -10 }),
+ makeRun({ id: 'na', result_type: 'numeric', applicable: false }),
+ makeRun({ id: 'zero', result_type: 'numeric', score: 0 }),
+ makeRun({ id: 'skipped', skipped: true }),
+ makeRun({ id: 'positive', result_type: 'numeric', score: 2 }),
+ makeRun({ id: 'error', status: 'failed' }),
+ makeRun({ id: 'boolean', result: true }),
+ ]
+ expect(rows.sort((a, b) => compareEvaluationResults(b, a)).map((run) => run.id)).toEqual([
+ 'positive',
+ 'zero',
+ 'negative',
+ 'boolean',
+ 'na',
+ 'skipped',
+ 'error',
+ ])
+ })
+
+ it.each([
+ [1 / 3, '0.333333'],
+ [123456789, '123456789'],
+ [-123456789, '-123456789'],
+ [0.0000000123456789, '1.23457e-8'],
+ [1234567.1234567, '1234567.123457'],
+ ])('formats score %s without dropping integer digits', (score, label) => {
+ expect(getEvaluationResultDisplay(makeRun({ result_type: 'numeric', score })).label).toBe(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 c8eacd3970af..f09872c6144d 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -74,7 +74,7 @@ export function EvalResultBadges({
const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(
generationEvaluationRunsLogic({ traceId })
)
- const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
+ const { detectorEvaluationIds, evaluations } = useValues(llmEvaluationsLogic)
const traceLogic = useMountedLogic(aiObservabilityTraceLogic)
const { setViewMode } = useActions(traceLogic)
@@ -100,6 +100,8 @@ export function EvalResultBadges({
{summaries.map((summary) => {
const { type, icon, label } = getEvalBadgeProps(summary.latestRun, {
trueIsFailure: detectorEvaluationIds.includes(summary.latestRun.evaluation_id),
+ passingRule: evaluations?.find((evaluation) => evaluation.id === summary.latestRun.evaluation_id)
+ ?.output_config.passing_rule,
})
return (
<Tooltip key={summary.latestRun.evaluation_id} title={<EvalTooltipContent {...summary} />}>
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx
new file mode 100644
index 000000000000..49ef4d67f9c4
--- /dev/null
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.stories.tsx
@@ -0,0 +1,65 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { EvaluationResultTag } from './EvaluationResultTag'
+
+const meta: Meta<typeof EvaluationResultTag> = {
+ title: 'Scenes-App/LLM observability/EvaluationResultTag',
+ component: EvaluationResultTag,
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+type Story = StoryObj<typeof EvaluationResultTag>
+
+export const Numeric: Story = {
+ render: () => (
+ <div className="flex flex-wrap gap-6">
+ <div className="space-y-2">
+ <div>Large score</div>
+ <EvaluationResultTag
+ run={{ status: 'completed', result: null, result_type: 'numeric', score: 123456789 }}
+ />
+ </div>
+ <div className="space-y-2">
+ <div>Fractional score</div>
+ <EvaluationResultTag
+ run={{ status: 'completed', result: null, result_type: 'numeric', score: 1 / 3 }}
+ />
+ </div>
+ <div className="space-y-2">
+ <div>Score without a passing rule</div>
+ <EvaluationResultTag run={{ status: 'completed', result: null, result_type: 'numeric', score: 0 }} />
+ </div>
+ <div className="space-y-2">
+ <div>Pass at or above 7</div>
+ <EvaluationResultTag
+ run={{ status: 'completed', result: null, result_type: 'numeric', score: 7 }}
+ passingRule={{ operator: 'gte', threshold: 7 }}
+ />
+ </div>
+ <div className="space-y-2">
+ <div>Below the passing threshold</div>
+ <EvaluationResultTag
+ run={{ status: 'completed', result: null, result_type: 'numeric', score: 6.5 }}
+ passingRule={{ operator: 'gte', threshold: 7 }}
+ />
+ </div>
+ <div className="space-y-2">
+ <div>Not applicable</div>
+ <EvaluationResultTag
+ run={{ status: 'completed', result: null, result_type: 'numeric', applicable: false }}
+ />
+ </div>
+ <div className="space-y-2">
+ <div>Skipped before scoring</div>
+ <EvaluationResultTag
+ run={{ status: 'completed', result: null, result_type: 'numeric', skipped: true }}
+ />
+ </div>
+ <div className="space-y-2">
+ <div>Evaluation error</div>
+ <EvaluationResultTag run={{ status: 'failed', result: null, result_type: 'numeric' }} />
+ </div>
+ </div>
+ ),
+}
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
index ef1d6142b404..84664b9f981d 100644
--- a/products/ai_observability/frontend/components/EvaluationResultTag.tsx
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
@@ -2,12 +2,22 @@ import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'
import { LemonTag } from '@posthog/lemon-ui'
import type { LemonTagProps } from '@posthog/lemon-ui'
-import type { EvaluationRun } from '../evaluations/types'
+import { formatNumericEvaluationScore, numericScorePasses } from '../evaluations/constants'
+import type { EvaluationOutputConfig, EvaluationRun } from '../evaluations/types'
import { capitalize } from '../sentimentUtils'
type EvaluationResultLike = Pick<
EvaluationRun,
- 'status' | 'result' | 'result_type' | 'evaluation_type' | 'sentiment_label' | 'skipped'
+ | 'status'
+ | 'result'
+ | 'result_type'
+ | 'evaluation_type'
+ | 'sentiment_label'
+ | 'skipped'
+ | 'score'
+ | 'score_min'
+ | 'score_max'
+ | 'applicable'
>
interface EvaluationResultDisplay {
@@ -20,6 +30,7 @@ interface EvaluationResultDisplay {
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']
}
const SENTIMENT_DISPLAY: Record<string, Pick<EvaluationResultDisplay, 'type' | 'icon' | 'sortValue'>> = {
@@ -47,6 +58,21 @@ export function getEvaluationResultDisplay(
if (run.skipped) {
return { type: 'muted', icon: <IconMinus />, label: 'Skipped', sortValue: 0.4 }
}
+ if (run.result_type === 'numeric') {
+ if (run.applicable === false) {
+ return { type: 'muted', icon: <IconMinus />, label: 'N/A', sortValue: 0.5 }
+ }
+ if (run.score == null || !Number.isFinite(run.score)) {
+ return { type: 'muted', icon: <IconMinus />, label: 'No score', sortValue: -1 }
+ }
+ const passed = numericScorePasses(run.score, options.passingRule)
+ return {
+ type: passed === null ? 'none' : passed ? 'success' : 'danger',
+ icon: passed === null ? <IconMinus /> : passed ? <IconCheck /> : <IconX />,
+ label: formatNumericEvaluationScore(run.score),
+ sortValue: 4,
+ }
+ }
if (isSentimentRun(run)) {
const sentimentLabel = (run.sentiment_label || 'unknown').toLowerCase()
const display = SENTIMENT_DISPLAY[sentimentLabel] ?? {
@@ -77,18 +103,31 @@ export function getEvaluationResultSortValue(
return getEvaluationResultDisplay(run, options).sortValue
}
+export function compareEvaluationResults(
+ a: EvaluationResultLike,
+ b: EvaluationResultLike,
+ aOptions: EvaluationResultDisplayOptions = {},
+ bOptions: EvaluationResultDisplayOptions = aOptions
+): number {
+ const aRank = getEvaluationResultSortValue(a, aOptions)
+ const bRank = getEvaluationResultSortValue(b, bOptions)
+ return aRank === 4 && bRank === 4 ? a.score! - b.score! : aRank - bRank
+}
+
export function EvaluationResultTag({
run,
trueIsFailure,
+ passingRule,
size,
}: {
run: EvaluationResultLike
trueIsFailure?: boolean
+ passingRule?: EvaluationOutputConfig['passing_rule']
size?: LemonTagProps['size']
}): JSX.Element {
- const { type, icon, label } = getEvaluationResultDisplay(run, { trueIsFailure })
+ const { type, icon, label } = getEvaluationResultDisplay(run, { trueIsFailure, passingRule })
return (
- <LemonTag type={type} icon={icon} size={size}>
+ <LemonTag type={type} icon={icon} size={size} title={run.score == null ? undefined : String(run.score)}>
{label}
</LemonTag>
)
diff --git a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
index 2c97a54e5291..a5c279f01c74 100644
--- a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
+++ b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
@@ -9,7 +9,7 @@ import { urls } from 'scenes/urls'
import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
import { EvaluationRun } from '../evaluations/types'
import type { generationEvaluationRunsLogicType } from '../generationEvaluationRunsLogic'
-import { EvaluationResultTag, getEvaluationResultSortValue } from './EvaluationResultTag'
+import { EvaluationResultTag, compareEvaluationResults } from './EvaluationResultTag'
import { EvaluationRunTargetCell } from './EvaluationRunTargetCell'
export function GenerationEvalRunsTable({
@@ -18,7 +18,7 @@ export function GenerationEvalRunsTable({
generationRunsLogic: BuiltLogic<generationEvaluationRunsLogicType>
}): JSX.Element {
const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(generationRunsLogic)
- const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
+ const { detectorEvaluationIds, evaluations } = useValues(llmEvaluationsLogic)
const columns: LemonTableColumns<EvaluationRun> = [
{
@@ -45,18 +45,22 @@ export function GenerationEvalRunsTable({
title: 'Result',
key: 'result',
render: (_, run) => (
- <EvaluationResultTag run={run} trueIsFailure={detectorEvaluationIds.includes(run.evaluation_id)} />
+ <EvaluationResultTag
+ run={run}
+ passingRule={
+ evaluations?.find((evaluation) => evaluation.id === run.evaluation_id)?.output_config
+ .passing_rule
+ }
+ trueIsFailure={detectorEvaluationIds.includes(run.evaluation_id)}
+ />
),
- sorter: (a, b) => {
- return (
- getEvaluationResultSortValue(b, {
- trueIsFailure: detectorEvaluationIds.includes(b.evaluation_id),
- }) -
- getEvaluationResultSortValue(a, {
- trueIsFailure: detectorEvaluationIds.includes(a.evaluation_id),
- })
- )
- },
+ sorter: (a, b) =>
+ compareEvaluationResults(
+ b,
+ a,
+ { trueIsFailure: detectorEvaluationIds.includes(b.evaluation_id) },
+ { trueIsFailure: detectorEvaluationIds.includes(a.evaluation_id) }
+ ),
},
{
title: 'Reasoning',
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 9137d65d1e60..ca6f19adae4e 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -30,9 +30,8 @@ import { SceneExport } from 'scenes/sceneTypes'
import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'
import { SceneStickyBar } from '~/layout/scenes/components/SceneStickyBar'
-import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
import { urls } from '~/scenes/urls'
-import { AccessControlLevel, AccessControlResourceType, ChartDisplayType, HogQLMathType } from '~/types'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
@@ -48,9 +47,11 @@ import { EvaluationReportsCallout } from './components/EvaluationReportsCallout'
import { EvaluationReportsTab } from './components/EvaluationReportsTab'
import { EvaluationRunsTable } from './components/EvaluationRunsTable'
import { EvaluationTriggers } from './components/EvaluationTriggers'
-import { EVALUATION_RUNS_QUERY_LIMIT, evaluationPassedHogQL, evaluationPassRateHogQL } from './constants'
+import { NumericEvaluationConfig } from './components/NumericEvaluationConfig'
+import { EVALUATION_RUNS_QUERY_LIMIT, formatNumericEvaluationScore, numericOutputConfigError } from './constants'
import {
evaluationOffersSessionTarget,
+ evaluationSupportsReportHistory,
evaluationSupportsReports,
evaluationSupportsRunOutcomes,
evaluationTypeHasEditableCriteria,
@@ -77,6 +78,9 @@ const RUNS_BACKFILL_TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'HH:m
export function AIObservabilityEvaluation(): JSX.Element {
const {
evaluation,
+ originalEvaluation,
+ isReportableEvaluation,
+ trendInsightUrl,
evaluationBackTarget,
evaluationLoading,
evaluationFormSubmitting,
@@ -86,6 +90,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
runsSummary,
runsBackfillId,
runsBackfill,
+ runsDateRange,
evaluationProviderKeyIssue,
activeTab,
canEnable,
@@ -94,6 +99,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
} = useValues(llmEvaluationLogic)
const { searchParams } = useValues(router)
const { featureFlags } = useValues(featureFlagLogic)
+ const numericEvaluationsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_NUMERIC_EVALS]
const settlingStrategyEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_SETTLING_STRATEGY]
const backfillsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVAL_BACKFILLS]
const {
@@ -105,6 +111,8 @@ export function AIObservabilityEvaluation(): JSX.Element {
saveEvaluation,
resetEvaluation,
setEvaluationType,
+ setOutputType,
+ patchOutputConfig,
setEvaluationTarget,
setSettleStrategy,
patchTargetConfig,
@@ -140,66 +148,10 @@ export function AIObservabilityEvaluation(): JSX.Element {
// here rendered a "wait 30 minutes" field holding a default the config never had.
const effectiveStrategy: EvaluationSettleStrategy =
evaluation.target_config.strategy ?? (isSessionTarget ? 'inactivity' : 'fixed_window')
- const isReportableEvaluation = evaluationSupportsReports(evaluation)
- const supportsRunOutcomes = evaluationSupportsRunOutcomes(evaluation)
+ const supportsRunOutcomes = evaluationSupportsRunOutcomes(originalEvaluation)
const isBooleanOutput = isBooleanEvaluationOutput(evaluation.output_type)
const hasEditableCriteria = evaluationTypeHasEditableCriteria(evaluation.evaluation_type)
- const trendInsightUrl =
- supportsRunOutcomes && !isNewEvaluation && evaluation.id
- ? urls.insightNew({
- query: {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- series: [
- {
- kind: NodeKind.EventsNode,
- event: '$ai_evaluation',
- custom_name: `${evaluation.name} — Pass rate`,
- math: HogQLMathType.HogQL,
- math_hogql: evaluationPassRateHogQL(evaluationPassedHogQL(evaluation)),
- properties: [
- {
- key: '$ai_evaluation_id',
- value: evaluation.id,
- operator: 'exact',
- type: 'event',
- },
- ],
- },
- ...(evaluation.output_config.allows_na
- ? [
- {
- kind: NodeKind.EventsNode as const,
- event: '$ai_evaluation',
- custom_name: `${evaluation.name} — N/A rate`,
- math: HogQLMathType.HogQL as const,
- math_hogql: `if(count() > 0, countIf(properties.$ai_evaluation_result IS NULL) / count() * 100, 0)`,
- properties: [
- {
- key: '$ai_evaluation_id',
- value: evaluation.id,
- operator: 'exact' as const,
- type: 'event' as const,
- },
- ],
- },
- ]
- : []),
- ],
- trendsFilter: {
- display: ChartDisplayType.ActionsLineGraph,
- },
- dateRange: {
- date_from: '-7d',
- },
- interval: 'day',
- },
- } as InsightVizNode,
- })
- : null
-
const configValid = isHog
? evaluation.evaluation_config.source.trim().length > 0
: isSentiment
@@ -225,7 +177,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
: 'Add an evaluation prompt before saving'
: !hasSelectedJudgeModel
? 'Select a judge model before saving'
- : undefined
+ : evaluation.output_type === 'numeric'
+ ? (numericOutputConfigError(evaluation.output_config) ?? undefined)
+ : undefined
const focusTriggers = (): void => {
setActiveTab('configuration')
@@ -254,7 +208,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
}
const reportLogic = evaluationReportLogic({ evaluationId: isNewEvaluation ? 'new' : evaluation.id })
- if (isReportableEvaluation && reportLogic.isMounted() && reportLogic.values.configError) {
+ if (evaluationSupportsReports(evaluation) && reportLogic.isMounted() && reportLogic.values.configError) {
lemonToast.error(reportLogic.values.configError)
return
}
@@ -405,7 +359,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
'data-attr': 'llma-evaluation-runs-tab',
content: (
<div className="max-w-6xl">
- <div className="flex justify-between items-center mb-4">
+ <div className="flex flex-wrap gap-4 justify-between items-center mb-4">
<div className="min-w-0">
<p className="text-muted text-sm m-0">
History of when this evaluation has been executed.
@@ -426,20 +380,32 @@ export function AIObservabilityEvaluation(): JSX.Element {
</div>
{runsSummary && (
<div className="flex flex-col items-end gap-1">
- <div className="flex gap-4 text-sm">
+ <div className="flex flex-wrap gap-4 text-sm">
<div className="text-center">
<div className="font-semibold text-lg">{runsSummary.total}</div>
<div className="text-muted">Total runs</div>
</div>
+ {evaluation.output_type === 'numeric' && (
+ <div className="text-center">
+ <div className="font-semibold text-lg">
+ {runsSummary.scoreMean == null
+ ? '–'
+ : formatNumericEvaluationScore(runsSummary.scoreMean)}
+ </div>
+ <div className="text-muted">Mean score</div>
+ </div>
+ )}
{supportsRunOutcomes && (
<div className="text-center">
<div className="font-semibold text-lg text-success">
- {runsSummary.successRate}%
+ {runsSummary.successRate == null
+ ? '–'
+ : `${runsSummary.successRate}%`}
</div>
<div className="text-muted">Success rate</div>
</div>
)}
- {supportsRunOutcomes && evaluation.output_config.allows_na && (
+ {supportsRunOutcomes && originalEvaluation?.output_config.allows_na && (
<div className="text-center">
<div className="font-semibold text-lg">
{runsSummary.applicabilityRate}%
@@ -455,7 +421,11 @@ export function AIObservabilityEvaluation(): JSX.Element {
</div>
</div>
<div className="text-muted text-xs">
- {runsBackfillId ? 'From this backfill' : 'Across all runs, all time'}
+ {runsBackfillId
+ ? 'From this backfill'
+ : runsDateRange.date_from === 'all'
+ ? 'Across all runs, all time'
+ : 'In the selected date range'}
</div>
</div>
)}
@@ -504,13 +474,18 @@ export function AIObservabilityEvaluation(): JSX.Element {
),
},
!isNewEvaluation &&
- isReportableEvaluation && {
+ evaluationSupportsReportHistory(originalEvaluation) && {
key: 'reports',
label: 'Reports',
'data-attr': 'llma-evaluation-reports-tab',
content: (
<EvaluationReportsTab
evaluationId={evaluation.id}
+ generationDisabledReason={
+ isReportableEvaluation
+ ? undefined
+ : 'Add a passing rule to generate new reports.'
+ }
userAccessLevel={evaluation.user_access_level ?? undefined}
onConfigureClick={() => setActiveTab('configuration')}
/>
@@ -555,7 +530,15 @@ export function AIObservabilityEvaluation(): JSX.Element {
<LemonSelect
value={evaluation.evaluation_type}
onChange={(value) => setEvaluationType(value as EvaluationType)}
- options={evaluationMethodOptions}
+ options={evaluationMethodOptions.map((option) => ({
+ ...option,
+ disabledReason:
+ !isNewEvaluation &&
+ evaluation.output_type === 'numeric' &&
+ option.value === 'sentiment'
+ ? 'Create a new evaluation to change its output type.'
+ : undefined,
+ }))}
fullWidth
/>
</LemonField.Pure>
@@ -730,6 +713,39 @@ export function AIObservabilityEvaluation(): JSX.Element {
</>
)}
+ {!isSentiment && (
+ <LemonField.Pure label="Output type">
+ <LemonSelect
+ value={evaluation.output_type}
+ options={[
+ { value: 'boolean', label: 'Boolean' },
+ {
+ value: 'numeric',
+ label: 'Numeric score',
+ disabledReason:
+ isNewEvaluation && !numericEvaluationsEnabled
+ ? 'Numeric evaluations are not enabled for this project.'
+ : undefined,
+ },
+ ]}
+ onChange={(value) =>
+ setOutputType(value as 'boolean' | 'numeric')
+ }
+ disabledReason={
+ !isNewEvaluation
+ ? 'Create a new evaluation to change its output type.'
+ : undefined
+ }
+ data-attr="llma-evaluation-output-type"
+ />
+ </LemonField.Pure>
+ )}
+ {evaluation.output_type === 'numeric' && (
+ <NumericEvaluationConfig
+ config={evaluation.output_config}
+ onChange={patchOutputConfig}
+ />
+ )}
<LemonField.Pure label="Description (optional)">
<LemonTextArea
value={evaluation.description || ''}
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
index d769b709b85d..d220494b4bd3 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
@@ -61,6 +61,7 @@ import {
PASS_RATE_WARNING_THRESHOLD,
} from './components/EvaluationMetrics'
import { OfflineEvaluationsTab } from './components/OfflineEvaluationsTab'
+import { formatNumericEvaluationScore } from './constants'
import { evaluationTypeUsesProviderKey } from './evaluationCapabilities'
import { EvaluationStats, evaluationMetricsLogic } from './evaluationMetricsLogic'
import { EvaluationTemplatesEmptyState } from './EvaluationTemplates'
@@ -369,6 +370,17 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
return <span className="text-muted text-sm">No runs</span>
}
+ if (evaluation.output_type === 'numeric') {
+ return (
+ <div className="text-sm">
+ <div>{`${stats.runs_count} runs`}</div>
+ <div>{`Mean score: ${stats.score_mean == null ? '–' : formatNumericEvaluationScore(stats.score_mean)}`}</div>
+ {evaluation.output_config.passing_rule && (
+ <div>{`Pass rate: ${stats.pass_rate == null ? '–' : `${stats.pass_rate.toFixed(1)}%`}`}</div>
+ )}
+ </div>
+ )
+ }
// Sentiment evals classify rather than pass/fail, so a pass rate is meaningless
if (evaluation.evaluation_type === 'sentiment') {
return (
@@ -379,11 +391,13 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
}
const passRateColor =
- stats.pass_rate >= PASS_RATE_SUCCESS_THRESHOLD
- ? 'text-success'
- : stats.pass_rate >= PASS_RATE_WARNING_THRESHOLD
- ? 'text-warning'
- : 'text-danger'
+ stats.pass_rate == null
+ ? 'text-muted'
+ : stats.pass_rate >= PASS_RATE_SUCCESS_THRESHOLD
+ ? 'text-success'
+ : stats.pass_rate >= PASS_RATE_WARNING_THRESHOLD
+ ? 'text-warning'
+ : 'text-danger'
return (
<div className="flex flex-col items-center">
@@ -391,7 +405,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
{stats.runs_count} run{stats.runs_count !== 1 ? 's' : ''}
</div>
<div className={`font-semibold ${passRateColor}`}>
- {parseFloat(stats.pass_rate.toFixed(2))}%
+ {stats.pass_rate == null ? '–' : `${parseFloat(stats.pass_rate.toFixed(2))}%`}
</div>
</div>
)
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
index 156f13982870..1a6f9c7f0383 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { BindLogic, Provider } from 'kea'
import { useMocks } from '~/mocks/jest'
@@ -134,4 +134,18 @@ describe('EvaluationCodeEditor', () => {
)
).toBeInTheDocument()
})
+
+ it.each([
+ ['Latency', 'return target.total_latency_seconds;'],
+ ['Cost', 'return target.total_cost_usd;'],
+ ])('enables N/A for the numeric %s example', (label, source) => {
+ logic.actions.loadEvaluationSuccess({ ...baseEvaluation, output_type: 'numeric' })
+ renderEditor()
+
+ fireEvent.click(screen.getByText(label))
+
+ expect(logic.values.evaluation?.evaluation_config).toEqual({ source })
+ expect(logic.values.evaluation?.output_config.allows_na).toBe(true)
+ expect(screen.getByText('Number or null')).toBeInTheDocument()
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
index 1b66f5fbe4de..5a27a3676734 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
@@ -9,8 +9,9 @@ import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'
import { useOpenAi } from '~/scenes/max/useOpenAi'
import { urls } from '~/scenes/urls'
+import { EvaluationResultTag } from '../../components/EvaluationResultTag'
import type { TestHogResultItemApi } from '../../generated/api.schemas'
-import { evaluationIsDetector } from '../constants'
+import { evaluationIsDetector, numericOutputConfigError, numericScorePasses } from '../constants'
import { HOG_EVAL_EXAMPLES } from '../hogEvalExamples'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import type { EvaluationTarget } from '../types'
@@ -198,24 +199,36 @@ 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 passed = hogTestResults?.filter((r) => r.result === !trueIsFailure).length ?? 0
- const failed = hogTestResults?.filter((r) => r.result === trueIsFailure).length ?? 0
- const na = hogTestResults?.filter((r) => r.result === null && !r.error).length ?? 0
+ const numeric = evaluation?.output_type === 'numeric'
+ const rule = evaluation?.output_config.passing_rule
+ const passed =
+ hogTestResults?.filter((r) =>
+ 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
+ ).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 (
<div className="border rounded p-3 space-y-2">
<div className="flex items-center justify-between">
- <div className="flex items-center gap-3 text-sm">
+ <div className="flex flex-wrap items-center gap-3 text-sm">
<span className="font-semibold">Test results</span>
{hogTestResults && (
<>
- <LemonTag type="success" icon={<IconCheck />}>
- {passed} passed
- </LemonTag>
- <LemonTag type="danger" icon={<IconX />}>
- {failed} failed
- </LemonTag>
+ {(!numeric || rule) && (
+ <>
+ <LemonTag type="success" icon={<IconCheck />}>
+ {passed} passed
+ </LemonTag>
+ <LemonTag type="danger" icon={<IconX />}>
+ {failed} failed
+ </LemonTag>
+ </>
+ )}
{na > 0 && (
<LemonTag type="muted" icon={<IconMinus />}>
{na} N/A
@@ -252,6 +265,20 @@ export function HogTestResultsPanel(): JSX.Element | null {
</Tooltip>
)
}
+ if (numeric) {
+ return (
+ <EvaluationResultTag
+ run={{
+ status: 'completed',
+ result: null,
+ result_type: 'numeric',
+ score: row.score,
+ applicable: row.score != null,
+ }}
+ passingRule={rule}
+ />
+ )
+ }
if (row.result === null) {
return (
<LemonTag type="muted" icon={<IconMinus />}>
@@ -323,7 +350,7 @@ export function HogTestResultsPanel(): JSX.Element | null {
export function EvaluationCodeEditor(): JSX.Element {
const { evaluation, hogTestResultsLoading } = useValues(llmEvaluationLogic)
- const { setHogSource, testHogOnSample } = useActions(llmEvaluationLogic)
+ const { setHogSource, setAllowsNA, testHogOnSample } = useActions(llmEvaluationLogic)
const { openAi } = useOpenAi()
if (!evaluation || evaluation.evaluation_type !== 'hog') {
@@ -354,7 +381,7 @@ export function EvaluationCodeEditor(): JSX.Element {
quickSuggestionsDelay: 300,
}}
/>
- <div className="flex justify-between items-center text-sm text-muted">
+ <div className="flex flex-wrap gap-2 justify-between items-center text-sm text-muted">
<div className="flex items-center gap-2">
<Tooltip
title={
@@ -370,6 +397,11 @@ export function EvaluationCodeEditor(): JSX.Element {
size="xsmall"
loading={hogTestResultsLoading}
disabled={!source.trim()}
+ disabledReason={
+ evaluation.output_type === 'numeric'
+ ? numericOutputConfigError(evaluation.output_config)
+ : null
+ }
onClick={() => testHogOnSample()}
data-attr="llma-evaluation-test-hog"
>
@@ -399,9 +431,13 @@ export function EvaluationCodeEditor(): JSX.Element {
<div className="flex items-center gap-2">
<span>Expected output:</span>
<LemonTag type="completion">
- {evaluation.output_config.allows_na
- ? 'Boolean or null (true/false/null)'
- : 'Boolean (true/false)'}
+ {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>
@@ -420,17 +456,33 @@ export function EvaluationCodeEditor(): JSX.Element {
</Link>
</div>
<div className="flex flex-wrap gap-1.5 mb-3">
- {HOG_EVAL_EXAMPLES.map((example) => (
+ {(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}
type="secondary"
size="xsmall"
- onClick={() => setHogSource(example.source)}
+ onClick={() => {
+ if (evaluation.output_type === 'numeric') {
+ setAllowsNA(true)
+ }
+ setHogSource(example.source)
+ }}
>
{example.label}
</LemonButton>
))}
</div>
+ {evaluation.output_type === 'numeric' && (
+ <p className="text-xs text-muted mb-3">
+ These examples enable N/A for missing cost or latency measurements.
+ </p>
+ )}
<h4 className="text-sm font-semibold mb-2">Available globals</h4>
<dl className="grid grid-cols-[max-content_minmax(0,1fr)] items-start gap-x-3 gap-y-2 text-sm text-muted">
{HOG_EVAL_COMMON_GLOBAL_DEFINITIONS.map((globalDefinition) => (
@@ -461,14 +513,20 @@ 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>
- Return <code>true</code> ({trueIsFailure ? 'fail' : 'pass'}) or <code>false</code> (
- {trueIsFailure ? 'pass' : 'fail'})
- {evaluation.output_config.allows_na ? (
+ {evaluation.output_type === 'numeric' ? (
+ <span>Return a number within the configured bounds.</span>
+ ) : (
<>
- {' '}
- or <code>null</code> (N/A)
+ Return <code>true</code> ({trueIsFailure ? 'fail' : 'pass'}) or <code>false</code> (
+ {trueIsFailure ? 'pass' : 'fail'})
+ {evaluation.output_config.allows_na ? (
+ <>
+ {' '}
+ or <code>null</code> (N/A)
+ </>
+ ) : null}
</>
- ) : null}
+ )}
</li>
{evaluation.output_config.allows_na && (
<li>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
index d5f84535961d..889cd10e61d4 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationMetrics.tsx
@@ -78,7 +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 to display. Create and enable evaluations to see metrics.
+ No enabled evaluations with pass rates. Enable a boolean evaluation or set a passing
+ threshold on a numeric evaluation.
</div>
</div>
)}
@@ -100,9 +101,13 @@ export function EvaluationMetrics(): JSX.Element {
/>
<SummaryCard
title="Pass rate"
- value={summaryMetrics.total_runs === 0 ? 'N/A' : `${summaryMetrics.overall_pass_rate}%`}
+ value={
+ summaryMetrics.overall_pass_rate == null
+ ? 'N/A'
+ : `${summaryMetrics.overall_pass_rate}%`
+ }
colorClass={
- summaryMetrics.total_runs > 0
+ summaryMetrics.overall_pass_rate != null
? getPassRateColor(summaryMetrics.overall_pass_rate)
: ''
}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx
index b1f26462358b..b6a0502ad6da 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationPromptEditor.tsx
@@ -25,11 +25,13 @@ export function EvaluationPromptEditor(): JSX.Element {
value={prompt}
onChange={setEvaluationPrompt}
placeholder={
- 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 === '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.`
}
@@ -37,12 +39,18 @@ Example: Is this response helpful and accurate? Return true if yes, false if no.
className="font-mono text-sm"
maxLength={2000}
/>
- <div className="flex justify-between items-center text-sm text-muted">
+ <div className="flex flex-wrap gap-2 justify-between items-center text-sm text-muted">
<div>{prompt.length}/2000 characters</div>
<div className="flex items-center gap-2">
<span>Expected output:</span>
<LemonTag type="completion">
- {allowsNA ? 'Boolean (true/false/NA)' : 'Boolean (true/false)'}
+ {evaluation.output_type === 'numeric'
+ ? allowsNA
+ ? 'Number or N/A'
+ : 'Number'
+ : allowsNA
+ ? 'Boolean (true/false/NA)'
+ : 'Boolean (true/false)'}
</LemonTag>
</div>
</div>
@@ -55,7 +63,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>
- {allowsNA ? (
+ {evaluation.output_type === 'numeric' ? (
+ <span>Describe the scoring scale and what each score means</span>
+ ) : allowsNA ? (
<>
Clearly instruct to return <code>true</code>, <code>false</code>, or{' '}
<code>N/A</code> when criteria doesn't apply
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
index 24dfa1fc320e..11563c94bb5b 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
@@ -153,6 +153,7 @@ function ReportSectionContent({
const RESULT_ORDER: Record<EvaluationOutputType, string[]> = {
boolean: ['pass', 'fail', 'na'],
+ numeric: ['pass', 'fail', 'na'],
sentiment: ['positive', 'neutral', 'negative'],
}
@@ -224,7 +225,7 @@ function getBooleanPassRate(
export function summarizeEvaluationReportResults(metrics: EvaluationReportStoredMetrics): string {
const resultMetrics = getResultMetrics(metrics)
- if ((metrics.output_type ?? 'boolean') === 'boolean') {
+ if (['boolean', 'numeric'].includes(metrics.output_type ?? 'boolean')) {
const passRate = getBooleanPassRate(metrics, resultMetrics)
const summaryParts = passRate == null ? [] : [`Pass rate ${formatResultRate(passRate, 1)}`]
summaryParts.push(
@@ -250,15 +251,20 @@ export function summarizeEvaluationReportResults(metrics: EvaluationReportStored
function MetricsCard({ metrics }: { metrics: EvaluationReportStoredMetrics }): JSX.Element {
const resultMetrics = getResultMetrics(metrics)
- const isBooleanMetrics = (metrics.output_type ?? 'boolean') === 'boolean'
+ const isBooleanMetrics = ['boolean', 'numeric'].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
const passRateDiffClass =
passRateDiff == null || passRateDiff === 0 ? 'text-muted' : passRateDiff > 0 ? 'text-success' : 'text-danger'
+ const passingRule =
+ metrics.output_config && 'passing_rule' in metrics.output_config ? metrics.output_config.passing_rule : null
return (
<div className="bg-bg-light border rounded p-3 mb-3">
+ {metrics.output_type === 'numeric' && passingRule && (
+ <p className="text-sm text-muted">{`Passing rule used for this report: score ${passingRule.operator === 'gte' ? '≥' : '≤'} ${passingRule.threshold}`}</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/EvaluationReportsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
index bc956d26a711..fe458ca9cce3 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
@@ -14,6 +14,7 @@ import { EvaluationReportViewer, summarizeEvaluationReportResults } from './Eval
interface EvaluationReportsTabProps {
evaluationId: string
+ generationDisabledReason?: string
userAccessLevel?: AccessControlLevel
/** Called when the user clicks the "Set up scheduled reports" CTA in the empty state. */
onConfigureClick: () => void
@@ -32,6 +33,7 @@ const STATUS_STYLES: Record<
export function EvaluationReportsTab({
evaluationId,
+ generationDisabledReason,
userAccessLevel,
onConfigureClick,
}: EvaluationReportsTabProps): JSX.Element {
@@ -47,11 +49,11 @@ export function EvaluationReportsTab({
<div className="bg-bg-light border rounded p-8 text-center space-y-3">
<h3 className="text-lg font-semibold m-0">No scheduled reports yet</h3>
<p className="text-muted text-sm m-0">
- Scheduled reports deliver AI-generated analysis of this evaluation's results to email or Slack
- on a recurring basis.
+ {generationDisabledReason ??
+ "Scheduled reports deliver AI-generated analysis of this evaluation's results to email or Slack on a recurring basis."}
</p>
<LemonButton type="primary" onClick={onConfigureClick}>
- Set up scheduled reports
+ {generationDisabledReason ? 'Configure evaluation' : 'Set up scheduled reports'}
</LemonButton>
</div>
</div>
@@ -60,8 +62,8 @@ export function EvaluationReportsTab({
return (
<div className="max-w-6xl">
- <div className="flex items-start justify-between gap-6 mb-4">
- <p className="min-w-0 text-muted text-sm m-0">
+ <div className="flex flex-wrap items-start justify-between gap-6 mb-4">
+ <p className="min-w-0 flex-1 basis-64 text-muted text-sm m-0">
History of AI-generated reports for this evaluation. Click a row to expand the full report. Schedule
and delivery targets are configured in the <Link onClick={onConfigureClick}>Configuration tab</Link>
.
@@ -86,6 +88,7 @@ export function EvaluationReportsTab({
size="small"
onClick={() => generateReport(activeReport.id)}
loading={generateResultLoading}
+ disabledReason={generationDisabledReason}
>
Generate now
</LemonButton>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
index 5b1f524113ba..3a3d2816091b 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsFilters.tsx
@@ -19,7 +19,7 @@ const BASE_FILTER_OPTIONS: FilterOption[] = [
const NA_FILTER_OPTION: FilterOption = { value: 'na', label: 'N/A' }
export function EvaluationRunsFilters(): JSX.Element | null {
- const { evaluation, runsSummary, evaluationRunsFilter } = useValues(llmEvaluationLogic)
+ const { originalEvaluation: evaluation, runsSummary, evaluationRunsFilter } = useValues(llmEvaluationLogic)
const { setEvaluationRunsFilter } = useActions(llmEvaluationLogic)
if (!runsSummary || runsSummary.total === 0) {
@@ -32,7 +32,12 @@ export function EvaluationRunsFilters(): JSX.Element | null {
onChange={(value) => {
setEvaluationRunsFilter(value, evaluationRunsFilter)
}}
- options={[...BASE_FILTER_OPTIONS, ...(evaluation?.output_config?.allows_na ? [NA_FILTER_OPTION] : [])]}
+ options={[
+ ...(evaluation?.output_type === 'numeric' && !evaluation.output_config.passing_rule
+ ? BASE_FILTER_OPTIONS.filter((option) => option.value === 'all')
+ : BASE_FILTER_OPTIONS),
+ ...(evaluation?.output_config?.allows_na ? [NA_FILTER_OPTION] : []),
+ ]}
size="small"
// pinned: autocapture data-attr - existing dashboards depend on it
data-attr="llma-evaluation-summary-filter"
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx
index 995921cef945..ca0dd4d9a056 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx
@@ -6,6 +6,7 @@ import { BindLogic, Provider } from 'kea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { getEvaluationResultDisplay } from '../../components/EvaluationResultTag'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import { EvaluationRun } from '../types'
import { EvaluationRunsTable } from './EvaluationRunsTable'
@@ -35,6 +36,23 @@ const passingRun: EvaluationRun = {
}
describe('EvaluationRunsTable', () => {
+ it.each([
+ [0, undefined, undefined, false, '0', 'none'],
+ [7, 'gte', 7, false, '7', 'success'],
+ [7, 'lte', 7, false, '7', 'success'],
+ [6, 'gte', 7, false, '6', 'danger'],
+ [8, 'lte', 7, false, '8', 'danger'],
+ [null, undefined, undefined, false, 'N/A', 'muted'],
+ [null, undefined, undefined, true, 'Skipped', 'muted'],
+ ] as const)('displays score %p with %p rule', (score, operator, threshold, skipped, label, type) => {
+ expect(
+ getEvaluationResultDisplay(
+ { ...passingRun, result: null, result_type: 'numeric', score, applicable: score != null, skipped },
+ { passingRule: operator ? { operator, threshold: threshold! } : null }
+ )
+ ).toMatchObject({ label, type })
+ })
+
let logic: ReturnType<typeof llmEvaluationLogic.build>
beforeEach(() => {
@@ -65,7 +83,7 @@ describe('EvaluationRunsTable', () => {
expect(screen.getByText('Could not load evaluation runs')).toBeInTheDocument()
expect(screen.getByText('Retry')).toBeInTheDocument()
- expect(screen.queryByText('No evaluation runs yet')).not.toBeInTheDocument()
+ expect(screen.queryByText('No evaluation runs found')).not.toBeInTheDocument()
})
it('warns that rows are stale when a refresh fails with runs already on screen', () => {
@@ -86,13 +104,13 @@ describe('EvaluationRunsTable', () => {
renderTable()
expect(screen.getByText('No runs match this filter')).toBeInTheDocument()
- expect(screen.queryByText('No evaluation runs yet')).not.toBeInTheDocument()
+ expect(screen.queryByText('No evaluation runs found')).not.toBeInTheDocument()
})
- it('shows the never-ran empty state when the evaluation truly has no runs', () => {
+ it('shows the empty state when no runs are found in the selected date range', () => {
logic.actions.loadEvaluationRunsSuccess([])
renderTable()
- expect(screen.getByText('No evaluation runs yet')).toBeInTheDocument()
+ expect(screen.getByText('No evaluation runs found')).toBeInTheDocument()
})
})
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index 4c0ba8361983..4d622629945e 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -3,10 +3,11 @@ import { useActions, useValues } from 'kea'
import { IconRefresh } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonSegmentedButton, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { EvaluationResultTag, getEvaluationResultSortValue } from '../../components/EvaluationResultTag'
+import { EvaluationResultTag, compareEvaluationResults } from '../../components/EvaluationResultTag'
import { EvaluationRunTargetCell } from '../../components/EvaluationRunTargetCell'
import { evaluationIsDetector } from '../constants'
import { evaluationSupportsRunOutcomes } from '../evaluationCapabilities'
@@ -39,10 +40,17 @@ function SentimentEvaluationRunsFilters(): JSX.Element {
}
export function EvaluationRunsTable(): JSX.Element {
- const { filteredEvaluationRuns, evaluationRuns, evaluationRunsError, evaluation, evaluationRunsLoading } =
- useValues(llmEvaluationLogic)
- const { refreshEvaluationRuns } = useActions(llmEvaluationLogic)
- const showOutcomeFilters = evaluationSupportsRunOutcomes(evaluation)
+ const {
+ filteredEvaluationRuns,
+ evaluationRuns,
+ evaluationRunsError,
+ originalEvaluation: evaluation,
+ evaluationRunsLoading,
+ runsDateRange,
+ runsBackfillId,
+ } = useValues(llmEvaluationLogic)
+ const { refreshEvaluationRuns, setRunsDates } = useActions(llmEvaluationLogic)
+ const showOutcomeFilters = evaluation?.output_type === 'numeric' || 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)
@@ -76,9 +84,11 @@ export function EvaluationRunsTable(): JSX.Element {
</div>
) : (
<div className="text-center py-8">
- <div className="text-muted mb-2">No evaluation runs yet</div>
+ <div className="text-muted mb-2">No evaluation runs found</div>
<div className="text-sm text-muted">
- Runs will appear here once this evaluation starts executing based on your triggers.
+ {runsBackfillId
+ ? 'Runs will appear here as this backfill progresses.'
+ : 'Try a wider date range, or check that the evaluation is enabled and its triggers match your data.'}
</div>
</div>
)
@@ -98,13 +108,14 @@ export function EvaluationRunsTable(): JSX.Element {
{
title: 'Result',
key: 'result',
- render: (_, run) => <EvaluationResultTag run={run} trueIsFailure={trueIsFailure} />,
- sorter: (a, b) => {
- return (
- getEvaluationResultSortValue(b, { trueIsFailure }) -
- getEvaluationResultSortValue(a, { trueIsFailure })
- )
- },
+ render: (_, run) => (
+ <EvaluationResultTag
+ run={run}
+ trueIsFailure={trueIsFailure}
+ passingRule={evaluation?.output_config.passing_rule}
+ />
+ ),
+ sorter: (a, b) => compareEvaluationResults(b, a, { trueIsFailure }),
},
{
title: 'Reasoning',
@@ -134,14 +145,22 @@ export function EvaluationRunsTable(): JSX.Element {
return (
<div className="space-y-4">
- <div className="flex justify-between items-center">
- {showOutcomeFilters ? (
- <EvaluationRunsFilters />
- ) : showSentimentFilters ? (
- <SentimentEvaluationRunsFilters />
- ) : (
- <div />
- )}
+ <div className="flex flex-wrap gap-2 justify-between items-center">
+ <div className="flex flex-wrap items-center gap-2">
+ {!runsBackfillId && (
+ <DateFilter
+ dateFrom={runsDateRange.date_from}
+ dateTo={runsDateRange.date_to}
+ onChange={setRunsDates}
+ size="small"
+ />
+ )}
+ {showOutcomeFilters ? (
+ <EvaluationRunsFilters />
+ ) : showSentimentFilters ? (
+ <SentimentEvaluationRunsFilters />
+ ) : null}
+ </div>
<LemonButton
type="secondary"
icon={<IconRefresh />}
diff --git a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.stories.tsx b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.stories.tsx
new file mode 100644
index 000000000000..ccde3ae802c9
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.stories.tsx
@@ -0,0 +1,35 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import type { EvaluationOutputConfig } from '../types'
+import { NumericEvaluationConfig } from './NumericEvaluationConfig'
+
+const meta: Meta<typeof NumericEvaluationConfig> = {
+ title: 'Scenes-App/LLM observability/NumericEvaluationConfig',
+ component: NumericEvaluationConfig,
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+type Story = StoryObj<typeof NumericEvaluationConfig>
+
+function Template({ narrow = false }: { narrow?: boolean }): JSX.Element {
+ const [config, setConfig] = useState<EvaluationOutputConfig>({
+ min: 0,
+ max: 10,
+ step: 0.5,
+ allows_na: true,
+ passing_rule: { operator: 'gte', threshold: 7 },
+ })
+ return (
+ <div className={narrow ? 'max-w-lg' : 'max-w-4xl'}>
+ <NumericEvaluationConfig
+ config={config}
+ onChange={(patch) => setConfig((current) => ({ ...current, ...patch }))}
+ />
+ </div>
+ )
+}
+
+export const Default: Story = { render: () => <Template /> }
+export const Narrow: Story = { render: () => <Template narrow /> }
diff --git a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx
new file mode 100644
index 000000000000..e263c954fef7
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx
@@ -0,0 +1,52 @@
+import { cleanup, fireEvent, render } from '@testing-library/react'
+
+import { numericOutputConfigError } from '../constants'
+import type { EvaluationOutputConfig } from '../types'
+import { NumericEvaluationConfig } from './NumericEvaluationConfig'
+
+describe('NumericEvaluationConfig', () => {
+ afterEach(cleanup)
+
+ it.each([
+ ['min', 'Minimum (optional)'],
+ ['max', 'Maximum (optional)'],
+ ['step', 'Step (optional)'],
+ ])('clears labeled %s without storing NaN', (field, label) => {
+ const onChange = jest.fn()
+ const config: EvaluationOutputConfig = {
+ min: 1,
+ max: 10,
+ step: 1,
+ passing_rule: { operator: 'gte', threshold: 7 },
+ }
+ const { getByLabelText, rerender } = render(<NumericEvaluationConfig config={config} onChange={onChange} />)
+ getByLabelText('Pass when score is')
+ const input = getByLabelText(label) as HTMLInputElement
+ fireEvent.change(input, {
+ target: { value: '' },
+ })
+ expect(onChange).toHaveBeenLastCalledWith({ [field]: null })
+ rerender(<NumericEvaluationConfig config={{ ...config, [field]: null }} onChange={onChange} />)
+ fireEvent.blur(input)
+ expect(input.value).toBe('')
+ fireEvent.change(input, { target: { value: '2' } })
+ expect(onChange).toHaveBeenLastCalledWith({ [field]: 2 })
+ })
+
+ it('keeps a cleared threshold empty and invalid until a number is entered', () => {
+ const onChange = jest.fn()
+ const config: EvaluationOutputConfig = { min: 1, max: 10, passing_rule: { operator: 'gte', threshold: 7 } }
+ const { getByLabelText, rerender } = render(<NumericEvaluationConfig config={config} onChange={onChange} />)
+ const input = getByLabelText('Threshold') as HTMLInputElement
+ fireEvent.change(input, { target: { value: '' } })
+ const cleared = { ...config, ...onChange.mock.calls[0][0] }
+ expect(numericOutputConfigError(cleared)).not.toBeNull()
+ rerender(<NumericEvaluationConfig config={cleared} onChange={onChange} />)
+ fireEvent.blur(input)
+ expect(input.value).toBe('')
+ fireEvent.change(input, { target: { value: '5' } })
+ const edited = { ...config, ...onChange.mock.calls[1][0] }
+ expect(edited.passing_rule.threshold).toBe(5)
+ expect(numericOutputConfigError(edited)).toBeNull()
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
new file mode 100644
index 000000000000..848d6addc8c6
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
@@ -0,0 +1,98 @@
+import { useId } from 'react'
+
+import { LemonBanner, LemonInput, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { numericOutputConfigError } from '../constants'
+import type { EvaluationOutputConfig } from '../types'
+
+export function NumericEvaluationConfig({
+ config,
+ onChange,
+}: {
+ config: EvaluationOutputConfig
+ onChange: (patch: EvaluationOutputConfig) => void
+}): JSX.Element {
+ const id = useId()
+ const rule = config.passing_rule
+ const error = numericOutputConfigError(config)
+ return (
+ <div className="space-y-4">
+ {error && <LemonBanner type="error">{error}</LemonBanner>}
+ <div className="flex flex-wrap gap-4">
+ {(['min', 'max', 'step'] as const).map((field) => (
+ <LemonField.Pure
+ key={field}
+ htmlFor={`${id}-${field}`}
+ label={{ min: 'Minimum (optional)', max: 'Maximum (optional)', step: 'Step (optional)' }[field]}
+ >
+ <LemonInput
+ id={`${id}-${field}`}
+ type="number"
+ value={config[field] ?? NaN}
+ onChange={(value) => onChange({ [field]: Number.isFinite(value) ? value : null })}
+ placeholder="Not set"
+ data-attr={`llma-evaluation-numeric-${field}`}
+ />
+ </LemonField.Pure>
+ ))}
+ </div>
+ <p className="text-muted text-sm">Bounds are inclusive. Step guides scoring without rounding results.</p>
+ <LemonSwitch
+ label="Allow N/A responses"
+ checked={config.allows_na ?? false}
+ onChange={(allows_na) => onChange({ allows_na })}
+ data-attr="llma-evaluation-numeric-allows-na"
+ />
+ <LemonSwitch
+ label="Set a passing rule"
+ checked={!!rule}
+ onChange={(enabled) =>
+ onChange({
+ passing_rule: enabled ? { operator: 'gte', threshold: config.min ?? config.max ?? 0 } : null,
+ })
+ }
+ data-attr="llma-evaluation-numeric-passing-rule"
+ />
+ {rule ? (
+ <div className="flex flex-wrap items-end gap-4">
+ <LemonField.Pure label="Pass when score is" htmlFor={`${id}-operator`}>
+ <LemonSelect
+ id={`${id}-operator`}
+ value={rule.operator}
+ options={[
+ { value: 'gte', label: 'At least (≥)' },
+ { value: 'lte', label: 'At most (≤)' },
+ ]}
+ onChange={(operator) => onChange({ passing_rule: { ...rule, operator } })}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Threshold" htmlFor={`${id}-threshold`}>
+ <LemonInput
+ id={`${id}-threshold`}
+ type="number"
+ value={rule.threshold}
+ onChange={(threshold) =>
+ onChange({
+ passing_rule: { ...rule, threshold: threshold ?? NaN },
+ })
+ }
+ min={config.min ?? undefined}
+ max={config.max ?? undefined}
+ step={config.step ?? 'any'}
+ data-attr="llma-evaluation-numeric-threshold"
+ />
+ </LemonField.Pure>
+ <p className="text-muted text-sm">
+ Changing this rule also updates how historical scores count as passes.
+ </p>
+ </div>
+ ) : (
+ <p className="text-muted text-sm">
+ Scores stay neutral without a passing rule. Add a rule to enable pass rates and reports.
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.ts
index 56c6f4eb901e..0498837fbed3 100644
--- a/products/ai_observability/frontend/evaluations/constants.ts
+++ b/products/ai_observability/frontend/evaluations/constants.ts
@@ -1,6 +1,6 @@
import { escapeHogQLString } from '~/queries/utils'
-import type { EvaluationConfig } from './types'
+import type { EvaluationConfig, EvaluationOutputConfig } from './types'
// Most-recent runs fetched for an evaluation's runs table and its result badges
export const EVALUATION_RUNS_QUERY_LIMIT = 250
@@ -21,6 +21,38 @@ const EVALUATION_RESULT_FALSE_HOGQL = "properties.$ai_evaluation_result = 'false
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
+ 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.'
+ }
+ if (min != null && max != null && min > max) {
+ return 'Minimum must be less than or equal to maximum.'
+ }
+ if (step != null && step <= 0) {
+ return 'Step must be greater than zero.'
+ }
+ if (
+ passing_rule &&
+ ((min != null && passing_rule.threshold < min) || (max != null && passing_rule.threshold > max))
+ ) {
+ return 'Set the passing threshold within the score bounds.'
+ }
+ return null
+}
+
+export const EVALUATION_NUMERIC_GRADED_HOGQL = `properties.$ai_evaluation_result_type = 'numeric' AND properties.$ai_evaluation_numeric_result IS NOT NULL AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != 'false') AND ${EVALUATION_NOT_SKIPPED_HOGQL}`
+export const EVALUATION_BOOLEAN_GRADED_HOGQL = `(isNull(properties.$ai_evaluation_result_type) OR properties.$ai_evaluation_result_type = 'boolean') AND properties.$ai_evaluation_result IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}`
+export const EVALUATION_NUMERIC_MEAN_HOGQL = `avgIf(toFloat(properties.$ai_evaluation_numeric_result), ${EVALUATION_NUMERIC_GRADED_HOGQL})`
+
+export function numericEvaluationPassedHogQL(evaluation: Pick<EvaluationConfig, 'output_config'>): string {
+ const rule = evaluation.output_config.passing_rule
+ if (!rule || !Number.isFinite(rule.threshold)) {
+ return 'false'
+ }
+ return `toFloat(properties.$ai_evaluation_numeric_result) ${rule.operator === 'gte' ? '>=' : '<='} ${rule.threshold}`
+}
+
/** A detector looks for a problem, so its true result is the undesirable one. */
export function evaluationIsDetector(evaluation: Pick<EvaluationConfig, 'output_config'>): boolean {
return evaluation.output_config.true_is_failure === true
@@ -35,9 +67,11 @@ export function evaluationPassedHogQL(evaluation: Pick<EvaluationConfig, 'output
* The HogQL for a pass rate, as a percentage of the graded runs. Skipped runs leave both sides of
* the ratio, so a detector never reads the false a skip stores as a pass.
*/
-export function evaluationPassRateHogQL(passedExpression: string): string {
- const graded = `countIf(properties.$ai_evaluation_result IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL})`
- return `if(${graded} > 0, countIf((${passedExpression}) AND ${EVALUATION_NOT_SKIPPED_HOGQL}) / ${graded} * 100, 0)`
+export function evaluationPassRateHogQL(
+ passedExpression: string,
+ gradedExpression = EVALUATION_BOOLEAN_GRADED_HOGQL
+): string {
+ return `countIf((${passedExpression}) AND (${gradedExpression})) / nullIf(countIf(${gradedExpression}), 0) * 100`
}
/** The HogQL that counts a pass across many evaluations at once, for a grouped or broken-down query. */
@@ -48,3 +82,17 @@ export function evaluationPassedHogQLForMany(detectorEvaluationIds: string[]): s
const ids = detectorEvaluationIds.map((id) => escapeHogQLString(id)).join(', ')
return `if(properties.$ai_evaluation_id IN (${ids}), ${EVALUATION_RESULT_FALSE_HOGQL}, ${EVALUATION_RESULT_TRUE_HOGQL})`
}
+
+export function formatNumericEvaluationScore(score: number): string {
+ return Number(Math.abs(score) >= 1 ? score.toFixed(6) : score.toPrecision(6)).toString()
+}
+
+export function numericScorePasses(
+ score: number | null | undefined,
+ rule: EvaluationOutputConfig['passing_rule']
+): boolean | null {
+ if (score == null || !Number.isFinite(score) || !rule || !Number.isFinite(rule.threshold)) {
+ return null
+ }
+ return rule.operator === 'gte' ? score >= rule.threshold : score <= rule.threshold
+}
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
index 64bc6c70506b..890234bdd6d2 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
@@ -1,5 +1,6 @@
import {
evaluationOffersSessionTarget,
+ evaluationSupportsReportHistory,
evaluationSupportsReports,
evaluationSupportsRunOutcomes,
} from './evaluationCapabilities'
@@ -18,20 +19,37 @@ describe('evaluationCapabilities', () => {
['sentiment', 'generation', true, false],
// Sentiment is generation-only, so the aggregate targets report on boolean alone.
// This pins the frontend twin of REPORTABLE_OUTPUT_TYPES_BY_TARGET.
- ['boolean', 'trace', true, false],
+ ['boolean', 'trace', true, true],
['sentiment', 'trace', false, false],
- ['boolean', 'session', true, false],
+ ['boolean', 'session', true, true],
['sentiment', 'session', false, false],
+ ['numeric', 'generation', false, false],
+ ['numeric', 'trace', false, false],
+ ['numeric', 'session', false, false],
])(
'supports the expected capabilities for %s %s evaluations',
(outputType, target, supportsReports, supportsRunOutcomes) => {
const evaluation = { output_type: outputType, target }
expect(evaluationSupportsReports(evaluation)).toBe(supportsReports)
+ expect(evaluationSupportsReportHistory(evaluation)).toBe(supportsReports || outputType === 'numeric')
expect(evaluationSupportsRunOutcomes(evaluation)).toBe(supportsRunOutcomes)
}
)
+ it.each(['generation', 'trace', 'session'] as const)(
+ 'supports numeric %s reports only with a passing rule',
+ (target) => {
+ const evaluation = {
+ target,
+ output_type: 'numeric' as const,
+ output_config: { passing_rule: { operator: 'gte' as const, threshold: 7 } },
+ }
+ expect(evaluationSupportsReports(evaluation)).toBe(true)
+ expect(evaluationSupportsRunOutcomes(evaluation)).toBe(true)
+ }
+ )
+
// An evaluation already targeting a session must keep the option listed even with the flag off,
// since the API and MCP can create one. Otherwise the picker renders the raw 'session' value.
it.each<[target: EvaluationTarget | null, settlingStrategyEnabled: boolean, offered: boolean]>([
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
index 14a94184e5ad..a5e30380ffe9 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -3,28 +3,42 @@ 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']),
- trace: new Set(['boolean']),
- session: new Set(['boolean']),
+ generation: new Set(['boolean', 'sentiment', 'numeric']),
+ trace: new Set(['boolean', 'numeric']),
+ session: new Set(['boolean', 'numeric']),
}
export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | null | undefined): boolean {
return outputType === 'boolean'
}
-export function evaluationSupportsReports(
+export function evaluationSupportsReportHistory(
evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined
): boolean {
- if (evaluation?.output_type == null || evaluation.target == null) {
- return false
- }
- return REPORTABLE_OUTPUT_TYPES_BY_TARGET[evaluation.target]?.has(evaluation.output_type) ?? false
+ return !!evaluation && (REPORTABLE_OUTPUT_TYPES_BY_TARGET[evaluation.target]?.has(evaluation.output_type) ?? false)
+}
+
+export function evaluationSupportsReports(
+ evaluation:
+ | (Pick<EvaluationConfig, 'output_type' | 'target'> & Partial<Pick<EvaluationConfig, 'output_config'>>)
+ | null
+ | undefined
+): boolean {
+ return (
+ evaluationSupportsReportHistory(evaluation) &&
+ (evaluation?.output_type !== 'numeric' || !!evaluation.output_config?.passing_rule)
+ )
}
export function evaluationSupportsRunOutcomes(
- evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined
+ evaluation:
+ | (Pick<EvaluationConfig, 'output_type' | 'target'> & Partial<Pick<EvaluationConfig, 'output_config'>>)
+ | null
+ | undefined
): boolean {
- return evaluation?.target === 'generation' && isBooleanEvaluationOutput(evaluation.output_type)
+ return evaluation?.output_type === 'numeric'
+ ? !!evaluation.output_config?.passing_rule
+ : isBooleanEvaluationOutput(evaluation?.output_type)
}
export function evaluationTypeUsesModelConfiguration(evaluationType: EvaluationType | null | undefined): boolean {
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
index 6c889c3cdfc1..71eb41b82645 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
@@ -1,3 +1,4 @@
+import { waitFor } from '@testing-library/react'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
@@ -6,7 +7,12 @@ import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { EVALUATION_NOT_SKIPPED_HOGQL, EVALUATION_RESULT_TRUE_HOGQL } from './constants'
+import {
+ EVALUATION_BOOLEAN_GRADED_HOGQL,
+ EVALUATION_NOT_SKIPPED_HOGQL,
+ EVALUATION_NUMERIC_GRADED_HOGQL,
+ EVALUATION_RESULT_TRUE_HOGQL,
+} from './constants'
import { evaluationMetricsLogic, EvaluationStatsRow } from './evaluationMetricsLogic'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
import { LLMJudgeEvaluation } from './types'
@@ -87,6 +93,143 @@ describe('evaluationMetricsLogic', () => {
evaluationsLogic.unmount()
})
+ it('loads stats once after evaluations finish loading on mount', async () => {
+ metricsLogic.unmount()
+ queryMock.mockClear()
+ evaluationsLogic.actions.loadEvaluations()
+ metricsLogic.mount()
+ await waitFor(() => expect(queryMock).toHaveBeenCalledTimes(1))
+ await expectLogic(metricsLogic).toFinishAllListeners()
+ expect(queryMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the latest stats when an older request finishes last', async () => {
+ queryMock.mockClear()
+ let resolveOld!: (response: { results: unknown[][] }) => void
+ queryMock.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOld = resolve
+ })
+ )
+ metricsLogic.actions.loadStats()
+ await waitFor(() => expect(queryMock).toHaveBeenCalledTimes(1))
+
+ queryMock.mockResolvedValueOnce({ results: [['new', 4, 0, 0, 4, 50, 2]] })
+ evaluationsLogic.actions.loadEvaluationsSuccess([
+ {
+ ...evaluation('new', null),
+ output_type: 'numeric',
+ output_config: { passing_rule: { operator: 'gte', threshold: 50 } },
+ },
+ ])
+ await waitFor(() => expect(metricsLogic.values.stats[0]?.evaluation_id).toBe('new'))
+ expect(queryMock.mock.calls[1][0].query).toContain(
+ ">= transform(properties.$ai_evaluation_id, ['new'], [50], toFloat(NULL))"
+ )
+
+ resolveOld({ results: [['old', 4, 0, 0, 4, 50, 0]] })
+ await expectLogic(metricsLogic).toFinishAllListeners()
+ expect(metricsLogic.values.stats[0].evaluation_id).toBe('new')
+ })
+
+ it.each(['gte', 'lte'] as const)('includes numeric %s outcomes in the overview pass rate', async (operator) => {
+ evaluationsLogic.actions.loadEvaluationsSuccess([
+ evaluation('boolean', null),
+ {
+ ...evaluation('numeric', null),
+ output_type: 'numeric',
+ output_config: { passing_rule: { operator, threshold: 0 } },
+ },
+ { ...evaluation('ungraded', null), output_type: 'numeric', output_config: {} },
+ ])
+ await expectLogic(metricsLogic).toFinishAllListeners()
+ const query = queryMock.mock.calls.at(-1)?.[0].query
+ expect(query).toContain(
+ `${operator === 'gte' ? '>=' : '<='} transform(properties.$ai_evaluation_id, ['numeric'], [0], toFloat(NULL))`
+ )
+ expect(query).not.toContain("'ungraded'")
+ metricsLogic.actions.loadStatsSuccess([
+ stats('boolean', 10, 10),
+ {
+ ...stats('numeric', 100, 0),
+ applicable_count: 0,
+ score_count: 80,
+ score_mean: 6.5,
+ numeric_pass_count: 40,
+ },
+ { ...stats('ungraded', 20, 0), score_count: 20, numeric_pass_count: 0 },
+ ])
+ expect(metricsLogic.values.summaryMetrics).toMatchObject({
+ total_runs: 130,
+ overall_pass_rate: 55.6,
+ failing_evaluations_count: 1,
+ })
+ expect(metricsLogic.values.evaluationsWithMetrics[1].stats).toMatchObject({
+ score_mean: 6.5,
+ pass_rate: 50,
+ applicable_count: 80,
+ })
+ expect(metricsLogic.values.chartQuery?.series[0].properties).toEqual([
+ expect.objectContaining({ value: ['boolean', 'numeric'] }),
+ ])
+ const math = metricsLogic.values.chartQuery?.series[0].math_hogql ?? ''
+ expect(math).toContain(
+ `toFloat(properties.$ai_evaluation_numeric_result) ${operator === 'gte' ? '>=' : '<='} 0`
+ )
+ expect(math).toContain("properties.$ai_evaluation_id = 'numeric'")
+ expect(math).toContain('properties.$ai_evaluation_applicable')
+ expect(math).toContain(EVALUATION_NOT_SKIPPED_HOGQL)
+ })
+
+ it('keeps thresholds aligned with their evaluation IDs and comparison directions', async () => {
+ evaluationsLogic.actions.loadEvaluationsSuccess([
+ ...(
+ [
+ { id: "quality'check", operator: 'gte', threshold: 7 },
+ { id: 'cost', operator: 'lte', threshold: 0.05 },
+ { id: 'accuracy', operator: 'gte', threshold: 0.9 },
+ { id: 'invalid', operator: 'gte', threshold: NaN },
+ { id: 'infinite', operator: 'lte', threshold: Infinity },
+ ] as const
+ ).map(({ id, operator, threshold }) => ({
+ ...evaluation(id, null),
+ output_type: 'numeric' as const,
+ output_config: { passing_rule: { operator, threshold } },
+ })),
+ evaluation('boolean', null),
+ ])
+ await expectLogic(metricsLogic).toFinishAllListeners()
+
+ const query = queryMock.mock.calls.at(-1)?.[0].query
+ expect(query).toContain(
+ ">= transform(properties.$ai_evaluation_id, ['quality\\'check', 'accuracy'], [7, 0.9], toFloat(NULL))"
+ )
+ expect(query).toContain("<= transform(properties.$ai_evaluation_id, ['cost'], [0.05], toFloat(NULL))")
+ expect(query).not.toMatch(/'invalid'|'infinite'|NaN|Infinity/)
+ expect(query).toContain(`AND ${EVALUATION_NUMERIC_GRADED_HOGQL}) as numeric_pass_count`)
+ })
+
+ it.each([false, true])('has no pass rate when numeric runs have no graded outcomes (rule: %s)', (hasRule) => {
+ evaluationsLogic.actions.loadEvaluationsSuccess([
+ {
+ ...evaluation('numeric', null),
+ output_type: 'numeric',
+ output_config: hasRule ? { passing_rule: { operator: 'gte', threshold: 100 } } : {},
+ },
+ ])
+ metricsLogic.actions.loadStatsSuccess([
+ { ...stats('numeric', 4, 0), score_count: hasRule ? 0 : 4, numeric_pass_count: 0 },
+ ])
+ expect(metricsLogic.values.summaryMetrics).toEqual({
+ total_runs: 4,
+ overall_pass_rate: null,
+ failing_evaluations_count: 0,
+ })
+ expect(metricsLogic.values.chartQuery !== null).toBe(hasRule)
+ expect(metricsLogic.values.evaluationsWithMetrics[0].stats?.pass_rate).toBeNull()
+ })
+
it('uses one filtered breakdown query and scopes metrics to the selected directory', () => {
const firstRootEvaluation = evaluation('root-one', null, "Root's evaluation")
const secondRootEvaluation = evaluation('root-two', null, "Root's evaluation")
@@ -161,7 +304,7 @@ describe('evaluationMetricsLogic', () => {
expect(mathHogql).toContain("properties.$ai_evaluation_result = 'false'")
// Both sides of the ratio drop skipped runs — otherwise the false a skip stores reads as
// a detector pass, and the chart disagrees with the list, which already excludes them.
- expect(mathHogql).toContain(`AND ${EVALUATION_NOT_SKIPPED_HOGQL}) /`)
+ expect(mathHogql).toContain(`AND ${EVALUATION_NOT_SKIPPED_HOGQL})) /`)
expect(mathHogql).toContain(`IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}`)
})
@@ -170,6 +313,7 @@ describe('evaluationMetricsLogic', () => {
const query = queryMock.mock.calls.at(-1)?.[0]
expect(query.query).toContain(`IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}`)
- expect(query.query).toContain(`${EVALUATION_RESULT_TRUE_HOGQL} AND ${EVALUATION_NOT_SKIPPED_HOGQL}`)
+ expect(query.query).toContain(`${EVALUATION_RESULT_TRUE_HOGQL} AND ${EVALUATION_BOOLEAN_GRADED_HOGQL}`)
+ expect(query.query).toContain(`countIf((false) AND ${EVALUATION_NUMERIC_GRADED_HOGQL})`)
})
})
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
index 2ca1442aa9be..6c2f987d6d94 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
@@ -11,13 +11,16 @@ import { ChartDisplayType, HogQLMathType, PropertyFilterType, PropertyOperator }
// eslint-disable-next-line import/no-cycle
import { PASS_RATE_SUCCESS_THRESHOLD } from './components/EvaluationMetrics'
import {
- EVALUATION_NOT_SKIPPED_HOGQL,
+ EVALUATION_BOOLEAN_GRADED_HOGQL,
+ EVALUATION_NUMERIC_GRADED_HOGQL,
+ EVALUATION_NUMERIC_MEAN_HOGQL,
+ numericEvaluationPassedHogQL,
EVALUATION_RESULT_TRUE_HOGQL,
evaluationIsDetector,
evaluationPassedHogQLForMany,
evaluationPassRateHogQL,
} from './constants'
-import { llmEvaluationsLogic } from './llmEvaluationsLogic'
+import { llmEvaluationsLogic, waitForEvaluationsSettled } from './llmEvaluationsLogic'
import { EvaluationConfig } from './types'
const MIN_RUNS_FOR_FAILING_STATUS = 3
@@ -30,21 +33,39 @@ export interface EvaluationStatsRow {
applicable_count: number
true_count: number
applicability_rate: number
+ score_count?: number
+ score_mean?: number | null
+ numeric_pass_count?: number
}
/** A stats row with the evaluation's own polarity applied. */
export interface EvaluationStats extends EvaluationStatsRow {
pass_count: number
- pass_rate: number
+ pass_rate: number | null
}
export interface SummaryMetrics {
total_runs: number
- overall_pass_rate: number
+ overall_pass_rate: number | null
failing_evaluations_count: number
}
-type RawStatsRow = [evaluation_id: string, runs_count: number, applicable_count: number, true_count: number]
+type RawStatsRow = [
+ evaluation_id: string,
+ runs_count: number,
+ applicable_count: number,
+ true_count: number,
+ score_count?: number,
+ score_mean?: number | null,
+ numeric_pass_count?: number,
+]
+
+function hasPassRate(evaluation: EvaluationConfig): boolean {
+ return (
+ evaluation.output_type === 'boolean' ||
+ (evaluation.output_type === 'numeric' && !!evaluation.output_config.passing_rule)
+ )
+}
export type EvaluationMetricsLogicProps = Record<string, never>
@@ -122,7 +143,7 @@ export interface evaluationMetricsLogicActions {
dateFrom: string | null
dateTo: string | null
} // llmEvaluationsLogic
- loadStats: () => any
+ loadStats: (_?: void) => void
loadStatsFailure: (
error: string,
errorObject?: any
@@ -131,23 +152,11 @@ export interface evaluationMetricsLogicActions {
errorObject?: any
}
loadStatsSuccess: (
- stats: {
- applicability_rate: number
- applicable_count: number
- evaluation_id: string
- runs_count: number
- true_count: number
- }[],
- payload?: any
+ stats: EvaluationStatsRow[],
+ payload?: void
) => {
- stats: {
- applicability_rate: number
- applicable_count: number
- evaluation_id: string
- runs_count: number
- true_count: number
- }[]
- payload?: any
+ stats: EvaluationStatsRow[]
+ payload?: void
}
refreshMetrics: () => {
value: true
@@ -209,18 +218,45 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
stats: [
[] as EvaluationStatsRow[],
{
- loadStats: async () => {
+ loadStats: async (_?: void, breakpoint?: () => void): Promise<EvaluationStatsRow[]> => {
+ await waitForEvaluationsSettled()
+ breakpoint?.()
const dateFrom = values.dateFilter.dateFrom || '-1d'
const dateTo = values.dateFilter.dateTo || null
+ // Threshold lookups avoid evaluating a separate condition for every evaluation on each run.
+ const numericPass =
+ (['gte', 'lte'] as const)
+ .flatMap((operator) => {
+ const rules = values.evaluations.flatMap((evaluation) => {
+ const rule = evaluation.output_config.passing_rule
+ return evaluation.output_type === 'numeric' &&
+ rule?.operator === operator &&
+ Number.isFinite(rule.threshold)
+ ? [{ id: evaluation.id, threshold: rule.threshold }]
+ : []
+ })
+ if (rules.length === 0) {
+ return []
+ }
+ const ids = rules.map(({ id }) => escapeHogQLString(id)).join(', ')
+ const thresholds = rules.map(({ threshold }) => threshold).join(', ')
+ return [
+ `toFloat(properties.$ai_evaluation_numeric_result) ${operator === 'gte' ? '>=' : '<='} transform(properties.$ai_evaluation_id, [${ids}], [${thresholds}], toFloat(NULL))`,
+ ]
+ })
+ .join(' OR ') || 'false'
const query: HogQLQuery = {
kind: NodeKind.HogQLQuery,
query: `
SELECT
properties.$ai_evaluation_id as evaluation_id,
count() as runs_count,
- countIf(properties.$ai_evaluation_result IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}) as applicable_count,
- countIf(${EVALUATION_RESULT_TRUE_HOGQL} AND ${EVALUATION_NOT_SKIPPED_HOGQL}) as true_count
+ countIf(${EVALUATION_BOOLEAN_GRADED_HOGQL}) as applicable_count,
+ 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
FROM events
WHERE event = '$ai_evaluation' AND {filters}
GROUP BY evaluation_id
@@ -235,6 +271,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
try {
const response = await api.query(query)
+ breakpoint?.()
return (response.results || []).map((row: RawStatsRow) => {
const runs_count = row[1]
@@ -244,6 +281,9 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
return {
evaluation_id: row[0],
+ 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,
runs_count,
applicable_count,
true_count,
@@ -251,6 +291,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
}
})
} catch (error) {
+ breakpoint?.()
console.error('Failed to load stats:', error)
return []
}
@@ -278,12 +319,29 @@ 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
+ return {
+ ...evaluation,
+ stats: {
+ ...stat,
+ applicable_count,
+ pass_count,
+ applicability_rate: stat.runs_count ? (applicable_count / stat.runs_count) * 100 : 0,
+ pass_rate:
+ applicable_count && evaluation.output_config.passing_rule
+ ? (pass_count / applicable_count) * 100
+ : null,
+ },
+ }
+ }
// Pass rate excludes N/A results (uses applicable_count as denominator)
const pass_count = evaluationIsDetector(evaluation)
? stat.applicable_count - stat.true_count
: stat.true_count
const pass_rate =
- stat.applicable_count > 0 ? Math.round((pass_count / stat.applicable_count) * 1000) / 10 : 0
+ stat.applicable_count > 0 ? Math.round((pass_count / stat.applicable_count) * 1000) / 10 : null
return { ...evaluation, stats: { ...stat, pass_count, pass_rate } }
})
},
@@ -297,27 +355,32 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
): SummaryMetrics => {
const ids = new Set(evaluationsForMetrics.map((evaluation) => evaluation.id))
const statsForMetrics = evaluationsWithMetrics
- .filter((evaluation) => ids.has(evaluation.id))
+ .filter((evaluation) => ids.has(evaluation.id) && hasPassRate(evaluation))
.map((evaluation) => evaluation.stats)
.filter((stat): stat is EvaluationStats => stat != null)
- const total_runs = statsForMetrics.reduce((sum, stat) => sum + stat.runs_count, 0)
+ const total_runs = evaluationsWithMetrics
+ .filter((evaluation) => ids.has(evaluation.id))
+ .reduce((sum, evaluation) => sum + (evaluation.stats?.runs_count ?? 0), 0)
const total_applicable = statsForMetrics.reduce((sum, stat) => sum + stat.applicable_count, 0)
const total_passes = statsForMetrics.reduce((sum, stat) => sum + stat.pass_count, 0)
// Overall pass rate excludes N/A results
- const overall_pass_rate = total_applicable > 0 ? (total_passes / total_applicable) * 100 : 0
+ // Keep an unmeasured pass rate distinct from measured zero passes.
+ const overall_pass_rate =
+ total_applicable > 0 ? Math.round((total_passes / total_applicable) * 1000) / 10 : null
const failing_count = statsForMetrics.filter((stat) => {
// Use applicable_count for minimum runs check
return (
stat.applicable_count >= MIN_RUNS_FOR_FAILING_STATUS &&
+ stat.pass_rate != null &&
stat.pass_rate < PASS_RATE_SUCCESS_THRESHOLD
)
}).length
return {
total_runs,
- overall_pass_rate: Math.round(overall_pass_rate * 10) / 10,
+ overall_pass_rate,
failing_evaluations_count: failing_count,
}
},
@@ -330,7 +393,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
dateFilter: { dateFrom: string | null; dateTo: string | null }
): TrendsQuery | null => {
const enabledEvaluations = evaluationsForMetrics
- .filter((evaluation) => evaluation.enabled && !evaluation.deleted)
+ .filter((evaluation) => evaluation.enabled && !evaluation.deleted && hasPassRate(evaluation))
.slice(0, MAX_EVALUATION_CHART_SERIES)
if (enabledEvaluations.length === 0) {
@@ -340,6 +403,24 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
const dateFrom = dateFilter.dateFrom || '-7d'
const dateTo = dateFilter.dateTo || null
const interval = getIntervalFromDateRange(dateFrom)
+ const numericEvaluations = enabledEvaluations.filter(
+ (evaluation) => evaluation.output_type === 'numeric'
+ )
+ let passedExpression = evaluationPassedHogQLForMany(
+ enabledEvaluations.filter(evaluationIsDetector).map((evaluation) => evaluation.id)
+ )
+ let gradedExpression = EVALUATION_BOOLEAN_GRADED_HOGQL
+ if (numericEvaluations.length > 0) {
+ const numericCases = numericEvaluations.flatMap((evaluation) => [
+ `properties.$ai_evaluation_id = ${escapeHogQLString(evaluation.id)}`,
+ numericEvaluationPassedHogQL(evaluation),
+ ])
+ const numericIds = numericEvaluations
+ .map((evaluation) => escapeHogQLString(evaluation.id))
+ .join(', ')
+ passedExpression = `multiIf(${numericCases.join(', ')}, ${passedExpression})`
+ gradedExpression = `if(properties.$ai_evaluation_id IN (${numericIds}), ${EVALUATION_NUMERIC_GRADED_HOGQL}, ${EVALUATION_BOOLEAN_GRADED_HOGQL})`
+ }
return {
kind: NodeKind.TrendsQuery,
@@ -348,11 +429,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
kind: NodeKind.EventsNode,
event: '$ai_evaluation',
math: HogQLMathType.HogQL,
- math_hogql: evaluationPassRateHogQL(
- evaluationPassedHogQLForMany(
- enabledEvaluations.filter(evaluationIsDetector).map((evaluation) => evaluation.id)
- )
- ),
+ math_hogql: evaluationPassRateHogQL(passedExpression, gradedExpression),
properties: [
{
key: '$ai_evaluation_id',
@@ -386,12 +463,17 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
refreshMetrics: () => {
actions.loadStats()
},
+ [llmEvaluationsLogic.actionTypes.loadEvaluationsSuccess]: () => {
+ actions.loadStats()
+ },
setDates: () => {
actions.loadStats()
},
})),
afterMount(({ actions }) => {
- actions.loadStats()
+ if (llmEvaluationsLogic.values.evaluationsSettled) {
+ actions.loadStats()
+ }
}),
])
diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
index 2bf1ecf6726c..537ff31ac85c 100644
--- a/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.test.ts
@@ -2,7 +2,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { evaluationsList, llmAnalyticsEvaluationReportsList } from '../generated/api'
import type { EvaluationApi, EvaluationReportApi } from '../generated/api.schemas'
-import { listAllEvaluationReports, listAllEvaluations } from './evaluationsApi'
+import { EvaluationsCreateBody } from '../generated/api.zod'
+import { evaluationFromApi, listAllEvaluationReports, listAllEvaluations } from './evaluationsApi'
jest.mock('../generated/api', () => ({
evaluationsList: jest.fn(),
@@ -69,6 +70,32 @@ const evaluationReportApi = (id: string, evaluation: string): EvaluationReportAp
})
describe('evaluationsApi', () => {
+ it.each([
+ { min: 0, max: 10, passing_rule: { operator: 'gte', threshold: 7 }, allows_na: true },
+ { true_is_failure: true, allows_na: false },
+ { allows_na: true },
+ {},
+ ])('preserves output settings through the generated schema: %j', (output_config) => {
+ expect(EvaluationsCreateBody.shape.output_config.parse(output_config)).toEqual(output_config)
+ })
+
+ it.each(['llm_judge', 'hog'] as const)('keeps numeric %s configurations in the list', (evaluation_type) => {
+ const output_config = {
+ min: 0,
+ max: 10,
+ allows_na: true,
+ passing_rule: { operator: 'gte' as const, threshold: 7 },
+ }
+ const evaluation = evaluationFromApi({
+ ...evaluationApi('1'),
+ evaluation_type,
+ evaluation_config: evaluation_type === 'hog' ? { source: 'return 7;' } : { prompt: 'Score correctness' },
+ output_type: 'numeric',
+ output_config,
+ })
+ expect(evaluation).toMatchObject({ evaluation_type, output_type: 'numeric', output_config })
+ })
+
it.each(['categorical', 'future_output'])(
'keeps supported rows when a page contains a future %s output',
async (output_type) => {
diff --git a/products/ai_observability/frontend/evaluations/evaluationsApi.ts b/products/ai_observability/frontend/evaluations/evaluationsApi.ts
index ae2e6c4c5151..bd57724e5071 100644
--- a/products/ai_observability/frontend/evaluations/evaluationsApi.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationsApi.ts
@@ -65,21 +65,21 @@ export function evaluationFromApi(evaluation: EvaluationApi): EvaluationConfig |
if (
evaluation.evaluation_type === 'llm_judge' &&
- evaluation.output_type === 'boolean' &&
+ (evaluation.output_type === 'boolean' || evaluation.output_type === 'numeric') &&
evaluation.evaluation_config &&
'prompt' in evaluation.evaluation_config
) {
return {
...baseEvaluation,
evaluation_type: 'llm_judge',
- output_type: 'boolean',
+ output_type: evaluation.output_type,
evaluation_config: { prompt: evaluation.evaluation_config.prompt },
}
}
if (
evaluation.evaluation_type === 'hog' &&
- evaluation.output_type === 'boolean' &&
+ (evaluation.output_type === 'boolean' || evaluation.output_type === 'numeric') &&
evaluation.evaluation_config &&
'source' in evaluation.evaluation_config &&
typeof evaluation.evaluation_config.source === 'string'
@@ -87,7 +87,7 @@ export function evaluationFromApi(evaluation: EvaluationApi): EvaluationConfig |
return {
...baseEvaluation,
evaluation_type: 'hog',
- output_type: 'boolean',
+ output_type: evaluation.output_type,
evaluation_config: { source: evaluation.evaluation_config.source },
}
}
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 2e9fd104fd8a..b76fa3d1ad95 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -1,14 +1,17 @@
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
+import { HogQLQuery } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ActivityScope } from '~/types'
import type { TestHogResponseApi } from '../generated/api.schemas'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
+import { numericScorePasses } from './constants'
import { evaluationReportLogic } from './evaluationReportLogic'
import { DEFAULT_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
@@ -265,6 +268,74 @@ describe('llmEvaluationLogic', () => {
logic.mount()
})
+ it.each([
+ [DEFAULT_HOG_SOURCE, 'return 0;'],
+ ['return 42;', 'return 42;'],
+ ])('updates only untouched Hog source %s when selecting numeric output', (source, expected) => {
+ const warning = jest.spyOn(lemonToast, 'warning')
+ logic.actions.setEvaluationType('hog')
+ logic.actions.setHogSource(source)
+ logic.actions.setTrueIsFailure(true)
+ logic.actions.setOutputType('numeric')
+ expect(logic.values.evaluation).toMatchObject({
+ output_type: 'numeric',
+ evaluation_config: { source: expected },
+ })
+ expect(logic.values.evaluation?.output_config).not.toHaveProperty('true_is_failure')
+ if (source === expected) {
+ expect(warning).toHaveBeenCalledWith(
+ 'Your code was kept. Update it to return a number and test it before enabling this evaluation.'
+ )
+ } else {
+ expect(warning).not.toHaveBeenCalled()
+ }
+ warning.mockRestore()
+ const numericConfig = { min: 0, max: 10, passing_rule: { operator: 'gte' as const, threshold: 7 } }
+ logic.actions.patchOutputConfig(numericConfig)
+ logic.actions.setOutputType('boolean')
+ expect(logic.values.evaluation).toMatchObject({
+ output_type: 'boolean',
+ evaluation_config: { source },
+ output_config: { true_is_failure: true },
+ })
+ expect(logic.values.evaluation?.output_config).not.toHaveProperty('passing_rule')
+ logic.actions.setOutputType('numeric')
+ expect(logic.values.evaluation?.output_config).toMatchObject(numericConfig)
+ logic.actions.patchOutputConfig({ max: 20 })
+ logic.actions.setOutputType('numeric')
+ expect(logic.values.evaluation?.output_config.max).toBe(20)
+ })
+
+ it('preserves numeric output while switching runtimes and locks saved output types', async () => {
+ const numeric = {
+ ...mockEvaluation,
+ output_type: 'numeric' as const,
+ output_config: {
+ min: 0,
+ max: 10,
+ allows_na: true,
+ passing_rule: { operator: 'gte' as const, threshold: 7 },
+ },
+ }
+ logic.actions.loadEvaluationSuccess(numeric)
+ logic.actions.setEvaluationType('hog')
+ expect(logic.values.evaluation).toMatchObject({
+ output_type: 'numeric',
+ output_config: numeric.output_config,
+ })
+ logic.actions.setEvaluationType('llm_judge')
+ expect(logic.values.evaluation).toMatchObject({
+ output_type: 'numeric',
+ output_config: numeric.output_config,
+ })
+ const savedLogic = llmEvaluationLogic({ evaluationId: 'saved-numeric' })
+ savedLogic.mount()
+ savedLogic.actions.loadEvaluationSuccess(numeric)
+ savedLogic.actions.setOutputType('boolean')
+ expect(savedLogic.values.evaluation?.output_type).toBe('numeric')
+ savedLogic.unmount()
+ })
+
it('setEvaluationName updates evaluation name', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
@@ -741,6 +812,150 @@ return result`,
})
describe('runsSummary', () => {
+ it('applies the selected dates to both runs and statistics, preserving the full backfill view', async () => {
+ const queries: HogQLQuery[] = []
+ useMocks({
+ get: {
+ '/api/projects/:teamId/evaluations/:id/backfills/:backfillId/': () => ({
+ id: 'backfill-1',
+ window_start: '2024-01-01T00:00:00Z',
+ window_end: '2024-02-01T00:00:00Z',
+ }),
+ },
+ post: {
+ '/api/environments/:teamId/query/HogQLQuery/': async ({ request }) => {
+ const { query } = (await request.json()) as { query: HogQLQuery }
+ queries.push(query)
+ return { results: query.query.includes('count() as total') ? [[4, 4, 3]] : [] }
+ },
+ },
+ })
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess', 'loadRunsStatsSuccess'])
+ expect(queries.length).toBeGreaterThan(0)
+ expect(queries.every((query) => query.filters?.dateRange?.date_from === '-7d')).toBe(true)
+
+ for (const dateRange of [
+ { date_from: '-30d', date_to: null },
+ { date_from: '2024-01-01', date_to: '2024-02-01' },
+ { date_from: 'all', date_to: null },
+ ]) {
+ queries.length = 0
+ await expectLogic(logic, () =>
+ logic.actions.setRunsDates(dateRange.date_from, dateRange.date_to)
+ ).toDispatchActions(['loadEvaluationRunsSuccess', 'loadRunsStatsSuccess'])
+ expect(queries).toHaveLength(2)
+ expect(queries.every((query) => query.query.includes('AND {filters}'))).toBe(true)
+ expect(queries.map((query) => query.filters?.dateRange)).toEqual([dateRange, dateRange])
+ expect(router.values.searchParams.date_from).toBe(dateRange.date_from)
+ }
+
+ queries.length = 0
+ await expectLogic(logic, () =>
+ router.actions.push(urls.aiObservabilityEvaluation('eval-123'), {
+ backfill_id: 'backfill-1',
+ date_from: '-7d',
+ })
+ ).toDispatchActions(['loadEvaluationRunsSuccess', 'loadRunsStatsSuccess'])
+ expect(queries).toHaveLength(2)
+ expect(
+ queries.every((query) => query.query.includes("$ai_evaluation_backfill_id = 'backfill-1'"))
+ ).toBe(true)
+ expect(queries.every((query) => !query.filters?.dateRange && !query.query.includes('{filters}'))).toBe(
+ true
+ )
+ })
+
+ it('loads numeric threshold counts after the evaluation configuration arrives', async () => {
+ logic.unmount()
+ const numeric: EvaluationConfig = {
+ ...mockEvaluation,
+ output_type: 'numeric',
+ output_config: { passing_rule: { operator: 'gte', threshold: 7 } },
+ }
+ let resolveEvaluation: (value: EvaluationConfig) => void = () => {}
+ const evaluationResponse = new Promise<EvaluationConfig>((resolve) => {
+ resolveEvaluation = resolve
+ })
+ useMocks({
+ get: { '/api/projects/:teamId/evaluations/:id/': () => evaluationResponse },
+ post: {
+ '/api/environments/:teamId/query/HogQLQuery/': async ({ request }) => {
+ const { query } = (await request.json()) as { query: { query: string } }
+ return {
+ results: query.query.includes('count() as total')
+ ? [[4, 0, 0, 4, 8, query.query.includes('>= 7') ? 4 : 0]]
+ : [],
+ }
+ },
+ },
+ })
+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
+ logic.mount()
+ await expectLogic(logic, () => resolveEvaluation(numeric)).toDispatchActions([
+ 'loadEvaluationSuccess',
+ 'loadRunsStatsSuccess',
+ ])
+ expect(logic.values.runsSummary).toMatchObject({ total: 4, scoreMean: 8, successRate: 100 })
+ })
+
+ it('uses numeric aggregate scores instead of the limited run list', () => {
+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
+ logic.mount()
+ logic.actions.loadEvaluationSuccess({
+ ...mockEvaluation,
+ output_type: 'numeric',
+ output_config: { passing_rule: { operator: 'gte', threshold: 7 } },
+ })
+ const savedTrendUrl = logic.values.trendInsightUrl
+ expect(savedTrendUrl).toContain('Pass%20rate')
+ expect(logic.values.isReportableEvaluation).toBe(true)
+ logic.actions.loadRunsStatsSuccess({
+ total: 1000,
+ applicable: 0,
+ trueCount: 0,
+ scoreCount: 800,
+ scoreMean: 6.5,
+ numericPassCount: 400,
+ })
+ expect(logic.values.runsSummary).toMatchObject({
+ total: 1000,
+ scoreMean: 6.5,
+ successful: 400,
+ successRate: 50,
+ applicabilityRate: 80,
+ })
+ logic.actions.loadEvaluationRunsSuccess([
+ { ...mockRuns[0], result_type: 'numeric', score: 6, result: null },
+ { ...mockRuns[1], result_type: 'numeric', score: 8, result: null },
+ ])
+ logic.actions.setEvaluationRunsFilter('pass', 'all')
+ logic.actions.patchOutputConfig({ passing_rule: { operator: 'lte', threshold: 7 } })
+ expect(logic.values.filteredEvaluationRuns.map((run) => run.score)).toEqual([8])
+ expect(logic.values.runsSummary?.successRate).toBe(50)
+ expect(logic.values.trendInsightUrl).toBe(savedTrendUrl)
+ expect(logic.values.isReportableEvaluation).toBe(true)
+ logic.actions.patchOutputConfig({ passing_rule: null })
+ expect(logic.values.filteredEvaluationRuns.map((run) => run.score)).toEqual([8])
+ expect(logic.values.runsSummary?.successRate).toBe(50)
+ expect(logic.values.trendInsightUrl).toBe(savedTrendUrl)
+ expect(logic.values.isReportableEvaluation).toBe(true)
+ logic.actions.saveEvaluationSuccess(logic.values.evaluation!)
+ expect(logic.values.isReportableEvaluation).toBe(false)
+ expect(logic.values.trendInsightUrl).toContain('Mean%20score')
+ logic.actions.patchOutputConfig({ passing_rule: { operator: 'gte', threshold: 5 } })
+ expect(logic.values.isReportableEvaluation).toBe(false)
+ })
+
+ it.each(['boolean', 'numeric'] as const)('has no success rate for ungraded %s runs', (output_type) => {
+ logic.actions.loadEvaluationSuccess({
+ ...mockEvaluation,
+ output_type,
+ output_config: { passing_rule: { operator: 'gte', threshold: 7 } },
+ })
+ logic.actions.loadRunsStatsSuccess({ total: 4, applicable: 0, trueCount: 0, scoreCount: 0 })
+ expect(logic.values.runsSummary?.successRate).toBeNull()
+ })
+
beforeEach(() => {
logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
logic.mount()
@@ -751,11 +966,13 @@ return result`,
})
it('calculates summary from server-side aggregate counts', async () => {
+ logic.actions.loadEvaluationSuccess(mockEvaluation)
logic.actions.loadRunsStatsSuccess({ total: 3, applicable: 2, trueCount: 1 })
await expectLogic(logic).toMatchValues({
runsSummary: {
total: 3,
+ scoreMean: null,
successful: 1,
failed: 1,
errors: 0,
@@ -1372,93 +1589,147 @@ return result`,
})
describe('Hog sample testing', () => {
- it('sends the trace aggregation window and clears completed results when it changes', async () => {
- let requestBody: Record<string, unknown> | undefined
- useMocks({
- post: {
- '/api/projects/:teamId/evaluations/test_hog/': async ({ request }) => {
- requestBody = (await request.json()) as Record<string, unknown>
- return {
- results: [
- {
- sample_id: 'trace-1',
- sample_type: 'trace',
- event_uuid: null,
- trace_id: 'trace-1',
- input_preview: 'hello',
- output_preview: 'world',
- result: true,
- reasoning: null,
- error: null,
- },
- ],
- }
- },
- },
- })
+ it.each([NaN, Infinity, -Infinity])('leaves scores ungraded for threshold %s', (threshold) => {
+ 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.setEvaluationTarget('trace')
- logic.actions.patchTargetConfig({ window_seconds: 120 })
- logic.actions.testHogOnSample()
+ logic.actions.setOutputType('numeric')
+ logic.actions.patchOutputConfig({ passing_rule: { operator: 'gte', threshold: NaN } })
- await expectLogic(logic)
- .toDispatchActions(['testHogOnSampleSuccess'])
- .toMatchValues({
- hogTestResults: [expect.objectContaining({ sample_id: 'trace-1', sample_type: 'trace' })],
- })
- expect(requestBody).toMatchObject({
- target: 'trace',
- target_config: { window_seconds: 120 },
- })
+ await expectLogic(logic, () => logic.actions.testHogOnSample()).toFinishAllListeners()
- logic.actions.patchTargetConfig({ window_seconds: 240 })
- await expectLogic(logic).toMatchValues({ hogTestResults: null })
+ expect(testSample).not.toHaveBeenCalled()
+ expect(logic.values.hogTestResults).toBeNull()
})
- it('does not restore results from a request whose target changed in flight', async () => {
- let resolveRequest: (value: TestHogResponseApi) => void = () => {}
- const pendingResponse = new Promise<TestHogResponseApi>((resolve) => {
- resolveRequest = resolve
- })
- useMocks({
- post: {
- '/api/projects/:teamId/evaluations/test_hog/': () => pendingResponse,
- },
- })
- logic = llmEvaluationLogic({ evaluationId: 'new' })
- logic.mount()
- await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ it.each(['boolean', 'numeric'] as const)(
+ 'sends %s output config and clears sample results after configuration changes',
+ async (outputType) => {
+ let requestBody: Record<string, unknown> | undefined
+ useMocks({
+ post: {
+ '/api/projects/:teamId/evaluations/test_hog/': async ({ request }) => {
+ requestBody = (await request.json()) as Record<string, unknown>
+ return {
+ results: [
+ {
+ sample_id: 'trace-1',
+ sample_type: 'trace',
+ event_uuid: null,
+ trace_id: 'trace-1',
+ input_preview: 'hello',
+ output_preview: 'world',
+ result: true,
+ reasoning: null,
+ error: null,
+ },
+ ],
+ }
+ },
+ },
+ })
+ logic = llmEvaluationLogic({ evaluationId: 'new' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
- logic.actions.setEvaluationType('hog')
- logic.actions.testHogOnSample()
- await expectLogic(logic).toMatchValues({ hogTestResultsLoading: true })
+ logic.actions.setEvaluationType('hog')
+ logic.actions.setOutputType(outputType)
+ if (outputType === 'numeric') {
+ logic.actions.patchOutputConfig({
+ min: 0,
+ max: 10,
+ passing_rule: { operator: 'gte', threshold: 7 },
+ })
+ }
+ logic.actions.setEvaluationTarget('trace')
+ logic.actions.patchTargetConfig({ window_seconds: 120 })
+ logic.actions.testHogOnSample()
- logic.actions.setEvaluationTarget('trace')
- await expectLogic(logic).toMatchValues({ hogTestResults: null })
- resolveRequest({
- results: [
- {
- sample_id: 'generation-1',
- sample_type: 'generation',
- event_uuid: 'generation-1',
- trace_id: 'trace-1',
- input_preview: 'hello',
- output_preview: 'world',
- result: true,
- reasoning: '',
- error: null,
+ await expectLogic(logic)
+ .toDispatchActions(['testHogOnSampleSuccess'])
+ .toMatchValues({
+ hogTestResults: [expect.objectContaining({ sample_id: 'trace-1', sample_type: 'trace' })],
+ })
+ expect(requestBody).toMatchObject({
+ target: 'trace',
+ output_type: outputType,
+ output_config:
+ outputType === 'numeric'
+ ? { min: 0, max: 10, allows_na: false, passing_rule: { operator: 'gte', threshold: 7 } }
+ : { allows_na: false },
+ target_config: { window_seconds: 120 },
+ })
+ expect(requestBody).not.toHaveProperty('allows_na')
+
+ if (outputType === 'numeric') {
+ logic.actions.patchOutputConfig({ passing_rule: { operator: 'gte', threshold: 5 } })
+ expect(logic.values.hogTestResults).not.toBeNull()
+ logic.actions.patchOutputConfig({ max: 20 })
+ } else {
+ logic.actions.patchTargetConfig({ window_seconds: 240 })
+ }
+ await expectLogic(logic).toMatchValues({ hogTestResults: null })
+ }
+ )
+
+ it.each(['target', 'passing_rule'])(
+ 'handles a %s change while a preview is in flight',
+ async (changedField) => {
+ let resolveRequest: (value: TestHogResponseApi) => void = () => {}
+ const pendingResponse = new Promise<TestHogResponseApi>((resolve) => {
+ resolveRequest = resolve
+ })
+ useMocks({
+ post: {
+ '/api/projects/:teamId/evaluations/test_hog/': () => pendingResponse,
},
- ],
- })
+ })
+ logic = llmEvaluationLogic({ evaluationId: 'new' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
- await expectLogic(logic)
- .toDispatchActions(['testHogOnSampleSuccess'])
- .toMatchValues({ hogTestResults: null })
- })
+ logic.actions.setEvaluationType('hog')
+ logic.actions.setOutputType('numeric')
+ logic.actions.testHogOnSample()
+ await expectLogic(logic).toMatchValues({ hogTestResultsLoading: true })
+
+ if (changedField === 'target') {
+ logic.actions.setEvaluationTarget('trace')
+ } else {
+ logic.actions.patchOutputConfig({ passing_rule: { operator: 'gte', threshold: 5 } })
+ }
+ await expectLogic(logic).toMatchValues({ hogTestResults: null })
+ resolveRequest({
+ results: [
+ {
+ sample_id: 'generation-1',
+ sample_type: 'generation',
+ event_uuid: 'generation-1',
+ trace_id: 'trace-1',
+ input_preview: 'hello',
+ output_preview: 'world',
+ result: null,
+ score: 7,
+ reasoning: '',
+ error: null,
+ },
+ ],
+ })
+
+ await expectLogic(logic)
+ .toDispatchActions(['testHogOnSampleSuccess'])
+ .toMatchValues({
+ hogTestResults: changedField === 'target' ? null : [expect.objectContaining({ score: 7 })],
+ })
+ }
+ )
})
describe('saveEvaluation list refresh', () => {
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index ab0a80500454..bc11da83705e 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -11,8 +11,9 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
+import { DateRange, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
import { MaxContextInput, createMaxContextHelpers } from '~/scenes/max/maxTypes'
-import { ActivityScope, Breadcrumb } from '~/types'
+import { ActivityScope, Breadcrumb, ChartDisplayType, HogQLMathType } from '~/types'
import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'
import {
@@ -23,16 +24,27 @@ import {
evaluationsTestHogCreate,
} from '../generated/api'
import type { EvaluationBackfillApi, TestHogRequestApi, TestHogResultItemApi } from '../generated/api.schemas'
+import type { EvaluationApiOutputConfig } from '../generated/api.schemas'
import { parsePlaygroundProviderKeyId } from '../ModelPicker'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmProviderKeysLogic'
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { EvaluationRunsStats, queryEvaluationRuns, queryEvaluationRunsStats } from '../utils'
import { evaluationErrorMessage } from './apiErrors'
-import { evaluationIsDetector } from './constants'
+import {
+ EVALUATION_NUMERIC_GRADED_HOGQL,
+ EVALUATION_NUMERIC_MEAN_HOGQL,
+ numericEvaluationPassedHogQL,
+ evaluationPassedHogQL,
+ evaluationPassRateHogQL,
+ evaluationIsDetector,
+ numericOutputConfigError,
+ numericScorePasses,
+} from './constants'
import {
evaluationCanResolveModel,
evaluationSupportsReports,
+ evaluationSupportsRunOutcomes,
isBooleanEvaluationOutput,
isLLMJudgeEvaluation,
} from './evaluationCapabilities'
@@ -44,6 +56,7 @@ import { EvaluationTemplateKey, defaultEvaluationTemplates } from './templates'
import type {
EvaluationConditionSet,
EvaluationConfig,
+ EvaluationOutputConfig,
EvaluationRun,
EvaluationRunsFilter,
EvaluationSettleStrategy,
@@ -145,8 +158,8 @@ function toLLMJudgeEvaluation(evaluation: EvaluationConfig): LLMJudgeEvaluation
...evaluation,
evaluation_type: 'llm_judge',
evaluation_config: { prompt: '' },
- output_type: 'boolean',
- output_config: { allows_na: false },
+ output_type: evaluation.output_type === 'numeric' ? 'numeric' : 'boolean',
+ output_config: evaluation.output_type === 'numeric' ? evaluation.output_config : { allows_na: false },
}
}
@@ -154,10 +167,13 @@ function toHogEvaluation(evaluation: EvaluationConfig): HogEvaluation {
return {
...evaluation,
evaluation_type: 'hog',
- evaluation_config: { source: DEFAULT_HOG_SOURCE },
- output_type: 'boolean',
+ evaluation_config: { source: evaluation.output_type === 'numeric' ? 'return 0;' : DEFAULT_HOG_SOURCE },
+ output_type: evaluation.output_type === 'numeric' ? 'numeric' : 'boolean',
model_configuration: null,
- output_config: { ...evaluation.output_config, allows_na: false },
+ output_config:
+ evaluation.output_type === 'numeric'
+ ? evaluation.output_config
+ : { ...evaluation.output_config, allows_na: false },
}
}
@@ -188,6 +204,22 @@ 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 (filter === 'na') {
+ return gradedRuns.filter((run) => run.applicable === false)
+ }
+ const rule = evaluation.output_config.passing_rule
+ if (!rule) {
+ return []
+ }
+ return gradedRuns.filter((run) => {
+ if (run.applicable === false || run.score == null) {
+ return false
+ }
+ const passed = numericScorePasses(run.score, rule)
+ return filter === 'pass' ? passed === true : filter === 'fail' ? passed === false : false
+ })
+ }
const passingResult = !(evaluation && evaluationIsDetector(evaluation))
if (filter === 'pass') {
return gradedRuns.filter((r) => r.result === passingResult)
@@ -208,11 +240,17 @@ function isTestableHogEvaluation(evaluation: EvaluationConfig | null): evaluatio
return evaluation?.evaluation_type === 'hog'
}
-function buildHogTestRequest(evaluation: TestableHogEvaluation): TestHogRequestApi {
+function buildHogTestRequest(evaluation: TestableHogEvaluation, forComparison = false): TestHogRequestApi {
+ const outputConfig = { ...evaluation.output_config }
+ // Rule edits re-grade the same sample, so they do not invalidate an in-flight preview.
+ if (forComparison) {
+ delete outputConfig.passing_rule
+ }
const request: TestHogRequestApi = {
source: evaluation.evaluation_config.source,
sample_count: 5,
- allows_na: evaluation.output_config?.allows_na ?? false,
+ output_type: evaluation.output_type,
+ output_config: outputConfig,
conditions: evaluation.conditions
.filter((condition) => condition.properties && condition.properties.length > 0)
.map((condition) => ({ properties: condition.properties })),
@@ -273,25 +311,30 @@ export interface llmEvaluationLogicValues {
hogTestResultsLoading: boolean
isForceRefresh: boolean
isNewEvaluation: boolean
+ isReportableEvaluation: boolean
maxContext: MaxContextInput[]
modelSelectionRequired: boolean
originalEvaluation: EvaluationConfig | null
+ outputConfigDrafts: Partial<Record<'boolean' | 'numeric', EvaluationOutputConfig>>
runsBackfill: EvaluationBackfillApi | null
runsBackfillId: string | null
runsBackfillLoading: boolean
+ runsDateRange: DateRange
runsStats: EvaluationRunsStats | null
runsStatsLoading: boolean
runsSummary: {
applicabilityRate: number
errors: number
failed: number
+ scoreMean: number | null
successful: number
- successRate: number
+ successRate: number | null
total: number
} | null
selectedModel: string
selectedPickerProviderKeyId: string | null
sidePanelContext: SidePanelSceneContext | null
+ trendInsightUrl: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -310,7 +353,7 @@ export interface llmEvaluationLogicActions {
loadEvaluation: () => {
value: true
}
- loadEvaluationRuns: () => any
+ loadEvaluationRuns: (_?: void) => void
loadEvaluationRunsFailure: (
error: string,
errorObject?: any
@@ -320,10 +363,10 @@ export interface llmEvaluationLogicActions {
}
loadEvaluationRunsSuccess: (
evaluationRuns: EvaluationRun[],
- payload?: any
+ payload?: void
) => {
evaluationRuns: EvaluationRun[]
- payload?: any
+ payload?: void
}
loadEvaluationSuccess: (evaluation: EvaluationConfig | null) => {
evaluation: EvaluationConfig | null
@@ -344,7 +387,7 @@ export interface llmEvaluationLogicActions {
runsBackfill: EvaluationBackfillApi | null
payload?: any
}
- loadRunsStats: () => any
+ loadRunsStats: (_?: void) => void
loadRunsStatsFailure: (
error: string,
errorObject?: any
@@ -354,10 +397,13 @@ export interface llmEvaluationLogicActions {
}
loadRunsStatsSuccess: (
runsStats: EvaluationRunsStats | null,
- payload?: any
+ payload?: void
) => {
runsStats: EvaluationRunsStats | null
- payload?: any
+ payload?: void
+ }
+ patchOutputConfig: (patch: EvaluationOutputConfig) => {
+ patch: EvaluationApiOutputConfig
}
patchTargetConfig: (patch: Partial<Omit<EvaluationTargetConfig, 'strategy'>>) => {
patch: Partial<Omit<EvaluationTargetConfig, 'strategy'>>
@@ -424,9 +470,21 @@ export interface llmEvaluationLogicActions {
setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => {
modelConfiguration: ModelConfiguration | null
}
+ setOutputType: (outputType: 'boolean' | 'numeric') => {
+ outputConfig: EvaluationApiOutputConfig | undefined
+ outputType: 'boolean' | 'numeric'
+ previousEvaluation: EvaluationConfig | null
+ }
setRunsBackfillId: (backfillId: string | null) => {
backfillId: string | null
}
+ setRunsDates: (
+ dateFrom: string | null,
+ dateTo: string | null
+ ) => {
+ dateFrom: string | null
+ dateTo: string | null
+ }
setSettleStrategy: (strategy: EvaluationSettleStrategy) => {
strategy: EvaluationSettleStrategy
}
@@ -457,6 +515,12 @@ export interface llmEvaluationLogicActions {
export interface llmEvaluationLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ isReportableEvaluation: (
+ isNewEvaluation: boolean,
+ evaluation: EvaluationConfig | null,
+ originalEvaluation: EvaluationConfig | null
+ ) => boolean
+ trendInsightUrl: (originalEvaluation: EvaluationConfig | null) => string | null
isNewEvaluation: (evaluationId: string) => boolean
evaluationBackTarget: (isNewEvaluation: boolean, searchParams: Record<string, any>) => EvaluationBackTarget
modelSelectionRequired: (
@@ -476,19 +540,20 @@ export interface llmEvaluationLogicMeta {
) => LLMProviderKey | null
runsSummary: (
runsStats: EvaluationRunsStats | null,
- evaluation: EvaluationConfig | null
+ originalEvaluation: EvaluationConfig | null
) => {
applicabilityRate: number
errors: number
failed: number
+ scoreMean: number | null
successful: number
- successRate: number
+ successRate: number | null
total: number
} | null
filteredEvaluationRuns: (
evaluationRuns: EvaluationRun[],
evaluationRunsFilter: EvaluationRunsFilter,
- evaluation: EvaluationConfig | null
+ originalEvaluation: EvaluationConfig | null
) => EvaluationRun[]
breadcrumbs: (
evaluation: EvaluationConfig | null,
@@ -531,12 +596,18 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
actions: [llmProviderKeysLogic, ['loadProviderKeys', 'loadEvaluationConfigSuccess']],
})),
- actions({
+ actions(({ values }) => ({
// Evaluation configuration actions
setEvaluationName: (name: string) => ({ name }),
setEvaluationDescription: (description: string) => ({ description }),
setEvaluationPrompt: (prompt: string) => ({ prompt }),
setEvaluationEnabled: (enabled: boolean) => ({ enabled }),
+ setOutputType: (outputType: 'boolean' | 'numeric') => ({
+ outputType,
+ previousEvaluation: values.evaluation,
+ outputConfig: values.outputConfigDrafts[outputType],
+ }),
+ patchOutputConfig: (patch: EvaluationOutputConfig) => ({ patch }),
setAllowsNA: (allowsNA: boolean) => ({ allowsNA }),
setTrueIsFailure: (trueIsFailure: boolean) => ({ trueIsFailure }),
setTriggerConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),
@@ -552,6 +623,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
// Tab navigation
setActiveTab: (tab: string) => ({ tab }),
setRunsBackfillId: (backfillId: string | null) => ({ backfillId }),
+ setRunsDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
// Evaluation management actions
saveEvaluation: true,
@@ -579,7 +651,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
filter,
previousFilter,
}),
- }),
+ })),
loaders(({ props, values, actions }) => ({
hogTestResults: [
@@ -594,9 +666,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!isTestableHogEvaluation(evaluation)) {
return null
}
+ if (evaluation.output_type === 'numeric' && numericOutputConfigError(evaluation.output_config)) {
+ return null
+ }
const request = buildHogTestRequest(evaluation)
- const requestFingerprint = JSON.stringify(request)
+ const requestFingerprint = JSON.stringify(buildHogTestRequest(evaluation, true))
let results: TestHogResultItemApi[]
try {
const response = await evaluationsTestHogCreate(teamId.toString(), request)
@@ -619,6 +694,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
input_preview: '',
output_preview: '',
result: null,
+ score: null,
reasoning: '',
error: typeof message === 'string' ? message : JSON.stringify(message),
},
@@ -629,7 +705,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
const currentEvaluation = values.evaluation
if (
!isTestableHogEvaluation(currentEvaluation) ||
- JSON.stringify(buildHogTestRequest(currentEvaluation)) !== requestFingerprint
+ JSON.stringify(buildHogTestRequest(currentEvaluation, true)) !== requestFingerprint
) {
return null
}
@@ -640,16 +716,19 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
evaluationRuns: [
[] as EvaluationRun[],
{
- loadEvaluationRuns: async () => {
+ loadEvaluationRuns: async (_?: void, breakpoint?: () => void) => {
if (!props.evaluationId || props.evaluationId === 'new') {
return []
}
- return await queryEvaluationRuns({
+ const runs = await queryEvaluationRuns({
evaluationId: props.evaluationId,
backfillId: values.runsBackfillId ?? undefined,
+ dateRange: values.runsBackfillId ? undefined : values.runsDateRange,
forceRefresh: values.isForceRefresh,
})
+ breakpoint?.()
+ return runs
},
},
],
@@ -668,22 +747,35 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
runsStats: [
null as EvaluationRunsStats | null,
{
- loadRunsStats: async () => {
- if (!props.evaluationId || props.evaluationId === 'new') {
+ loadRunsStats: async (_?: void, breakpoint?: () => void): Promise<EvaluationRunsStats | null> => {
+ if (!props.evaluationId || props.evaluationId === 'new' || !values.evaluation) {
return null
}
-
- return await queryEvaluationRunsStats({
+ const stats = await queryEvaluationRunsStats({
+ evaluation: values.originalEvaluation ?? values.evaluation,
evaluationId: props.evaluationId,
backfillId: values.runsBackfillId ?? undefined,
+ dateRange: values.runsBackfillId ? undefined : values.runsDateRange,
forceRefresh: values.isForceRefresh,
})
+ breakpoint?.()
+ return stats
},
},
],
})),
- reducers({
+ reducers(({ props }) => ({
+ outputConfigDrafts: [
+ {} as Partial<Record<'boolean' | 'numeric', EvaluationOutputConfig>>,
+ {
+ loadEvaluationSuccess: () => ({}),
+ setOutputType: (state, { previousEvaluation }) =>
+ props.evaluationId === 'new' && previousEvaluation && previousEvaluation.output_type !== 'sentiment'
+ ? { ...state, [previousEvaluation.output_type]: previousEvaluation.output_config }
+ : state,
+ },
+ ],
originalEvaluation: [
null as EvaluationConfig | null,
{
@@ -701,8 +793,42 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
? { ...state, evaluation_config: { ...state.evaluation_config, prompt } }
: state,
setEvaluationEnabled: (state, { enabled }) => (state ? { ...state, enabled } : null),
+ setOutputType: (state, { outputType, outputConfig }) => {
+ if (
+ !state ||
+ props.evaluationId !== 'new' ||
+ state.evaluation_type === 'sentiment' ||
+ state.output_type === outputType
+ ) {
+ return state
+ }
+ const output_config = outputConfig ?? { allows_na: state.output_config.allows_na ?? false }
+ if (state.evaluation_type === 'hog') {
+ const source = state.evaluation_config.source
+ return {
+ ...state,
+ output_type: outputType,
+ output_config,
+ 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,
+ },
+ }
+ }
+ return { ...state, output_type: outputType, output_config }
+ },
+ patchOutputConfig: (state, { patch }) =>
+ state?.output_type === 'numeric'
+ ? { ...state, output_config: { ...state.output_config, ...patch } }
+ : state,
setAllowsNA: (state, { allowsNA }) =>
- state && isBooleanEvaluationOutput(state.output_type)
+ state && state.output_type !== 'sentiment'
? { ...state, output_config: { ...state.output_config, allows_na: allowsNA } }
: state,
setTrueIsFailure: (state, { trueIsFailure }) =>
@@ -723,6 +849,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return toHogEvaluation(state)
}
if (evaluationType === 'sentiment') {
+ if (props.evaluationId !== 'new' && state.output_type === 'numeric') {
+ return state
+ }
return toSentimentEvaluation(state)
}
return toLLMJudgeEvaluation(state)
@@ -766,6 +895,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
},
],
hogTestResults: {
+ setOutputType: () => null,
+ patchOutputConfig: (state, { patch }) =>
+ Object.keys(patch).every((key) => key === 'passing_rule') ? state : null,
clearHogTestResults: () => null,
setAllowsNA: () => null,
setEvaluationTarget: () => null,
@@ -839,6 +971,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setEvaluationDescription: () => true,
setEvaluationPrompt: () => true,
setEvaluationEnabled: () => true,
+ setOutputType: () => true,
+ patchOutputConfig: () => true,
setAllowsNA: () => true,
setTrueIsFailure: () => true,
setTriggerConditions: () => true,
@@ -867,6 +1001,19 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setRunsBackfillId: (_, { backfillId }) => backfillId,
},
],
+ runsDateRange: [
+ { date_from: '-7d', date_to: null } as DateRange,
+ {
+ setRunsDates: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom ?? '-7d', date_to: dateTo }),
+ },
+ ],
+ runsStats: [
+ null as EvaluationRunsStats | null,
+ {
+ setRunsDates: () => null,
+ setRunsBackfillId: () => null,
+ },
+ ],
activeTab: [
'configuration' as string,
{
@@ -876,9 +1023,25 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
requestedTab ?? (evaluation?.id ? 'runs' : 'configuration'),
},
],
- }),
+ })),
listeners(({ actions, values, props }) => ({
+ setOutputType: ({ outputType, previousEvaluation }) => {
+ if (
+ props.evaluationId === 'new' &&
+ previousEvaluation?.evaluation_type === 'hog' &&
+ previousEvaluation.output_type !== outputType &&
+ isTestableHogEvaluation(values.evaluation) &&
+ 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.`
+ )
+ }
+ },
+ loadEvaluationSuccess: () => {
+ actions.loadRunsStats()
+ },
loadEvaluationConfigSuccess: () => {
// The new-eval draft's enabled default is read before the team's evaluation config has
// loaded — correct it once we know the draft can't actually resolve a model.
@@ -974,6 +1137,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
loadEvaluationRuns: () => {
actions.loadRunsStats()
},
+ setRunsDates: () => {
+ actions.loadEvaluationRuns()
+ },
setEvaluationRunsFilter: ({ filter, previousFilter }) => {
// pinned: analytics event name - renaming it breaks existing dashboards
@@ -1157,13 +1323,89 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
},
setEvaluationType: () => {
- if (!evaluationSupportsReports(values.evaluation) && values.activeTab === 'reports') {
+ if (!values.isReportableEvaluation && values.activeTab === 'reports') {
actions.setActiveTab('configuration')
}
},
})),
selectors({
+ isReportableEvaluation: [
+ (s) => [s.isNewEvaluation, s.evaluation, s.originalEvaluation],
+ (
+ isNewEvaluation: boolean,
+ evaluation: EvaluationConfig | null,
+ originalEvaluation: EvaluationConfig | null
+ ): boolean => evaluationSupportsReports(isNewEvaluation ? evaluation : originalEvaluation),
+ ],
+ trendInsightUrl: [
+ (s) => [s.originalEvaluation],
+ (evaluation: EvaluationConfig | null): string | null =>
+ evaluation &&
+ (evaluationSupportsRunOutcomes(evaluation) || evaluation.output_type === 'numeric') &&
+ evaluation.id
+ ? urls.insightNew({
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ {
+ kind: NodeKind.EventsNode,
+ event: '$ai_evaluation',
+ 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)),
+ properties: [
+ {
+ key: '$ai_evaluation_id',
+ value: evaluation.id,
+ operator: 'exact',
+ type: 'event',
+ },
+ ],
+ },
+ ...(evaluation.output_type !== 'numeric' && evaluation.output_config.allows_na
+ ? [
+ {
+ kind: NodeKind.EventsNode as const,
+ event: '$ai_evaluation',
+ custom_name: `${evaluation.name} — N/A rate`,
+ math: HogQLMathType.HogQL as const,
+ math_hogql: `if(count() > 0, countIf(properties.$ai_evaluation_result IS NULL) / count() * 100, 0)`,
+ properties: [
+ {
+ key: '$ai_evaluation_id',
+ value: evaluation.id,
+ operator: 'exact' as const,
+ type: 'event' as const,
+ },
+ ],
+ },
+ ]
+ : []),
+ ],
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ },
+ dateRange: {
+ date_from: '-7d',
+ },
+ interval: 'day',
+ },
+ } as InsightVizNode,
+ })
+ : null,
+ ],
+
isNewEvaluation: [(_, props) => [props.evaluationId], (evaluationId: string) => evaluationId === 'new'],
evaluationBackTarget: [
@@ -1195,6 +1437,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!evaluation) {
return false
}
+ if (evaluation.output_type === 'numeric' && numericOutputConfigError(evaluation.output_config)) {
+ return false
+ }
const hasValidName = (evaluation.name?.length ?? 0) > 0
const hasValidConditions =
(evaluation.conditions?.length ?? 0) > 0 &&
@@ -1245,30 +1490,40 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
],
runsSummary: [
- (s) => [s.runsStats, s.evaluation],
+ (s) => [s.runsStats, s.originalEvaluation],
(stats: EvaluationRunsStats | null, evaluation: EvaluationConfig | null) => {
if (!stats || stats.total === 0) {
return null
}
- const { total, applicable, trueCount } = stats
- const passed = evaluation && evaluationIsDetector(evaluation) ? applicable - trueCount : trueCount
+ const { total, trueCount } = stats
+ const applicable = evaluation?.output_type === 'numeric' ? (stats.scoreCount ?? 0) : stats.applicable
+ const passed =
+ evaluation?.output_type === 'numeric'
+ ? (stats.numericPassCount ?? 0)
+ : evaluation && evaluationIsDetector(evaluation)
+ ? applicable - trueCount
+ : trueCount
// Applicable runs excludes N/A results
const failed = applicable - passed
return {
total,
+ scoreMean: stats.scoreMean ?? null,
successful: passed,
failed,
errors: 0,
- successRate: applicable > 0 ? Math.round((passed / applicable) * 100) : 0,
+ successRate:
+ evaluationSupportsRunOutcomes(evaluation) && applicable > 0
+ ? Math.round((passed / applicable) * 100)
+ : null,
applicabilityRate: total > 0 ? Math.round((applicable / total) * 100) : 0,
}
},
],
filteredEvaluationRuns: [
- (s) => [s.evaluationRuns, s.evaluationRunsFilter, s.evaluation],
+ (s) => [s.evaluationRuns, s.evaluationRunsFilter, s.originalEvaluation],
(
runs: EvaluationRun[],
filter: EvaluationRunsFilter,
@@ -1345,14 +1600,21 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
const requestedBackfillId = searchParams.backfill_id ?? null
+ const dateFrom = searchParams.date_from ?? '-7d'
+ const dateTo = searchParams.date_to ?? null
+ const datesChanged = dateFrom !== values.runsDateRange.date_from || dateTo !== values.runsDateRange.date_to
if (requestedBackfillId !== values.runsBackfillId) {
actions.setRunsBackfillId(requestedBackfillId)
- actions.loadEvaluationRuns()
- actions.loadRunsStats()
+ if (!datesChanged) {
+ actions.loadEvaluationRuns()
+ }
if (requestedBackfillId) {
actions.loadRunsBackfill()
}
}
+ if (datesChanged) {
+ actions.setRunsDates(dateFrom, dateTo)
+ }
// Only reload when navigating to a different evaluation, not on search param changes (e.g., pagination)
const newEvaluationId = id && id !== 'new' ? id : 'new'
@@ -1366,6 +1628,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
})),
actionToUrl(({ props }) => ({
+ setRunsDates: ({ dateFrom, dateTo }) => [
+ router.values.location.pathname,
+ { ...router.values.searchParams, date_from: dateFrom ?? '-7d', date_to: dateTo ?? undefined },
+ router.values.hashParams,
+ { replace: true },
+ ],
setActiveTab: ({ tab }) => {
const defaultTab = props.evaluationId === 'new' ? 'configuration' : 'runs'
const evaluationTab = tab === defaultTab ? undefined : tab
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index 35aa972762b8..ddc944c0883e 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -1,6 +1,7 @@
import { AccessControlLevel, AnyPropertyFilter, UserBasicType } from '~/types'
import type {
+ EvaluationApiOutputConfig,
EvaluationReportCitationApi,
EvaluationReportMetricsApi,
EvaluationReportRunApi,
@@ -12,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'
+export type EvaluationOutputType = 'boolean' | 'sentiment' | 'numeric'
export type EvaluationStatus = 'active' | 'paused' | 'error'
export type EvaluationStatusReason =
| 'provider_key_required'
@@ -32,12 +33,7 @@ export interface ModelConfiguration {
provider_key_name?: string | null
}
-export interface EvaluationOutputConfig {
- allows_na?: boolean
- /** Whether a true result means the evaluation found a problem. Absent or false means a true
- * result is a pass, which is what every evaluation stored before this field intends. */
- true_is_failure?: boolean
-}
+export type EvaluationOutputConfig = EvaluationApiOutputConfig
/** Settle config for aggregate targets (trace, session). A missing `strategy` resolves per target:
* 'fixed_window' for a trace, because rows saved before strategies existed mean exactly that, and
@@ -94,13 +90,13 @@ export interface BaseEvaluationConfig {
export interface LLMJudgeEvaluation extends BaseEvaluationConfig {
evaluation_type: 'llm_judge'
- output_type: 'boolean'
+ output_type: 'boolean' | 'numeric'
evaluation_config: LLMJudgeEvaluationConfig
}
export interface HogEvaluation extends BaseEvaluationConfig {
evaluation_type: 'hog'
- output_type: 'boolean'
+ output_type: 'boolean' | 'numeric'
evaluation_config: HogEvaluationConfig
}
@@ -138,6 +134,9 @@ export interface EvaluationRun {
result: boolean | null
sentiment_label?: string | null
sentiment_score?: number | null
+ score?: number | null
+ score_min?: number | null
+ score_max?: number | null
applicable?: boolean
// A skipped run completed without grading anything. Its `result` is still false when the
// evaluation disallows N/A, so it has to be read alongside this rather than on its own.
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index a3c87ba3d9e4..1456850cd9d6 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -815,12 +815,14 @@ export const EvaluationTypeEnumApi = {
/**
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `sentiment` - Sentiment
*/
export type OutputTypeEnumApi = (typeof OutputTypeEnumApi)[keyof typeof OutputTypeEnumApi]
export const OutputTypeEnumApi = {
Boolean: 'boolean',
+ Numeric: 'numeric',
Sentiment: 'sentiment',
} as const
@@ -912,7 +914,7 @@ export type EvaluationApiEvaluationConfig =
}
| {
/**
- * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
+ * 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.
* @minLength 1
*/
source: string
@@ -923,13 +925,46 @@ export type EvaluationApiEvaluationConfig =
}
/**
- * 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.
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+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
+
+/**
+ * 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': {}.
*/
export type EvaluationApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
- /** 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 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.
+ * @nullable
+ */
+ min?: number | null
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: EvaluationApiOutputConfigPassingRule
}
/**
@@ -997,12 +1032,13 @@ 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. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `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. */
+ /** 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?: 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[]
@@ -1152,7 +1188,7 @@ export type PatchedEvaluationApiEvaluationConfig =
}
| {
/**
- * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
+ * 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.
* @minLength 1
*/
source: string
@@ -1163,13 +1199,46 @@ export type PatchedEvaluationApiEvaluationConfig =
}
/**
- * 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.
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+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
+
+/**
+ * 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': {}.
*/
export type PatchedEvaluationApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
- /** 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 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.
+ * @nullable
+ */
+ min?: number | null
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: PatchedEvaluationApiOutputConfigPassingRule
}
/**
@@ -1237,12 +1306,13 @@ 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. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `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. */
+ /** 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?: 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[]
@@ -1269,8 +1339,63 @@ export interface PatchedEvaluationApi {
readonly user_access_level?: string | null
}
+/**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+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
+
+/**
+ * Output settings used to validate the preview, including numeric bounds 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. */
+ true_is_failure?: boolean
+ /**
+ * Inclusive minimum numeric score. Omit for no lower bound.
+ * @nullable
+ */
+ min?: number | null
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: TestHogRequestApiOutputConfigPassingRule
+}
+
export type TestHogRequestApiConditionsItem = { [key: string]: unknown }
+/**
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
+ */
+export type HogEvaluationOutputTypeEnumApi =
+ (typeof HogEvaluationOutputTypeEnumApi)[keyof typeof HogEvaluationOutputTypeEnumApi]
+
+export const HogEvaluationOutputTypeEnumApi = {
+ Boolean: 'boolean',
+ Numeric: 'numeric',
+} as const
+
export interface TestHogTargetConfigApi {
/**
* Aggregation window for trace samples, in seconds.
@@ -1287,8 +1412,15 @@ export interface TestHogTargetConfigApi {
}
export interface TestHogRequestApi {
+ /** Expected output: boolean or numeric. Sentiment is not supported by Hog.
+ *
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric */
+ output_type?: HogEvaluationOutputTypeEnumApi
+ /** Output settings used to validate the preview, including numeric bounds and allows_na. */
+ output_config?: TestHogRequestApiOutputConfig
/**
- * Hog source code to test. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
+ * 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.
* @minLength 1
*/
source: string
@@ -1313,6 +1445,11 @@ export interface TestHogRequestApi {
}
export interface TestHogResultItemApi {
+ /**
+ * Raw numeric score, or null when no numeric score was produced.
+ * @nullable
+ */
+ score?: number | null
/** Stable identifier for the sampled generation, trace, or session. */
sample_id: string
/** Type of sampled unit: generation, trace, or session.
@@ -1872,6 +2009,49 @@ export const GenerationStatusEnumApi = {
MetricsUnavailable: 'metrics_unavailable',
} as const
+/**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+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
+
+/**
+ * Numeric score 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. */
+ true_is_failure?: boolean
+ /**
+ * Inclusive minimum numeric score. Omit for no lower bound.
+ * @nullable
+ */
+ min?: number | null
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: EvaluationReportMetricsApiOutputConfigPassingRule
+}
+
/**
* Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative.
*/
@@ -1895,9 +2075,12 @@ 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_config?: EvaluationReportMetricsApiOutputConfig
/** Evaluation result type. Stored metrics without this field represent boolean evaluations.
*
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnumApi
/** Number of evaluation results in the report period. */
@@ -1925,10 +2108,13 @@ export interface EvaluationReportMetricsApi {
* @nullable
*/
previous_result_rates?: EvaluationReportMetricsApiPreviousResultRates
- /** Boolean pass percentage, excluding results marked not applicable. */
- pass_rate?: number
/**
- * Boolean pass percentage for the previous period, or null when unavailable.
+ * Boolean or numeric pass percentage, excluding N/A results. Null when no numeric scores were produced.
+ * @nullable
+ */
+ pass_rate?: number | null
+ /**
+ * Boolean or numeric pass percentage for 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 4e21ad828c8c..cc1127ecff64 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -259,6 +259,8 @@ export const EvaluationRunsCreateBody = /* @__PURE__ */ zod.object({
export const evaluationsCreateBodyNameMax = 400
export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
+export const evaluationsCreateBodyOutputConfigStepExclusiveMin = 0
+
export const evaluationsCreateBodyConditionsItemIdMax = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -307,7 +309,7 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
}),
zod.object({
@@ -324,10 +326,10 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
.describe(
- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ "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_config: zod
.object({
@@ -339,12 +341,32 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe(
- '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 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsCreateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores 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."
+ "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': {}."
),
conditions: zod
.array(
@@ -563,6 +585,8 @@ export const EvaluationsBackfillsEstimateCreateBody = /* @__PURE__ */ zod.object
export const evaluationsUpdateBodyNameMax = 400
export const evaluationsUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
+export const evaluationsUpdateBodyOutputConfigStepExclusiveMin = 0
+
export const evaluationsUpdateBodyConditionsItemIdMax = 100
export const evaluationsUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -611,7 +635,7 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
}),
zod.object({
@@ -628,10 +652,10 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
.describe(
- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ "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_config: zod
.object({
@@ -643,12 +667,32 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe(
- '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 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsUpdateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores 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."
+ "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': {}."
),
conditions: zod
.array(
@@ -769,6 +813,8 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
export const evaluationsPartialUpdateBodyNameMax = 400
export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
+export const evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin = 0
+
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -818,7 +864,7 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
}),
zod.object({
@@ -835,11 +881,11 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
.optional()
.describe(
- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ "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_config: zod
.object({
@@ -851,12 +897,32 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe(
- '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 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores 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."
+ "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': {}."
),
conditions: zod
.array(
@@ -977,6 +1043,8 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
/**
* Test Hog evaluation code against sample events without saving.
*/
+export const evaluationsTestHogCreateBodyOutputTypeDefault = `boolean`
+export const evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin = 0
export const evaluationsTestHogCreateBodySampleCountDefault = 5
export const evaluationsTestHogCreateBodySampleCountMax = 10
@@ -992,11 +1060,51 @@ export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMin =
export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax = 86400
export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
+ output_type: zod
+ .enum(['boolean', 'numeric'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric')
+ .default(evaluationsTestHogCreateBodyOutputTypeDefault)
+ .describe(
+ 'Expected output: boolean or numeric. Sentiment is not supported by Hog.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric'
+ ),
+ output_config: zod
+ .object({
+ allows_na: zod
+ .boolean()
+ .optional()
+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: 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.'
+ ),
+ 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ ),
+ })
+ .optional()
+ .describe('Output settings used to validate the preview, including numeric bounds and allows_na.'),
source: zod
.string()
.min(1)
.describe(
- 'Hog source code to test. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
sample_count: zod
.number()
diff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
index 4fb793011104..4b3cef481781 100644
--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
@@ -964,15 +964,23 @@ function SystemMessageDisplay({ promptId }: { promptId: string }): JSX.Element {
</div>
<AnimatedCollapsible collapsed={collapsed}>
- <LemonTextArea
- className="text-sm w-full"
- placeholder="System instructions for the AI assistant..."
- value={prompt.systemPrompt}
- onChange={(value) => setSystemPrompt(value, promptId)}
- minRows={2}
- maxRows={undefined}
- onPressCmdEnter={() => submitPrompt()}
- />
+ <div>
+ {prompt.sourceType === 'evaluation' && (
+ <p className="text-xs text-muted">
+ Playground runs test your prompt without applying evaluation output rules. Saved
+ evaluations apply those rules when they run.
+ </p>
+ )}
+ <LemonTextArea
+ className="text-sm w-full"
+ placeholder="System instructions for the AI assistant..."
+ value={prompt.systemPrompt}
+ onChange={(value) => setSystemPrompt(value, promptId)}
+ minRows={2}
+ maxRows={undefined}
+ onPressCmdEnter={() => submitPrompt()}
+ />
+ </div>
</AnimatedCollapsible>
</div>
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
index 655249cd47fa..b178bdb9d260 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
@@ -1695,13 +1695,14 @@ describe('llmPlaygroundLogic', () => {
expect(llmPlaygroundPromptsLogic.values.messages).toEqual([])
})
- it('should set system prompt and model from fetched evaluation', async () => {
+ it.each(['boolean', 'numeric'])('loads a %s evaluation into Playground', async (outputType) => {
useMocks({
get: {
'/api/environments/:team_id/evaluations/:id/': {
id: 'eval-1',
name: 'judge-eval',
evaluation_type: 'llm_judge',
+ output_type: outputType,
evaluation_config: { prompt: 'Rate the response.' },
model_configuration: { model: 'gpt-5', provider_key_id: null },
},
@@ -1716,6 +1717,8 @@ describe('llmPlaygroundLogic', () => {
await expectLogic(llmPlaygroundPromptsLogic).toFinishAllListeners()
expect(llmPlaygroundPromptsLogic.values.systemPrompt).toBe('Rate the response.')
+ expect(llmPlaygroundPromptsLogic.values.model).toBe('gpt-5')
+ expect(router.values.searchParams).toHaveProperty('source_evaluation_id', 'eval-1')
})
it('should show error toast when prompt fetch fails', async () => {
@@ -1817,12 +1820,23 @@ describe('llmPlaygroundLogic', () => {
expect(router.values.searchParams).not.toHaveProperty('source_evaluation_id')
})
- it('saveAsNewEvaluation should call create API', async () => {
- let createCalled = false
+ it.each([
+ { output_type: 'boolean', output_config: undefined },
+ { output_type: 'boolean', output_config: { allows_na: true, true_is_failure: true } },
+ {
+ output_type: 'numeric',
+ output_config: { min: 0, max: 100, allows_na: true, passing_rule: { operator: 'gte', threshold: 70 } },
+ },
+ { output_type: 'sentiment', output_config: { aggregate: 'mean' } },
+ ])('saveAsNewEvaluation preserves output settings: %j', async ({ output_type, output_config }) => {
+ let createdBody: Record<string, unknown> | undefined
useMocks({
+ get: {
+ '/api/projects/:team_id/evaluations/:id/': { output_type, output_config },
+ },
post: {
- '/api/environments/:team_id/evaluations/': () => {
- createCalled = true
+ '/api/environments/:team_id/evaluations/': async ({ request }) => {
+ createdBody = (await request.json()) as Record<string, unknown>
return [201, { id: 'eval-new', name: 'saved-eval' }]
},
},
@@ -1830,6 +1844,15 @@ describe('llmPlaygroundLogic', () => {
llmPlaygroundPromptsLogic.actions.setSystemPrompt('Judge prompt')
const promptId = llmPlaygroundPromptsLogic.values.promptConfigs[0].id
+ if (output_config) {
+ llmPlaygroundPromptsLogic.actions.setPromptConfigs([
+ {
+ ...llmPlaygroundPromptsLogic.values.promptConfigs[0],
+ sourceType: 'evaluation',
+ sourceEvaluationId: 'eval-source',
+ },
+ ])
+ }
llmPlaygroundPromptsLogic.actions.saveAsNewEvaluation(promptId, 'saved-eval', {
model: 'gpt-5',
provider: 'openai',
@@ -1838,11 +1861,42 @@ describe('llmPlaygroundLogic', () => {
await expectLogic(llmPlaygroundPromptsLogic).toFinishAllListeners()
- expect(createCalled).toBe(true)
+ expect(createdBody).toMatchObject({
+ evaluation_config: { prompt: 'Judge prompt' },
+ output_type: output_type === 'sentiment' ? 'boolean' : output_type,
+ enabled: false,
+ })
+ expect(createdBody?.output_config).toEqual(output_type === 'sentiment' ? undefined : output_config)
expect(router.values.searchParams).toHaveProperty('source_evaluation_id', 'eval-new')
expect(router.values.searchParams).not.toHaveProperty('source_prompt_name')
})
+ it('does not create a boolean copy when the source evaluation cannot be loaded', async () => {
+ const createEvaluation = jest.fn(() => [201, { id: 'eval-new', name: 'saved-eval' }])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/evaluations/:id/': () => [404, { detail: 'Not found' }],
+ },
+ post: {
+ '/api/environments/:team_id/evaluations/': createEvaluation,
+ },
+ })
+ const prompt = llmPlaygroundPromptsLogic.values.promptConfigs[0]
+ llmPlaygroundPromptsLogic.actions.setPromptConfigs([
+ { ...prompt, sourceType: 'evaluation', sourceEvaluationId: 'eval-missing' },
+ ])
+ llmPlaygroundPromptsLogic.actions.saveAsNewEvaluation(prompt.id, 'saved-eval', {
+ model: 'gpt-5',
+ provider: 'openai',
+ provider_key_id: null,
+ })
+
+ await expectLogic(llmPlaygroundPromptsLogic).toFinishAllListeners()
+
+ expect(createEvaluation).not.toHaveBeenCalled()
+ expect(llmPlaygroundPromptsLogic.values.saving).toBe(false)
+ })
+
it('saveToLinkedPrompt should call update API with current system prompt', async () => {
let updatedPrompt: string | undefined
useMocks({
@@ -1879,20 +1933,21 @@ describe('llmPlaygroundLogic', () => {
expect(updatedPrompt).toBe('Updated prompt.')
})
- it('saveToLinkedEvaluation should call update API', async () => {
- let updateCalled = false
+ it.each(['boolean', 'numeric'])('saveToLinkedEvaluation preserves %s output settings', async (outputType) => {
+ let updatedBody: Record<string, unknown> | undefined
useMocks({
get: {
'/api/environments/:team_id/evaluations/:id/': {
id: 'eval-linked',
name: 'linked-eval',
evaluation_type: 'llm_judge',
+ output_type: outputType,
evaluation_config: { prompt: 'Old eval prompt.' },
},
},
patch: {
- '/api/environments/:team_id/evaluations/:id/': () => {
- updateCalled = true
+ '/api/environments/:team_id/evaluations/:id/': async ({ request }) => {
+ updatedBody = (await request.json()) as Record<string, unknown>
return [200, { id: 'eval-linked', name: 'linked-eval' }]
},
},
@@ -1915,7 +1970,10 @@ describe('llmPlaygroundLogic', () => {
await expectLogic(llmPlaygroundPromptsLogic).toFinishAllListeners()
- expect(updateCalled).toBe(true)
+ expect(updatedBody).toEqual({
+ evaluation_config: { prompt: 'New eval prompt.' },
+ model_configuration: { model: 'gpt-5', provider: 'openai', provider_key_id: null },
+ })
})
})
})
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
index 682a634d40d3..ed1cb65f36c2 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
@@ -12,7 +12,12 @@ import { urls } from 'scenes/urls'
import { llmEvaluationLogic } from '../evaluations/llmEvaluationLogic'
import type { EvaluationConfig } from '../evaluations/types'
-import { llmPromptsCreate, llmPromptsNamePartialUpdate, llmPromptsNameRetrieve } from '../generated/api'
+import {
+ evaluationsRetrieve,
+ llmPromptsCreate,
+ llmPromptsNamePartialUpdate,
+ llmPromptsNameRetrieve,
+} from '../generated/api'
import { normalizeMessage } from '../messageNormalization'
import { llmPromptLogic } from '../prompts/llmPromptLogic'
import { getApiErrorDetail } from '../prompts/utils'
@@ -1516,13 +1521,19 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
return
}
try {
+ const sourceEvaluation =
+ prompt.sourceType === 'evaluation' && prompt.sourceEvaluationId
+ ? await evaluationsRetrieve(String(teamId), prompt.sourceEvaluationId)
+ : null
+ const compatibleSource = sourceEvaluation?.output_type === 'sentiment' ? null : sourceEvaluation
// nosemgrep: prefer-codegen-api
const created = await api.create<EvaluationConfig>(`/api/environments/${teamId}/evaluations/`, {
name,
evaluation_type: 'llm_judge',
evaluation_config: { prompt: prompt.systemPrompt },
model_configuration: modelConfig,
- output_type: 'boolean',
+ output_type: compatibleSource?.output_type ?? 'boolean',
+ ...(compatibleSource ? { output_config: compatibleSource.output_config } : {}),
conditions: [],
enabled: false,
})
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 8b5a655c07e8..62d5318fe644 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -75,6 +75,30 @@ function makeEvaluationRunRow({
}
describe('mapEvaluationRunRow', () => {
+ 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
+ row[16] = -5
+ row[17] = 10
+ expect(mapEvaluationRunRow(row)).toMatchObject({
+ result_type: 'numeric',
+ result: null,
+ score: Number(score),
+ score_min: -5,
+ score_max: 10,
+ })
+ })
+
+ it.each([null, true, false, '', 'true', 'false'])(
+ 'does not read a numeric score from the boolean result property (%p)',
+ (result) => {
+ expect(mapEvaluationRunRow(makeEvaluationRunRow({ result, resultType: 'numeric' }))).toMatchObject({
+ result: null,
+ score: null,
+ })
+ }
+ )
+
it('maps sentiment rows without coercing missing boolean results to false', () => {
const run = mapEvaluationRunRow(
makeEvaluationRunRow({
@@ -2981,5 +3005,8 @@ describe('queryEvaluationRuns', () => {
await queryEvaluationRuns({ evaluationId: 'eval-1' })
expect(queryHogQL.mock.calls[0][0]).not.toContain('$ai_evaluation_backfill_id')
+ expect(queryHogQL.mock.calls[0][0]).toContain('properties.$ai_evaluation_numeric_result as score')
+ expect(queryHogQL.mock.calls[0][0]).toContain('properties.$ai_evaluation_numeric_result_min as score_min')
+ expect(queryHogQL.mock.calls[0][0]).toContain('properties.$ai_evaluation_numeric_result_max as score_max')
})
})
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index d0f3d50267e4..7c3924e2241b 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -4,16 +4,19 @@ import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { isObject, isString } from 'lib/utils/guards'
-import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
+import { DateRange, LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import { escapeHogQLString, hogql } from '~/queries/utils'
import type { SpanAggregation } from './aiObservabilityTraceDataLogic'
import {
- EVALUATION_NOT_SKIPPED_HOGQL,
+ EVALUATION_BOOLEAN_GRADED_HOGQL,
+ EVALUATION_NUMERIC_GRADED_HOGQL,
+ EVALUATION_NUMERIC_MEAN_HOGQL,
+ numericEvaluationPassedHogQL,
EVALUATION_RESULT_TRUE_HOGQL,
EVALUATION_RUNS_QUERY_LIMIT,
} from './evaluations/constants'
-import type { EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'
+import type { EvaluationConfig, EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'
import type { SummarizeRequestApi } from './generated/api.schemas'
import {
AnthropicDocumentMessage,
@@ -1127,6 +1130,9 @@ type RawEvaluationRunRow = [
sentiment_score: number | string | null,
session_id: string | null,
skipped: boolean | string | null,
+ score?: number | string | null,
+ score_min?: number | string | null,
+ score_max?: number | string | null,
]
export function normalizeEvaluationType(value: unknown): EvaluationType | undefined {
@@ -1137,7 +1143,7 @@ export function normalizeEvaluationType(value: unknown): EvaluationType | undefi
}
export function normalizeEvaluationOutputType(value: unknown): EvaluationOutputType | undefined {
- if (value === 'boolean' || value === 'sentiment') {
+ if (value === 'boolean' || value === 'sentiment' || value === 'numeric') {
return value
}
return undefined
@@ -1173,6 +1179,9 @@ export interface NormalizedEvaluationResultProperties {
rawResultType?: unknown
rawSentimentLabel?: unknown
rawSentimentScore?: unknown
+ rawScore?: unknown
+ rawScoreMin?: unknown
+ rawScoreMax?: unknown
}
export function normalizeEvaluationResultProperties({
@@ -1182,9 +1191,20 @@ export function normalizeEvaluationResultProperties({
rawResultType,
rawSentimentLabel,
rawSentimentScore,
+ rawScore,
+ rawScoreMin,
+ rawScoreMax,
}: NormalizedEvaluationResultProperties): Pick<
EvaluationRun,
- 'evaluation_type' | 'result_type' | 'result' | 'sentiment_label' | 'sentiment_score' | 'applicable'
+ | 'evaluation_type'
+ | 'result_type'
+ | 'result'
+ | 'sentiment_label'
+ | 'sentiment_score'
+ | 'applicable'
+ | 'score'
+ | 'score_min'
+ | 'score_max'
> {
const evaluationType = normalizeEvaluationType(rawEvaluationType)
const sentimentLabel =
@@ -1195,6 +1215,7 @@ export function normalizeEvaluationResultProperties({
const result =
resultType === 'sentiment' ||
+ resultType === 'numeric' ||
isExplicitEvaluationNotApplicable(rawApplicable) ||
rawResult === null ||
rawResult === undefined
@@ -1207,6 +1228,17 @@ export function normalizeEvaluationResultProperties({
result,
sentiment_label: sentimentLabel,
sentiment_score: normalizeOptionalNumber(rawSentimentScore),
+ ...(resultType === 'numeric'
+ ? {
+ score:
+ isExplicitEvaluationNotApplicable(rawApplicable) ||
+ (typeof rawScore !== 'number' && (typeof rawScore !== 'string' || !rawScore.trim()))
+ ? null
+ : normalizeOptionalNumber(rawScore),
+ score_min: normalizeOptionalNumber(rawScoreMin),
+ score_max: normalizeOptionalNumber(rawScoreMax),
+ }
+ : {}),
applicable: normalizeEvaluationApplicable(rawApplicable),
}
}
@@ -1219,6 +1251,9 @@ export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
rawResultType: row[10],
rawSentimentLabel: row[11],
rawSentimentScore: row[12],
+ rawScore: row[15],
+ rawScoreMin: row[16],
+ rawScoreMax: row[17],
})
return {
@@ -1241,12 +1276,13 @@ export async function queryEvaluationRuns(params: {
traceId?: string
sessionId?: string
backfillId?: string
+ dateRange?: DateRange
/** Bounds the scan so it can prune partitions. Omitted for the trace and generation surfaces,
* which read a single unit's runs and have always been unbounded. */
lookbackDays?: number
forceRefresh?: boolean
}): Promise<EvaluationRun[]> {
- const { evaluationId, traceId, sessionId, backfillId, lookbackDays, forceRefresh } = params
+ const { evaluationId, traceId, sessionId, backfillId, dateRange, lookbackDays, forceRefresh } = params
const propertyValue = evaluationId || traceId || sessionId
@@ -1275,13 +1311,17 @@ export async function queryEvaluationRuns(params: {
properties.$ai_sentiment_label as sentiment_label,
properties.$ai_sentiment_score as sentiment_score,
properties.$ai_session_id as session_id,
- properties.$ai_evaluation_skipped as skipped
+ 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
FROM events
WHERE
event = '$ai_evaluation'
AND ${hogql.raw(`properties.${propertyName}`)} = ${propertyValue}
${backfillId ? hogql.raw(`AND properties.$ai_evaluation_backfill_id = ${escapeHogQLString(backfillId)}`) : hogql.raw('')}
${lookbackDays ? hogql.raw(`AND timestamp >= now() - INTERVAL ${Math.floor(lookbackDays)} DAY`) : hogql.raw('')}
+ ${dateRange ? hogql.raw('AND {filters}') : hogql.raw('')}
ORDER BY timestamp DESC
LIMIT ${EVALUATION_RUNS_QUERY_LIMIT}
`
@@ -1289,7 +1329,10 @@ export async function queryEvaluationRuns(params: {
const response = await api.queryHogQL(
query,
{ scene: 'AIObservability', productKey: 'llm_analytics' },
- { ...(forceRefresh && { refresh: 'force_blocking' }) }
+ {
+ ...(dateRange && { queryParams: { filters: { dateRange } } }),
+ ...(forceRefresh && { refresh: 'force_blocking' }),
+ }
)
return (response.results || []).map(mapEvaluationRunRow)
@@ -1299,6 +1342,9 @@ export interface EvaluationRunsStats {
total: number
applicable: number
trueCount: number
+ scoreCount?: number
+ scoreMean?: number | null
+ numericPassCount?: number
}
// Counts every matching run server-side. queryEvaluationRuns caps its fetch at
@@ -1306,12 +1352,14 @@ export interface EvaluationRunsStats {
// undercounting. Counting semantics mirror the evaluations list view (evaluationMetricsLogic)
// so both surfaces report the same totals.
export async function queryEvaluationRunsStats(params: {
+ evaluation?: EvaluationConfig | null
evaluationId?: string
traceId?: string
backfillId?: string
+ dateRange?: DateRange
forceRefresh?: boolean
}): Promise<EvaluationRunsStats> {
- const { evaluationId, traceId, backfillId, forceRefresh } = params
+ const { evaluation, evaluationId, traceId, backfillId, dateRange, forceRefresh } = params
const propertyValue = evaluationId || traceId
@@ -1324,19 +1372,26 @@ export async function queryEvaluationRunsStats(params: {
const query = hogql`
SELECT
count() as total,
- countIf(properties.$ai_evaluation_result IS NOT NULL AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as applicable,
- countIf(${hogql.raw(EVALUATION_RESULT_TRUE_HOGQL)} AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as true_count
+ countIf(${hogql.raw(EVALUATION_BOOLEAN_GRADED_HOGQL)}) as applicable,
+ 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
FROM events
WHERE
event = '$ai_evaluation'
AND ${hogql.raw(`properties.${propertyName}`)} = ${propertyValue}
${backfillId ? hogql.raw(`AND properties.$ai_evaluation_backfill_id = ${escapeHogQLString(backfillId)}`) : hogql.raw('')}
+ ${dateRange ? hogql.raw('AND {filters}') : hogql.raw('')}
`
const response = await api.queryHogQL(
query,
{ scene: 'AIObservability', productKey: 'llm_analytics' },
- { ...(forceRefresh && { refresh: 'force_blocking' }) }
+ {
+ ...(dateRange && { queryParams: { filters: { dateRange } } }),
+ ...(forceRefresh && { refresh: 'force_blocking' }),
+ }
)
const row = response.results?.[0]
@@ -1349,5 +1404,8 @@ export async function queryEvaluationRunsStats(params: {
total: Number(row[0]) || 0,
applicable: Number(row[1]) || 0,
trueCount: Number(row[2]) || 0,
+ scoreCount: Number(row[3]) || 0,
+ scoreMean: Number(row[3]) > 0 ? normalizeOptionalNumber(row[4]) : null,
+ numericPassCount: Number(row[5]) || 0,
}
}
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index 98aa5623c362..d607697fa48a 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -519,12 +519,14 @@ tools:
description: >
Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and
model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a
- boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional
- evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A
- session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass
- `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it
- paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit
- `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.
+ boolean or finite number). For 'hog' and 'llm_judge', choose output_type='boolean' or 'numeric'; numeric
+ output_config accepts min, max, step, allows_na, and passing_rule. 'sentiment': output_type='sentiment',
+ omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation'
+ (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the
+ 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events
+ immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by
+ llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are
+ '$ai_evaluation' events.
llma-evaluation-delete:
operation: evaluations_destroy
enabled: true
@@ -811,8 +813,8 @@ tools:
runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against
session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's
aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period.
- Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog
- code before creating or updating a 'hog' type evaluation.
+ Returns per-sample raw boolean or numeric results, N/A when allowed, errors, reasoning, and input/output
+ previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.
llma-evaluation-update:
operation: evaluations_partial_update
enabled: true
@@ -825,14 +827,17 @@ tools:
title: Update evaluation
description: >
Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it,
- call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config,
- or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider
- and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or
- provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to
- hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain
- editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or
- 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a
- directory, or pass null to move it to the top level.
+ call llma-evaluation-list first to look it up by name. Changing to or from numeric output requires a new
+ evaluation; for numeric evaluations, update output_config to change bounds, N/A handling, or passing_rule. A
+ passing rule has operator 'gte' or 'lte' and a finite threshold. Rule edits reinterpret historical scores;
+ saved reports stay unchanged. Toggle enabled, change its runtime type or evaluation config, or change the
+ model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model.
+ When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both
+ fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or
+ sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable.
+ provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'.
+ Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or
+ pass null to move it to the top level.
param_overrides:
id:
aliases:
diff --git a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2 b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
index 188239be955b..554fe8585936 100644
--- a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
+++ b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
@@ -11,8 +11,8 @@ schemas below are rendered from the backend Pydantic models at build time, so th
| `description` | no | Defaults to `""`. |
| `evaluation_type` | yes | `"hog"`, `"llm_judge"`, or `"sentiment"`. |
| `evaluation_config` | yes | Shape depends on `evaluation_type` (below). |
-| `output_type` | yes | `"boolean"` for `hog`/`llm_judge`; `"sentiment"` for `sentiment`. |
-| `output_config` | no | `{ "allows_na": bool, "true_is_failure": bool }` for boolean; `{}` for sentiment. |
+| `output_type` | yes | `"boolean"` or `"numeric"` for `hog`/`llm_judge`; `"sentiment"` for `sentiment`. |
+| `output_config` | no | `{ "allows_na": bool, "true_is_failure": bool }` for boolean; numeric settings below; `{}` for sentiment. |
| `model_configuration` | llm_judge only | Provider + model; key ID optional. Rejected on `hog`/`sentiment`. |
| `target` | no | `"generation"` (default), `"trace"`, or `"session"`. Sentiment supports only `"generation"`. |
| `target_config` | trace/session only | Settle config discriminated on `strategy` (below); defaults to a 30-minute fixed window for `trace`, and to a 1-hour inactivity window for `session`. |
@@ -20,7 +20,9 @@ schemas below are rendered from the backend Pydantic models at build time, so th
| `enabled` | no | Defaults to `false`. Create disabled, then flip with `llma-evaluation-update`. |
Valid `(evaluation_type, output_type)` pairs: `(hog, boolean)`, `(llm_judge, boolean)`,
-`(sentiment, sentiment)`.
+`(hog, numeric)`, `(llm_judge, numeric)`, `(sentiment, sentiment)`.
+The output type cannot change after creation.
+Numeric evaluations require the `llm-analytics-numeric-evaluations` rollout flag for the project. Existing numeric evaluations remain editable when it is off.
## `target` and `target_config`
@@ -80,10 +82,24 @@ Valid `(evaluation_type, output_type)` pairs: `(hog, boolean)`, `(llm_judge, boo
{{ pydantic_schema("products.ai_observability.backend.models.evaluation_configs.BooleanOutputConfig") }}
```
-`allows_na: true` lets the evaluator return N/A (skip) in addition to pass/fail.
+`allows_na: true` lets the evaluator return N/A in addition to true/false. N/A differs from an execution error that skips a run.
`true_is_failure: true` treats a raw `true` result as a failure and a raw `false` result as a pass.
Leave it `false` for the default mapping.
+### numeric output
+
+```json
+{{ pydantic_schema("products.ai_observability.backend.models.evaluation_configs.NumericOutputConfig") }}
+```
+
+Return a finite number, not a boolean or numeric string.
+Optional `min` and `max` are inclusive; an out-of-bounds score skips that run.
+`step` guides scoring without rounding results.
+`allows_na` defaults to false; set it to true to allow `null` from Hog.
+Set `passing_rule` to `{"operator": "gte", "threshold": 7}` (at least 7) or use `lte` (at most).
+Without a passing rule, scores remain ungraded and reports are unavailable.
+Changing the rule reinterprets historical scores; previously generated reports stay unchanged.
+
### sentiment output
Empty object: `{}`.
diff --git a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
index 4d342a2312fa..57be644f0718 100644
--- a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
@@ -32,6 +32,12 @@ types:
Results from all types land in ClickHouse as `$ai_evaluation` events. Boolean
evaluations (`llm_judge` and `hog`) set `$ai_evaluation_result`; sentiment
evaluations set `$ai_sentiment_*` properties instead.
+Both `hog` and `llm_judge` also support `output_type: "numeric"`.
+Numeric runs store their raw score in `$ai_evaluation_numeric_result`, with optional `$ai_evaluation_numeric_result_min` and `$ai_evaluation_numeric_result_max`.
+They never set `$ai_evaluation_result`.
+Use `output_config.passing_rule` to interpret scores: `gte` means at least the threshold and `lte` means at most.
+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.
This skill covers the full lifecycle: list/inspect/manage evaluation configs, run
them on specific generations, query individual results, and configure evaluation
@@ -60,18 +66,19 @@ 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` or `sentiment` |
-| `$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 |
+| 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`.
For evaluations that don't support N/A, this property may be `null` — treat null as "applicable".
@@ -200,8 +207,8 @@ posthog:llma-evaluation-test-hog
}
```
-The handler returns the boolean result for each of the most recent N `$ai_generation`
-events. Iterate on the source until it behaves as expected, then promote it via
+The handler returns raw boolean or numeric results for the sampled units.
+For numeric previews, send `output_type: "numeric"` and the saved `output_config`, including `allows_na: true` if null is allowed. Iterate on the source until it behaves as expected, then promote it via
`llma-evaluation-create`:
```json
diff --git a/products/experiments/backend/llm_metric_templates.py b/products/experiments/backend/llm_metric_templates.py
index 0466373e0822..883a6c9f61b0 100644
--- a/products/experiments/backend/llm_metric_templates.py
+++ b/products/experiments/backend/llm_metric_templates.py
@@ -63,6 +63,9 @@ def build_eval_pass_rate_metric(prompt_name: str) -> ExperimentRatioMetric:
# The applicable guard excludes N/A evaluations (applicable=false) but keeps events
# where the property isn't set at all (JSONExtractRaw returns '' for missing keys).
applicable_filter = HogQLPropertyFilter(key="JSONExtractRaw(properties, '$ai_evaluation_applicable') != 'false'")
+ boolean_filter = HogQLPropertyFilter(
+ key="JSONExtractString(properties, '$ai_evaluation_result_type') IN ('', 'boolean')"
+ )
return ExperimentRatioMetric(
name="Eval pass rate",
numerator=EventsNode(
@@ -71,6 +74,7 @@ def build_eval_pass_rate_metric(prompt_name: str) -> ExperimentRatioMetric:
_prompt_filter(prompt_name),
HogQLPropertyFilter(key="JSONExtractBool(properties, '$ai_evaluation_result')"),
applicable_filter,
+ boolean_filter,
],
),
denominator=EventsNode(
@@ -78,6 +82,7 @@ def build_eval_pass_rate_metric(prompt_name: str) -> ExperimentRatioMetric:
properties=[
_prompt_filter(prompt_name),
applicable_filter,
+ boolean_filter,
],
),
)
diff --git a/products/experiments/backend/test/test_create_from_prompt.py b/products/experiments/backend/test/test_create_from_prompt.py
index 8ff621efbec3..a9cb83c4f1c6 100644
--- a/products/experiments/backend/test/test_create_from_prompt.py
+++ b/products/experiments/backend/test/test_create_from_prompt.py
@@ -119,6 +119,12 @@ class TestExperimentsCreateFromPrompt(APILicensedTest):
properties = source_or_numerator["properties"]
prompt_filter = next(p for p in properties if p.get("key") == "$ai_prompt_name")
self.assertEqual(prompt_filter["value"], self.prompt_name)
+ if template_name == "eval_pass_rate":
+ for source in (metric["numerator"], metric["denominator"]):
+ self.assertIn(
+ "JSONExtractString(properties, '$ai_evaluation_result_type') IN ('', 'boolean')",
+ [prop["key"] for prop in source["properties"]],
+ )
def test_multiple_templates_creates_one_metric_each(self) -> None:
# Pick all available templates so we exercise both mean and ratio shapes.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index bbd3143294d2..f694aee5e2b9 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6939,7 +6939,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.",
+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean or finite number). For 'hog' and 'llm_judge', choose output_type='boolean' or 'numeric'; numeric output_config accepts min, max, step, allows_na, and passing_rule. 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -7177,7 +7177,7 @@
}
},
"llma-evaluation-test-hog": {
- "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
+ "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample raw boolean or numeric results, N/A when allowed, errors, reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Test Hog evaluation code",
@@ -7191,7 +7191,7 @@
}
},
"llma-evaluation-update": {
- "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or pass null to move it to the top level.",
+ "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it, call llma-evaluation-list first to look it up by name. Changing to or from numeric output requires a new evaluation; for numeric evaluations, update output_config to change bounds, N/A handling, or passing_rule. A passing rule has operator 'gte' or 'lte' and a finite threshold. Rule edits reinterpret historical scores; saved reports stay unchanged. Toggle enabled, change its runtime type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or pass null to move it to the top level.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d922ed14dd13..43746cfd84ba 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -7150,7 +7150,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.",
+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean or finite number). For 'hog' and 'llm_judge', choose output_type='boolean' or 'numeric'; numeric output_config accepts min, max, step, allows_na, and passing_rule. 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. `target` accepts 'generation' (default), 'trace', or 'session'. A session target runs once per `$ai_session_id` and defaults to the 'inactivity' settle strategy. Pass `enabled` as a boolean (true to start scoring new $ai_generation events immediately, false to create it paused). To organize the evaluation, pass a `directory_id` returned by llma-evaluation-directory-list. Omit `directory_id` or pass null to keep it at the top level. Results are '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -7388,7 +7388,7 @@
}
},
"llma-evaluation-test-hog": {
- "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
+ "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals, 'session' samples whole sessions that have gone quiet and runs against session-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window; for session previews, pass target_config.quiet_period_seconds to match its quiet period. Returns per-sample raw boolean or numeric results, N/A when allowed, errors, reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Test Hog evaluation code",
@@ -7402,7 +7402,7 @@
}
},
"llma-evaluation-update": {
- "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it, call llma-evaluation-list first to look it up by name. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or pass null to move it to the top level.",
+ "description": "Partially update an AI observability evaluation. Requires the evaluation `id` (UUID). If you don't have it, call llma-evaluation-list first to look it up by name. Changing to or from numeric output requires a new evaluation; for numeric evaluations, update output_config to change bounds, N/A handling, or passing_rule. A passing rule has operator 'gte' or 'lte' and a finite threshold. Rule edits reinterpret historical scores; saved reports stay unchanged. Toggle enabled, change its runtime type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned. `target` accepts 'generation', 'trace', or 'session'. Pass a `directory_id` returned by llma-evaluation-directory-list to move the evaluation into a directory, or pass null to move it to the top level.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8eaca719d3fe..02869c8d9d85 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -37526,7 +37526,7 @@ export namespace Schemas {
prompt: string;
} | {
/**
- * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
+ * 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.
* @minLength 1
*/
source: string;
@@ -37536,13 +37536,46 @@ export namespace Schemas {
};
/**
- * 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.
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ 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;
+ } | 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': {}.
*/
export type EvaluationOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
- /** 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 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.
+ * @nullable
+ */
+ min?: number | null;
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null;
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null;
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: EvaluationOutputConfigPassingRule;
};
/**
@@ -37630,6 +37663,7 @@ export namespace Schemas {
/**
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `sentiment` - Sentiment
*/
export type OutputTypeEnum = typeof OutputTypeEnum[keyof typeof OutputTypeEnum];
@@ -37637,6 +37671,7 @@ export namespace Schemas {
export const OutputTypeEnum = {
Boolean: 'boolean',
+ Numeric: 'numeric',
Sentiment: 'sentiment',
} as const;
@@ -37751,12 +37786,13 @@ 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. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `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. */
+ /** 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?: 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[];
@@ -38062,6 +38098,49 @@ export namespace Schemas {
reason?: string;
}
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ 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;
+ } | null;
+
+ /**
+ * Numeric score 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. */
+ true_is_failure?: boolean;
+ /**
+ * Inclusive minimum numeric score. Omit for no lower bound.
+ * @nullable
+ */
+ min?: number | null;
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null;
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null;
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: EvaluationReportMetricsOutputConfigPassingRule;
+ };
+
/**
* Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative.
*/
@@ -38085,9 +38164,12 @@ 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_config?: EvaluationReportMetricsOutputConfig;
/** Evaluation result type. Stored metrics without this field represent boolean evaluations.
*
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnum;
/** Number of evaluation results in the report period. */
@@ -38115,10 +38197,13 @@ export namespace Schemas {
* @nullable
*/
previous_result_rates?: EvaluationReportMetricsPreviousResultRates;
- /** Boolean pass percentage, excluding results marked not applicable. */
- pass_rate?: number;
/**
- * Boolean pass percentage for the previous period, or null when unavailable.
+ * Boolean or numeric pass percentage, excluding N/A results. Null when no numeric scores were produced.
+ * @nullable
+ */
+ pass_rate?: number | null;
+ /**
+ * Boolean or numeric pass percentage for the previous period, or null when unavailable.
* @nullable
*/
previous_pass_rate?: number | null;
@@ -48448,6 +48533,18 @@ export namespace Schemas {
AnyUser: 'any-user',
} as const;
+ /**
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
+ */
+ export type HogEvaluationOutputTypeEnum = typeof HogEvaluationOutputTypeEnum[keyof typeof HogEvaluationOutputTypeEnum];
+
+
+ export const HogEvaluationOutputTypeEnum = {
+ Boolean: 'boolean',
+ Numeric: 'numeric',
+ } as const;
+
/**
* Variable: {key, type: string|number|boolean, default}.
*/
@@ -71187,7 +71284,7 @@ export namespace Schemas {
prompt: string;
} | {
/**
- * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
+ * 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.
* @minLength 1
*/
source: string;
@@ -71197,13 +71294,46 @@ export namespace Schemas {
};
/**
- * 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.
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ 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;
+ } | 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': {}.
*/
export type PatchedEvaluationOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
- /** 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 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.
+ * @nullable
+ */
+ min?: number | null;
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null;
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null;
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: PatchedEvaluationOutputConfigPassingRule;
};
/**
@@ -71269,12 +71399,13 @@ 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. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
+ /** Output format: 'boolean', 'numeric' for a finite score, or 'sentiment' for sentiment analysis.
*
* * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric
* * `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. */
+ /** 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?: 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[];
@@ -97814,6 +97945,49 @@ export namespace Schemas {
temperature?: number | null;
}
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ 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;
+ } | null;
+
+ /**
+ * Output settings used to validate the preview, including numeric bounds 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. */
+ true_is_failure?: boolean;
+ /**
+ * Inclusive minimum numeric score. Omit for no lower bound.
+ * @nullable
+ */
+ min?: number | null;
+ /**
+ * Inclusive maximum numeric score. Omit for no upper bound.
+ * @nullable
+ */
+ max?: number | null;
+ /**
+ * Optional positive input increment. Does not round evaluation results.
+ * @minimum 0
+ * @exclusiveMinimum true
+ * @nullable
+ */
+ step?: number | null;
+ /**
+ * Optional numeric passing rule. Null removes the rule; historical scores use the current rule.
+ * @nullable
+ */
+ passing_rule?: TestHogRequestOutputConfigPassingRule;
+ };
+
export type TestHogRequestConditionsItem = { [key: string]: unknown };
export interface TestHogTargetConfig {
@@ -97832,8 +98006,15 @@ export namespace Schemas {
}
export interface TestHogRequest {
+ /** Expected output: boolean or numeric. Sentiment is not supported by Hog.
+ *
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `numeric` - Numeric */
+ output_type?: HogEvaluationOutputTypeEnum;
+ /** Output settings used to validate the preview, including numeric bounds and allows_na. */
+ output_config?: TestHogRequestOutputConfig;
/**
- * Hog source code to test. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
+ * 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.
* @minLength 1
*/
source: string;
@@ -97858,6 +98039,11 @@ export namespace Schemas {
}
export interface TestHogResultItem {
+ /**
+ * Raw numeric score, or null when no numeric score was produced.
+ * @nullable
+ */
+ score?: number | null;
/** Stable identifier for the sampled generation, trace, or session. */
sample_id: string;
/** Type of sampled unit: generation, trace, or session.
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 617ffabadeff..283e55231a33 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -561,6 +561,8 @@ export const EvaluationsCreateParams = () => zod.object({
export const evaluationsCreateBodyNameMax = 400
export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
+export const evaluationsCreateBodyOutputConfigStepExclusiveMin = 0
+
export const evaluationsCreateBodyConditionsItemIdMax = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -609,7 +611,7 @@ export const EvaluationsCreateBody = () => zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
}),
zod.object({
@@ -626,10 +628,10 @@ export const EvaluationsCreateBody = () => zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
.describe(
- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ "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_config: zod
.object({
@@ -641,12 +643,32 @@ export const EvaluationsCreateBody = () => zod
.boolean()
.optional()
.describe(
- '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 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsCreateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores 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."
+ "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': {}."
),
conditions: zod
.array(
@@ -785,6 +807,8 @@ export const EvaluationsPartialUpdateParams = () => zod.object({
export const evaluationsPartialUpdateBodyNameMax = 400
export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
+export const evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin = 0
+
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -834,7 +858,7 @@ export const EvaluationsPartialUpdateBody = () => zod
.string()
.min(1)
.describe(
- 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
}),
zod.object({
@@ -851,11 +875,11 @@ export const EvaluationsPartialUpdateBody = () => zod
"Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
),
output_type: zod
- .enum(['boolean', 'sentiment'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .enum(['boolean', 'numeric', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric\n\* `sentiment` - Sentiment')
.optional()
.describe(
- "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ "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_config: zod
.object({
@@ -867,12 +891,32 @@ export const EvaluationsPartialUpdateBody = () => zod
.boolean()
.optional()
.describe(
- '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 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsPartialUpdateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores 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."
+ "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': {}."
),
conditions: zod
.array(
@@ -1013,6 +1057,9 @@ export const EvaluationsTestHogCreateParams = () => zod.object({
),
})
+export const evaluationsTestHogCreateBodyOutputTypeDefault = `boolean`
+export const evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin = 0
+
export const evaluationsTestHogCreateBodySampleCountDefault = 5
export const evaluationsTestHogCreateBodySampleCountMax = 10
@@ -1027,11 +1074,51 @@ export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMin =
export const evaluationsTestHogCreateBodyTargetConfigOneQuietPeriodSecondsMax = 86400
export const EvaluationsTestHogCreateBody = () => zod.object({
+ output_type: zod
+ .enum(['boolean', 'numeric'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric')
+ .default(evaluationsTestHogCreateBodyOutputTypeDefault)
+ .describe(
+ 'Expected output: boolean or numeric. Sentiment is not supported by Hog.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `numeric` - Numeric'
+ ),
+ output_config: zod
+ .object({
+ allows_na: zod
+ .boolean()
+ .optional()
+ .describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: 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.'
+ ),
+ 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.'),
+ step: zod
+ .number()
+ .gt(evaluationsTestHogCreateBodyOutputConfigStepExclusiveMin)
+ .nullish()
+ .describe('Optional positive input increment. Does not round evaluation results.'),
+ 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()
+ .describe(
+ 'Optional numeric passing rule. Null removes the rule; historical scores use the current rule.'
+ ),
+ })
+ .optional()
+ .describe('Output settings used to validate the preview, including numeric bounds and allows_na.'),
source: zod
.string()
.min(1)
.describe(
- 'Hog source code to test. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ '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.'
),
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 b78b181a8d94..c53d58cfdbcd 100644
--- a/services/mcp/src/lib/trace-property-allowlist.generated.ts
+++ b/services/mcp/src/lib/trace-property-allowlist.generated.ts
@@ -36,6 +36,9 @@ export const AI_TAXONOMY_EVENT_PROPERTIES = [
'$ai_evaluation_key_type',
'$ai_evaluation_model',
'$ai_evaluation_name',
+ '$ai_evaluation_numeric_result',
+ '$ai_evaluation_numeric_result_max',
+ '$ai_evaluation_numeric_result_min',
'$ai_evaluation_provider',
'$ai_evaluation_reasoning',
'$ai_evaluation_result',
diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.ts
index ac10b6071a68..425c92b3e9d9 100644
--- a/services/mcp/src/tools/generated/ai_observability.ts
+++ b/services/mcp/src/tools/generated/ai_observability.ts
@@ -1281,6 +1281,12 @@ const llmaEvaluationTestHog = (): ToolBase<
handler: async (context: Context, params: z.infer<ReturnType<typeof LlmaEvaluationTestHogSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
+ if (params.output_type !== undefined) {
+ body['output_type'] = params.output_type
+ }
+ if (params.output_config !== undefined) {
+ body['output_config'] = params.output_config
+ }
if (params.source !== undefined) {
body['source'] = params.source
}
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 bbcc23cd980e..5d644a3784f9 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 true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
+ "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.",
"minLength": 1,
"type": "string"
}
@@ -163,22 +163,79 @@
"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.",
+ "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': {}.",
"properties": {
"allows_na": {
"description": "Whether the evaluation can return N/A for non-applicable generations.",
"type": "boolean"
},
+ "max": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive maximum numeric score. Omit for no upper bound."
+ },
+ "min": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive minimum numeric score. Omit for no lower bound."
+ },
+ "passing_rule": {
+ "anyOf": [
+ {
+ "properties": {
+ "operator": {
+ "description": "Pass at or above (gte), or at or below (lte), the threshold.",
+ "enum": ["gte", "lte"],
+ "type": "string"
+ },
+ "threshold": {
+ "description": "Finite passing threshold within any configured score bounds.",
+ "type": "number"
+ }
+ },
+ "required": ["operator", "threshold"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional numeric passing rule. Null removes the rule; historical scores use the current rule."
+ },
+ "step": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional positive input increment. Does not round evaluation results."
+ },
"true_is_failure": {
- "description": "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 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. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment",
- "enum": ["boolean", "sentiment"],
+ "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"],
"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 44f5ccaee00d..777e7b66f4df 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
@@ -17,6 +17,83 @@
},
"type": "array"
},
+ "output_config": {
+ "description": "Output settings used to validate the preview, including numeric bounds and allows_na.",
+ "properties": {
+ "allows_na": {
+ "description": "Whether the evaluation can return N/A for non-applicable generations.",
+ "type": "boolean"
+ },
+ "max": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive maximum numeric score. Omit for no upper bound."
+ },
+ "min": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive minimum numeric score. Omit for no lower bound."
+ },
+ "passing_rule": {
+ "anyOf": [
+ {
+ "properties": {
+ "operator": {
+ "description": "Pass at or above (gte), or at or below (lte), the threshold.",
+ "enum": ["gte", "lte"],
+ "type": "string"
+ },
+ "threshold": {
+ "description": "Finite passing threshold within any configured score bounds.",
+ "type": "number"
+ }
+ },
+ "required": ["operator", "threshold"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional numeric passing rule. Null removes the rule; historical scores use the current rule."
+ },
+ "step": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "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.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "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"],
+ "type": "string"
+ },
"sample_count": {
"default": 5,
"description": "Number of recent $ai_generation events to test against (1–10, default 5).",
@@ -25,7 +102,7 @@
"type": "number"
},
"source": {
- "description": "Hog source code to test. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
+ "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.",
"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 e87591b624f1..00808a79ec8a 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 true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
+ "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.",
"minLength": 1,
"type": "string"
}
@@ -166,22 +166,79 @@
"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.",
+ "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': {}.",
"properties": {
"allows_na": {
"description": "Whether the evaluation can return N/A for non-applicable generations.",
"type": "boolean"
},
+ "max": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive maximum numeric score. Omit for no upper bound."
+ },
+ "min": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Inclusive minimum numeric score. Omit for no lower bound."
+ },
+ "passing_rule": {
+ "anyOf": [
+ {
+ "properties": {
+ "operator": {
+ "description": "Pass at or above (gte), or at or below (lte), the threshold.",
+ "enum": ["gte", "lte"],
+ "type": "string"
+ },
+ "threshold": {
+ "description": "Finite passing threshold within any configured score bounds.",
+ "type": "number"
+ }
+ },
+ "required": ["operator", "threshold"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional numeric passing rule. Null removes the rule; historical scores use the current rule."
+ },
+ "step": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional positive input increment. Does not round evaluation results."
+ },
"true_is_failure": {
- "description": "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 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. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment",
- "enum": ["boolean", "sentiment"],
+ "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"],
"type": "string"
},
"target": {
diff --git a/services/mcp/tests/unit/llma-evaluation-output-config.test.ts b/services/mcp/tests/unit/llma-evaluation-output-config.test.ts
index f43814d705c6..cf2f92bafdc6 100644
--- a/services/mcp/tests/unit/llma-evaluation-output-config.test.ts
+++ b/services/mcp/tests/unit/llma-evaluation-output-config.test.ts
@@ -10,6 +10,7 @@ describe('llma-evaluation-update output settings', () => {
{ output_config: { allows_na: true } },
{ output_config: { allows_na: false } },
{ output_config: {} },
+ { output_config: { min: 0, max: 10, passing_rule: { operator: 'gte', threshold: 7 } } },
{ name: 'Renamed evaluation' },
])('only sends the supplied settings for %j', async (body) => {
const request = vi.fn().mockResolvedValue({})
@@ -27,4 +28,9 @@ describe('llma-evaluation-update output settings', () => {
body,
})
})
+
+ it.each(['true', 'false', 1, 0, null])('rejects malformed detector flag %j', (true_is_failure) => {
+ const tool = GENERATED_TOOLS['llma-evaluation-update']!()
+ expect(tool.schema.safeParse({ id: 'evaluation-1', output_config: { true_is_failure } }).success).toBe(false)
+ })
})
diff --git a/services/mcp/tests/unit/llma-identifier-contracts.test.ts b/services/mcp/tests/unit/llma-identifier-contracts.test.ts
index b8c84fee1b69..c4cc3ca85d82 100644
--- a/services/mcp/tests/unit/llma-identifier-contracts.test.ts
+++ b/services/mcp/tests/unit/llma-identifier-contracts.test.ts
@@ -19,6 +19,17 @@ function createContext(): { context: Context; requestMock: ReturnType<typeof vi.
// and values those traces record, so dropping an alias map or making `provider` required again
// fails here.
describe('llma identifier contracts', () => {
+ it.each([
+ { min: 0, max: 10, passing_rule: { operator: 'gte', threshold: 7 }, allows_na: true },
+ { true_is_failure: true, allows_na: false },
+ { allows_na: true },
+ {},
+ ])('preserves output settings through the update schema: %j', (output_config) => {
+ const tool = GENERATED_TOOLS['llma-evaluation-update']!()
+ const parsed = tool.schema.parse({ id: 'evaluation-1', output_config }) as { output_config: unknown }
+ expect(parsed.output_config).toEqual(output_config)
+ })
+
// The write tools share the mismatch, so they share the alias map. Without that, an agent that
// succeeds with `evaluationId` on get is rejected the moment it updates or deletes.
describe.each([['llma-evaluation-get'], ['llma-evaluation-update'], ['llma-evaluation-delete']])(