:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): steer sentiment eval reports to user messages, not reasoning (#74697)
Radu Raicea156649eac18d
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.pyindex 9c24c9cd094b..14bdf1ed526d 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py@@ -269,7 +269,7 @@ def run_eval_report_agent(agent = create_react_agent(model=llm,- tools=get_eval_report_tools(evaluation_target),+ tools=get_eval_report_tools(evaluation_target, output_type),prompt=system_prompt,state_schema=EvalReportAgentState,)diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.pyindex f83943c553e4..7a63a5dff0ac 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py@@ -34,9 +34,8 @@ You build the report incrementally by calling three output tools:- **`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, target ID, score when available, and truncated reasoning.-- **`sample_eval_results(outcome="all"|{outcome_options}, limit)`**: sample evaluation rows with their full reasoning.+{reasoning_tool_section}- **`list_all_eval_results(max_reasoning_length=80)`**: compact overview of all results, with outcome, target ID, and score when available. {result_overview_detail}+- **`sample_eval_results(outcome="all"|{outcome_options}, limit{sample_ordering_signature})`**: sample evaluation rows. {sample_ordering_instruction}{detail_tools_section}- **`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.@@ -44,12 +43,12 @@ You build the report incrementally by calling three output tools:## Grounding rule{grounding_rule}-+{sentiment_guidance_section}## Suggested workflow1. 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.+3. {outcome_analysis_step}4. {detail_step}5. Optionally inspect recent report runs for continuity.6. Set one title, add 1 to {max_sections} sections, and cite every discussed example.@@ -81,6 +80,7 @@ def build_eval_report_system_prompt(f"```\n{report_prompt_guidance.strip()}\n```\n")+ sentiment_guidance_section = ""if output_type == "sentiment":result_semantics = ("Sentiment labels classify the user messages associated with each generation as positive, neutral, or "@@ -89,6 +89,32 @@ def build_eval_report_system_prompt()analysis_outcome = "negative"primary_outcome = "positive"+ reasoning_tool_section = ""+ result_overview_detail = "Classifier reasoning is omitted."+ sample_ordering_signature = ', order_by="recent"|"score"'+ sample_ordering_instruction = 'Use `order_by="score"` to return the highest-confidence sentiment labels first. Classifier reasoning is omitted.'+ analysis_sample_arguments = f'outcome="{analysis_outcome}", order_by="score"'+ outcome_analysis_step = (+ f"Sample `{analysis_outcome}` outcomes with `sample_eval_results({analysis_sample_arguments})`, then inspect "+ "the user messages in those generations."+ )+ sentiment_guidance_section = (+ "\n## How to analyze sentiment\n\n"+ "This is a sentiment evaluation. The point of this report is to help the reader understand **who is "+ "frustrated and why**, grounded in what users actually said.\n\n"+ "- **Use user messages instead of reasoning.** Sentiment is produced by a classifier, not a judge, so it "+ "has no per-result explanation. The result tools omit reasoning for this evaluation.\n"+ "- **Read what the user said instead.** Sentiment classifies only the **last user message** in each "+ "generation's input. To understand a negative result, load the generation itself (`sample_generation_details`, "+ "then `get_generation_detail` or `get_generation_text_repr`) and look at that last user message. That is "+ "where the frustration is.\n"+ "- **Start with the highest-confidence negative results.** "+ '`sample_eval_results(outcome="negative", order_by="score")` returns negative results from highest to lowest '+ "score. Sample enough results to find recurring themes in what users are complaining about, then cite "+ "representative examples.\n"+ "- Ground every claim about frustration in the user's own words. Quote or closely paraphrase the actual "+ "last user message from real negative generations you cited.\n"+ )elif output_type == "boolean":evaluated_unit = "trace" if evaluation_target == "trace" else "generation"result_semantics = (@@ -98,6 +124,18 @@ def build_eval_report_system_prompt()analysis_outcome = "fail"primary_outcome = "pass"+ reasoning_tool_section = (+ "- **`get_top_outcome_reasons(outcome, limit)`**: grouped reasoning strings for one outcome. "+ f"If omitted, outcome defaults to `{analysis_outcome}`.\n"+ )+ result_overview_detail = "Includes truncated reasoning."+ sample_ordering_signature = ""+ sample_ordering_instruction = 'Rows include full reasoning. Use the default `order_by="recent"`.'+ analysis_sample_arguments = f'outcome="{analysis_outcome}"'+ outcome_analysis_step = (+ f"Inspect grouped reasons and sample relevant outcomes, using `{analysis_outcome}` and `{primary_outcome}` "+ "as starting points."+ )else:raise ValueError(f"Unsupported evaluation report output type: {output_type}")@@ -113,7 +151,7 @@ def build_eval_report_system_prompt()grounding_rule = f"""For every recurring outcome pattern or quality issue you describe:-1. Call `sample_eval_results(outcome=\"{analysis_outcome}\")` to find candidate trace IDs. Sample `{primary_outcome}` as contrast when useful.+1. Call `sample_eval_results({analysis_sample_arguments})` to find candidate trace IDs. Sample `{primary_outcome}` as contrast when useful.2. Call `sample_trace_details(trace_ids)` to inspect the actual traces.3. Call `add_citation(generation_id=\"\", trace_id=trace_id, reason=reason)` for each example you use.4. Reference the trace ID inline with single backticks so the renderer can link it.@@ -134,7 +172,7 @@ If a trace cannot be resolved, try another example. If none resolve, report the)grounding_rule = f"""For every recurring outcome pattern or quality issue you describe:-1. Call `sample_eval_results(outcome=\"{analysis_outcome}\")` to find candidate generation IDs. Sample `{primary_outcome}` as contrast when useful.+1. Call `sample_eval_results({analysis_sample_arguments})` 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.@@ -152,13 +190,17 @@ If a generation cannot be resolved, try another example. If none resolve, reportevaluation_target=evaluation_target,evaluation_prompt_section=prompt_section,result_semantics=result_semantics,+ sentiment_guidance_section=sentiment_guidance_section,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,+ reasoning_tool_section=reasoning_tool_section,+ result_overview_detail=result_overview_detail,+ sample_ordering_signature=sample_ordering_signature,+ sample_ordering_instruction=sample_ordering_instruction,+ outcome_analysis_step=outcome_analysis_step,citation_tool_instruction=citation_tool_instruction,detail_tools_section=detail_tools_section,grounding_rule=grounding_rule,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.pyindex 63e0f3237ca8..121419f7118f 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@@ -58,6 +58,23 @@ class TestSystemPromptFormat(SimpleTestCase):self.assertIn('outcome="all"|"positive"|"neutral"|"negative"', formatted)self.assertNotIn("pass rate", formatted.lower())+ def test_sentiment_prompt_directs_agent_to_user_message_not_reasoning(self):+ formatted = self._build_prompt(output_type="sentiment")++ self.assertIn("Use user messages instead of reasoning", formatted)+ self.assertIn("last user message", formatted)+ self.assertIn("frustrated and why", formatted)+ self.assertIn('sample_eval_results(outcome="negative", order_by="score")', formatted)+ self.assertNotIn("get_top_outcome_reasons", formatted)+ self.assertNotIn("Inspect grouped reasons", formatted)++ def test_boolean_prompt_omits_sentiment_guidance(self):+ formatted = self._build_prompt(output_type="boolean")++ self.assertNotIn("How to analyze sentiment", formatted)+ self.assertIn("get_top_outcome_reasons", formatted)+ self.assertIn("Inspect grouped reasons", formatted)+def test_trace_prompt_uses_only_trace_detail_workflow(self):formatted = self._build_prompt(evaluation_target="trace")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.pyindex 451e9e899829..6847e273429d 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@@ -221,12 +221,12 @@ class TestSummaryMetrics(SimpleTestCase):class TestTargetAwareEvalResults(SimpleTestCase):- def _state(self, evaluation_target: str) -> dict:+ def _state(self, evaluation_target: str, output_type: str = "boolean") -> dict:return {"team_id": 1,"evaluation_id": "eval-id","evaluation_target": evaluation_target,- "output_type": "boolean",+ "output_type": output_type,"period_start": "2026-04-08T14:00:00+00:00","period_end": "2026-04-08T15:00:00+00:00","trace_id_allowlist": [],@@ -275,6 +275,36 @@ class TestTargetAwareEvalResults(SimpleTestCase):self.assertIn("properties.$ai_target_id", query)self.assertIn("properties.$ai_target_event_id", query)+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ def test_sentiment_list_omits_classifier_reasoning(self, mock_execute_hogql):+ mock_execute_hogql.side_effect = [+ [[1]],+ [[_VALID_GEN_ID, "negative", None, 0.91, "identical classifier reasoning"]],+ ]++ result = _list_all_eval_results_fn(state=self._state("generation", "sentiment"))++ self.assertIn(f"negative (0.91) | {_VALID_GEN_ID}", result)+ self.assertNotIn("classifier reasoning", result)++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ def test_sentiment_sample_orders_by_score_and_omits_reasoning(self, mock_execute_hogql):+ mock_execute_hogql.return_value = [[_VALID_GEN_ID, "negative", "identical classifier reasoning", None, 0.91]]++ result = json.loads(+ _sample_eval_results_fn(+ state=self._state("generation", "sentiment"),+ outcome="negative",+ order_by="score",+ )+ )++ self.assertEqual(+ result,+ [{"generation_id": _VALID_GEN_ID, "outcome": "negative", "score": 0.91}],+ )+ self.assertIn("ORDER BY score DESC, timestamp DESC", mock_execute_hogql.call_args.args[1])+class TestTraceDetailTools(SimpleTestCase):def _state(self) -> dict:@@ -361,15 +391,18 @@ class TestTraceDetailTools(SimpleTestCase):mock_fetch.assert_not_called()mock_execute_hogql.assert_not_called()- def test_target_specific_tool_sets_do_not_expose_irrelevant_detail_tools(self):- generation_tools = {tool.name for tool in get_eval_report_tools("generation")}- trace_tools = {tool.name for tool in get_eval_report_tools("trace")}+ def test_target_and_output_specific_tool_sets_do_not_expose_irrelevant_tools(self):+ generation_tools = {tool.name for tool in get_eval_report_tools("generation", "boolean")}+ trace_tools = {tool.name for tool in get_eval_report_tools("trace", "boolean")}+ sentiment_tools = {tool.name for tool in get_eval_report_tools("generation", "sentiment")}self.assertIn("sample_generation_details", generation_tools)self.assertNotIn("sample_trace_details", generation_tools)self.assertIn("sample_trace_details", trace_tools)self.assertIn("get_trace_detail", trace_tools)self.assertNotIn("sample_generation_details", trace_tools)+ self.assertIn("get_top_outcome_reasons", generation_tools)+ self.assertNotIn("get_top_outcome_reasons", sentiment_tools)class TestUuidRegex(SimpleTestCase):diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.pyindex 357947da2759..79eb6fb18f96 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py@@ -13,7 +13,7 @@ import timeimport randomfrom collections.abc import Callablefrom datetime import UTC, datetime, timedelta-from typing import TYPE_CHECKING, Annotated, TypeVar+from typing import TYPE_CHECKING, Annotated, Literal, TypeVarfrom django.db.models import Q@@ -461,10 +461,11 @@ def list_all_eval_results() -> str:"""Get a compact overview of evaluation results in the period.- Returns up to 500 results as condensed rows: outcome, target 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 the target-specific detail tool.+ Returns up to 500 results as condensed rows with outcome and target ID.+ Boolean results include truncated reasoning, while sentiment results include+ scores without classifier reasoning. When there are more than 500 results,+ returns a random sample. Use this as your first scan to spot patterns before+ drilling into specific examples with the target-specific detail tool.Args:max_reasoning_length: Truncate reasoning strings to this many characters (default 80)@@ -533,10 +534,13 @@ def list_all_eval_results(target_id = str(row[0]) if row[0] else "?"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"{outcome}{score} | {target_id} | {reasoning}")+ fields = [f"{outcome}{score}", target_id]+ if output_type != "sentiment":+ reasoning = (row[4] or "")[:max_reasoning_length]+ if row[4] and len(row[4]) > max_reasoning_length:+ reasoning += "..."+ fields.append(reasoning)+ lines.append(" | ".join(fields))if is_sampled:header = f"Total: {total_count} results (showing random sample of {len(lines)})\n"@@ -550,14 +554,17 @@ def sample_eval_results(state: Annotated[dict, InjectedState],outcome: str = "all",limit: int = 50,+ order_by: Literal["recent", "score"] = "recent",) -> str:- """Sample evaluation runs with target ID, outcome, score, and reasoning.+ """Sample evaluation runs with target ID and outcome.- Call multiple times with different filters to understand patterns.+ Boolean results include reasoning. Sentiment results include scores without+ classifier reasoning and can be ordered by score.Args:outcome: "all" or one of the output type's supported outcomeslimit: Maximum number of results to return (default 50)+ order_by: "recent" or "score"; score ordering is only available for sentiment"""limit = min(max(1, limit), 500)team_id = state["team_id"]@@ -566,6 +573,9 @@ def sample_eval_results(ts_end = _ch_ts(state["period_end"])output_type, definition = _resolve_output_type(state.get("output_type"))evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))+ if order_by == "score" and output_type != "sentiment":+ return json.dumps({"error": "Score ordering is only available for sentiment results"})+ order_clause = "ORDER BY score DESC, timestamp DESC" if order_by == "score" else "ORDER BY timestamp DESC"# Whitelisted filter fragment: outcome predicates come only from the trusted# outcome definition, never directly from the LLM-controlled argument.@@ -593,7 +603,7 @@ def sample_eval_results(AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}{filter_clause}- ORDER BY timestamp DESC+ {order_clause}LIMIT {{limit}}""",placeholders={@@ -611,10 +621,11 @@ def sample_eval_results(entry = {target_id_key: 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]+ else:+ entry["reasoning"] = row[2] or ""result.append(entry)return json.dumps(result, indent=2)@@ -1372,7 +1383,6 @@ _COMMON_OVERVIEW_TOOLS: list[BaseTool] = [_COMMON_FOLLOWUP_TOOLS: list[BaseTool] = [list_recent_report_runs,get_report_run,- get_top_outcome_reasons,]_GENERATION_DETAIL_TOOLS: list[BaseTool] = [sample_generation_details, get_generation_detail, get_generation_text_repr]@@ -1384,11 +1394,12 @@ _OUTPUT_TOOLS: list[BaseTool] = []-def get_eval_report_tools(evaluation_target: str) -> list[BaseTool]:- """Return the shared report tools plus only the details relevant to this target."""+def get_eval_report_tools(evaluation_target: str, output_type: str = "boolean") -> list[BaseTool]:+ """Return the shared report tools plus only the tools relevant to this evaluation."""target = resolve_evaluation_target(evaluation_target)detail_tools = _TRACE_DETAIL_TOOLS if target == TRACE_TARGET else _GENERATION_DETAIL_TOOLS- return [*_COMMON_OVERVIEW_TOOLS, *detail_tools, *_COMMON_FOLLOWUP_TOOLS, *_OUTPUT_TOOLS]+ reasoning_tools = [] if output_type == "sentiment" else [get_top_outcome_reasons]+ return [*_COMMON_OVERVIEW_TOOLS, *detail_tools, *_COMMON_FOLLOWUP_TOOLS, *reasoning_tools, *_OUTPUT_TOOLS]# Preserve the original export for callers that build generation report agents directly.