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): support sentiment evaluation reports (#70564)

Radu Raiceab82115073db6
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 2f391500deeb..3b9fd2d78f8f 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -12,6 +12,7 @@ from posthog.hogql import ast
from posthog.clickhouse.client.connection import Workload
from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
from posthog.temporal.ai_observability.eval_reports.types import (
CheckCountTriggeredEvalReportInput,
CheckCountTriggeredEvalReportOutput,
@@ -51,7 +52,6 @@ async def fetch_due_eval_reports_activity(
for pk in EvaluationReport.objects.deliverable()
.filter(
next_delivery_date__lte=now_with_buffer,
- evaluation__output_type="boolean",
)
.exclude(frequency=EvaluationReport.Frequency.EVERY_N)
.values_list("id", flat=True)
@@ -111,7 +111,6 @@ def _fetch_count_triggered_eval_report_candidate_ids() -> list[str]:
.filter(
frequency=EvaluationReport.Frequency.EVERY_N,
trigger_threshold__isnull=False,
- evaluation__output_type="boolean",
)
.values_list("id", flat=True)
]
@@ -129,7 +128,6 @@ def _check_count_triggered_eval_report_sync(
id=report_id,
frequency=EvaluationReport.Frequency.EVERY_N,
trigger_threshold__isnull=False,
- evaluation__output_type="boolean",
)
.select_related("evaluation", "team")
.first()
@@ -168,13 +166,16 @@ def _count_eval_results_for_report(report: "EvaluationReport", since: dt.datetim
# as toDateTime64(..., 6, <team_tz>) with correct TZ alignment. A bare string
# would be coerced in the team's timezone and silently shift the comparison
# by the team's offset.
+ outcome_definition = get_outcome_definition(report.evaluation.output_type)
+ # nosemgrep: hogql-fstring-audit (the predicate comes from fixed internal output-type definitions)
query = parse_select(
- """
+ f"""
SELECT count() as total
FROM events
WHERE event = '$ai_evaluation'
- AND properties.$ai_evaluation_id = {evaluation_id}
- AND timestamp >= {since}
+ AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {outcome_definition.event_predicate}
+ AND timestamp >= {{since}}
""",
placeholders={
"evaluation_id": ast.Constant(value=str(report.evaluation_id)),
@@ -196,6 +197,7 @@ def _find_nth_eval_timestamp(
evaluation_id: str,
n: int,
before: dt.datetime,
+ output_type: str = "boolean",
) -> dt.datetime:
"""Find the timestamp of the Nth-most-recent eval result.
@@ -211,16 +213,19 @@ def _find_nth_eval_timestamp(
team = Team.objects.get(id=team_id)
# Pass `before` as a datetime so HogQL serializes it as toDateTime64(..., 6, <team_tz>)
# instead of a bare string that would be coerced in the team's timezone.
+ outcome_definition = get_outcome_definition(output_type)
+ # nosemgrep: hogql-fstring-audit (the predicate comes from fixed internal output-type definitions)
query = parse_select(
- """
+ f"""
SELECT min(ts) FROM (
SELECT timestamp as ts
FROM events
WHERE event = '$ai_evaluation'
- AND properties.$ai_evaluation_id = {evaluation_id}
- AND timestamp <= {before}
+ AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {outcome_definition.event_predicate}
+ AND timestamp <= {{before}}
ORDER BY timestamp DESC
- LIMIT {limit}
+ LIMIT {{limit}}
)
""",
placeholders={
@@ -306,6 +311,7 @@ async def prepare_report_context_activity(
evaluation_id=str(evaluation.id),
n=report.trigger_threshold or 100,
before=now,
+ output_type=evaluation.output_type,
)
else:
period_start = now - _period_for_scheduled_report(report, now)
@@ -334,6 +340,7 @@ async def prepare_report_context_activity(
evaluation_description=evaluation.description or "",
evaluation_prompt=evaluation.evaluation_config.get("prompt", ""),
evaluation_type=evaluation.evaluation_type,
+ output_type=evaluation.output_type,
period_start=period_start.isoformat(),
period_end=period_end.isoformat(),
previous_period_start=previous_period_start.isoformat(),
@@ -367,6 +374,7 @@ async def run_eval_report_agent_activity(
evaluation_description=inputs.evaluation_description,
evaluation_prompt=inputs.evaluation_prompt,
evaluation_type=inputs.evaluation_type,
+ output_type=inputs.output_type,
period_start=inputs.period_start,
period_end=inputs.period_end,
previous_period_start=inputs.previous_period_start,
@@ -395,14 +403,17 @@ async def store_report_run_activity(
from posthog.models.event.util import create_event
from posthog.models.team import Team
+ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import ( # noqa: PLC0415 -- keeps report agent dependencies off the activity import path
+ EvalReportMetrics,
+ normalize_report_content_payload,
+ )
from products.ai_observability.backend.models.evaluation_reports import EvaluationReportRun
- # Mirror content.metrics into the legacy `metadata` JSONField so existing
- # consumers that read from it (e.g. the UI's run preview before Commit 2's
- # frontend refresh) still work.
- content = inputs.content or {}
+ # Mirror content.metrics into the legacy `metadata` JSONField for consumers that still read it.
+ content = normalize_report_content_payload(inputs.content or {})
metrics = content.get("metrics", {}) or {}
+ parsed_metrics = EvalReportMetrics.from_dict(metrics)
run = EvaluationReportRun.objects.create(
report_id=inputs.report_id,
@@ -426,20 +437,30 @@ async def store_report_run_activity(
"$ai_report_title": content.get("title", ""),
"$ai_report_period_start": inputs.period_start,
"$ai_report_period_end": inputs.period_end,
- # Metrics for querying/alerting (flattened from content.metrics)
- "$ai_report_total_runs": metrics.get("total_runs", 0),
- "$ai_report_pass_count": metrics.get("pass_count", 0),
- "$ai_report_fail_count": metrics.get("fail_count", 0),
- "$ai_report_na_count": metrics.get("na_count", 0),
- "$ai_report_pass_rate": metrics.get("pass_rate", 0.0),
- "$ai_report_previous_pass_rate": metrics.get("previous_pass_rate"),
- "$ai_report_previous_total_runs": metrics.get("previous_total_runs"),
+ "$ai_report_output_type": parsed_metrics.output_type,
+ "$ai_report_result_counts": parsed_metrics.result_counts,
+ "$ai_report_result_rates": parsed_metrics.result_rates,
+ "$ai_report_previous_result_counts": parsed_metrics.previous_result_counts,
+ "$ai_report_previous_result_rates": parsed_metrics.previous_result_rates,
+ "$ai_report_total_runs": parsed_metrics.total_runs,
+ "$ai_report_previous_total_runs": parsed_metrics.previous_total_runs,
# Structured content + citations for downstream consumption
"$ai_report_content": content,
"$ai_report_citations": citations,
"$ai_report_referenced_generation_ids": all_referenced_ids,
"$ai_report_section_count": len(content.get("sections", [])),
}
+ if parsed_metrics.output_type == "boolean":
+ # Preserve the original flat properties for existing boolean-report consumers.
+ properties.update(
+ {
+ "$ai_report_pass_count": parsed_metrics.result_counts["pass"],
+ "$ai_report_fail_count": parsed_metrics.result_counts["fail"],
+ "$ai_report_na_count": parsed_metrics.result_counts["na"],
+ "$ai_report_pass_rate": parsed_metrics.pass_rate,
+ "$ai_report_previous_pass_rate": parsed_metrics.previous_pass_rate,
+ }
+ )
create_event(
event_uuid=uuid.uuid4(),
diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.py
index adf9620b624a..aee5e631518a 100644
--- a/posthog/temporal/ai_observability/eval_reports/delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py
@@ -34,6 +34,11 @@ _EMAIL_TH_STYLE = (
)
_EMAIL_TD_STYLE = 'style="border: 1px solid #ddd; padding: 8px 12px;"'
+_OUTCOME_LABELS = {
+ "boolean": (("pass", "Pass"), ("fail", "Fail"), ("na", "N/A")),
+ "sentiment": (("positive", "Positive"), ("neutral", "Neutral"), ("negative", "Negative")),
+}
+
def _inline_email_styles(html: str) -> str:
"""Add inline styles to HTML elements for email client compatibility."""
@@ -123,65 +128,59 @@ def _format_pass_rate(rate: float | None) -> str:
return f"{rate:.2f}%"
-def _render_metrics_block_html(metrics: EvalReportMetrics) -> str:
- """Render the metrics block as HTML (table + period-over-period row).
+def _format_outcome_value(metrics: EvalReportMetrics, outcome: str) -> str:
+ count = metrics.result_counts[outcome]
+ if metrics.output_type == "boolean":
+ return str(count)
- Lives at the top of the email body so the reader sees the trusted numbers
- before reading the agent's analysis.
- """
- period = f"{_format_period_for_display(metrics.period_start)} → {_format_period_for_display(metrics.period_end)}"
- delta = ""
- if metrics.previous_pass_rate is not None:
- diff = metrics.pass_rate - metrics.previous_pass_rate
- arrow = "▲" if diff > 0 else ("▼" if diff < 0 else "—")
- delta = f" ({arrow} {abs(diff):.2f}pp vs previous)"
-
- table = (
- "<table>"
- "<tr><th>Total runs</th><th>Pass</th><th>Fail</th><th>N/A</th><th>Pass rate</th></tr>"
- f"<tr>"
- f"<td>{metrics.total_runs}</td>"
- f"<td>{metrics.pass_count}</td>"
- f"<td>{metrics.fail_count}</td>"
- f"<td>{metrics.na_count}</td>"
- f"<td><strong>{_format_pass_rate(metrics.pass_rate)}</strong>{delta}</td>"
- f"</tr>"
- "</table>"
- )
- table = _inline_email_styles(table)
- return f'<p class="muted"><strong>Period</strong>: {period}</p>\n{table}\n'
+ rate = metrics.result_rates.get(outcome)
+ value = str(count) if rate is None else f"{count} ({_format_pass_rate(rate)})"
+ previous_rate = (metrics.previous_result_rates or {}).get(outcome)
+ if rate is None or previous_rate is None:
+ return value
-def _build_pass_rate_bar(pass_rate: float, width: int = 30) -> str:
- """Build an ASCII bar representing the pass rate percentage."""
- filled = round(pass_rate / 100 * width)
- return "█" * filled + "·" * (width - filled)
+ diff = rate - previous_rate
+ arrow = "▲" if diff > 0 else ("▼" if diff < 0 else "•")
+ return f"{value} {arrow} {abs(diff):.2f}pp"
-def _render_metrics_slack_blocks(metrics: EvalReportMetrics) -> list[dict]:
- """Render the metrics block as a Slack code block with ASCII dashboard style."""
- W = 36 # inner width between │ pipes
+def _format_boolean_pass_rate_value(metrics: EvalReportMetrics) -> str:
+ value = _format_pass_rate(metrics.pass_rate)
+ if metrics.previous_pass_rate is None:
+ return value
- delta = ""
- if metrics.previous_pass_rate is not None:
- diff = metrics.pass_rate - metrics.previous_pass_rate
- arrow = "▲" if diff > 0 else ("▼" if diff < 0 else "—")
- delta = f" {arrow} {abs(diff):.2f}pp"
+ diff = metrics.pass_rate - metrics.previous_pass_rate
+ arrow = "▲" if diff > 0 else ("▼" if diff < 0 else "•")
+ return f"{value} ({arrow} {abs(diff):.2f}pp vs previous)"
- bar = _build_pass_rate_bar(metrics.pass_rate)
- rate = _format_pass_rate(metrics.pass_rate)
- runs_label = f"{metrics.total_runs} runs"
- # Line with rate left-aligned and runs right-aligned
- rate_str = f" {rate}{delta}"
- rate_line = f"{rate_str}{runs_label:>{W - len(rate_str)}}"
+def _render_metrics_block_html(metrics: EvalReportMetrics) -> str:
+ """Render trusted outcome counts and rates as an HTML table.
- counts = f" pass {metrics.pass_count} · fail {metrics.fail_count} · n/a {metrics.na_count}"
+ Lives at the top of the email body so the reader sees the trusted numbers
+ before reading the agent's analysis.
+ """
+ period = f"{_format_period_for_display(metrics.period_start)} → {_format_period_for_display(metrics.period_end)}"
+ 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":
+ 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>"
+ table = _inline_email_styles(table)
+ return f'<p class="muted"><strong>Period</strong>: {period}</p>\n{table}\n'
- top = f"┌─ pass rate {'─' * (W - 12)}┐"
- bot = f"└{'─' * W}┘"
- code_block = f"{top}\n│{f' {bar}':<{W}}│\n│{rate_line:<{W}}│\n│{counts:<{W}}│\n{bot}"
+def _render_metrics_slack_blocks(metrics: EvalReportMetrics) -> list[dict]:
+ """Render the metrics block as a compact, output-type-neutral Slack dashboard."""
+ outcome_lines = [
+ f"{label}: {_format_outcome_value(metrics, outcome)}" for outcome, label in _OUTCOME_LABELS[metrics.output_type]
+ ]
+ if metrics.output_type == "boolean":
+ outcome_lines.append(f"Pass rate: {_format_boolean_pass_rate_value(metrics)}")
+ code_block = "\n".join([f"Total runs: {metrics.total_runs}", *outcome_lines])
blocks: list[dict] = [
{
diff --git a/posthog/temporal/ai_observability/eval_reports/emit_signal.py b/posthog/temporal/ai_observability/eval_reports/emit_signal.py
index 10ee26f15647..203cb870e5c4 100644
--- a/posthog/temporal/ai_observability/eval_reports/emit_signal.py
+++ b/posthog/temporal/ai_observability/eval_reports/emit_signal.py
@@ -73,13 +73,14 @@ SUMMARIZE_REPORT_SYSTEM_PROMPT = """You are a concise technical writer. Your job
Unlike a per-result signal (one judge verdict), a report is an analytical narrative over many evaluation results in a time window. It already contains a title, several titled sections, metrics, and citations to specific generations. Your output should distill that narrative into a signal that fits alongside signals from other observability tools.
You will be given:
-- Evaluation context: name, optional description, and the judge criteria prompt
+- Evaluation context: name, optional description, and evaluation criteria when applicable
- Report period (start/end timestamps)
-- Report content: the agent-chosen title, sections (each with a title and markdown body), citations, and structured metrics (total_runs, pass_count, fail_count, na_count, pass_rate, previous_pass_rate)
+- Report content: the agent-chosen title, sections (each with a title and markdown body), citations, and structured metrics. Metrics include the evaluation output type plus current and previous outcome counts and rates.
Produce:
1. A short title (max 100 chars) capturing the report's main finding as a statement, not a question.
Good: "Pass rate dropped 14pp on the cost-cap eval"
+ Good: "Negative sentiment concentrated in checkout questions"
Good: "Tool-call loops concentrated in the weekend refresh batch"
Bad: "Evaluation report for cost-cap-v2"
Bad: "Pass rate was 72%"
@@ -87,7 +88,7 @@ Produce:
2. A 4-8 sentence description that explains:
- Open with what the evaluation is measuring (derived from the evaluation name, description, and judge criteria prompt). Name the evaluation explicitly — the reader may have no prior context. One sentence is enough.
- What changed or is notable about the evaluation's behavior over the period
- - Concrete metrics that support the finding (pass_rate, delta vs previous period if available, total_runs)
+ - Concrete metrics that support the finding (outcome rates, period-over-period changes, and total runs)
- Any pattern the report identifies (e.g. specific failure mode, particular model, time-of-day clustering)
- If citations are present, reference that traces are available for investigation
@@ -98,7 +99,7 @@ Produce:
- 0.8-0.9 = high, should be prioritized
- 1.0 = critical, act immediately
-Base significance on: magnitude of pass_rate change, absolute failure rate, breadth across generations (citation count as proxy), and how actionable the finding is from the report's prose.
+Base significance on: the magnitude of the outcome-distribution change, the prevalence of concerning outcomes in the evaluation's own semantics, breadth across generations (citation count as proxy), and how actionable the finding is from the report's prose. A sentiment label describes the user's message, not whether the AI response was good or bad.
The output will be fed into a signal grouping and investigation system that groups related findings across observability tools. Write for an engineer who hasn't seen this evaluation before.
@@ -121,7 +122,7 @@ def _build_eval_report_signal_prompt(inputs: EmitEvalReportSignalInputs, content
if inputs.evaluation_description:
parts.append(f"\nEVALUATION DESCRIPTION: {inputs.evaluation_description}")
if inputs.evaluation_prompt:
- parts.append(f"\nEVALUATION PROMPT (judge criteria):\n{inputs.evaluation_prompt}")
+ parts.append(f"\nEVALUATION CRITERIA:\n{inputs.evaluation_prompt}")
parts.append(f"\nREPORT PERIOD: {inputs.period_start} → {inputs.period_end}")
parts.append(f"\nREPORT CONTENT (JSON):\n{json.dumps(content, default=str)}")
return "\n".join(parts)
diff --git a/posthog/temporal/ai_observability/eval_reports/output_types.py b/posthog/temporal/ai_observability/eval_reports/output_types.py
new file mode 100644
index 000000000000..a0e96547cf82
--- /dev/null
+++ b/posthog/temporal/ai_observability/eval_reports/output_types.py
@@ -0,0 +1,52 @@
+"""Trusted query definitions for evaluation report outcomes."""
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class EvaluationReportOutcomeDefinition:
+ outcomes: tuple[str, ...]
+ outcome_predicates: Mapping[str, str]
+ event_predicate: str
+ result_expression: str
+ applicable_expression: str
+ score_expression: str
+
+
+_OUTCOME_DEFINITIONS: Mapping[str, EvaluationReportOutcomeDefinition] = {
+ "boolean": EvaluationReportOutcomeDefinition(
+ outcomes=("pass", "fail", "na"),
+ outcome_predicates={
+ "pass": "properties.$ai_evaluation_result = true AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)",
+ "fail": "properties.$ai_evaluation_result = false AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)",
+ "na": "properties.$ai_evaluation_applicable = false",
+ },
+ event_predicate="(properties.$ai_evaluation_result_type = 'boolean' OR isNull(properties.$ai_evaluation_result_type))",
+ result_expression="properties.$ai_evaluation_result",
+ applicable_expression="properties.$ai_evaluation_applicable",
+ score_expression="NULL",
+ ),
+ "sentiment": EvaluationReportOutcomeDefinition(
+ outcomes=("positive", "neutral", "negative"),
+ outcome_predicates={
+ "positive": "properties.$ai_sentiment_label = 'positive'",
+ "neutral": "properties.$ai_sentiment_label = 'neutral'",
+ "negative": "properties.$ai_sentiment_label = 'negative'",
+ },
+ event_predicate="properties.$ai_evaluation_result_type = 'sentiment'",
+ result_expression="properties.$ai_sentiment_label",
+ applicable_expression="NULL",
+ score_expression="properties.$ai_sentiment_score",
+ ),
+}
+
+SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = tuple(_OUTCOME_DEFINITIONS)
+
+
+def get_outcome_definition(output_type: str | None) -> EvaluationReportOutcomeDefinition:
+ normalized_output_type = output_type or "boolean"
+ try:
+ return _OUTCOME_DEFINITIONS[normalized_output_type]
+ except KeyError as error:
+ raise ValueError(f"Unsupported evaluation report output type: {normalized_output_type}") from 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 0acc7087ea69..df0759a4732b 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -12,7 +12,8 @@ from langgraph.prebuilt import create_react_agent
from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from posthog.llm.gateway_client import resolve_ai_gateway_config
-from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import EVAL_REPORT_SYSTEM_PROMPT
+from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
+from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import build_eval_report_system_prompt
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
MIN_REPORT_SECTIONS,
@@ -24,7 +25,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.state import Ev
from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
EVAL_REPORT_TOOLS,
_ch_ts,
- _fetch_period_counts,
+ _fetch_period_summary,
)
from posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_client
@@ -37,6 +38,7 @@ def _compute_metrics(
period_start: str,
period_end: str,
previous_period_start: str,
+ output_type: str = "boolean",
) -> EvalReportMetrics:
"""Compute report metrics directly via HogQL (independent of agent state).
@@ -44,33 +46,27 @@ def _compute_metrics(
with zero counts and logs the exception. The agent cannot fabricate numbers
because this function is the sole source of truth for `content.metrics`.
"""
- empty = EvalReportMetrics(period_start=period_start, period_end=period_end)
+ empty = EvalReportMetrics(output_type=output_type, period_start=period_start, period_end=period_end)
try:
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)
- pass_count, fail_count, na_count, total = _fetch_period_counts(team_id, evaluation_id, ts_start, ts_end)
- prev_pass, prev_fail, _prev_na, prev_total = _fetch_period_counts(
- team_id, evaluation_id, ts_prev_start, ts_start
+ result_counts, total = _fetch_period_summary(team_id, evaluation_id, ts_start, ts_end, definition)
+ previous_result_counts, previous_total = _fetch_period_summary(
+ team_id, evaluation_id, ts_prev_start, ts_start, definition
)
- applicable = pass_count + fail_count
- pass_rate = round(pass_count / applicable * 100, 2) if applicable > 0 else 0.0
- prev_applicable = prev_pass + prev_fail
- previous_pass_rate = round(prev_pass / prev_applicable * 100, 2) if prev_applicable > 0 else None
-
return EvalReportMetrics(
+ output_type=output_type,
total_runs=total,
- pass_count=pass_count,
- fail_count=fail_count,
- na_count=na_count,
- pass_rate=pass_rate,
+ result_counts=result_counts,
period_start=period_start,
period_end=period_end,
- previous_total_runs=prev_total,
- previous_pass_rate=previous_pass_rate,
+ previous_total_runs=previous_total,
+ previous_result_counts=previous_result_counts,
)
except Exception:
logger.exception("llma_eval_reports_metrics_computation_failed")
@@ -90,7 +86,7 @@ def _fallback_content(evaluation_name: str, metrics: EvalReportMetrics, reason:
f"Check that the evaluation is enabled and that `$ai_generation` events "
f"are being ingested."
)
- else:
+ elif metrics.output_type == "boolean":
trend = ""
if metrics.previous_pass_rate is not None:
diff = metrics.pass_rate - metrics.previous_pass_rate
@@ -103,8 +99,29 @@ def _fallback_content(evaluation_name: str, metrics: EvalReportMetrics, reason:
summary = (
f"**Pass rate: {metrics.pass_rate}%**{trend} across {metrics.total_runs} runs. "
- f"{metrics.pass_count} passed, {metrics.fail_count} failed, {metrics.na_count} N/A."
+ f"{metrics.result_counts['pass']} passed, {metrics.result_counts['fail']} failed, "
+ f"{metrics.result_counts['na']} N/A."
)
+ else:
+ positive_rate = metrics.result_rates["positive"]
+ trend = ""
+ previous_positive_rate = (
+ metrics.previous_result_rates.get("positive") if metrics.previous_result_rates is not None else None
+ )
+ if previous_positive_rate is not None:
+ diff = positive_rate - previous_positive_rate
+ if diff > 1:
+ trend = f"; Positive is up from {previous_positive_rate}%"
+ elif diff < -1:
+ trend = f"; Positive is down from {previous_positive_rate}%"
+ else:
+ trend = f"; Positive is stable vs {previous_positive_rate}%"
+
+ distribution = ", ".join(
+ f"{label} {metrics.result_rates[outcome]}% ({metrics.result_counts[outcome]} {outcome})"
+ for outcome, label in (("positive", "Positive"), ("neutral", "Neutral"), ("negative", "Negative"))
+ )
+ summary = f"**Outcome distribution:** {distribution}{trend}, across {metrics.total_runs} runs."
return EvalReportContent(
title=f"Automated fallback report for {evaluation_name}",
@@ -166,6 +183,7 @@ def run_eval_report_agent(
period_end: str,
previous_period_start: str,
report_prompt_guidance: str = "",
+ output_type: str = "boolean",
) -> EvalReportContent:
"""Run the evaluation report agent and return the generated content.
@@ -181,31 +199,26 @@ def run_eval_report_agent(
# Compute metrics first — we need them for both the final content AND the
# fallback path, so guarantee they're ready before the agent even runs.
- metrics = _compute_metrics(team_id, evaluation_id, period_start, period_end, previous_period_start)
+ metrics = _compute_metrics(
+ team_id,
+ evaluation_id,
+ period_start,
+ period_end,
+ previous_period_start,
+ output_type=output_type,
+ )
llm = build_langchain_chat_client(EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports")
- 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 = ""
- if report_prompt_guidance and report_prompt_guidance.strip():
- guidance_section = (
- "\n## Additional guidance from the user (per-report)\n\n"
- "The user provided the following custom guidance for this specific report. "
- "Treat it as a steer on focus / scope / section choices, not as a replacement "
- "for the core instructions above.\n\n"
- f"```\n{report_prompt_guidance.strip()}\n```\n"
- )
-
- system_prompt = EVAL_REPORT_SYSTEM_PROMPT.format(
+ system_prompt = build_eval_report_system_prompt(
evaluation_name=evaluation_name,
- evaluation_description_section=description_section,
+ evaluation_description=evaluation_description,
evaluation_type=evaluation_type,
- evaluation_prompt_section=prompt_section,
+ evaluation_prompt=evaluation_prompt,
+ output_type=output_type,
period_start=period_start,
period_end=period_end,
- report_prompt_guidance_section=guidance_section,
- max_sections=MAX_REPORT_SECTIONS,
+ report_prompt_guidance=report_prompt_guidance,
)
agent = create_react_agent(
@@ -226,6 +239,7 @@ def run_eval_report_agent(
"evaluation_description": evaluation_description,
"evaluation_prompt": evaluation_prompt,
"evaluation_type": evaluation_type,
+ "output_type": output_type,
"period_start": period_start,
"period_end": period_end,
"previous_period_start": 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 9ed45c91f4c2..4b86fccedaeb 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
@@ -1,4 +1,7 @@
-"""System prompt for the evaluation report agent (v2 — agent-chosen sections)."""
+"""System prompt construction for the evaluation report agent."""
+
+from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
+from posthog.temporal.ai_observability.eval_reports.report_agent.schema import MAX_REPORT_SECTIONS
EVAL_REPORT_SYSTEM_PROMPT = """You are an evaluation report agent for PostHog's AI observability platform. Your job is to analyze results from an LLM evaluation and produce a concise, grounded, example-backed report.
@@ -7,7 +10,7 @@ EVAL_REPORT_SYSTEM_PROMPT = """You are an evaluation report agent for PostHog's
Evaluation: **{evaluation_name}**
{evaluation_description_section}Evaluation type: {evaluation_type}
{evaluation_prompt_section}
-**Pass / fail semantics:** The evaluation returns a boolean. **True = pass** means the generation satisfied the criteria above. **False = fail** means it did not. Read the criteria carefully — a "fail" is not inherently bad. For example, if the criterion is "detect frustration", then fail = no frustration detected, which is correct behavior on a neutral query. Always interpret results through the lens of the evaluation's specific criteria, not a generic "pass = good / fail = bad" assumption.
+**Result semantics:** {result_semantics}
Report period: {period_start} → {period_end}
@@ -15,57 +18,106 @@ Report period: {period_start} → {period_end}
You build the report incrementally by calling three output tools:
-1. **`set_title(title)`** — **call exactly once**. One scannable headline that tells the reader the main finding at a glance. Not generic — specific. Examples:
- - "Pass rate steady at 94%, dip in 14:00 UTC bucket"
- - "Volume dropped to zero — likely pipeline issue"
- - "Cost regression: gpt-5-mini 3x more expensive than last week"
-
-2. **`add_section(title, content)`** — **call 1 to {max_sections} times**. Each call appends a titled markdown section. The FIRST section you add is the TL;DR (it lands as the Slack main message). Following sections go into the thread. Prefer fewer substantive sections over many with filler.
-
-3. **`add_citation(generation_id, trace_id, reason)`** — **call for every example you discuss**. Structured trace references supporting your findings. Always call `sample_generation_details` first to verify the generation exists and get its `trace_id` — you must pass both. Use a short free-form `reason` like `"high_cost"`, `"refusal"`, `"regression_at_14:00"`, `"empty_output"`. A report without citations is a report without evidence.
+1. **`set_title(title)`**: call exactly once. Write one specific, scannable headline that tells the reader the main finding at a glance.
+2. **`add_section(title, content)`**: call 1 to {max_sections} times. The first section is the TL;DR. Prefer fewer substantive sections over filler.
+3. **`add_citation(generation_id, trace_id, reason)`**: call for every example you discuss. Always call `sample_generation_details` first to verify the generation and get its `trace_id`.
-## What NOT to do
+## What not to do
-- **Don't restate raw numbers in prose.** The UI/email/Slack renders `metrics` (total_runs, pass/fail counts, pass rate, period-over-period delta) as a separate structured block. Your job is analysis on top of the numbers, not re-transcription. Bad: "Pass rate: 94.34%. Total runs: 53. Pass count: 50..." Good: "The late-period dip in the 14:00 bucket accounts for ~2 points of the pass-rate decline."
-- **Don't invent sections just to fill space.** If the report is boring (healthy, no regressions), 1 or 2 sections is fine. If it's interesting, 3-5 is plenty. Never 6 unless you genuinely need all 6.
-- **Don't speculate beyond the data.** Every claim should be traceable to a tool call result. If you're uncertain, say so explicitly.
-- **Don't emit emoji or marketing-speak.** Be technical and factual.
+- Don't restate raw numbers in prose. The viewer renders trusted metrics, including total runs and result counts, rates, and period-over-period comparisons. Analyze the numbers instead of transcribing them.
+- Don't invent sections just to fill space. One or two sections is enough for a routine report.
+- Don't speculate beyond the data. Every claim should be traceable to a tool result. State uncertainty clearly.
+- Don't emit emoji or marketing language. Be technical and factual.
## Query tools available
-- **`get_summary_metrics()`** — pass/fail/NA counts and pass rate, current and previous period. Good first call to orient.
-- **`get_pass_rate_over_time(bucket="hour"|"day")`** — time-series pass rate buckets. Use to spot trends and anomalies.
-- **`get_top_failure_reasons(limit)`** — grouped failure `reasoning` strings with counts. Good for quick failure-mode overview.
-- **`list_all_eval_results(max_reasoning_length=80)`** — compact overview of ALL results: verdict + generation_id + truncated reasoning per row. Call this early to see the full picture before drilling into specifics.
-- **`sample_eval_results(filter="all"|"pass"|"fail"|"na", limit)`** — sample eval run rows including generation_id + verdict + full reasoning.
-- **`sample_generation_details(generation_ids)`** — full generation data (input, output, model, tokens, **trace_id**). REQUIRED before citing — gives you the trace_id to pass to `add_citation`.
-- **`list_recent_report_runs(since_days, limit)`** — compact index of prior runs for this evaluation: run_id + title + period + pass_rate. Use to scan what past reports covered before drilling in.
-- **`get_report_run(run_id)`** — full content of a specific past run, looked up via `list_recent_report_runs`. Use for delta analysis / continuity with earlier findings.
+- **`get_summary_metrics()`**: outcome counts and rates for the current and previous periods. Call this first.
+- **`get_result_distribution_over_time(bucket="hour"|"day")`**: time-series outcome distributions. Use it to spot trends and anomalies.
+- **`get_top_outcome_reasons(outcome, limit)`**: grouped reasoning strings for one outcome. If omitted, outcome defaults to `{analysis_outcome}`.
+- **`list_all_eval_results(max_reasoning_length=80)`**: compact overview of all results, with outcome, generation ID, score when available, and truncated reasoning.
+- **`sample_eval_results(outcome="all"|{outcome_options}, limit)`**: sample evaluation rows with their full reasoning.
+- **`sample_generation_details(generation_ids)`**: generation data including input, output, model, tokens, and trace ID. Call this before citing.
+- **`get_generation_detail(generation_id)`**: complete data for one generation and its evaluation results.
+- **`list_recent_report_runs(since_days, limit)`**: compact index of prior runs with title, period, total runs, and result rates.
+- **`get_report_run(run_id)`**: full content for a prior report run.
-## Grounding rule — every claim needs an example
+## Grounding rule
-Your report is only useful if the reader can click through to real examples. For every failure pattern or quality issue you describe, you MUST:
+For every recurring outcome pattern or quality issue you describe:
-1. Call `sample_eval_results(filter="fail")` to get generation_ids.
-2. Call `sample_generation_details(generation_ids)` to get the trace_id and actual input/output.
-3. Call `add_citation(generation_id, trace_id, reason)` for each example.
-4. Reference the example inline in your section content by writing the generation_id in backticks, e.g. `<generation_id>` — the renderer turns these into clickable trace links. Use single backticks only, never double backticks.
+1. Call `sample_eval_results(outcome="{analysis_outcome}")` to find candidate generation IDs. Sample `{primary_outcome}` as contrast when useful.
+2. Call `sample_generation_details(generation_ids)` to inspect the actual input and output and obtain each trace ID.
+3. Call `add_citation(generation_id, trace_id, reason)` for each example you use.
+4. Reference the generation ID inline with single backticks so the renderer can link it.
-If `sample_generation_details` returns empty for a generation_id, try others from the same filter. If none resolve, note that as a data quality issue but still try passing generations too — they provide useful contrast.
+If a generation cannot be resolved, try another example. If none resolve, report the data-quality limitation.
## Suggested workflow
-1. Call `get_summary_metrics()` — orient on volume and pass rate.
-2. Call `list_all_eval_results()` — scan every result at a glance. Look for patterns in verdicts and reasoning before diving deeper.
-3. Call `get_pass_rate_over_time(bucket="hour")` or `"day"` — spot trends.
-4. Call `get_top_failure_reasons()` if there are any failures.
-5. Call `sample_eval_results(filter="fail")` to get failing generation_ids with full reasoning. Also `sample_eval_results(filter="pass")` for contrast examples.
-6. Call `sample_generation_details(...)` on 3-5 interesting generation_ids (mix of pass and fail) to get trace_ids + full content. This is NOT optional — you need trace_ids to cite.
-7. (Optional) Call `list_recent_report_runs()` to see what recent runs covered, then `get_report_run(run_id)` on one or two interesting ones for continuity with prior analyses.
-8. Decide your title and section structure.
-9. Call `set_title(...)` once.
-10. Call `add_section(...)` 1 to {max_sections} times — first section is the TL;DR. Embed `<generation_id>` references inline so readers can click through to examples.
-11. Call `add_citation(...)` for each trace you discussed — at minimum 2-3 per report.
-12. Return — the graph automatically computes and attaches the trusted metrics.
+1. Call `get_summary_metrics()` and `list_all_eval_results()`.
+2. Call `get_result_distribution_over_time(bucket="hour")` or `"day"`.
+3. Inspect grouped reasons and sample relevant outcomes, using `{analysis_outcome}` and `{primary_outcome}` as starting points.
+4. Call `sample_generation_details(...)` on 3-5 useful examples.
+5. Optionally inspect recent report runs for continuity.
+6. Set one title, add 1 to {max_sections} sections, and cite every discussed trace.
+7. Return. The graph attaches the trusted metrics automatically.
{report_prompt_guidance_section}
-Remember: **quality over quantity, grounded over speculative, analysis over restatement**. The reader should come away with a clear understanding of what happened and (if anything) what to do about it."""
+Remember: quality over quantity, grounded over speculative, analysis over restatement. The reader should understand what happened and what, if anything, to do about it."""
+
+
+def build_eval_report_system_prompt(
+ *,
+ evaluation_name: str,
+ evaluation_description: str,
+ evaluation_prompt: str,
+ evaluation_type: str,
+ output_type: str,
+ period_start: str,
+ period_end: str,
+ report_prompt_guidance: str = "",
+) -> str:
+ definition = get_outcome_definition(output_type)
+ 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 = ""
+ if report_prompt_guidance.strip():
+ guidance_section = (
+ "\n## Additional guidance from the user\n\n"
+ "Use this guidance to focus the report without replacing the instructions above.\n\n"
+ f"```\n{report_prompt_guidance.strip()}\n```\n"
+ )
+
+ if output_type == "sentiment":
+ result_semantics = (
+ "Sentiment labels classify the user messages associated with each generation as positive, neutral, or "
+ "negative. They describe the user's expressed tone, not response quality or a pass/fail verdict. The "
+ "sentiment score is model confidence in the label, not sentiment intensity."
+ )
+ analysis_outcome = "negative"
+ primary_outcome = "positive"
+ elif output_type == "boolean":
+ result_semantics = (
+ "The evaluation returns a boolean. True means the generation satisfied the configured criteria and false "
+ "means it did not. A fail is not inherently bad: always interpret pass and fail through the evaluation's "
+ "specific criteria rather than treating them as generic quality verdicts."
+ )
+ analysis_outcome = "fail"
+ primary_outcome = "pass"
+ else:
+ raise ValueError(f"Unsupported evaluation report output type: {output_type}")
+
+ outcome_options = "|".join(f'"{outcome}"' for outcome in definition.outcomes)
+ return EVAL_REPORT_SYSTEM_PROMPT.format(
+ evaluation_name=evaluation_name,
+ evaluation_description_section=description_section,
+ evaluation_type=evaluation_type,
+ evaluation_prompt_section=prompt_section,
+ result_semantics=result_semantics,
+ period_start=period_start,
+ period_end=period_end,
+ report_prompt_guidance_section=guidance_section,
+ max_sections=MAX_REPORT_SECTIONS,
+ outcome_options=outcome_options,
+ analysis_outcome=analysis_outcome,
+ primary_outcome=primary_outcome,
+ )
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 ca18a3c06228..7096c102a0c5 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py
@@ -13,6 +13,9 @@ analysis rather than number formatting.
"""
from dataclasses import dataclass, field
+from typing import Literal, overload
+
+from posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition
# Hard cap on the number of agent-chosen sections. Prevents section sprawl and
# keeps reports scannable. The agent is also instructed to lean lean — quality
@@ -21,6 +24,45 @@ MAX_REPORT_SECTIONS = 6
MIN_REPORT_SECTIONS = 1
+def normalize_result_counts(output_type: str, counts: dict[str, int] | None) -> dict[str, int]:
+ definition = get_outcome_definition(output_type)
+ source = counts or {}
+ return {outcome: int(source.get(outcome, 0)) for outcome in definition.outcomes}
+
+
+def calculate_result_rates(
+ output_type: str,
+ counts: dict[str, int],
+ *,
+ empty_as_none: bool = False,
+) -> dict[str, float] | None:
+ normalized_counts = normalize_result_counts(output_type, counts)
+ result_count = sum(normalized_counts.values())
+ if result_count == 0:
+ return None if empty_as_none else dict.fromkeys(normalized_counts, 0.0)
+ return {outcome: round(count / result_count * 100, 2) for outcome, count in normalized_counts.items()}
+
+
+@overload
+def calculate_boolean_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: ...
+
+
+@overload
+def calculate_boolean_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:
+ pass_count = counts.get("pass", 0)
+ applicable_count = pass_count + counts.get("fail", 0)
+ if applicable_count == 0:
+ return None if empty_as_none else 0.0
+ return round(pass_count / applicable_count * 100, 2)
+
+
@dataclass
class Citation:
"""A trace reference cited by the agent to ground a specific finding.
@@ -78,42 +120,165 @@ class EvalReportMetrics:
to avoid confusion; per-model/per-bucket/cost breakdowns are deferred.
"""
+ output_type: str = "boolean"
total_runs: int = 0
- pass_count: int = 0
- fail_count: int = 0
- na_count: int = 0
- pass_rate: float = 0.0
+ result_counts: dict[str, int] = field(default_factory=dict)
+ result_rates: dict[str, float] = field(default_factory=dict)
period_start: str = ""
period_end: str = ""
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)
previous_pass_rate: float | None = None
+ def __post_init__(self) -> None:
+ definition = get_outcome_definition(self.output_type)
+ self.result_counts = normalize_result_counts(self.output_type, self.result_counts)
+
+ if not self.result_rates:
+ self.result_rates = calculate_result_rates(self.output_type, self.result_counts) or {}
+ else:
+ calculated_rates = calculate_result_rates(self.output_type, self.result_counts) or {}
+ self.result_rates = {
+ outcome: float(self.result_rates.get(outcome, calculated_rates[outcome]))
+ for outcome in definition.outcomes
+ }
+
+ if self.previous_result_counts is not None:
+ self.previous_result_counts = normalize_result_counts(self.output_type, self.previous_result_counts)
+ if self.previous_result_rates is None:
+ if self.previous_result_counts is not None:
+ self.previous_result_rates = calculate_result_rates(
+ self.output_type, self.previous_result_counts, empty_as_none=True
+ )
+ elif self.previous_result_counts is not None:
+ calculated_previous_rates = calculate_result_rates(self.output_type, self.previous_result_counts) or {}
+ self.previous_result_rates = {
+ outcome: float(self.previous_result_rates.get(outcome, calculated_previous_rates[outcome]))
+ for outcome in definition.outcomes
+ }
+ else:
+ self.previous_result_rates = {
+ outcome: float(rate)
+ for outcome, rate in self.previous_result_rates.items()
+ if outcome in definition.outcomes
+ }
+
+ if self.output_type == "boolean":
+ self.pass_rate = calculate_boolean_pass_rate(self.result_counts)
+ if self.previous_result_counts is not None:
+ self.previous_pass_rate = calculate_boolean_pass_rate(self.previous_result_counts, empty_as_none=True)
+ else:
+ self.previous_pass_rate = None
+
def to_dict(self) -> dict:
- return {
+ metrics = {
+ "output_type": self.output_type,
"total_runs": self.total_runs,
- "pass_count": self.pass_count,
- "fail_count": self.fail_count,
- "na_count": self.na_count,
- "pass_rate": self.pass_rate,
+ "result_counts": self.result_counts,
+ "result_rates": self.result_rates,
"period_start": self.period_start,
"period_end": self.period_end,
"previous_total_runs": self.previous_total_runs,
- "previous_pass_rate": self.previous_pass_rate,
+ "previous_result_counts": self.previous_result_counts,
+ "previous_result_rates": self.previous_result_rates,
}
+ if self.output_type == "boolean":
+ metrics.update(
+ {
+ "pass_rate": self.pass_rate,
+ "previous_pass_rate": self.previous_pass_rate,
+ }
+ )
+ return metrics
@staticmethod
def from_dict(data: dict) -> "EvalReportMetrics":
- return EvalReportMetrics(
+ output_type = data.get("output_type", "boolean")
+ result_counts = dict(data.get("result_counts") or {})
+ if output_type == "boolean" and "result_counts" not in data:
+ result_counts = {
+ "pass": data.get("pass_count", 0),
+ "fail": data.get("fail_count", 0),
+ "na": data.get("na_count", 0),
+ }
+
+ metrics = EvalReportMetrics(
+ output_type=output_type,
total_runs=data.get("total_runs", 0),
- pass_count=data.get("pass_count", 0),
- fail_count=data.get("fail_count", 0),
- na_count=data.get("na_count", 0),
- pass_rate=data.get("pass_rate", 0.0),
+ result_counts=result_counts,
+ result_rates=dict(data.get("result_rates") or {}),
period_start=data.get("period_start", ""),
period_end=data.get("period_end", ""),
previous_total_runs=data.get("previous_total_runs"),
+ previous_result_counts=(
+ dict(data["previous_result_counts"]) if data.get("previous_result_counts") is not None else None
+ ),
+ previous_result_rates=(
+ dict(data["previous_result_rates"]) if data.get("previous_result_rates") is not None else None
+ ),
previous_pass_rate=data.get("previous_pass_rate"),
)
+ if metrics.output_type == "boolean" 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:
+ metrics.previous_pass_rate = float(data["previous_pass_rate"])
+ return metrics
+
+
+_LEGACY_BOOLEAN_COUNT_FIELDS = frozenset({"pass_count", "fail_count", "na_count"})
+
+
+_KNOWN_METRIC_FIELDS = {
+ "output_type",
+ "total_runs",
+ "result_counts",
+ "result_rates",
+ "period_start",
+ "period_end",
+ "previous_total_runs",
+ "previous_result_counts",
+ "previous_result_rates",
+ "pass_rate",
+ "previous_pass_rate",
+} | _LEGACY_BOOLEAN_COUNT_FIELDS
+
+
+def _has_result_counts(data: dict) -> bool:
+ return isinstance(data.get("result_counts"), dict) or (
+ data.get("output_type", "boolean") == "boolean" and bool(_LEGACY_BOOLEAN_COUNT_FIELDS.intersection(data))
+ )
+
+
+def normalize_metrics_payload(data: dict) -> dict:
+ """Upgrade stored metrics without turning missing historical values into zero."""
+ extensions = {key: value for key, value in data.items() if key not in _KNOWN_METRIC_FIELDS}
+ normalized = EvalReportMetrics.from_dict(data).to_dict()
+
+ if not _has_result_counts(data):
+ normalized.pop("result_counts", None)
+ provided_rates = data.get("result_rates")
+ if isinstance(provided_rates, dict):
+ normalized_rates = normalized.get("result_rates", {})
+ normalized["result_rates"] = {
+ outcome: normalized_rates[outcome] for outcome in provided_rates if outcome in normalized_rates
+ }
+ else:
+ normalized.pop("result_rates", None)
+ if data.get("pass_rate") is None:
+ normalized.pop("pass_rate", None)
+
+ return {**extensions, **normalized}
+
+
+def normalize_report_content_payload(data: dict) -> dict:
+ """Upgrade a stored report at the read/write boundary without mutating it."""
+ normalized = dict(data)
+ metrics = data.get("metrics")
+ if isinstance(metrics, dict):
+ normalized["metrics"] = normalize_metrics_payload(metrics)
+ return normalized
@dataclass
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 99b8aae0c05a..8a02b1cfea41 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
@@ -28,6 +28,7 @@ class EvalReportAgentState(TypedDict):
evaluation_description: str
evaluation_prompt: str
evaluation_type: str
+ output_type: str
period_start: str
period_end: str
previous_period_start: str
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
index 78f1e88ccb17..4a661f6feefc 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py
@@ -12,7 +12,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.graph import (
_fallback_content,
_validate_agent_output,
)
-from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import EVAL_REPORT_SYSTEM_PROMPT
+from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import build_eval_report_system_prompt
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
Citation,
@@ -23,46 +23,64 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
class TestSystemPromptFormat(SimpleTestCase):
- """Sanity: prompt format slots match the kwargs passed by run_eval_report_agent."""
-
- def test_format_with_all_expected_args(self):
- formatted = EVAL_REPORT_SYSTEM_PROMPT.format(
+ def _build_prompt(self, output_type: str = "boolean", guidance: str = "") -> str:
+ return build_eval_report_system_prompt(
evaluation_name="Test Eval",
- evaluation_description_section="Description: foo\n",
+ evaluation_description="foo",
evaluation_type="llm_judge",
- evaluation_prompt_section="Prompt:\ncriteria\n",
+ evaluation_prompt="criteria",
+ output_type=output_type,
period_start="2026-04-08T14:00:00+00:00",
period_end="2026-04-08T15:00:00+00:00",
- report_prompt_guidance_section="",
- max_sections=MAX_REPORT_SECTIONS,
+ report_prompt_guidance=guidance,
)
+
+ def test_format_with_all_expected_args(self):
+ formatted = self._build_prompt()
self.assertIn("Test Eval", formatted)
self.assertIn("llm_judge", formatted)
self.assertIn(str(MAX_REPORT_SECTIONS), formatted)
self.assertNotIn("{", formatted.split("```")[0]) # No unfilled placeholders
def test_format_with_guidance_section(self):
- guidance_section = "\n## User guidance\n\n```\nFocus on cost regressions\n```\n"
- formatted = EVAL_REPORT_SYSTEM_PROMPT.format(
- evaluation_name="X",
- evaluation_description_section="",
- evaluation_type="hog",
- evaluation_prompt_section="",
- period_start="",
- period_end="",
- report_prompt_guidance_section=guidance_section,
- max_sections=MAX_REPORT_SECTIONS,
- )
+ formatted = self._build_prompt(guidance="Focus on cost regressions")
self.assertIn("Focus on cost regressions", formatted)
+ def test_sentiment_prompt_explains_semantics_without_pass_rate_framing(self):
+ formatted = self._build_prompt(output_type="sentiment")
+
+ self.assertIn("classify the user messages", formatted)
+ self.assertIn("not response quality", formatted)
+ self.assertIn('outcome="all"|"positive"|"neutral"|"negative"', formatted)
+ self.assertNotIn("pass rate", formatted.lower())
+
+
+class TestComputeMetrics(SimpleTestCase):
+ @patch.object(graph, "_fetch_period_summary")
+ def test_computes_sentiment_rates_from_all_known_labels(self, mock_fetch):
+ mock_fetch.side_effect = [
+ ({"positive": 2, "neutral": 1, "negative": 1}, 4),
+ ({"positive": 1, "neutral": 1, "negative": 0}, 2),
+ ]
+
+ metrics = graph._compute_metrics(
+ team_id=1,
+ evaluation_id="eval-id",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ previous_period_start="2026-04-08T13:00:00+00:00",
+ output_type="sentiment",
+ )
+
+ self.assertEqual(metrics.result_rates, {"positive": 50.0, "neutral": 25.0, "negative": 25.0})
+ self.assertEqual(metrics.previous_result_rates, {"positive": 50.0, "neutral": 50.0, "negative": 0.0})
+
class TestFallbackContent(SimpleTestCase):
def test_zero_runs_produces_no_runs_message(self):
metrics = EvalReportMetrics(
total_runs=0,
- pass_count=0,
- fail_count=0,
- pass_rate=0.0,
+ result_counts={"pass": 0, "fail": 0, "na": 0},
period_start="2026-04-08T14:00:00+00:00",
period_end="2026-04-08T15:00:00+00:00",
)
@@ -76,10 +94,7 @@ class TestFallbackContent(SimpleTestCase):
def test_populated_metrics_stable_trend(self):
metrics = EvalReportMetrics(
total_runs=100,
- pass_count=80,
- fail_count=20,
- na_count=0,
- pass_rate=80.0,
+ result_counts={"pass": 80, "fail": 20, "na": 0},
previous_pass_rate=80.0,
)
content = _fallback_content("Helpfulness", metrics, "validation failed")
@@ -97,16 +112,18 @@ class TestFallbackContent(SimpleTestCase):
def test_populated_metrics_trend(self, _name, pass_rate, previous_pass_rate, expected_phrase):
metrics = EvalReportMetrics(
total_runs=10,
- pass_count=int(pass_rate / 10),
- fail_count=10 - int(pass_rate / 10),
- pass_rate=pass_rate,
+ result_counts={
+ "pass": int(pass_rate / 10),
+ "fail": 10 - int(pass_rate / 10),
+ "na": 0,
+ },
previous_pass_rate=previous_pass_rate,
)
content = _fallback_content("X", metrics, "why")
self.assertIn(expected_phrase, content.sections[0].content)
def test_includes_fallback_note(self):
- metrics = EvalReportMetrics(total_runs=1, pass_count=1, pass_rate=100.0)
+ metrics = EvalReportMetrics(total_runs=1, result_counts={"pass": 1, "fail": 0, "na": 0})
content = _fallback_content("X", metrics, "custom reason here")
self.assertIn("custom reason here", content.sections[0].content)
self.assertIn("fallback", content.sections[0].content.lower())
@@ -116,6 +133,22 @@ class TestFallbackContent(SimpleTestCase):
content = _fallback_content("X", metrics, "reason")
self.assertEqual(content.citations, [])
+ def test_sentiment_fallback_reports_distribution_without_pass_rate_framing(self):
+ metrics = EvalReportMetrics(
+ output_type="sentiment",
+ total_runs=4,
+ result_counts={"positive": 2, "neutral": 1, "negative": 1},
+ previous_result_counts={"positive": 1, "neutral": 1, "negative": 0},
+ )
+
+ content = _fallback_content("Tone", metrics, "agent timed out")
+ body = content.sections[0].content
+
+ self.assertIn("Positive 50.0%", body)
+ self.assertIn("Neutral 25.0%", body)
+ self.assertIn("Negative 25.0%", body)
+ self.assertNotIn("pass rate", body.lower())
+
class TestValidateAgentOutput(SimpleTestCase):
def _valid_content(self) -> EvalReportContent:
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 a6d63b0fdf2d..faa7f7ad5ceb 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
@@ -2,6 +2,7 @@
from django.test import SimpleTestCase
+from posthog.temporal.ai_observability.eval_reports.output_types import SUPPORTED_EVAL_REPORT_OUTPUT_TYPES
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
MIN_REPORT_SECTIONS,
@@ -11,6 +12,13 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
ReportSection,
)
+from products.ai_observability.backend.models.evaluation_configs import REPORTABLE_OUTPUT_TYPES
+
+
+class TestOutputTypeRegistry(SimpleTestCase):
+ def test_backend_reportability_matches_report_adapters(self):
+ self.assertSetEqual(set(REPORTABLE_OUTPUT_TYPES), set(SUPPORTED_EVAL_REPORT_OUTPUT_TYPES))
+
class TestCitation(SimpleTestCase):
def test_to_dict(self):
@@ -61,26 +69,25 @@ class TestEvalReportMetrics(SimpleTestCase):
def test_to_dict(self):
m = EvalReportMetrics(
total_runs=100,
- pass_count=80,
- fail_count=18,
- na_count=2,
- pass_rate=81.63,
+ result_counts={"pass": 80, "fail": 18, "na": 2},
period_start="2026-04-08T14:00:00+00:00",
period_end="2026-04-08T15:00:00+00:00",
previous_total_runs=90,
- previous_pass_rate=75.0,
+ previous_result_counts={"pass": 60, "fail": 20, "na": 10},
)
self.assertEqual(
m.to_dict(),
{
+ "output_type": "boolean",
"total_runs": 100,
- "pass_count": 80,
- "fail_count": 18,
- "na_count": 2,
- "pass_rate": 81.63,
+ "result_counts": {"pass": 80, "fail": 18, "na": 2},
+ "result_rates": {"pass": 80.0, "fail": 18.0, "na": 2.0},
"period_start": "2026-04-08T14:00:00+00:00",
"period_end": "2026-04-08T15:00:00+00:00",
"previous_total_runs": 90,
+ "previous_result_counts": {"pass": 60, "fail": 20, "na": 10},
+ "previous_result_rates": {"pass": 66.67, "fail": 22.22, "na": 11.11},
+ "pass_rate": 81.63,
"previous_pass_rate": 75.0,
},
)
@@ -88,19 +95,68 @@ class TestEvalReportMetrics(SimpleTestCase):
def test_from_dict_defaults(self):
m = EvalReportMetrics.from_dict({})
self.assertEqual(m.total_runs, 0)
- self.assertEqual(m.pass_count, 0)
+ self.assertEqual(m.output_type, "boolean")
+ self.assertEqual(m.result_counts, {"pass": 0, "fail": 0, "na": 0})
+ self.assertEqual(m.result_rates, {"pass": 0.0, "fail": 0.0, "na": 0.0})
self.assertEqual(m.pass_rate, 0.0)
self.assertEqual(m.period_start, "")
self.assertIsNone(m.previous_pass_rate)
self.assertIsNone(m.previous_total_runs)
+ def test_normalizes_legacy_boolean_json(self):
+ metrics = EvalReportMetrics.from_dict(
+ {
+ "total_runs": 11,
+ "pass_count": 8,
+ "fail_count": 2,
+ "na_count": 1,
+ "pass_rate": 80.0,
+ "previous_total_runs": 5,
+ "previous_pass_rate": 60.0,
+ }
+ )
+
+ self.assertEqual(metrics.output_type, "boolean")
+ self.assertEqual(metrics.result_counts, {"pass": 8, "fail": 2, "na": 1})
+ self.assertEqual(metrics.result_rates, {"pass": 72.73, "fail": 18.18, "na": 9.09})
+ self.assertIsNone(metrics.previous_result_counts)
+ self.assertIsNone(metrics.previous_result_rates)
+ self.assertEqual(metrics.previous_pass_rate, 60.0)
+ self.assertNotIn("pass_count", metrics.to_dict())
+ self.assertNotIn("fail_count", metrics.to_dict())
+ self.assertNotIn("na_count", metrics.to_dict())
+
+ def test_preserves_legacy_pass_rate_when_counts_are_partial(self):
+ metrics = EvalReportMetrics.from_dict({"total_runs": 10, "pass_count": 9, "pass_rate": 90.0})
+
+ self.assertEqual(metrics.pass_rate, 90.0)
+ self.assertEqual(metrics.result_rates["pass"], 100.0)
+
+ def test_sentiment_metrics_roundtrip(self):
+ original = EvalReportMetrics(
+ output_type="sentiment",
+ total_runs=4,
+ result_counts={"positive": 2, "neutral": 1, "negative": 1},
+ period_start="2026-04-08T00:00:00+00:00",
+ period_end="2026-04-08T01:00:00+00:00",
+ previous_total_runs=2,
+ previous_result_counts={"positive": 1, "neutral": 1, "negative": 0},
+ )
+
+ roundtripped = EvalReportMetrics.from_dict(original.to_dict())
+
+ self.assertEqual(roundtripped, original)
+ self.assertEqual(roundtripped.result_rates, {"positive": 50.0, "neutral": 25.0, "negative": 25.0})
+ self.assertEqual(
+ roundtripped.previous_result_rates,
+ {"positive": 50.0, "neutral": 50.0, "negative": 0.0},
+ )
+ self.assertNotIn("pass_count", original.to_dict())
+
def test_roundtrip_with_nulls(self):
original = EvalReportMetrics(
total_runs=5,
- pass_count=5,
- fail_count=0,
- na_count=0,
- pass_rate=100.0,
+ result_counts={"pass": 5, "fail": 0, "na": 0},
period_start="2026-04-08T00:00:00+00:00",
period_end="2026-04-08T01:00:00+00:00",
previous_total_runs=None,
@@ -125,7 +181,7 @@ class TestEvalReportContent(SimpleTestCase):
ReportSection(title="Caveats", content="One dip at 14:00."),
],
citations=[Citation(generation_id="g1", trace_id="t1", reason="example")],
- metrics=EvalReportMetrics(total_runs=53, pass_count=50, fail_count=3, pass_rate=94.34),
+ metrics=EvalReportMetrics(total_runs=53, result_counts={"pass": 50, "fail": 3, "na": 0}),
)
d = c.to_dict()
self.assertEqual(d["title"], "Pass rate steady at 94%")
@@ -165,7 +221,7 @@ class TestEvalReportContent(SimpleTestCase):
title="T",
sections=[ReportSection(title="S", content="C")],
citations=[Citation(generation_id="g", trace_id="t", reason="r")],
- metrics=EvalReportMetrics(total_runs=1, pass_rate=100.0),
+ metrics=EvalReportMetrics(total_runs=1, result_counts={"pass": 1, "fail": 0, "na": 0}),
)
roundtripped = EvalReportContent.from_dict(original.to_dict())
self.assertEqual(roundtripped.title, original.title)
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 fee5fe6b2d9f..973e432ea067 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
@@ -4,6 +4,7 @@ import json
import datetime as dt
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.test import SimpleTestCase
from django.utils import timezone
@@ -23,6 +24,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
add_citation,
add_section,
get_report_run,
+ get_summary_metrics,
list_recent_report_runs,
set_title,
)
@@ -36,6 +38,7 @@ _add_section_fn = add_section.func # type: ignore[attr-defined]
_add_citation_fn = add_citation.func # type: ignore[attr-defined]
_list_recent_report_runs_fn = list_recent_report_runs.func # type: ignore[attr-defined]
_get_report_run_fn = get_report_run.func # type: ignore[attr-defined]
+_get_summary_metrics_fn = get_summary_metrics.func # type: ignore[attr-defined]
def _state_with_empty_report() -> dict:
@@ -88,6 +91,82 @@ class TestWidenedTsWindow(SimpleTestCase):
self.assertEqual(ts_end.year, 2099)
+class TestSummaryMetrics(SimpleTestCase):
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_boolean_keeps_pass_rate_separate_from_outcome_distribution(self, mock_execute_hogql):
+ mock_execute_hogql.side_effect = [
+ [[80, 18, 2, 100]],
+ [[7, 2, 1, 10]],
+ ]
+ state = {
+ "team_id": 1,
+ "evaluation_id": "eval-id",
+ "output_type": "boolean",
+ "period_start": "2026-04-08T14:00:00+00:00",
+ "period_end": "2026-04-08T15:00:00+00:00",
+ "previous_period_start": "2026-04-08T13:00:00+00:00",
+ }
+
+ result = json.loads(_get_summary_metrics_fn(state=state))
+
+ self.assertEqual(
+ result["current_period"]["result_rates"],
+ {"pass": 80.0, "fail": 18.0, "na": 2.0},
+ )
+ self.assertEqual(result["current_period"]["pass_rate"], 81.63)
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_boolean_current_period_preserves_zero_pass_rate_when_no_results_are_applicable(self, mock_execute_hogql):
+ mock_execute_hogql.side_effect = [
+ [[0, 0, 4, 4]],
+ [[0, 0, 3, 3]],
+ ]
+ state = {
+ "team_id": 1,
+ "evaluation_id": "eval-id",
+ "output_type": "boolean",
+ "period_start": "2026-04-08T14:00:00+00:00",
+ "period_end": "2026-04-08T15:00:00+00:00",
+ "previous_period_start": "2026-04-08T13:00:00+00:00",
+ }
+
+ result = json.loads(_get_summary_metrics_fn(state=state))
+
+ self.assertEqual(result["current_period"]["pass_rate"], 0.0)
+ self.assertIsNone(result["previous_period"]["pass_rate"])
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_sentiment_uses_label_predicates_and_returns_distribution(self, mock_execute_hogql):
+ mock_execute_hogql.side_effect = [
+ [[2, 1, 1, 4]],
+ [[1, 1, 0, 2]],
+ ]
+ state = {
+ "team_id": 1,
+ "evaluation_id": "eval-id",
+ "output_type": "sentiment",
+ "period_start": "2026-04-08T14:00:00+00:00",
+ "period_end": "2026-04-08T15:00:00+00:00",
+ "previous_period_start": "2026-04-08T13:00:00+00:00",
+ }
+
+ result = json.loads(_get_summary_metrics_fn(state=state))
+
+ self.assertEqual(result["output_type"], "sentiment")
+ self.assertEqual(
+ result["current_period"]["result_counts"],
+ {"positive": 2, "neutral": 1, "negative": 1},
+ )
+ self.assertEqual(
+ result["current_period"]["result_rates"],
+ {"positive": 50.0, "neutral": 25.0, "negative": 25.0},
+ )
+ current_query = mock_execute_hogql.call_args_list[0].args[1]
+ self.assertIn("properties.$ai_sentiment_label = 'positive'", current_query)
+ self.assertIn("properties.$ai_evaluation_result_type = 'sentiment'", current_query)
+ self.assertNotIn("properties.$ai_evaluation_result = true", current_query)
+
+
class TestUuidRegex(SimpleTestCase):
def test_matches_canonical_uuid(self):
self.assertIsNotNone(_UUID_RE.fullmatch("12345678-1234-1234-1234-123456789abc"))
@@ -305,6 +384,7 @@ class TestListAndGetReportRun(BaseTest):
self.assertEqual(result[0]["title"], "Recent report")
self.assertEqual(result[0]["pass_rate"], 94.2)
self.assertEqual(result[0]["total_runs"], 53)
+ self.assertNotIn("result_rates", result[0])
self.assertIn("run_id", result[0])
# Full content intentionally omitted
self.assertNotIn("content", result[0])
@@ -324,6 +404,8 @@ class TestListAndGetReportRun(BaseTest):
self.assertEqual(result["content"]["title"], "Recent report")
self.assertEqual(len(result["content"]["sections"]), 1)
self.assertEqual(result["metadata"]["pass_rate"], 94.2)
+ self.assertNotIn("result_counts", result["metadata"])
+ self.assertNotIn("result_rates", result["metadata"])
def test_list_includes_back_to_back_previous_run(self):
# Regression: period_end exactly equal to the current period_start used to be
@@ -354,7 +436,10 @@ class TestListAndGetReportRun(BaseTest):
content={
"title": "Content-only metrics",
"sections": [],
- "metrics": {"pass_rate": 42.5, "total_runs": 8},
+ "metrics": {
+ "total_runs": 8,
+ "result_counts": {"pass": 6, "fail": 2, "na": 0},
+ },
},
metadata={},
period_start=now - dt.timedelta(hours=2),
@@ -362,7 +447,8 @@ class TestListAndGetReportRun(BaseTest):
)
result = json.loads(_list_recent_report_runs_fn(state=self.state))
entry = next(r for r in result if r["run_id"] == str(content_only_run.id))
- self.assertEqual(entry["pass_rate"], 42.5)
+ self.assertEqual(entry["pass_rate"], 75.0)
+ self.assertEqual(entry["result_rates"], {"pass": 75.0, "fail": 25.0, "na": 0.0})
self.assertEqual(entry["total_runs"], 8)
def test_get_rejects_non_uuid(self):
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 5f2463a9d1b5..613297b92fcf 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -17,10 +17,18 @@ from langgraph.prebuilt import InjectedState
from posthog.hogql import ast
+from posthog.temporal.ai_observability.eval_reports.output_types import (
+ EvaluationReportOutcomeDefinition,
+ get_outcome_definition,
+)
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
MAX_REPORT_SECTIONS,
Citation,
ReportSection,
+ calculate_boolean_pass_rate,
+ calculate_result_rates,
+ normalize_metrics_payload,
+ normalize_report_content_payload,
)
if TYPE_CHECKING:
@@ -53,6 +61,48 @@ _WIDENED_TS_START_SENTINEL = "2020-01-01T00:00:00+00:00"
_WIDENED_TS_END_SENTINEL = "2099-01-01T00:00:00+00:00"
+def _resolve_output_type(output_type: str | None) -> tuple[str, EvaluationReportOutcomeDefinition]:
+ normalized_output_type = output_type or "boolean"
+ return normalized_output_type, get_outcome_definition(normalized_output_type)
+
+
+def _summary_select_sql(definition: EvaluationReportOutcomeDefinition) -> str:
+ count_columns = [
+ f"countIf({definition.outcome_predicates[outcome]}) as {outcome}_count" for outcome in definition.outcomes
+ ]
+ return ",\n ".join([*count_columns, "count() as total"])
+
+
+def _parse_summary_row(
+ definition: EvaluationReportOutcomeDefinition,
+ row: list[int | float | str | None] | tuple[int | float | str | None, ...] | None,
+) -> tuple[dict[str, int], int]:
+ values = row or ()
+ counts = {
+ outcome: _summary_value_as_int(values[index]) if index < len(values) else 0
+ for index, outcome in enumerate(definition.outcomes)
+ }
+ total_index = len(definition.outcomes)
+ total = _summary_value_as_int(values[total_index]) if total_index < len(values) else 0
+ return counts, total
+
+
+def _summary_value_as_int(value: int | float | str | None) -> int:
+ return int(value) if value is not None else 0
+
+
+def _outcome_for_result(output_type: str, result: object, applicable: object = None) -> str | None:
+ if output_type == "sentiment":
+ return result if isinstance(result, str) and result in ("positive", "neutral", "negative") else None
+ if applicable is False:
+ return "na"
+ outcomes_by_result: dict[object, str] = {True: "pass", False: "fail"}
+ try:
+ return outcomes_by_result.get(result)
+ except TypeError:
+ return None
+
+
def _widened_ts_window(state: dict) -> tuple[datetime, datetime]:
"""Return (ts_start, ts_end) datetimes widened for generation-event lookups.
@@ -130,26 +180,25 @@ def _execute_hogql_via_ai_events(team: "Team", query_str: str, placeholders: dic
return result.results or []
-def _fetch_period_counts(
- team_id: int, evaluation_id: str, ts_start: datetime, ts_end: datetime
-) -> tuple[int, int, int, int]:
- """Fetch pass/fail/NA/total counts for a single time window.
-
- Returns (pass_count, fail_count, na_count, total).
- """
+def _fetch_period_summary(
+ team_id: int,
+ evaluation_id: str,
+ ts_start: datetime,
+ ts_end: datetime,
+ definition: EvaluationReportOutcomeDefinition,
+) -> tuple[dict[str, int], int]:
+ """Fetch trusted outcome counts and total runs for one time window."""
rows = _execute_hogql(
team_id,
- """
+ f"""
SELECT
- countIf(properties.$ai_evaluation_result = true AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)) as pass_count,
- countIf(properties.$ai_evaluation_result = false AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)) as fail_count,
- countIf(properties.$ai_evaluation_applicable = false) as na_count,
- count() as total
+ {_summary_select_sql(definition)}
FROM events
WHERE event = '$ai_evaluation'
- AND properties.$ai_evaluation_id = {evaluation_id}
- AND timestamp >= {ts_start}
- AND timestamp < {ts_end}
+ AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {definition.event_predicate}
+ AND timestamp >= {{ts_start}}
+ AND timestamp < {{ts_end}}
""",
placeholders={
"evaluation_id": ast.Constant(value=evaluation_id),
@@ -157,15 +206,32 @@ def _fetch_period_counts(
"ts_end": ast.Constant(value=ts_end),
},
)
- row = rows[0] if rows else [0, 0, 0, 0]
- return int(row[0]), int(row[1]), int(row[2]), int(row[3])
+ return _parse_summary_row(definition, rows[0] if rows else None)
+
+
+def _period_summary_dict(
+ output_type: str,
+ result_counts: dict[str, int],
+ total_runs: int,
+ *,
+ empty_rates_as_none: bool = False,
+) -> dict:
+ result_rates = calculate_result_rates(output_type, result_counts, empty_as_none=empty_rates_as_none)
+ summary: dict = {
+ "total_runs": total_runs,
+ "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)
+ return summary
@tool
def get_summary_metrics(
state: Annotated[dict, InjectedState],
) -> str:
- """Get pass/fail/NA counts and pass rate for the current period AND the previous period.
+ """Get outcome counts and rates for the current and previous periods.
Returns current and previous period statistics for comparison. Call this first
to understand the baseline. Note: these numbers are also computed mechanically
@@ -177,40 +243,29 @@ def get_summary_metrics(
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
ts_prev_start = _ch_ts(state["previous_period_start"])
+ output_type, definition = _resolve_output_type(state.get("output_type"))
- pass_count, fail_count, na_count, total = _fetch_period_counts(team_id, evaluation_id, ts_start, ts_end)
- prev_pass, prev_fail, prev_na, prev_total = _fetch_period_counts(team_id, evaluation_id, ts_prev_start, ts_start)
-
- applicable = pass_count + fail_count
- pass_rate = round(pass_count / applicable * 100, 2) if applicable > 0 else 0.0
- prev_applicable = prev_pass + prev_fail
- previous_pass_rate = round(prev_pass / prev_applicable * 100, 2) if prev_applicable > 0 else None
+ result_counts, total = _fetch_period_summary(team_id, evaluation_id, ts_start, ts_end, definition)
+ previous_result_counts, previous_total = _fetch_period_summary(
+ team_id, evaluation_id, ts_prev_start, ts_start, definition
+ )
result = {
- "current_period": {
- "total_runs": total,
- "pass_count": pass_count,
- "fail_count": fail_count,
- "na_count": na_count,
- "pass_rate": pass_rate,
- },
- "previous_period": {
- "total_runs": prev_total,
- "pass_count": prev_pass,
- "fail_count": prev_fail,
- "na_count": prev_na,
- "pass_rate": previous_pass_rate,
- },
+ "output_type": output_type,
+ "current_period": _period_summary_dict(output_type, result_counts, total),
+ "previous_period": _period_summary_dict(
+ output_type, previous_result_counts, previous_total, empty_rates_as_none=True
+ ),
}
return json.dumps(result, indent=2)
@tool
-def get_pass_rate_over_time(
+def get_result_distribution_over_time(
state: Annotated[dict, InjectedState],
bucket: str = "hour",
) -> str:
- """Get time-series pass rate data bucketed by hour or day.
+ """Get time-series outcome counts and rates bucketed by hour or day.
Use this to spot trends, anomalies, or degradations over the report period.
@@ -221,6 +276,7 @@ def get_pass_rate_over_time(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
+ output_type, definition = _resolve_output_type(state.get("output_type"))
# Whitelisted truncation function — `bucket` is an LLM-controlled arg, so pick
# from a fixed set rather than interpolating arbitrary identifiers into SQL.
@@ -231,12 +287,11 @@ def get_pass_rate_over_time(
f"""
SELECT
{trunc_fn}(timestamp) as bucket,
- countIf(properties.$ai_evaluation_result = true AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)) as pass_count,
- countIf(properties.$ai_evaluation_result = false AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)) as fail_count,
- count() as total
+ {_summary_select_sql(definition)}
FROM events
WHERE event = '$ai_evaluation'
AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {definition.event_predicate}
AND timestamp >= {{ts_start}}
AND timestamp < {{ts_end}}
GROUP BY bucket
@@ -251,18 +306,8 @@ def get_pass_rate_over_time(
result = []
for row in rows:
- passes = int(row[1])
- fails = int(row[2])
- applicable = passes + fails
- result.append(
- {
- "bucket": str(row[0]),
- "pass_count": passes,
- "fail_count": fails,
- "total": int(row[3]),
- "pass_rate": round(passes / applicable * 100, 2) if applicable > 0 else None,
- }
- )
+ result_counts, total = _parse_summary_row(definition, row[1:])
+ result.append({"bucket": str(row[0]), **_period_summary_dict(output_type, result_counts, total)})
return json.dumps(result, indent=2)
@@ -277,7 +322,7 @@ def list_all_eval_results(
) -> str:
"""Get a compact overview of evaluation results in the period.
- Returns up to 500 results as condensed rows: verdict, generation_id, and
+ Returns up to 500 results as condensed rows: outcome, generation_id, and
truncated reasoning. When there are more than 500 results, returns a random
sample. Use this as your first scan to spot patterns before drilling into
specific examples with sample_generation_details.
@@ -289,6 +334,7 @@ def list_all_eval_results(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
+ output_type, definition = _resolve_output_type(state.get("output_type"))
shared_placeholders = {
"evaluation_id": ast.Constant(value=evaluation_id),
@@ -299,13 +345,14 @@ def list_all_eval_results(
# First get total count to know if we need to sample.
count_rows = _execute_hogql(
team_id,
- """
+ f"""
SELECT count() as cnt
FROM events
WHERE event = '$ai_evaluation'
- AND properties.$ai_evaluation_id = {evaluation_id}
- AND timestamp >= {ts_start}
- AND timestamp < {ts_end}
+ AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {definition.event_predicate}
+ AND timestamp >= {{ts_start}}
+ AND timestamp < {{ts_end}}
""",
placeholders=shared_placeholders,
)
@@ -321,12 +368,14 @@ def list_all_eval_results(
f"""
SELECT
properties.$ai_target_event_id as generation_id,
- properties.$ai_evaluation_result as result,
- properties.$ai_evaluation_applicable as applicable,
+ {definition.result_expression} as result,
+ {definition.applicable_expression} as applicable,
+ {definition.score_expression} as score,
properties.$ai_evaluation_reasoning as reasoning
FROM events
WHERE event = '$ai_evaluation'
AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {definition.event_predicate}
AND timestamp >= {{ts_start}}
AND timestamp < {{ts_end}}
{order_clause}
@@ -339,19 +388,12 @@ def list_all_eval_results(
lines = []
for row in rows:
gen_id = str(row[0]) if row[0] else "?"
- applicable = row[2]
- if applicable is False:
- verdict = "na"
- elif row[1] is True:
- verdict = "pass"
- elif row[1] is False:
- verdict = "fail"
- else:
- verdict = "?"
- reasoning = (row[3] or "")[:max_reasoning_length]
- if row[3] and len(row[3]) > max_reasoning_length:
+ outcome = _outcome_for_result(output_type, row[1], row[2]) or "?"
+ score = f" ({row[3]:.2f})" if isinstance(row[3], int | float) else ""
+ reasoning = (row[4] or "")[:max_reasoning_length]
+ if row[4] and len(row[4]) > max_reasoning_length:
reasoning += "..."
- lines.append(f"{verdict} | {gen_id} | {reasoning}")
+ lines.append(f"{outcome}{score} | {gen_id} | {reasoning}")
if is_sampled:
header = f"Total: {total_count} results (showing random sample of {len(lines)})\n"
@@ -363,15 +405,15 @@ def list_all_eval_results(
@tool
def sample_eval_results(
state: Annotated[dict, InjectedState],
- filter: str = "all",
+ outcome: str = "all",
limit: int = 50,
) -> str:
- """Sample evaluation runs with generation_id, result, and reasoning.
+ """Sample evaluation runs with generation ID, outcome, score, and reasoning.
Call multiple times with different filters to understand patterns.
Args:
- filter: "all", "pass", "fail", or "na"
+ outcome: "all" or one of the output type's supported outcomes
limit: Maximum number of results to return (default 50)
"""
limit = min(max(1, limit), 500)
@@ -379,28 +421,30 @@ def sample_eval_results(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
+ output_type, definition = _resolve_output_type(state.get("output_type"))
- # Whitelisted filter fragment — `filter` is an LLM-controlled arg; pick
- # from a fixed set rather than interpolating arbitrary SQL.
+ # Whitelisted filter fragment: outcome predicates come only from the trusted
+ # outcome definition, never directly from the LLM-controlled argument.
filter_clause = ""
- if filter == "pass":
- filter_clause = "AND properties.$ai_evaluation_result = true AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)"
- elif filter == "fail":
- filter_clause = "AND properties.$ai_evaluation_result = false AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)"
- elif filter == "na":
- filter_clause = "AND properties.$ai_evaluation_applicable = false"
+ if outcome != "all":
+ outcome_predicate = definition.outcome_predicates.get(outcome)
+ if outcome_predicate is None:
+ return json.dumps({"error": f"Unsupported {output_type} outcome: {outcome}"})
+ filter_clause = f"AND {outcome_predicate}"
rows = _execute_hogql(
team_id,
f"""
SELECT
properties.$ai_target_event_id as generation_id,
- properties.$ai_evaluation_result as result,
+ {definition.result_expression} as result,
properties.$ai_evaluation_reasoning as reasoning,
- properties.$ai_evaluation_applicable as applicable
+ {definition.applicable_expression} as applicable,
+ {definition.score_expression} as score
FROM events
WHERE event = '$ai_evaluation'
AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {definition.event_predicate}
AND timestamp >= {{ts_start}}
AND timestamp < {{ts_end}}
{filter_clause}
@@ -417,15 +461,14 @@ def sample_eval_results(
result = []
for row in rows:
- applicable = row[3]
- eval_result = None if applicable is False else row[1]
- result.append(
- {
- "generation_id": str(row[0]) if row[0] else "",
- "result": eval_result,
- "reasoning": row[2] or "",
- }
- )
+ entry = {
+ "generation_id": str(row[0]) if row[0] else "",
+ "outcome": _outcome_for_result(output_type, row[1], row[3]),
+ "reasoning": row[2] or "",
+ }
+ if output_type == "sentiment":
+ entry["score"] = row[4]
+ result.append(entry)
return json.dumps(result, indent=2)
@@ -636,7 +679,10 @@ def get_generation_detail(
"""
SELECT
properties.$ai_evaluation_id as eval_id,
+ properties.$ai_evaluation_result_type as result_type,
properties.$ai_evaluation_result as result,
+ 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
FROM events
@@ -652,14 +698,21 @@ def get_generation_detail(
evals = []
for er in eval_rows:
- applicable = er[3]
- evals.append(
- {
- "evaluation_id": str(er[0]) if er[0] else "",
- "result": None if applicable is False else er[1],
- "reasoning": er[2] or "",
- }
- )
+ output_type = str(er[1]) if er[1] else "boolean"
+ try:
+ get_outcome_definition(output_type)
+ except ValueError:
+ continue
+ raw_result = er[3] if output_type == "sentiment" else er[2]
+ entry = {
+ "evaluation_id": str(er[0]) if er[0] else "",
+ "output_type": output_type,
+ "outcome": _outcome_for_result(output_type, raw_result, er[6]),
+ "reasoning": er[5] or "",
+ }
+ if output_type == "sentiment":
+ entry["score"] = er[4]
+ evals.append(entry)
result: dict = {
"generation_id": str(row[0]) if row[0] else "",
@@ -788,7 +841,7 @@ def list_recent_report_runs(
) -> str:
"""List metadata for previous report runs of this evaluation.
- Returns a compact index: run_id, period, title, pass rate, total runs.
+ Returns a compact index: run_id, period, title, outcome rates, total runs.
No full content — use this to discover which past runs look interesting,
then call `get_report_run(run_id)` to pull the full narrative for the ones
worth reading. This two-step pattern keeps context small when scanning a
@@ -828,17 +881,22 @@ def list_recent_report_runs(
# `metadata` mirror is maintained in the store activity for legacy consumers.
# Prefer content so this tool stays correct even if the mirror is removed.
metrics = content.get("metrics", {}) if isinstance(content.get("metrics"), dict) else {}
- result.append(
- {
- "run_id": str(run.id),
- "period_start": str(run.period_start),
- "period_end": str(run.period_end),
- "title": content.get("title", ""),
- "pass_rate": metrics.get("pass_rate", metadata.get("pass_rate")),
- "total_runs": metrics.get("total_runs", metadata.get("total_runs")),
- "delivery_status": run.delivery_status,
- }
- )
+ normalized_metrics = normalize_metrics_payload({**metadata, **metrics})
+ output_type = normalized_metrics["output_type"]
+ entry = {
+ "run_id": str(run.id),
+ "period_start": str(run.period_start),
+ "period_end": str(run.period_end),
+ "title": content.get("title", ""),
+ "output_type": output_type,
+ "total_runs": normalized_metrics["total_runs"],
+ "delivery_status": run.delivery_status,
+ }
+ if "result_rates" in normalized_metrics:
+ entry["result_rates"] = normalized_metrics["result_rates"]
+ if output_type == "boolean" and "pass_rate" in normalized_metrics:
+ entry["pass_rate"] = normalized_metrics["pass_rate"]
+ result.append(entry)
return json.dumps(result, indent=2, default=str)
@@ -869,13 +927,16 @@ def get_report_run(
except EvaluationReportRun.DoesNotExist:
return json.dumps({"error": f"Run {run_id} not found for this evaluation"})
+ content = normalize_report_content_payload(run.content) if isinstance(run.content, dict) else run.content
+ metadata = normalize_metrics_payload(run.metadata) if isinstance(run.metadata, dict) else run.metadata
+
return json.dumps(
{
"run_id": str(run.id),
"period_start": str(run.period_start),
"period_end": str(run.period_end),
- "content": run.content,
- "metadata": run.metadata,
+ "content": content,
+ "metadata": metadata,
"delivery_status": run.delivery_status,
},
indent=2,
@@ -884,37 +945,44 @@ def get_report_run(
@tool
-def get_top_failure_reasons(
+def get_top_outcome_reasons(
state: Annotated[dict, InjectedState],
+ outcome: str = "",
limit: int = 10,
) -> str:
- """Get grouped failure reasoning strings for quick failure mode overview.
+ """Get grouped reasoning strings for one output-type-specific outcome.
Args:
- limit: Maximum number of failure reason groups to return (default 10)
+ outcome: Outcome to analyze. Defaults to fail for boolean or negative for sentiment.
+ limit: Maximum number of reason groups to return (default 10)
"""
limit = min(max(1, limit), 500)
team_id = state["team_id"]
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
+ output_type, definition = _resolve_output_type(state.get("output_type"))
+ selected_outcome = outcome or ("negative" if output_type == "sentiment" else "fail")
+ outcome_predicate = definition.outcome_predicates.get(selected_outcome)
+ if outcome_predicate is None:
+ return json.dumps({"error": f"Unsupported {output_type} outcome: {selected_outcome}"})
rows = _execute_hogql(
team_id,
- """
+ f"""
SELECT
properties.$ai_evaluation_reasoning as reasoning,
count() as cnt
FROM events
WHERE event = '$ai_evaluation'
- AND properties.$ai_evaluation_id = {evaluation_id}
- AND properties.$ai_evaluation_result = false
- AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)
- AND timestamp >= {ts_start}
- AND timestamp < {ts_end}
+ AND properties.$ai_evaluation_id = {{evaluation_id}}
+ AND {definition.event_predicate}
+ AND {outcome_predicate}
+ AND timestamp >= {{ts_start}}
+ AND timestamp < {{ts_end}}
GROUP BY reasoning
ORDER BY cnt DESC
- LIMIT {limit}
+ LIMIT {{limit}}
""",
placeholders={
"evaluation_id": ast.Constant(value=evaluation_id),
@@ -949,7 +1017,7 @@ def set_title(
titles like "Evaluation report" or "Analysis summary".
Good examples:
- - "Pass rate steady at 94%, dip at 14:00 UTC bucket"
+ - "Outcome distribution steady, dip at 14:00 UTC bucket"
- "Volume dropped to zero — likely pipeline issue"
- "Cost regression: gpt-5-mini 3x more expensive than last week"
@@ -978,8 +1046,8 @@ def add_section(
over many with filler. By convention, the FIRST section you add should be the
executive summary / TL;DR — it's what lands in the Slack main message.
- Don't restate raw counts like "total_runs: 53, pass_count: 50" in prose — the
- viewer renders a separate metrics block. Focus on analysis, comparisons,
+ Don't restate raw counts like "total_runs: 53" in prose. The viewer renders
+ a separate metrics block. Focus on analysis, comparisons,
hypotheses, and concrete recommendations.
Reference specific traces by calling add_citation separately with the
@@ -1042,7 +1110,7 @@ def add_citation(
EVAL_REPORT_TOOLS = [
# Query tools (read-only, agent calls as needed)
get_summary_metrics,
- get_pass_rate_over_time,
+ get_result_distribution_over_time,
list_all_eval_results,
sample_eval_results,
sample_generation_details,
@@ -1050,7 +1118,7 @@ EVAL_REPORT_TOOLS = [
get_generation_text_repr,
list_recent_report_runs,
get_report_run,
- get_top_failure_reasons,
+ get_top_outcome_reasons,
# Output tools (mutate state["report"])
set_title,
add_section,
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 8745ca3fa1c3..dbef28332841 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -1,20 +1,180 @@
import datetime as dt
+from contextlib import asynccontextmanager
+import pytest
from posthog.test.base import BaseTest
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
from django.utils import timezone
from posthog.temporal.ai_observability.eval_reports.activities import (
_check_count_triggered_eval_report_sync,
+ _count_eval_results_for_report,
_fetch_count_triggered_eval_report_candidate_ids,
+ _find_nth_eval_timestamp,
_period_for_scheduled_report,
+ run_eval_report_agent_activity,
+ store_report_run_activity,
)
+from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
+from posthog.temporal.ai_observability.eval_reports.types import RunEvalReportAgentInput, StoreReportRunInput
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun
from products.ai_observability.backend.models.evaluations import Evaluation
+async def test_run_agent_activity_forwards_sentiment_output_type() -> None:
+ @asynccontextmanager
+ async def noop_heartbeater():
+ yield
+
+ content = EvalReportContent(metrics=EvalReportMetrics(output_type="sentiment"))
+ inputs = RunEvalReportAgentInput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ evaluation_name="Sentiment",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="sentiment",
+ output_type="sentiment",
+ 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",
+ )
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.activities.Heartbeater",
+ return_value=noop_heartbeater(),
+ ),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.report_agent.run_eval_report_agent",
+ return_value=content,
+ ) as run_agent,
+ ):
+ result = await run_eval_report_agent_activity(inputs)
+
+ assert result.content["metrics"]["output_type"] == "sentiment"
+ assert run_agent.call_args.kwargs["output_type"] == "sentiment"
+
+
+async def test_store_sentiment_report_emits_generic_metrics_only() -> None:
+ report_run = MagicMock(id="run-id", report_id="report-id")
+ expected_result_counts = {"positive": 2, "neutral": 3, "negative": 5}
+ content = {
+ "title": "Sentiment shifted negative",
+ "sections": [],
+ "citations": [],
+ "metrics": {
+ "output_type": "sentiment",
+ "total_runs": 10,
+ "result_counts": expected_result_counts,
+ "result_rates": {"positive": 20.0, "neutral": 30.0, "negative": 50.0},
+ },
+ }
+ inputs = StoreReportRunInput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ content=content,
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ )
+
+ with (
+ patch(
+ "products.ai_observability.backend.models.evaluation_reports.EvaluationReportRun.objects.create",
+ return_value=report_run,
+ ),
+ patch("posthog.models.team.Team.objects.get", return_value=MagicMock()),
+ patch("posthog.models.event.util.create_event") as create_event,
+ ):
+ result = await store_report_run_activity(inputs)
+
+ properties = create_event.call_args.kwargs["properties"]
+ assert result.report_run_id == "run-id"
+ assert properties["$ai_report_output_type"] == "sentiment"
+ assert properties["$ai_report_result_counts"] == expected_result_counts
+ assert "$ai_report_pass_rate" not in properties
+
+
+async def test_store_legacy_boolean_report_emits_normalized_generic_metrics() -> None:
+ report_run = MagicMock(id="run-id", report_id="report-id")
+ content = {
+ "metrics": {
+ "total_runs": 10,
+ "pass_count": 6,
+ "fail_count": 3,
+ "na_count": 1,
+ "pass_rate": 66.67,
+ }
+ }
+ inputs = StoreReportRunInput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ content=content,
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ )
+
+ with (
+ patch(
+ "products.ai_observability.backend.models.evaluation_reports.EvaluationReportRun.objects.create",
+ return_value=report_run,
+ ) as create_report_run,
+ patch("posthog.models.team.Team.objects.get", return_value=MagicMock()),
+ patch("posthog.models.event.util.create_event") as create_event,
+ ):
+ await store_report_run_activity(inputs)
+
+ properties = create_event.call_args.kwargs["properties"]
+ stored_content = create_report_run.call_args.kwargs["content"]
+ stored_metrics = stored_content["metrics"]
+ assert stored_metrics["result_counts"] == {"pass": 6, "fail": 3, "na": 1}
+ assert create_report_run.call_args.kwargs["metadata"] == stored_metrics
+ assert "pass_count" not in stored_metrics
+ assert "fail_count" not in stored_metrics
+ assert "na_count" not in stored_metrics
+ assert properties["$ai_report_output_type"] == "boolean"
+ assert properties["$ai_report_result_counts"] == {"pass": 6, "fail": 3, "na": 1}
+ assert properties["$ai_report_result_rates"] == {"pass": 60.0, "fail": 30.0, "na": 10.0}
+ assert properties["$ai_report_pass_rate"] == 66.67
+
+
+def test_count_trigger_uses_current_output_type() -> None:
+ report = MagicMock(team_id=1, team=MagicMock(), evaluation_id="evaluation-id")
+ report.evaluation.output_type = "sentiment"
+
+ with (
+ patch("posthog.hogql.parser.parse_select", return_value=MagicMock()) as parse_select,
+ patch("posthog.hogql.query.execute_hogql_query", return_value=Mock(results=[[4]])),
+ ):
+ result = _count_eval_results_for_report(report, dt.datetime(2026, 7, 1, tzinfo=dt.UTC))
+
+ assert result == 4
+ assert "properties.$ai_evaluation_result_type = 'sentiment'" in parse_select.call_args.args[0]
+
+
+def test_manual_count_window_uses_current_output_type() -> None:
+ before = dt.datetime(2026, 7, 2, tzinfo=dt.UTC)
+ expected = before - dt.timedelta(hours=2)
+
+ with (
+ patch("posthog.hogql.parser.parse_select", return_value=MagicMock()) as parse_select,
+ patch("posthog.hogql.query.execute_hogql_query", return_value=Mock(results=[[expected]])),
+ patch("posthog.models.Team.objects.get", return_value=MagicMock()),
+ ):
+ result = _find_nth_eval_timestamp(1, "evaluation-id", 100, before, output_type="sentiment")
+
+ assert result == expected
+ assert "properties.$ai_evaluation_result_type = 'sentiment'" in parse_select.call_args.args[0]
+
+
def _prepare_sync(report_id: str, manual: bool = False):
"""Call the inner sync logic of prepare_report_context_activity directly.
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 e33d72649e37..0ddb5776f79b 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py
@@ -235,10 +235,7 @@ class TestMetricsBlockHtml(SimpleTestCase):
def test_renders_all_counts(self):
metrics = EvalReportMetrics(
total_runs=100,
- pass_count=80,
- fail_count=18,
- na_count=2,
- pass_rate=81.63,
+ result_counts={"pass": 80, "fail": 18, "na": 2},
period_start="2026-04-08T14:00:00+00:00",
period_end="2026-04-08T15:00:00+00:00",
)
@@ -251,24 +248,50 @@ class TestMetricsBlockHtml(SimpleTestCase):
self.assertIn("Apr 08, 2026 14:00 UTC", html)
def test_renders_delta_up(self):
- metrics = EvalReportMetrics(total_runs=10, pass_count=9, pass_rate=90.0, previous_pass_rate=80.0)
+ metrics = EvalReportMetrics(
+ total_runs=10,
+ result_counts={"pass": 9, "fail": 1, "na": 0},
+ previous_pass_rate=80.0,
+ )
html = _render_metrics_block_html(metrics)
self.assertIn("▲", html)
self.assertIn("10.00pp", html)
def test_renders_delta_down(self):
- metrics = EvalReportMetrics(total_runs=10, pass_count=5, pass_rate=50.0, previous_pass_rate=80.0)
+ metrics = EvalReportMetrics(
+ total_runs=10,
+ result_counts={"pass": 5, "fail": 5, "na": 0},
+ previous_pass_rate=80.0,
+ )
html = _render_metrics_block_html(metrics)
self.assertIn("▼", html)
self.assertIn("30.00pp", html)
def test_no_delta_when_previous_is_none(self):
- metrics = EvalReportMetrics(total_runs=10, pass_count=9, pass_rate=90.0, previous_pass_rate=None)
+ metrics = EvalReportMetrics(total_runs=10, result_counts={"pass": 9, "fail": 1, "na": 0})
html = _render_metrics_block_html(metrics)
self.assertNotIn("▲", html)
self.assertNotIn("▼", html)
self.assertNotIn("pp vs previous", html)
+ def test_renders_sentiment_distribution_without_boolean_labels(self):
+ metrics = EvalReportMetrics(
+ output_type="sentiment",
+ total_runs=10,
+ result_counts={"positive": 4, "neutral": 1, "negative": 5},
+ result_rates={"positive": 40.0, "neutral": 10.0, "negative": 50.0},
+ previous_result_rates={"positive": 60.0, "neutral": 10.0, "negative": 30.0},
+ )
+
+ html = _render_metrics_block_html(metrics)
+
+ self.assertIn("Positive", html)
+ self.assertIn("Neutral", html)
+ self.assertIn("Negative", html)
+ self.assertIn("50.00%", html)
+ self.assertNotIn("Pass", html)
+ self.assertNotIn("Fail", html)
+
class TestDeliverReport(SimpleTestCase):
"""End-to-end tests for deliver_report — mocks the email+slack sub-functions."""
@@ -279,7 +302,7 @@ class TestDeliverReport(SimpleTestCase):
title=title,
sections=[ReportSection(title="Summary", content="All good.")],
citations=[Citation(generation_id="g", trace_id="t", reason="example")],
- metrics=EvalReportMetrics(total_runs=10, pass_count=9, pass_rate=90.0),
+ metrics=EvalReportMetrics(total_runs=10, result_counts={"pass": 9, "fail": 1, "na": 0}),
).to_dict()
def _make_report_run(self):
@@ -409,7 +432,7 @@ class TestDeliverSlackReport(SimpleTestCase):
title="A nice punchline",
sections=sections,
citations=[],
- metrics=EvalReportMetrics(total_runs=10, pass_count=9, pass_rate=90.0),
+ metrics=EvalReportMetrics(total_runs=10, result_counts={"pass": 9, "fail": 1, "na": 0}),
).to_dict()
run.report_id = "report-id"
run.id = "run-id"
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
index 25ce3506690b..ce32fbe126f6 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_workflow.py
@@ -1,8 +1,70 @@
import pytest
from unittest.mock import patch
-from posthog.temporal.ai_observability.eval_reports.types import CheckCountTriggeredEvalReportOutput
-from posthog.temporal.ai_observability.eval_reports.workflow import _check_count_triggered_eval_report_candidates
+from posthog.temporal.ai_observability.eval_reports.types import (
+ CheckCountTriggeredEvalReportOutput,
+ GenerateAndDeliverEvalReportWorkflowInput,
+ PrepareReportContextOutput,
+ RunEvalReportAgentInput,
+ RunEvalReportAgentOutput,
+ StoreReportRunOutput,
+)
+from posthog.temporal.ai_observability.eval_reports.workflow import (
+ GenerateAndDeliverEvalReportWorkflow,
+ _check_count_triggered_eval_report_candidates,
+)
+
+
+async def test_generate_workflow_forwards_sentiment_output_type() -> None:
+ activity_inputs: list[object] = []
+ responses = iter(
+ [
+ PrepareReportContextOutput(
+ report_id="report-id",
+ team_id=1,
+ evaluation_id="evaluation-id",
+ evaluation_name="Sentiment",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="sentiment",
+ output_type="sentiment",
+ 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",
+ ),
+ RunEvalReportAgentOutput(
+ report_id="report-id",
+ content={},
+ period_start="2026-07-01T00:00:00+00:00",
+ period_end="2026-07-02T00:00:00+00:00",
+ ),
+ StoreReportRunOutput(report_run_id="run-id"),
+ None,
+ ]
+ )
+
+ async def fake_execute_activity(_activity, inputs, **_kwargs):
+ activity_inputs.append(inputs)
+ return next(responses)
+
+ with (
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.execute_activity",
+ new=fake_execute_activity,
+ ),
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.workflow.temporalio.workflow.patched",
+ return_value=False,
+ ),
+ ):
+ await GenerateAndDeliverEvalReportWorkflow().run(
+ GenerateAndDeliverEvalReportWorkflowInput(report_id="report-id", manual=True)
+ )
+
+ agent_input = activity_inputs[1]
+ assert isinstance(agent_input, RunEvalReportAgentInput)
+ assert agent_input.output_type == "sentiment"
@pytest.mark.asyncio
diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.py
index 31ab51310b19..d19389e2d777 100644
--- a/posthog/temporal/ai_observability/eval_reports/types.py
+++ b/posthog/temporal/ai_observability/eval_reports/types.py
@@ -50,6 +50,7 @@ class PrepareReportContextOutput:
period_end: str
previous_period_start: str
report_prompt_guidance: str = ""
+ output_type: str = "boolean"
@dataclasses.dataclass
@@ -65,6 +66,7 @@ class RunEvalReportAgentInput:
period_end: str
previous_period_start: str
report_prompt_guidance: str = ""
+ output_type: str = "boolean"
@dataclasses.dataclass
diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.py
index caa41f69cacf..986edb1eb754 100644
--- a/posthog/temporal/ai_observability/eval_reports/workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py
@@ -237,6 +237,7 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
evaluation_description=context.evaluation_description,
evaluation_prompt=context.evaluation_prompt,
evaluation_type=context.evaluation_type,
+ output_type=context.output_type,
period_start=context.period_start,
period_end=context.period_end,
previous_period_start=context.previous_period_start,
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index 2b7ca69d72c0..974319fe5801 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -1,7 +1,7 @@
"""API endpoints for evaluation report configuration and report run history."""
import datetime as dt
-from typing import Any
+from typing import Any, cast
from django.conf import settings
from django.db.models import QuerySet
@@ -9,7 +9,7 @@ from django.utils import timezone
import structlog
from asgiref.sync import async_to_sync
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
@@ -20,14 +20,18 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.event_usage import report_user_action
from posthog.models.integration import Integration
from posthog.permissions import AccessControlPermission
+from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (
+ normalize_metrics_payload,
+ normalize_report_content_payload,
+)
from products.ai_observability.backend.api.metrics import llma_track_latency
-from products.ai_observability.backend.models.evaluation_configs import (
- REPORTABLE_OUTPUT_TYPES,
- evaluation_supports_reports,
+from products.ai_observability.backend.models.evaluation_configs import OutputType, evaluation_supports_reports
+from products.ai_observability.backend.models.evaluation_reports import (
+ EvaluationReport,
+ EvaluationReportQuerySet,
+ EvaluationReportRun,
)
-from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun
-from products.ai_observability.backend.models.evaluations import EvaluationTarget
from products.workflows.backend.utils.rrule_utils import validate_rrule
logger = structlog.get_logger(__name__)
@@ -36,6 +40,7 @@ SCHEDULE_RRULE_ERROR = (
"Scheduled reports support daily or weekly cadences. Use 'FREQ=DAILY' or 'FREQ=WEEKLY;BYDAY=MO,FR'."
)
VALID_WEEKDAYS = {"MO", "TU", "WE", "TH", "FR", "SA", "SU"}
+REPORT_NOT_SUPPORTED_ERROR = "Reports are not supported for this evaluation."
def default_schedule_anchor() -> dt.datetime:
@@ -191,10 +196,8 @@ 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):
- raise serializers.ValidationError("Reports are only supported for boolean evaluations.")
- if value.target == EvaluationTarget.TRACE:
- raise serializers.ValidationError("Reports are not yet supported for trace-level evaluations.")
+ if not evaluation_supports_reports(value.output_type, value.target):
+ raise serializers.ValidationError(REPORT_NOT_SUPPORTED_ERROR)
return value
def validate_rrule(self, value: str) -> str:
@@ -354,7 +357,144 @@ class EvaluationReportListSerializer(EvaluationReportSerializer):
read_only_fields = [f for f in EvaluationReportSerializer.Meta.read_only_fields if f != "created_by"]
+class EvaluationReportSectionSerializer(serializers.Serializer):
+ title = serializers.CharField(
+ required=False,
+ help_text="Agent-generated section heading.",
+ )
+ content = serializers.CharField(
+ required=False,
+ help_text="Markdown narrative for this section.",
+ )
+
+
+class EvaluationReportCitationSerializer(serializers.Serializer):
+ generation_id = serializers.CharField(
+ required=False,
+ help_text="Generation UUID referenced by this citation.",
+ )
+ trace_id = serializers.CharField(
+ required=False,
+ help_text="Trace identifier containing the referenced generation.",
+ )
+ reason = serializers.CharField(
+ required=False,
+ help_text="Short explanation of why the generation is cited.",
+ )
+
+
+class EvaluationReportMetricsSerializer(serializers.Serializer):
+ output_type = serializers.ChoiceField(
+ choices=OutputType.choices,
+ required=False,
+ help_text="Evaluation result type. Stored metrics without this field represent boolean evaluations.",
+ )
+ total_runs = serializers.IntegerField(
+ required=False,
+ help_text="Number of evaluation results in the report period.",
+ )
+ result_counts = serializers.DictField(
+ child=serializers.IntegerField(),
+ required=False,
+ help_text="Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative.",
+ )
+ result_rates = serializers.DictField(
+ child=serializers.FloatField(),
+ required=False,
+ help_text="Percentage by output-specific result label, from 0 to 100.",
+ )
+ period_start = serializers.CharField(
+ required=False,
+ help_text="ISO 8601 start of the evaluation window represented by these metrics.",
+ )
+ period_end = serializers.CharField(
+ required=False,
+ help_text="ISO 8601 end of the evaluation window represented by these metrics.",
+ )
+ previous_total_runs = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Number of evaluation results in the previous comparison period, or null when unavailable.",
+ )
+ previous_result_counts = serializers.DictField(
+ child=serializers.IntegerField(),
+ required=False,
+ allow_null=True,
+ help_text="Count by result label for the previous period, or null when unavailable.",
+ )
+ previous_result_rates = serializers.DictField(
+ child=serializers.FloatField(),
+ required=False,
+ allow_null=True,
+ help_text="Percentage by result label for the previous period, or null when unavailable.",
+ )
+ pass_rate = serializers.FloatField(
+ required=False,
+ help_text="Boolean pass percentage, excluding results marked not applicable.",
+ )
+ previous_pass_rate = serializers.FloatField(
+ required=False,
+ allow_null=True,
+ help_text="Boolean pass percentage for the previous period, or null when unavailable.",
+ )
+
+
+class EvaluationReportRunContentSerializer(serializers.Serializer):
+ title = serializers.CharField(
+ required=False,
+ help_text="Agent-generated report headline.",
+ )
+ sections = EvaluationReportSectionSerializer(
+ many=True,
+ required=False,
+ help_text="Ordered narrative sections in the report.",
+ )
+ citations = EvaluationReportCitationSerializer(
+ many=True,
+ required=False,
+ help_text="Trace references grounding findings in the report.",
+ )
+ metrics = EvaluationReportMetricsSerializer(
+ required=False,
+ allow_null=True,
+ help_text="Structured metrics computed for the report period.",
+ )
+
+
+@extend_schema_field(EvaluationReportRunContentSerializer)
+class _EvaluationReportRunContentField(serializers.JSONField):
+ def to_representation(self, value: Any) -> Any:
+ representation = cast(Any, super().to_representation(value))
+ return normalize_report_content_payload(representation) if isinstance(representation, dict) else representation
+
+
+@extend_schema_field(EvaluationReportMetricsSerializer)
+class _EvaluationReportMetricsField(serializers.JSONField):
+ def to_representation(self, value: Any) -> Any:
+ representation = cast(Any, super().to_representation(value))
+ return normalize_metrics_payload(representation) if isinstance(representation, dict) else representation
+
+
+@extend_schema_field(serializers.ListSerializer(child=serializers.CharField()))
+class _EvaluationReportDeliveryErrorsField(serializers.JSONField):
+ pass
+
+
class EvaluationReportRunSerializer(serializers.ModelSerializer):
+ content = _EvaluationReportRunContentField(
+ read_only=True,
+ help_text="Structured report narrative, citations, and metrics. Legacy runs may contain only some fields.",
+ )
+ metadata = _EvaluationReportMetricsField(
+ read_only=True,
+ allow_null=True,
+ help_text="Legacy mirror of content.metrics. May contain partial boolean metrics on older runs.",
+ )
+ delivery_errors = _EvaluationReportDeliveryErrorsField(
+ read_only=True,
+ help_text="Delivery error messages. Empty when all configured deliveries succeeded.",
+ )
+
class Meta:
model = EvaluationReportRun
fields = [
@@ -372,12 +512,12 @@ class EvaluationReportRunSerializer(serializers.ModelSerializer):
extra_kwargs = {
"id": {"help_text": "UUID of this report run."},
"report": {"help_text": "UUID of the report config that generated this run."},
- "content": {"help_text": "Generated report content (markdown or structured text)."},
- "metadata": {"help_text": "Run metadata including model used, token counts, and generation stats."},
"period_start": {"help_text": "Start of the evaluation window covered by this report."},
"period_end": {"help_text": "End of the evaluation window covered by this report."},
- "delivery_status": {"help_text": "'pending', 'delivered', or 'failed'."},
- "delivery_errors": {"help_text": "List of delivery error messages if delivery failed."},
+ "delivery_status": {
+ "help_text": "Delivery result: 'pending', 'delivered', 'partial_failure', or 'failed'."
+ },
+ "created_at": {"help_text": "When this report run was created."},
}
@@ -401,19 +541,23 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse
return super().get_serializer_class()
def safely_get_queryset(self, queryset: QuerySet[EvaluationReport]) -> QuerySet[EvaluationReport]:
- queryset = queryset.filter(team_id=self.team_id, evaluation__output_type__in=REPORTABLE_OUTPUT_TYPES).order_by(
- "-created_at"
+ report_queryset = cast(
+ EvaluationReportQuerySet,
+ queryset.filter(team_id=self.team_id).order_by("-created_at"),
)
+ # Generate validates eligibility explicitly so unsupported legacy rows return a useful 400.
+ if self.action != "generate":
+ report_queryset = report_queryset.reportable()
if self.action not in ("update", "partial_update"):
- queryset = queryset.filter(deleted=False)
+ report_queryset = report_queryset.filter(deleted=False)
evaluation_id = self.request.query_params.get("evaluation")
if evaluation_id:
query_serializer = EvaluationReportListQuerySerializer(data={"evaluation": evaluation_id})
query_serializer.is_valid(raise_exception=True)
- queryset = queryset.filter(evaluation_id=query_serializer.validated_data["evaluation"])
+ report_queryset = report_queryset.filter(evaluation_id=query_serializer.validated_data["evaluation"])
- return queryset
+ return report_queryset
@llma_track_latency("llma_evaluation_reports_list")
@extend_schema(parameters=[EvaluationReportListQuerySerializer])
@@ -536,16 +680,8 @@ 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):
- return Response(
- {"error": "Reports are only supported for boolean evaluations."},
- status=status.HTTP_400_BAD_REQUEST,
- )
- if report.evaluation.target == EvaluationTarget.TRACE:
- return Response(
- {"error": "Reports are not yet supported for trace-level evaluations."},
- status=status.HTTP_400_BAD_REQUEST,
- )
+ if not evaluation_supports_reports(report.evaluation.output_type, report.evaluation.target):
+ raise serializers.ValidationError({"evaluation": REPORT_NOT_SUPPORTED_ERROR})
try:
from posthog.temporal.ai_observability.eval_reports.constants import GENERATE_EVAL_REPORT_WORKFLOW_NAME
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 96e17b64b19e..405916c740fc 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -709,7 +709,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
with transaction.atomic():
instance = serializer.save()
- if evaluation_supports_reports(instance.output_type) and instance.target == EvaluationTarget.GENERATION:
+ if evaluation_supports_reports(instance.output_type, instance.target):
# 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.
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 85ba6728958f..9513509ca2fd 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py
@@ -1,9 +1,11 @@
+import uuid
import datetime as dt
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
@@ -13,10 +15,138 @@ from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+from products.ai_observability.backend.api.evaluation_reports import EvaluationReportRunSerializer
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun
from products.ai_observability.backend.models.evaluations import Evaluation, EvaluationTarget
+class TestEvaluationReportRunSerializer(SimpleTestCase):
+ def test_normalizes_legacy_metrics_without_backfilling_stored_json(self) -> None:
+ legacy_metrics = {
+ "total_runs": 10,
+ "pass_count": 7,
+ "fail_count": 2,
+ "na_count": 1,
+ "pass_rate": 77.78,
+ }
+ content = {
+ "title": "Legacy report",
+ "metrics": legacy_metrics,
+ "legacy_extension": "preserved",
+ }
+ now = timezone.now()
+ run = EvaluationReportRun(
+ report_id=uuid.uuid4(),
+ content=content,
+ metadata=legacy_metrics,
+ period_start=now - dt.timedelta(hours=1),
+ period_end=now,
+ delivery_errors=["Email delivery failed"],
+ created_at=now,
+ )
+
+ serialized = EvaluationReportRunSerializer(run).data
+
+ expected_counts = {"pass": 7, "fail": 2, "na": 1}
+ self.assertEqual(serialized["content"]["metrics"]["result_counts"], expected_counts)
+ self.assertEqual(serialized["metadata"]["result_counts"], expected_counts)
+ self.assertEqual(serialized["content"]["legacy_extension"], "preserved")
+ for legacy_field in ("pass_count", "fail_count", "na_count"):
+ self.assertNotIn(legacy_field, serialized["content"]["metrics"])
+ self.assertNotIn(legacy_field, serialized["metadata"])
+ self.assertEqual(run.content, content)
+ self.assertEqual(serialized["delivery_errors"], ["Email delivery failed"])
+
+ @parameterized.expand(
+ [
+ (
+ "missing_counts",
+ {"total_runs": 10, "pass_rate": 80.0},
+ None,
+ None,
+ 80.0,
+ ),
+ (
+ "missing_all_outcomes",
+ {"total_runs": 10},
+ None,
+ None,
+ None,
+ ),
+ (
+ "explicit_zero_counts",
+ {
+ "output_type": "boolean",
+ "total_runs": 0,
+ "result_counts": {"pass": 0, "fail": 0, "na": 0},
+ },
+ {"pass": 0, "fail": 0, "na": 0},
+ {"pass": 0.0, "fail": 0.0, "na": 0.0},
+ 0.0,
+ ),
+ (
+ "explicit_legacy_zero_counts",
+ {
+ "total_runs": 0,
+ "pass_count": 0,
+ "fail_count": 0,
+ "na_count": 0,
+ },
+ {"pass": 0, "fail": 0, "na": 0},
+ {"pass": 0.0, "fail": 0.0, "na": 0.0},
+ 0.0,
+ ),
+ (
+ "partial_rates_without_counts",
+ {
+ "output_type": "sentiment",
+ "total_runs": 10,
+ "result_rates": {"positive": 60.0},
+ },
+ None,
+ {"positive": 60.0},
+ None,
+ ),
+ ]
+ )
+ def test_preserves_historical_metric_presence(
+ self,
+ _name: str,
+ stored_metrics: dict[str, object],
+ expected_counts: dict[str, int] | None,
+ expected_rates: dict[str, float] | None,
+ expected_pass_rate: float | None,
+ ) -> None:
+ now = timezone.now()
+ run = EvaluationReportRun(
+ report_id=uuid.uuid4(),
+ content={"metrics": stored_metrics},
+ metadata=stored_metrics,
+ period_start=now - dt.timedelta(hours=1),
+ period_end=now,
+ created_at=now,
+ )
+
+ serialized = EvaluationReportRunSerializer(run).data
+
+ for serialized_metrics in (serialized["content"]["metrics"], serialized["metadata"]):
+ self.assertEqual(serialized_metrics["total_runs"], stored_metrics["total_runs"])
+ if expected_counts is None:
+ self.assertNotIn("result_counts", serialized_metrics)
+ else:
+ self.assertEqual(serialized_metrics["result_counts"], expected_counts)
+
+ if expected_rates is None:
+ self.assertNotIn("result_rates", serialized_metrics)
+ else:
+ self.assertEqual(serialized_metrics["result_rates"], expected_rates)
+
+ if expected_pass_rate is None:
+ self.assertNotIn("pass_rate", serialized_metrics)
+ else:
+ self.assertEqual(serialized_metrics["pass_rate"], expected_pass_rate)
+
+
class TestEvaluationReportApi(APIBaseTest):
def setUp(self):
super().setUp()
@@ -81,6 +211,12 @@ class TestEvaluationReportApi(APIBaseTest):
conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
)
+ def _create_unsupported_output_evaluation(self) -> Evaluation:
+ evaluation = self._create_boolean_evaluation(name="Unsupported output Eval")
+ Evaluation.objects.filter(id=evaluation.id).update(output_type="unsupported")
+ evaluation.refresh_from_db()
+ return evaluation
+
def _create_trace_evaluation(self) -> Evaluation:
return Evaluation.objects.create(
team=self.team,
@@ -204,7 +340,7 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertEqual(report.rrule, "FREQ=WEEKLY;BYDAY=MO,FR")
self.assertEqual(report.delivery_targets, [{"type": "email", "value": "[email protected]"}])
- def test_create_rejects_sentiment_evaluation(self):
+ def test_create_accepts_sentiment_evaluation(self):
sentiment_evaluation = self._create_sentiment_evaluation()
response = self.client.post(
self.base_url,
@@ -217,15 +353,21 @@ class TestEvaluationReportApi(APIBaseTest):
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.json().get("attr"), "evaluation")
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ report = EvaluationReport.objects.get(evaluation=sentiment_evaluation)
+ self.assertEqual(response.json()["id"], str(report.id))
- def test_create_rejects_trace_target_evaluation(self):
- trace_evaluation = self._create_trace_evaluation()
+ @parameterized.expand([("trace_target", "trace"), ("unsupported_output", "unsupported")])
+ def test_create_rejects_unreportable_evaluation(self, _name: str, evaluation_kind: str) -> None:
+ evaluation = (
+ self._create_trace_evaluation()
+ if evaluation_kind == "trace"
+ else self._create_unsupported_output_evaluation()
+ )
response = self.client.post(
self.base_url,
{
- "evaluation": str(trace_evaluation.id),
+ "evaluation": str(evaluation.id),
"frequency": "every_n",
"trigger_threshold": 100,
"delivery_targets": [],
@@ -236,36 +378,45 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json().get("attr"), "evaluation")
- def test_deliverable_excludes_trace_target_reports(self):
- # A report directly attached to a trace eval (e.g. created before the eval switched targets,
- # bypassing the serializer) must not enter the delivery pipeline.
- gen_report = self._create_report()
+ def test_deliverable_includes_reportable_generation_evaluations_only(self):
+ boolean_report = self._create_report()
+ sentiment_report = self._create_report(evaluation=self._create_sentiment_evaluation())
trace_report = self._create_report(evaluation=self._create_trace_evaluation())
+ unsupported_report = self._create_report(evaluation=self._create_unsupported_output_evaluation())
deliverable_ids = set(EvaluationReport.objects.deliverable().values_list("id", flat=True))
- self.assertIn(gen_report.id, deliverable_ids)
+ self.assertEqual(deliverable_ids, {boolean_report.id, sentiment_report.id})
self.assertNotIn(trace_report.id, deliverable_ids)
-
- def test_generate_rejects_trace_target_evaluation(self):
- report = self._create_report(evaluation=self._create_trace_evaluation())
+ self.assertNotIn(unsupported_report.id, deliverable_ids)
+
+ @parameterized.expand([("trace_target", "trace"), ("unsupported_output", "unsupported")])
+ def test_generate_rejects_unreportable_evaluation(self, _name: str, evaluation_kind: str) -> None:
+ evaluation = (
+ self._create_trace_evaluation()
+ if evaluation_kind == "trace"
+ else self._create_unsupported_output_evaluation()
+ )
+ report = self._create_report(evaluation=evaluation)
response = self.client.post(f"{self.base_url}{report.id}/generate/")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- def test_list_excludes_sentiment_reports(self):
+ def test_list_includes_sentiment_and_excludes_unreportable_reports(self):
sentiment_evaluation = self._create_sentiment_evaluation()
- EvaluationReport.objects.create(
+ sentiment_report = EvaluationReport.objects.create(
team=self.team,
evaluation=sentiment_evaluation,
frequency=EvaluationReport.Frequency.EVERY_N,
trigger_threshold=100,
delivery_targets=[],
)
+ self._create_report(evaluation=self._create_trace_evaluation())
+ self._create_report(evaluation=self._create_unsupported_output_evaluation())
response = self.client.get(self.base_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response.json()["results"]), 0)
+ self.assertEqual([result["id"] for result in response.json()["results"]], [str(sentiment_report.id)])
def test_create_scheduled_sets_next_delivery_date(self):
response = self.client.post(self.base_url, self._scheduled_payload(rrule="FREQ=WEEKLY;BYDAY=MO"), format="json")
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index e11391c6a1b2..911c94042ed6 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -291,7 +291,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(Evaluation.objects.filter(name="Will Rollback").count(), 0)
self.assertEqual(EvaluationReport.objects.count(), 0)
- def test_can_create_sentiment_evaluation_without_default_report(self):
+ def test_can_create_sentiment_evaluation_with_default_report(self):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
{
@@ -311,7 +311,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(evaluation.evaluation_config, {"source": "user_messages"})
self.assertEqual(evaluation.output_type, "sentiment")
self.assertEqual(evaluation.output_config, {})
- self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 0)
+ self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 1)
def test_rejects_sentiment_evaluation_with_trace_target(self):
response = self.client.post(
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index 670abf77a43e..87746742eb29 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -116,15 +116,15 @@ EVALUATION_CONFIG_CONTENT_KEYS: dict[str, str] = {
EvaluationType.SENTIMENT.value: "source",
}
-REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (OutputType.BOOLEAN.value,)
+REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (OutputType.BOOLEAN.value, OutputType.SENTIMENT.value)
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) -> bool:
- return output_type in REPORTABLE_OUTPUT_TYPES
+def evaluation_supports_reports(output_type: str | None, target: str | None) -> bool:
+ return output_type in REPORTABLE_OUTPUT_TYPES and target == "generation"
def get_evaluation_config_content_key(evaluation_type: str | None) -> str | None:
diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.py
index 8129e6421535..186913b383fa 100644
--- a/products/ai_observability/backend/models/evaluation_reports.py
+++ b/products/ai_observability/backend/models/evaluation_reports.py
@@ -9,18 +9,22 @@ from posthog.models.utils import UUIDTModel
from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule
+from .evaluation_configs import REPORTABLE_OUTPUT_TYPES
from .evaluations import EvaluationTarget
class EvaluationReportQuerySet(models.QuerySet):
- def deliverable(self) -> "EvaluationReportQuerySet":
- # Reports run a generation-oriented agent, so trace-target evals never deliver — this
- # also covers evals switched from generation to trace after a report was created.
+ def reportable(self) -> "EvaluationReportQuerySet":
return self.filter(
+ evaluation__output_type__in=REPORTABLE_OUTPUT_TYPES,
+ evaluation__target=EvaluationTarget.GENERATION,
+ )
+
+ def deliverable(self) -> "EvaluationReportQuerySet":
+ return self.reportable().filter(
enabled=True,
deleted=False,
evaluation__deleted=False,
- evaluation__target=EvaluationTarget.GENERATION,
)
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 62984e2e2071..051e91987088 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -41,8 +41,10 @@ import { EvaluationTriggers } from './components/EvaluationTriggers'
import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'
import {
evaluationSupportsReports,
+ evaluationSupportsRunSummary,
evaluationTypeHasEditableCriteria,
evaluationTypeUsesModelConfiguration,
+ isBooleanEvaluationOutput,
} from './evaluationCapabilities'
import { evaluationReportLogic } from './evaluationReportLogic'
import { DEFAULT_TRACE_WINDOW_SECONDS, LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'
@@ -96,10 +98,12 @@ export function AIObservabilityEvaluation(): JSX.Element {
const isHog = evaluation.evaluation_type === 'hog'
const isSentiment = evaluation.evaluation_type === 'sentiment'
const isReportableEvaluation = evaluationSupportsReports(evaluation)
+ const supportsRunSummary = evaluationSupportsRunSummary(evaluation)
+ const isBooleanOutput = isBooleanEvaluationOutput(evaluation.output_type)
const hasEditableCriteria = evaluationTypeHasEditableCriteria(evaluation.evaluation_type)
const trendInsightUrl =
- isReportableEvaluation && !isNewEvaluation && evaluation.id
+ supportsRunSummary && !isNewEvaluation && evaluation.id
? urls.insightNew({
query: {
kind: NodeKind.InsightVizNode,
@@ -364,7 +368,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="font-semibold text-lg">{runsSummary.total}</div>
<div className="text-muted">Total runs</div>
</div>
- {isReportableEvaluation && (
+ {supportsRunSummary && (
<div className="text-center">
<div className="font-semibold text-lg text-success">
{runsSummary.successRate}%
@@ -372,7 +376,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="text-muted">Success rate</div>
</div>
)}
- {isReportableEvaluation && evaluation.output_config.allows_na && (
+ {supportsRunSummary && evaluation.output_config.allows_na && (
<div className="text-center">
<div className="font-semibold text-lg">
{runsSummary.applicabilityRate}%
@@ -531,7 +535,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
</span>
</div>
- {isReportableEvaluation && (
+ {isBooleanOutput && (
<Field
name="allows_na"
label={
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
new file mode 100644
index 000000000000..3121dd892e3f
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx
@@ -0,0 +1,113 @@
+import { cleanup, render, screen } from '@testing-library/react'
+
+import type { EvaluationReportRun, EvaluationReportStoredMetrics } from '../types'
+import { EvaluationReportViewer, summarizeEvaluationReportResults } from './EvaluationReportViewer'
+
+function buildMetrics(fields: EvaluationReportStoredMetrics): EvaluationReportStoredMetrics {
+ return {
+ total_runs: 10,
+ period_start: '2026-07-01T00:00:00Z',
+ period_end: '2026-07-02T00:00:00Z',
+ previous_total_runs: null,
+ previous_result_counts: null,
+ previous_result_rates: null,
+ ...fields,
+ }
+}
+
+function buildReportRun(metrics: EvaluationReportStoredMetrics): EvaluationReportRun {
+ return {
+ id: 'run-id',
+ report: 'report-id',
+ content: { title: 'Evaluation report', sections: [], citations: [], metrics },
+ metadata: null,
+ period_start: '2026-07-01T00:00:00Z',
+ period_end: '2026-07-02T00:00:00Z',
+ delivery_status: 'delivered',
+ delivery_errors: [],
+ created_at: '2026-07-02T00:00:00Z',
+ }
+}
+
+describe('EvaluationReportViewer', () => {
+ afterEach(cleanup)
+
+ it.each<[name: string, fields: EvaluationReportStoredMetrics, expected: string]>([
+ [
+ 'sentiment metrics',
+ {
+ output_type: 'sentiment',
+ result_counts: { positive: 4, neutral: 3, negative: 2 },
+ result_rates: { positive: 44.44, neutral: 33.33, negative: 22.22 },
+ },
+ 'Positive 4 (44.4%) · Neutral 3 (33.3%) · Negative 2 (22.2%)',
+ ],
+ [
+ 'boolean metrics',
+ {
+ output_type: 'boolean',
+ result_counts: { pass: 7, fail: 2, na: 1 },
+ result_rates: { pass: 70, fail: 20, na: 10 },
+ pass_rate: 77.78,
+ },
+ 'Pass rate 77.8% · Pass 7 · Fail 2 · N/A 1',
+ ],
+ ['partial boolean metrics', { pass_rate: 80 }, 'Pass rate 80.0%'],
+ [
+ 'partial sentiment metrics',
+ {
+ output_type: 'sentiment',
+ result_rates: { positive: 60, neutral: 30, negative: 10 },
+ },
+ 'Positive 60.0% · Neutral 30.0% · Negative 10.0%',
+ ],
+ ])('summarizes %s without inventing missing counts', (_, fields, expected) => {
+ expect(summarizeEvaluationReportResults(buildMetrics(fields))).toBe(expected)
+ })
+
+ it('shows boolean pass rate once and keeps outcome percentages hidden', () => {
+ const metrics = buildMetrics({
+ output_type: 'boolean',
+ result_counts: { pass: 8, fail: 1, na: 1 },
+ result_rates: { pass: 80, fail: 10, na: 10 },
+ pass_rate: 88.89,
+ previous_pass_rate: 80,
+ })
+
+ render(<EvaluationReportViewer reportRun={buildReportRun(metrics)} compact />)
+
+ expect(screen.getByText('Pass rate')).toBeTruthy()
+ expect(screen.getByText('88.89%')).toBeTruthy()
+ expect(screen.getByText('Pass')).toBeTruthy()
+ expect(screen.getByText('8').classList.contains('text-success')).toBe(true)
+ expect(screen.getByText('Fail').nextElementSibling?.classList.contains('text-danger')).toBe(true)
+ expect(screen.getByText(/8.89pp vs previous/).classList.contains('text-success')).toBe(true)
+ expect(screen.queryByText('(80.00%)')).toBeNull()
+ })
+
+ it('shows sentiment outcome distribution without boolean pass-rate framing', () => {
+ const metrics = buildMetrics({
+ output_type: 'sentiment',
+ result_counts: { positive: 4, neutral: 3, negative: 3 },
+ result_rates: { positive: 40, neutral: 30, negative: 30 },
+ })
+
+ render(<EvaluationReportViewer reportRun={buildReportRun(metrics)} compact />)
+
+ expect(screen.queryByText('Pass rate')).toBeNull()
+ expect(screen.getByText('Positive')).toBeTruthy()
+ expect(screen.getByText('(40.00%)')).toBeTruthy()
+ expect(screen.getAllByText('(30.00%)')).toHaveLength(2)
+ })
+
+ it('preserves a leading heading when a legacy section has no title', () => {
+ const reportRun = buildReportRun(buildMetrics({ pass_rate: 80 }))
+ reportRun.content.sections = [{ content: '# Important context\n\nKeep this detail.' }]
+
+ render(<EvaluationReportViewer reportRun={reportRun} compact />)
+
+ const markdown = document.querySelector('[data-testid="react-markdown"]')
+ expect(markdown?.textContent).toContain('# Important context')
+ expect(markdown?.textContent).toContain('Keep this detail.')
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
index ce6f98c2a4fa..74a4d72c4e40 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx
@@ -7,9 +7,10 @@ import { urls } from 'scenes/urls'
import type {
EvaluationReportCitation,
- EvaluationReportMetrics,
+ EvaluationOutputType,
EvaluationReportRun,
EvaluationReportSection,
+ EvaluationReportStoredMetrics,
} from '../types'
// Rewrite each cited generation_id in the content into a markdown link to the
@@ -60,6 +61,9 @@ function linkifyCitations(content: string, citations: EvaluationReportCitation[]
// well-defined subset of CommonMark: up to 3 leading spaces, then 1-6 `#`,
// then at least one space/tab, then the title text.
function stripRedundantLeadingHeading(content: string, sectionTitle: string): string {
+ if (!sectionTitle.trim()) {
+ return content
+ }
const lines = content.split('\n')
if (lines.length === 0) {
return content
@@ -98,7 +102,10 @@ function ReportSectionContent({
section: EvaluationReportSection
citations: EvaluationReportCitation[]
}): JSX.Element {
- const markdown = linkifyCitations(stripRedundantLeadingHeading(section.content, section.title), citations)
+ const markdown = linkifyCitations(
+ stripRedundantLeadingHeading(section.content ?? '', section.title ?? ''),
+ citations
+ )
return (
<LemonMarkdown lowKeyHeadings className="text-sm">
{markdown}
@@ -106,53 +113,159 @@ function ReportSectionContent({
)
}
-function formatPassRate(rate: number | null | undefined): string {
+const RESULT_ORDER: Record<EvaluationOutputType, string[]> = {
+ boolean: ['pass', 'fail', 'na'],
+ sentiment: ['positive', 'neutral', 'negative'],
+}
+
+interface EvaluationReportResultMetric {
+ key: string
+ label: string
+ count?: number
+ rate?: number
+ previousRate?: number
+}
+
+function formatResultLabel(result: string): string {
+ if (result.toLowerCase() === 'na') {
+ return 'N/A'
+ }
+ const label = result.split('_').join(' ')
+ return label.length > 0 ? `${label[0].toUpperCase()}${label.slice(1)}` : result
+}
+
+function formatResultRate(rate: number | null | undefined, fractionDigits = 2): string {
if (rate == null) {
- return '—'
+ return '–'
+ }
+ return `${rate.toFixed(fractionDigits)}%`
+}
+
+function getResultMetrics(metrics: EvaluationReportStoredMetrics): EvaluationReportResultMetric[] {
+ const resultCounts = metrics.result_counts ?? {}
+ const totalResults = Object.values(resultCounts).reduce((total, count) => total + count, 0)
+ const calculatedResultRates: Record<string, number> = {}
+ if (totalResults > 0) {
+ for (const [key, count] of Object.entries(resultCounts)) {
+ calculatedResultRates[key] = (count / totalResults) * 100
+ }
+ }
+ const genericResultRates = metrics.result_rates ?? {}
+ const resultRates = Object.keys(genericResultRates).length > 0 ? genericResultRates : calculatedResultRates
+ const previousResultRates = metrics.previous_result_rates
+ const resultKeys = new Set([...Object.keys(resultCounts), ...Object.keys(resultRates)])
+ const configuredOrder = RESULT_ORDER[metrics.output_type ?? 'boolean'] ?? []
+ const orderedKeys = [...configuredOrder.filter((key) => resultKeys.delete(key)), ...Array.from(resultKeys).sort()]
+
+ return orderedKeys.map((key) => ({
+ key,
+ label: formatResultLabel(key),
+ count: resultCounts[key],
+ rate: resultRates[key],
+ previousRate: previousResultRates?.[key],
+ }))
+}
+
+function getBooleanPassRate(
+ metrics: EvaluationReportStoredMetrics,
+ resultMetrics: EvaluationReportResultMetric[]
+): number | undefined {
+ if (metrics.pass_rate != null) {
+ return metrics.pass_rate
}
- return `${rate.toFixed(2)}%`
+ const passCount = resultMetrics.find(({ key }) => key === 'pass')?.count
+ const failCount = resultMetrics.find(({ key }) => key === 'fail')?.count
+ if (passCount == null || failCount == null || passCount + failCount === 0) {
+ return undefined
+ }
+ return (passCount / (passCount + failCount)) * 100
}
-function MetricsCard({ metrics }: { metrics: EvaluationReportMetrics }): JSX.Element {
- // Period-over-period delta (if we have a previous pass rate to compare)
- let deltaEl: JSX.Element | null = null
- if (metrics.previous_pass_rate != null) {
- const diff = metrics.pass_rate - metrics.previous_pass_rate
- const arrow = diff > 0 ? '▲' : diff < 0 ? '▼' : '—'
- const color = diff > 0 ? 'text-success' : diff < 0 ? 'text-danger' : 'text-muted'
- deltaEl = (
- <span className={`text-xs ml-1 ${color}`}>
- {arrow} {Math.abs(diff).toFixed(2)}pp vs previous
- </span>
+export function summarizeEvaluationReportResults(metrics: EvaluationReportStoredMetrics): string {
+ const resultMetrics = getResultMetrics(metrics)
+ if ((metrics.output_type ?? 'boolean') === 'boolean') {
+ const passRate = getBooleanPassRate(metrics, resultMetrics)
+ const summaryParts = passRate == null ? [] : [`Pass rate ${formatResultRate(passRate, 1)}`]
+ summaryParts.push(
+ ...resultMetrics.filter(({ count }) => count != null).map(({ label, count }) => `${label} ${count}`)
)
+ return summaryParts.join(' · ') || '–'
}
+ const summary = resultMetrics
+ .map(({ label, count, rate }) => {
+ if (count == null && rate == null) {
+ return null
+ }
+ if (count == null) {
+ return `${label} ${formatResultRate(rate, 1)}`
+ }
+ return rate == null ? `${label} ${count}` : `${label} ${count} (${formatResultRate(rate, 1)})`
+ })
+ .filter((value): value is string => value != null)
+ .join(' · ')
+ return summary || '–'
+}
+
+function MetricsCard({ metrics }: { metrics: EvaluationReportStoredMetrics }): JSX.Element {
+ const resultMetrics = getResultMetrics(metrics)
+ const isBooleanMetrics = (metrics.output_type ?? 'boolean') === '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'
+
return (
<div className="bg-bg-light border rounded p-3 mb-3">
<div className="flex items-center gap-6 flex-wrap text-sm">
- <div>
- <div className="text-muted text-xs">Pass rate</div>
- <div className="font-semibold">
- {formatPassRate(metrics.pass_rate)}
- {deltaEl}
- </div>
- </div>
<div>
<div className="text-muted text-xs">Total runs</div>
- <div className="font-semibold">{metrics.total_runs}</div>
- </div>
- <div>
- <div className="text-muted text-xs">Pass</div>
- <div className="font-semibold text-success">{metrics.pass_count}</div>
- </div>
- <div>
- <div className="text-muted text-xs">Fail</div>
- <div className="font-semibold text-danger">{metrics.fail_count}</div>
- </div>
- <div>
- <div className="text-muted text-xs">N/A</div>
- <div className="font-semibold">{metrics.na_count}</div>
+ <div className="font-semibold">{metrics.total_runs ?? '–'}</div>
</div>
+ {passRate != null && (
+ <div>
+ <div className="text-muted text-xs">Pass rate</div>
+ <div className="font-semibold">
+ {formatResultRate(passRate)}
+ {passRateDiff != null && (
+ <span className={`text-xs ml-1 ${passRateDiffClass}`}>
+ {passRateDiff === 0 ? '→' : passRateDiff > 0 ? '▲' : '▼'}{' '}
+ {Math.abs(passRateDiff).toFixed(2)}pp vs previous
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ {resultMetrics.map(({ key, label, count, rate, previousRate }) => {
+ const diff = previousRate == null || rate == null ? null : rate - previousRate
+ const arrow = diff == null || diff === 0 ? '→' : diff > 0 ? '▲' : '▼'
+ const booleanCountClass =
+ isBooleanMetrics && key === 'pass'
+ ? 'text-success'
+ : isBooleanMetrics && key === 'fail'
+ ? 'text-danger'
+ : ''
+ if (count == null && (isBooleanMetrics || rate == null)) {
+ return null
+ }
+ return (
+ <div key={key}>
+ <div className="text-muted text-xs">{label}</div>
+ <div className={`font-semibold ${booleanCountClass}`}>
+ {count ?? '–'}
+ {!isBooleanMetrics && rate != null && (
+ <span className="text-muted"> ({formatResultRate(rate)})</span>
+ )}
+ {!isBooleanMetrics && diff != null && (
+ <span className="text-xs text-muted ml-1">
+ {arrow} {Math.abs(diff).toFixed(2)}pp vs previous
+ </span>
+ )}
+ </div>
+ </div>
+ )
+ })}
{metrics.previous_total_runs != null && (
<div>
<div className="text-muted text-xs">Previous runs</div>
@@ -186,8 +299,8 @@ export function EvaluationReportViewer({
compact?: boolean
}): JSX.Element {
const content = reportRun.content
- const sections = content.sections ?? []
- const metrics = content.metrics
+ const sections = useMemo(() => content.sections ?? [], [content.sections])
+ const metrics = content.metrics ?? reportRun.metadata
const citations = useMemo(() => content.citations ?? [], [content.citations])
// Default to executive summary (first section) expanded. Memoized so Expand/Collapse all
@@ -280,7 +393,7 @@ export function EvaluationReportViewer({
onChange={(keys) => setExpandedKeys(keys as string[])}
panels={sections.map((section, idx) => ({
key: idx.toString(),
- header: section.title,
+ header: section.title?.trim() || 'Section',
content: <ReportSectionContent section={section} citations={citations} />,
}))}
/>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
index 4fec882bb347..05e76902872e 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportsTab.tsx
@@ -7,7 +7,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { evaluationReportLogic } from '../evaluationReportLogic'
import type { EvaluationReportRun } from '../types'
-import { EvaluationReportViewer } from './EvaluationReportViewer'
+import { EvaluationReportViewer, summarizeEvaluationReportResults } from './EvaluationReportViewer'
interface EvaluationReportsTabProps {
evaluationId: string
@@ -100,11 +100,11 @@ export function EvaluationReportsTab({ evaluationId, onConfigureClick }: Evaluat
),
},
{
- title: 'Pass rate',
- key: 'pass_rate',
+ title: 'Results',
+ key: 'results',
render: (_, run: EvaluationReportRun) => {
- const pct = run.content?.metrics?.pass_rate ?? run.metadata?.pass_rate
- return typeof pct === 'number' ? `${pct.toFixed(1)}%` : '–'
+ const metrics = run.content?.metrics ?? run.metadata
+ return metrics ? summarizeEvaluationReportResults(metrics) : '–'
},
},
{
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index 18dca4f4acc6..b50891fa3e2d 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -8,7 +8,7 @@ import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { EvaluationResultTag, getEvaluationResultSortValue } from '../../components/EvaluationResultTag'
import { EvaluationRunTargetCell } from '../../components/EvaluationRunTargetCell'
-import { evaluationSupportsReports } from '../evaluationCapabilities'
+import { evaluationSupportsRunSummary } from '../evaluationCapabilities'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import { EvaluationRun, SentimentEvaluationRunsFilter } from '../types'
import { EvaluationSummaryControls, EvaluationSummaryPanel } from './EvaluationSummaryPanel'
@@ -40,7 +40,7 @@ function SentimentEvaluationRunsFilters(): JSX.Element {
export function EvaluationRunsTable(): JSX.Element {
const { filteredEvaluationRuns, evaluation, evaluationRunsLoading, runsLookup } = useValues(llmEvaluationLogic)
const { refreshEvaluationRuns } = useActions(llmEvaluationLogic)
- const showSummary = evaluationSupportsReports(evaluation)
+ const showSummary = evaluationSupportsRunSummary(evaluation)
const showSentimentFilters = evaluation?.evaluation_type === 'sentiment'
const columns: LemonTableColumns<EvaluationRun> = [
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
index 9a1cb917bac2..3ae2cf1ec61d 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
@@ -1,9 +1,21 @@
-import { evaluationSupportsReports } from './evaluationCapabilities'
+import { evaluationSupportsReports, evaluationSupportsRunSummary } from './evaluationCapabilities'
+import type { EvaluationOutputType, EvaluationTarget } from './types'
describe('evaluationCapabilities', () => {
- it('supports reports only for boolean generation-target evaluations', () => {
- expect(evaluationSupportsReports({ output_type: 'boolean', target: 'generation' })).toBe(true)
- expect(evaluationSupportsReports({ output_type: 'boolean', target: 'trace' })).toBe(false)
- expect(evaluationSupportsReports({ output_type: 'sentiment', target: 'generation' })).toBe(false)
- })
+ it.each<
+ [outputType: EvaluationOutputType, target: EvaluationTarget, supportsReports: boolean, supportsSummary: boolean]
+ >([
+ ['boolean', 'generation', true, true],
+ ['sentiment', 'generation', true, false],
+ ['boolean', 'trace', false, false],
+ ['sentiment', 'trace', false, false],
+ ])(
+ 'supports the expected capabilities for %s %s evaluations',
+ (outputType, target, supportsReports, supportsSummary) => {
+ const evaluation = { output_type: outputType, target }
+
+ expect(evaluationSupportsReports(evaluation)).toBe(supportsReports)
+ expect(evaluationSupportsRunSummary(evaluation)).toBe(supportsSummary)
+ }
+ )
})
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
index 86a702013c3a..8c714bc0654a 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -1,5 +1,7 @@
import type { EvaluationConfig, EvaluationOutputType, EvaluationType, LLMJudgeEvaluation } from './types'
+const REPORTABLE_OUTPUT_TYPES: ReadonlySet<EvaluationOutputType> = new Set(['boolean', 'sentiment'])
+
export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | null | undefined): boolean {
return outputType === 'boolean'
}
@@ -9,7 +11,17 @@ export function evaluationSupportsReports(
): boolean {
// Trace-level evals aren't supported by the report agent yet — the backend rejects
// report creation for them, so hide the report UI rather than surface that error.
- return isBooleanEvaluationOutput(evaluation?.output_type) && evaluation?.target !== 'trace'
+ return (
+ evaluation?.target === 'generation' &&
+ evaluation.output_type != null &&
+ REPORTABLE_OUTPUT_TYPES.has(evaluation.output_type)
+ )
+}
+
+export function evaluationSupportsRunSummary(
+ evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined
+): boolean {
+ return evaluation?.target === 'generation' && isBooleanEvaluationOutput(evaluation.output_type)
}
export function evaluationTypeUsesModelConfiguration(evaluationType: EvaluationType | null | undefined): boolean {
diff --git a/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts b/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts
index 02dc9d889860..3ba32e790750 100644
--- a/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts
@@ -257,11 +257,12 @@ export async function persistReportDraft(
}
const targets = buildDeliveryTargets(draft)
- if (activeReport) {
+ const report = activeReport ?? (await loadReportsForEvaluation(teamId, evaluationId))[0]
+ if (report) {
await llmAnalyticsEvaluationReportsPartialUpdate(
teamId.toString(),
- activeReport.id,
- buildReportUpdatePayload(draft, activeReport, targets) as EvaluationReportPatchBody
+ report.id,
+ buildReportUpdatePayload(draft, report, targets) as EvaluationReportPatchBody
)
return true
}
@@ -425,9 +426,7 @@ export const evaluationReportLogic = kea<evaluationReportLogicType>([
loadReportRuns: async (reportId: string) => {
const teamId = requireCurrentTeamId(values.currentTeamId)
const response = await llmAnalyticsEvaluationReportsRunsList(teamId.toString(), reportId)
- // The runs endpoint is paginated (DRF envelope); unwrap results so the
- // reducer gets an array rather than the {count, next, previous, results} object.
- return (response?.results || []) as unknown as EvaluationReportRun[]
+ return response?.results || []
},
},
],
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index d16d86b8b89a..d6a9527e27d4 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -1088,14 +1088,14 @@ describe('llmEvaluationLogic', () => {
})
})
- it('switching to sentiment moves away from reports tab', async () => {
+ it('switching to sentiment keeps the reports tab active', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
logic.actions.setActiveTab('reports')
logic.actions.setEvaluationType('sentiment')
await expectLogic(logic).toMatchValues({
- activeTab: 'configuration',
+ activeTab: 'reports',
})
})
@@ -1353,6 +1353,62 @@ describe('llmEvaluationLogic', () => {
reportLogic.unmount()
}
})
+
+ it('updates the backend-created report when saving a new sentiment evaluation', async () => {
+ let evaluationCreateCount = 0
+ let reportListCount = 0
+ let reportCreateCount = 0
+ let reportUpdateCount = 0
+ const pushSpy = jest.spyOn(router.actions, 'push').mockImplementation(() => {})
+
+ useMocks({
+ get: {
+ '/api/projects/:teamId/llm_analytics/evaluation_reports/': () => {
+ reportListCount += 1
+ return { results: [mockEvaluationReport] }
+ },
+ },
+ post: {
+ '/api/projects/:teamId/evaluations/': () => {
+ evaluationCreateCount += 1
+ return mockSentimentEvaluation
+ },
+ '/api/projects/:teamId/llm_analytics/evaluation_reports/': () => {
+ reportCreateCount += 1
+ return mockEvaluationReport
+ },
+ },
+ patch: {
+ '/api/projects/:teamId/llm_analytics/evaluation_reports/:id/': () => {
+ reportUpdateCount += 1
+ return mockEvaluationReport
+ },
+ },
+ })
+
+ logic = llmEvaluationLogic({ evaluationId: 'new', evaluationType: 'sentiment' })
+ const reportLogic = evaluationReportLogic({ evaluationId: 'new' })
+ logic.mount()
+ reportLogic.mount()
+
+ try {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ logic.actions.setEvaluationName('Sentiment evaluation')
+ reportLogic.actions.setDraftTriggerThreshold(500)
+ reportLogic.actions.setDraftEmailValue('[email protected]')
+
+ logic.actions.saveEvaluation()
+
+ await expectLogic(logic).toFinishAllListeners()
+ expect(evaluationCreateCount).toBe(1)
+ expect(reportListCount).toBe(1)
+ expect(reportUpdateCount).toBe(1)
+ expect(reportCreateCount).toBe(0)
+ } finally {
+ pushSpy.mockRestore()
+ reportLogic.unmount()
+ }
+ })
})
describe('saveEvaluation failure handling', () => {
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index b8055c13c2df..0dccad62f67a 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -26,7 +26,7 @@ import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'
import {
evaluationCanResolveModel,
evaluationSupportsReports,
- evaluationTypeDefaultsToBooleanOutput,
+ evaluationSupportsRunSummary,
isBooleanEvaluationOutput,
isLLMJudgeEvaluation,
} from './evaluationCapabilities'
@@ -276,7 +276,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!teamId || !props.evaluationId || props.evaluationId === 'new') {
return null
}
- if (!evaluationSupportsReports(values.evaluation)) {
+ if (!evaluationSupportsRunSummary(values.evaluation)) {
return null
}
@@ -770,8 +770,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
})
}
},
- setEvaluationType: ({ evaluationType }) => {
- if (!evaluationTypeDefaultsToBooleanOutput(evaluationType) && values.activeTab === 'reports') {
+ setEvaluationType: () => {
+ if (!evaluationSupportsReports(values.evaluation) && values.activeTab === 'reports') {
actions.setActiveTab('configuration')
}
},
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index e235d139eeae..c7c2d47b97f1 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -1,5 +1,12 @@
import { AnyPropertyFilter, UserBasicType } from '~/types'
+import type {
+ EvaluationReportCitationApi,
+ EvaluationReportMetricsApi,
+ EvaluationReportRunApi,
+ EvaluationReportRunContentApi,
+ EvaluationReportSectionApi,
+} from '../generated/api.schemas'
import { LLMProvider } from '../settings/llmProviderKeysLogic'
export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'
@@ -167,52 +174,12 @@ export interface EvaluationReport {
created_at: string
}
-/** A titled markdown section of the report (v2: agent-chosen title). */
-export interface EvaluationReportSection {
- title: string
- content: string
-}
-
-/** A trace reference cited by the agent to ground a specific finding. */
-export interface EvaluationReportCitation {
- generation_id: string
- trace_id: string
- reason: string
-}
-
-/** Structured metrics computed mechanically from ClickHouse (agent cannot fabricate). */
-export interface EvaluationReportMetrics {
- total_runs: number
- pass_count: number
- fail_count: number
- na_count: number
- pass_rate: number
- period_start: string
- period_end: string
- previous_total_runs: number | null
- previous_pass_rate: number | null
-}
-
-/** Top-level report content stored in EvaluationReportRun.content. */
-export interface EvaluationReportRunContent {
- title: string
- sections: EvaluationReportSection[]
- citations: EvaluationReportCitation[]
- metrics: EvaluationReportMetrics
-}
-
-export interface EvaluationReportRun {
- id: string
- report: string
- content: EvaluationReportRunContent
- /** Legacy mirror of content.metrics — populated by the store activity for backwards compat. */
- metadata: EvaluationReportMetrics
- period_start: string
- period_end: string
- delivery_status: 'pending' | 'delivered' | 'partial_failure' | 'failed'
- delivery_errors: string[]
- created_at: string
-}
+export type EvaluationReportSection = EvaluationReportSectionApi
+export type EvaluationReportCitation = EvaluationReportCitationApi
+export type EvaluationReportMetrics = EvaluationReportMetricsApi
+export type EvaluationReportStoredMetrics = EvaluationReportMetricsApi
+export type EvaluationReportRunContent = EvaluationReportRunContentApi
+export type EvaluationReportRun = EvaluationReportRunApi
export type SentimentEvaluationRunsFilter = 'negative' | 'positive' | 'neutral' | 'all'
export type EvaluationSummaryFilter = 'pass' | 'fail' | 'na' | SentimentEvaluationRunsFilter
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index c28a66ed1e8c..1318c256dcba 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -1225,6 +1225,95 @@ export interface PatchedEvaluationReportUpdateApi {
readonly created_at?: string
}
+export interface EvaluationReportSectionApi {
+ /** Agent-generated section heading. */
+ title?: string
+ /** Markdown narrative for this section. */
+ content?: string
+}
+
+export interface EvaluationReportCitationApi {
+ /** Generation UUID referenced by this citation. */
+ generation_id?: string
+ /** Trace identifier containing the referenced generation. */
+ trace_id?: string
+ /** Short explanation of why the generation is cited. */
+ reason?: string
+}
+
+/**
+ * Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative.
+ */
+export type EvaluationReportMetricsApiResultCounts = { [key: string]: number }
+
+/**
+ * Percentage by output-specific result label, from 0 to 100.
+ */
+export type EvaluationReportMetricsApiResultRates = { [key: string]: number }
+
+/**
+ * Count by result label for the previous period, or null when unavailable.
+ * @nullable
+ */
+export type EvaluationReportMetricsApiPreviousResultCounts = { [key: string]: number } | null
+
+/**
+ * Percentage by result label for the previous period, or null when unavailable.
+ * @nullable
+ */
+export type EvaluationReportMetricsApiPreviousResultRates = { [key: string]: number } | null
+
+export interface EvaluationReportMetricsApi {
+ /** Evaluation result type. Stored metrics without this field represent boolean evaluations.
+ *
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment */
+ output_type?: OutputTypeEnumApi
+ /** Number of evaluation results in the report period. */
+ total_runs?: number
+ /** Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative. */
+ result_counts?: EvaluationReportMetricsApiResultCounts
+ /** Percentage by output-specific result label, from 0 to 100. */
+ result_rates?: EvaluationReportMetricsApiResultRates
+ /** ISO 8601 start of the evaluation window represented by these metrics. */
+ period_start?: string
+ /** ISO 8601 end of the evaluation window represented by these metrics. */
+ period_end?: string
+ /**
+ * Number of evaluation results in the previous comparison period, or null when unavailable.
+ * @nullable
+ */
+ previous_total_runs?: number | null
+ /**
+ * Count by result label for the previous period, or null when unavailable.
+ * @nullable
+ */
+ previous_result_counts?: EvaluationReportMetricsApiPreviousResultCounts
+ /**
+ * Percentage by result label for the previous period, or null when unavailable.
+ * @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.
+ * @nullable
+ */
+ previous_pass_rate?: number | null
+}
+
+export interface EvaluationReportRunContentApi {
+ /** Agent-generated report headline. */
+ title?: string
+ /** Ordered narrative sections in the report. */
+ sections?: EvaluationReportSectionApi[]
+ /** Trace references grounding findings in the report. */
+ citations?: EvaluationReportCitationApi[]
+ /** Structured metrics computed for the report period. */
+ metrics?: EvaluationReportMetricsApi | null
+}
+
/**
* * `pending` - Pending
* * `delivered` - Delivered
@@ -1245,23 +1334,24 @@ export interface EvaluationReportRunApi {
readonly id: string
/** UUID of the report config that generated this run. */
readonly report: string
- /** Generated report content (markdown or structured text). */
- readonly content: unknown
- /** Run metadata including model used, token counts, and generation stats. */
- readonly metadata: unknown
+ /** Structured report narrative, citations, and metrics. Legacy runs may contain only some fields. */
+ readonly content: EvaluationReportRunContentApi
+ /** Legacy mirror of content.metrics. May contain partial boolean metrics on older runs. */
+ readonly metadata: EvaluationReportMetricsApi | null
/** Start of the evaluation window covered by this report. */
readonly period_start: string
/** End of the evaluation window covered by this report. */
readonly period_end: string
- /** 'pending', 'delivered', or 'failed'.
+ /** Delivery result: 'pending', 'delivered', 'partial_failure', or 'failed'.
*
* * `pending` - Pending
* * `delivered` - Delivered
* * `partial_failure` - Partial Failure
* * `failed` - Failed */
readonly delivery_status: DeliveryStatusEnumApi
- /** List of delivery error messages if delivery failed. */
- readonly delivery_errors: unknown
+ /** Delivery error messages. Empty when all configured deliveries succeeded. */
+ readonly delivery_errors: readonly string[]
+ /** When this report run was created. */
readonly created_at: string
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2154d2730fa2..265d9dc48701 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22789,28 +22789,118 @@ export namespace Schemas {
readonly created_at: string;
}
+ export interface EvaluationReportCitation {
+ /** Generation UUID referenced by this citation. */
+ generation_id?: string;
+ /** Trace identifier containing the referenced generation. */
+ trace_id?: string;
+ /** Short explanation of why the generation is cited. */
+ reason?: string;
+ }
+
+ /**
+ * Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative.
+ */
+ export type EvaluationReportMetricsResultCounts = {[key: string]: number};
+
+ /**
+ * Percentage by output-specific result label, from 0 to 100.
+ */
+ export type EvaluationReportMetricsResultRates = {[key: string]: number};
+
+ /**
+ * Count by result label for the previous period, or null when unavailable.
+ * @nullable
+ */
+ export type EvaluationReportMetricsPreviousResultCounts = {[key: string]: number} | null;
+
+ /**
+ * Percentage by result label for the previous period, or null when unavailable.
+ * @nullable
+ */
+ export type EvaluationReportMetricsPreviousResultRates = {[key: string]: number} | null;
+
+ export interface EvaluationReportMetrics {
+ /** Evaluation result type. Stored metrics without this field represent boolean evaluations.
+ *
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment */
+ output_type?: OutputTypeEnum;
+ /** Number of evaluation results in the report period. */
+ total_runs?: number;
+ /** Count by output-specific result label, such as pass/fail/N/A or positive/neutral/negative. */
+ result_counts?: EvaluationReportMetricsResultCounts;
+ /** Percentage by output-specific result label, from 0 to 100. */
+ result_rates?: EvaluationReportMetricsResultRates;
+ /** ISO 8601 start of the evaluation window represented by these metrics. */
+ period_start?: string;
+ /** ISO 8601 end of the evaluation window represented by these metrics. */
+ period_end?: string;
+ /**
+ * Number of evaluation results in the previous comparison period, or null when unavailable.
+ * @nullable
+ */
+ previous_total_runs?: number | null;
+ /**
+ * Count by result label for the previous period, or null when unavailable.
+ * @nullable
+ */
+ previous_result_counts?: EvaluationReportMetricsPreviousResultCounts;
+ /**
+ * Percentage by result label for the previous period, or null when unavailable.
+ * @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.
+ * @nullable
+ */
+ previous_pass_rate?: number | null;
+ }
+
+ export interface EvaluationReportSection {
+ /** Agent-generated section heading. */
+ title?: string;
+ /** Markdown narrative for this section. */
+ content?: string;
+ }
+
+ export interface EvaluationReportRunContent {
+ /** Agent-generated report headline. */
+ title?: string;
+ /** Ordered narrative sections in the report. */
+ sections?: EvaluationReportSection[];
+ /** Trace references grounding findings in the report. */
+ citations?: EvaluationReportCitation[];
+ /** Structured metrics computed for the report period. */
+ metrics?: EvaluationReportMetrics | null;
+ }
+
export interface EvaluationReportRun {
/** UUID of this report run. */
readonly id: string;
/** UUID of the report config that generated this run. */
readonly report: string;
- /** Generated report content (markdown or structured text). */
- readonly content: unknown;
- /** Run metadata including model used, token counts, and generation stats. */
- readonly metadata: unknown;
+ /** Structured report narrative, citations, and metrics. Legacy runs may contain only some fields. */
+ readonly content: EvaluationReportRunContent;
+ /** Legacy mirror of content.metrics. May contain partial boolean metrics on older runs. */
+ readonly metadata: EvaluationReportMetrics | null;
/** Start of the evaluation window covered by this report. */
readonly period_start: string;
/** End of the evaluation window covered by this report. */
readonly period_end: string;
- /** 'pending', 'delivered', or 'failed'.
+ /** Delivery result: 'pending', 'delivered', 'partial_failure', or 'failed'.
*
* * `pending` - Pending
* * `delivered` - Delivered
* * `partial_failure` - Partial Failure
* * `failed` - Failed */
readonly delivery_status: DeliveryStatusEnum;
- /** List of delivery error messages if delivery failed. */
- readonly delivery_errors: unknown;
+ /** Delivery error messages. Empty when all configured deliveries succeeded. */
+ readonly delivery_errors: readonly string[];
+ /** When this report run was created. */
readonly created_at: string;
}