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.

fix(llma): add $ai_evaluation to trace summarization event types (#53533)

eason525446cb6837
diff --git a/posthog/temporal/llm_analytics/trace_summarization/constants.py b/posthog/temporal/llm_analytics/trace_summarization/constants.py
index b6fc761574d2..c8ce65da92f2 100644
--- a/posthog/temporal/llm_analytics/trace_summarization/constants.py
+++ b/posthog/temporal/llm_analytics/trace_summarization/constants.py
@@ -43,6 +43,21 @@ MAX_TRACE_EVENTS_LIMIT = 50
# workers for minutes.
MAX_TRACE_PROPERTIES_SIZE = 2_000_000
+# AI event types used in trace queries (sampling and fetching).
+# Mirrors `AI_EVENT_NAMES` in posthog/hogql_queries/ai/ai_table_resolver.py
+# and the Node.js list in nodejs/src/ingestion/ai/process-ai-event.ts —
+# kept as a tuple here so HogQL placeholders can build a deterministic
+# `event IN (...)` clause from a single source.
+AI_EVENT_TYPES = (
+ "$ai_span",
+ "$ai_generation",
+ "$ai_embedding",
+ "$ai_evaluation",
+ "$ai_metric",
+ "$ai_feedback",
+ "$ai_trace",
+)
+
# Schedule configuration
SCHEDULE_INTERVAL_HOURS = 1 # How often the coordinator runs
diff --git a/posthog/temporal/llm_analytics/trace_summarization/sampling.py b/posthog/temporal/llm_analytics/trace_summarization/sampling.py
index f8fbffb0dc8a..b7c898e60251 100644
--- a/posthog/temporal/llm_analytics/trace_summarization/sampling.py
+++ b/posthog/temporal/llm_analytics/trace_summarization/sampling.py
@@ -22,6 +22,7 @@ from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.llm_analytics.trace_summarization.constants import (
+ AI_EVENT_TYPES,
MAX_TRACE_EVENTS_LIMIT,
MAX_TRACE_PROPERTIES_SIZE,
)
@@ -138,7 +139,7 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> l
count() as event_count,
sum(length(properties)) as total_properties_size
FROM events
- WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')
+ WHERE event IN {event_types}
AND timestamp >= toDateTime({start_ts}, 'UTC')
AND timestamp < toDateTime({end_ts}, 'UTC')
AND properties.$ai_trace_id != ''
@@ -157,6 +158,7 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> l
query_type="GenerationsForSampling",
query=generations_query,
placeholders={
+ "event_types": ast.Tuple(exprs=[ast.Constant(value=e) for e in AI_EVENT_TYPES]),
"start_ts": ast.Constant(value=start_dt_str),
"end_ts": ast.Constant(value=end_dt_str),
"limit": ast.Constant(value=max_items),
@@ -206,7 +208,7 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> l
count() as event_count,
sum(length(properties)) as total_properties_size
FROM events
- WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')
+ WHERE event IN {event_types}
AND timestamp >= toDateTime({start_ts}, 'UTC')
AND timestamp < toDateTime({end_ts}, 'UTC')
AND properties.$ai_trace_id != ''
@@ -224,6 +226,7 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> l
query_type="TracesForSampling",
query=traces_query,
placeholders={
+ "event_types": ast.Tuple(exprs=[ast.Constant(value=e) for e in AI_EVENT_TYPES]),
"start_ts": ast.Constant(value=start_dt_str),
"end_ts": ast.Constant(value=end_dt_str),
"limit": ast.Constant(value=max_items),
diff --git a/products/llm_analytics/backend/text_repr/formatters/event_formatter.py b/products/llm_analytics/backend/text_repr/formatters/event_formatter.py
index 761cbd6b5970..9ccac458020b 100644
--- a/products/llm_analytics/backend/text_repr/formatters/event_formatter.py
+++ b/products/llm_analytics/backend/text_repr/formatters/event_formatter.py
@@ -177,6 +177,54 @@ def format_embedding_text_repr(event: dict[str, Any], options: FormatterOptions
return formatted_text
+def format_evaluation_text_repr(event: dict[str, Any], options: FormatterOptions | None = None) -> str:
+ """
+ Generate text representation of an evaluation event.
+ Shows the evaluation name, result (pass/fail/N/A), and reasoning.
+ """
+ lines: list[str] = []
+ props = event.get("properties", {})
+
+ eval_name = props.get("$ai_evaluation_name", "Unknown evaluation")
+ result = props.get("$ai_evaluation_result")
+ applicable = props.get("$ai_evaluation_applicable")
+ reasoning = props.get("$ai_evaluation_reasoning")
+ runtime = props.get("$ai_evaluation_runtime")
+ model = props.get("$ai_evaluation_model")
+
+ # Result line
+ if applicable is False or applicable == "false":
+ result_str = "N/A"
+ elif result is True or result == "true":
+ result_str = "PASS"
+ elif result is False or result == "false":
+ result_str = "FAIL"
+ else:
+ result_str = "UNKNOWN"
+
+ # Runtime hint: hog evals are deterministic; llm_judge verdicts are probabilistic
+ # from a specific model — the summarizer should weigh these differently.
+ if runtime == "llm_judge" and model:
+ result_str = f"{result_str} (llm_judge/{model})"
+ elif runtime:
+ result_str = f"{result_str} ({runtime})"
+
+ lines.append(SEPARATOR)
+ lines.append("")
+ if reasoning:
+ lines.append(f"EVALUATION: {eval_name} | Result: {result_str} | Reasoning: {reasoning}")
+ else:
+ lines.append(f"EVALUATION: {eval_name} | Result: {result_str}")
+ lines.append("")
+
+ formatted_text = "\n".join(lines)
+
+ if options and options.get("include_line_numbers", False):
+ formatted_text = add_line_numbers(formatted_text)
+
+ return formatted_text
+
+
def format_event_text_repr(event: dict[str, Any], options: FormatterOptions | None = None) -> str:
"""
Generate complete text representation of any LLM event.
@@ -193,6 +241,9 @@ def format_event_text_repr(event: dict[str, Any], options: FormatterOptions | No
if event_type == "$ai_embedding":
return format_embedding_text_repr(event, options)
+ if event_type == "$ai_evaluation":
+ return format_evaluation_text_repr(event, options)
+
# Default to generation formatter for $ai_generation and other events
return format_generation_text_repr(event, options)
diff --git a/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py b/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py
index 5d3e1d4c9455..8bafd5a12eef 100644
--- a/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py
+++ b/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py
@@ -11,6 +11,7 @@ from datetime import datetime
from ..event_formatter import (
_dict_to_yaml_lines,
format_embedding_text_repr,
+ format_evaluation_text_repr,
format_event_text_repr_from_ai_events_row,
format_generation_text_repr,
)
@@ -197,6 +198,109 @@ class TestErrorFormattingEmbedding:
assert error_string in result
+class TestEvaluationFormatting:
+ def test_evaluation_pass_with_reasoning(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Factual accuracy",
+ "$ai_evaluation_result": True,
+ "$ai_evaluation_reasoning": "The response is factually correct.",
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "EVALUATION: Factual accuracy | Result: PASS | Reasoning: The response is factually correct." in result
+
+ def test_evaluation_fail_with_reasoning(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Relevance check",
+ "$ai_evaluation_result": False,
+ "$ai_evaluation_reasoning": "The response does not address the query.",
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert (
+ "EVALUATION: Relevance check | Result: FAIL | Reasoning: The response does not address the query." in result
+ )
+
+ def test_evaluation_na(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Code quality",
+ "$ai_evaluation_result": False,
+ "$ai_evaluation_applicable": False,
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "EVALUATION: Code quality | Result: N/A" in result
+
+ def test_evaluation_string_result(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Check",
+ "$ai_evaluation_result": "true",
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "EVALUATION: Check | Result: PASS" in result
+
+ def test_evaluation_no_reasoning(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Quick check",
+ "$ai_evaluation_result": True,
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "EVALUATION: Quick check | Result: PASS" in result
+ assert "Reasoning:" not in result
+
+ def test_evaluation_missing_name(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_result": False,
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "EVALUATION: Unknown evaluation | Result: FAIL" in result
+
+ def test_evaluation_hog_runtime(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Length check",
+ "$ai_evaluation_result": True,
+ "$ai_evaluation_runtime": "hog",
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "EVALUATION: Length check | Result: PASS (hog)" in result
+
+ def test_evaluation_llm_judge_runtime_with_model(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Factual accuracy",
+ "$ai_evaluation_result": False,
+ "$ai_evaluation_runtime": "llm_judge",
+ "$ai_evaluation_model": "gpt-4",
+ "$ai_evaluation_reasoning": "Claim contradicts source.",
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "Result: FAIL (llm_judge/gpt-4)" in result
+ assert "Reasoning: Claim contradicts source." in result
+
+ def test_evaluation_llm_judge_runtime_without_model(self):
+ event = {
+ "properties": {
+ "$ai_evaluation_name": "Judge",
+ "$ai_evaluation_result": True,
+ "$ai_evaluation_runtime": "llm_judge",
+ }
+ }
+ result = format_evaluation_text_repr(event)
+ assert "Result: PASS (llm_judge)" in result
+
+
class TestFormatEventTextReprFromAiEventsRow:
"""Adapter for callers reading the ai_events dedicated-column shape.
diff --git a/products/llm_analytics/backend/text_repr/formatters/test/test_trace_formatter.py b/products/llm_analytics/backend/text_repr/formatters/test/test_trace_formatter.py
index bb628bb90a2b..c90c52e425f6 100644
--- a/products/llm_analytics/backend/text_repr/formatters/test/test_trace_formatter.py
+++ b/products/llm_analytics/backend/text_repr/formatters/test/test_trace_formatter.py
@@ -107,6 +107,78 @@ class TestGetEventSummary:
summary = _get_event_summary(event)
assert "ERROR" in summary
+ def test_evaluation_summary_pass(self):
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {
+ "$ai_evaluation_name": "Factual accuracy",
+ "$ai_evaluation_result": True,
+ },
+ }
+ summary = _get_event_summary(event)
+ assert "Factual accuracy" in summary
+ assert "PASS" in summary
+
+ def test_evaluation_summary_fail(self):
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {
+ "$ai_evaluation_name": "Relevance",
+ "$ai_evaluation_result": False,
+ },
+ }
+ summary = _get_event_summary(event)
+ assert "Relevance" in summary
+ assert "FAIL" in summary
+
+ def test_evaluation_summary_na(self):
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {
+ "$ai_evaluation_name": "Code quality",
+ "$ai_evaluation_applicable": False,
+ },
+ }
+ summary = _get_event_summary(event)
+ assert "Code quality" in summary
+ assert "N/A" in summary
+
+ def test_evaluation_summary_default_name(self):
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {"$ai_evaluation_result": True},
+ }
+ summary = _get_event_summary(event)
+ assert "evaluation" in summary
+
+ def test_evaluation_summary_includes_hog_runtime(self):
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {
+ "$ai_evaluation_name": "Length check",
+ "$ai_evaluation_result": True,
+ "$ai_evaluation_runtime": "hog",
+ },
+ }
+ summary = _get_event_summary(event)
+ assert "Length check" in summary
+ assert "hog" in summary
+ assert "PASS" in summary
+
+ def test_evaluation_summary_includes_llm_judge_runtime(self):
+ event = {
+ "event": "$ai_evaluation",
+ "properties": {
+ "$ai_evaluation_name": "Factual accuracy",
+ "$ai_evaluation_result": False,
+ "$ai_evaluation_runtime": "llm_judge",
+ },
+ }
+ summary = _get_event_summary(event)
+ assert "Factual accuracy" in summary
+ assert "llm_judge" in summary
+ assert "FAIL" in summary
+
def test_unknown_event_type(self):
"""Should return event type for unknown events."""
event = {"event": "custom_event", "properties": {}}
@@ -352,6 +424,25 @@ class TestRenderTree:
# Should render without error
assert len(lines) > 0
+ def test_render_evaluation_node(self):
+ nodes = [
+ {
+ "event": {
+ "id": "eval1",
+ "event": "$ai_evaluation",
+ "properties": {
+ "$ai_evaluation_name": "Accuracy",
+ "$ai_evaluation_result": True,
+ "$ai_evaluation_reasoning": "Looks good.",
+ },
+ }
+ }
+ ]
+ lines = _render_tree(nodes, {"include_markers": True, "collapsed": False})
+ result = "\n".join(lines)
+ assert "[EVAL]" in result
+ assert "Accuracy" in result
+
def test_render_event_link(self):
"""Should create event links for other event types."""
nodes = [
diff --git a/products/llm_analytics/backend/text_repr/formatters/trace_formatter.py b/products/llm_analytics/backend/text_repr/formatters/trace_formatter.py
index 8fc944d8282b..2d81f28b6a83 100644
--- a/products/llm_analytics/backend/text_repr/formatters/trace_formatter.py
+++ b/products/llm_analytics/backend/text_repr/formatters/trace_formatter.py
@@ -143,6 +143,27 @@ def _get_event_summary(event: dict[str, Any]) -> str:
summary += f" ({', '.join(parts)})"
return summary
+ if event_type == "$ai_evaluation":
+ eval_name = props.get("$ai_evaluation_name", "evaluation")
+ result = props.get("$ai_evaluation_result")
+ applicable = props.get("$ai_evaluation_applicable")
+ runtime = props.get("$ai_evaluation_runtime")
+
+ parts = []
+ if runtime:
+ parts.append(runtime)
+ if applicable is False or applicable == "false":
+ parts.append("N/A")
+ elif result is True or result == "true":
+ parts.append("PASS")
+ elif result is False or result == "false":
+ parts.append("FAIL")
+
+ summary = eval_name
+ if parts:
+ summary += f" ({', '.join(parts)})"
+ return summary
+
return event_type
@@ -191,13 +212,15 @@ def _get_node_prefix(event_type: str) -> str:
return "[SPAN]"
elif event_type == "$ai_embedding":
return "[EMBED]"
+ elif event_type == "$ai_evaluation":
+ return "[EVAL]"
else:
return "[EVENT]"
def _is_expandable_event(event_type: str) -> bool:
"""Check if event type supports expandable content."""
- return event_type in ("$ai_generation", "$ai_span", "$ai_embedding")
+ return event_type in ("$ai_generation", "$ai_span", "$ai_embedding", "$ai_evaluation")
def _render_collapsed_node(prefix: str, current_prefix: str, node_prefix: str, summary: str) -> str: