diff --git a/packages/gooddata-eval/AGENTS.md b/packages/gooddata-eval/AGENTS.md index 65deb9ef7..ed8726f9a 100644 --- a/packages/gooddata-eval/AGENTS.md +++ b/packages/gooddata-eval/AGENTS.md @@ -67,6 +67,19 @@ which is why `knowledge_question` can reuse `GeneralQuestionEvaluator` verbatim. `agent_switcher_input`, `agentic_memory` items `memory_input`. `agentic_knowledge` items keep earlier user turns in `expected_output.setup_turns` (`question` is the graded turn); their evaluator lives in `core/evaluators/knowledge.py` but is agentic-only, so it is not in the single-shot registry. +`agentic_summary` is not `agentic_dashboard_summary`: that kind builds the context itself from a +dashboard id and grades a rubric; this one sends the context the UI sent (any widget, tab and filter +state), re-executes the stored widget executions, asks follow-ups and checks the figures. +`agentic_summary` items need `agentic_summary_input` (scope, one stored execution per widget, +follow-ups) plus `user_context`: the UI's context without result ids, which expire, so the kind +re-executes the stored executions on every run. Their `question` is a readable scenario line the +judge reads; the text sent to the agent is `agentic_summary_input.question` or the UI's own. +An execution may carry a `baseline` (has data, rows, value sum): data that differs stops the item +before the chat as an ERROR (`data_baseline_changed`), because the run would say nothing about the +agent; an execution that fails or whose result cannot be read stops it as `widget_execution_failed`. +Both causes are on `SETUP_ERRORS` in `core/outcome.py`. An unknown key in an `expected_output` or its +`format` is rejected before any execution. Every turn's figures are checked against the tables the agent read in the conversation +(`core/evaluators/chat_summary_figures.py`); an invented or miscomputed figure fails the run. ## Running the pipeline @@ -188,7 +201,8 @@ That default is correct: agent tool calls create real server-side objects (metri Adding a kind to `PARALLEL_SAFE_TEST_KINDS` is a deliberate assertion that it is read-only, which nothing in the package can prove for you. An item can still be held back: `item_runs_in_parallel` runs an `agentic_search` item with `setup_turns` serially, because -the clearance covers the search and not free-text turns sent before it. +the clearance covers the search and not free-text turns sent before it. An `agentic_summary` +item with a `question` of its own or with `follow_ups` runs serially for the same reason. **The SSE client's retry predicate is load-bearing.** The backoff loop and the retryable status set (429/500/502/503/504) live in `core/_retry.py`, shared by the chat, takeaway and diff --git a/packages/gooddata-eval/README.md b/packages/gooddata-eval/README.md index d0a6e1ea3..dcb0f6394 100644 --- a/packages/gooddata-eval/README.md +++ b/packages/gooddata-eval/README.md @@ -320,11 +320,12 @@ linking ran. Pass `TAVERN_E2E_SKIP_TRACE_LINK=1` to opt out of linking altogethe their eval kind, and states latency for each: - **Single-shot** — kinds that send exactly one chat message per run: every non-agentic kind, plus - `agentic_general_question`, `agentic_guardrail`, `agentic_search` and `agentic_memory`. + `agentic_general_question`, `agentic_guardrail`, `agentic_search`, `agentic_memory` and + `agentic_describe_object`. - **Multi-turn** — kinds that drive a simulated user or fixture turns: `agentic_visualization` (and `vis_agentic`), `agentic_metric_skill`, `agentic_alert_skill`, `agentic_dashboard_skill`, `agentic_document_skill`, `agentic_kda_skill`, `agentic_anomaly_detection`, `agentic_what_if`, - `agentic_agent_switcher`, `agentic_knowledge` and `agentic_conversation`. + `agentic_agent_switcher`, `agentic_knowledge`, `agentic_summary` and `agentic_conversation`. ```json "summary": { diff --git a/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py b/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py index 91986e21f..072a3a543 100644 --- a/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py +++ b/packages/gooddata-eval/src/gooddata_eval/cli/agentic_runner.py @@ -16,9 +16,11 @@ from gooddata_eval.core.agentic.agent_switcher import evaluate_agentic_agent_switcher from gooddata_eval.core.agentic.alert_skill import evaluate_agentic_alert_skill from gooddata_eval.core.agentic.anomaly_detection import evaluate_agentic_anomaly_detection +from gooddata_eval.core.agentic.chat_summary import evaluate_agentic_summary from gooddata_eval.core.agentic.conversation import ConversationFixture, evaluate_agentic_conversation from gooddata_eval.core.agentic.dashboard_skill import evaluate_agentic_dashboard_skill from gooddata_eval.core.agentic.dashboard_summary import evaluate_agentic_dashboard_summary +from gooddata_eval.core.agentic.describe_object import evaluate_agentic_describe_object from gooddata_eval.core.agentic.document_skill import evaluate_agentic_document_skill from gooddata_eval.core.agentic.forecasting import evaluate_agentic_forecasting from gooddata_eval.core.agentic.general_question import evaluate_agentic_general_question @@ -69,6 +71,8 @@ class _LfKw(TypedDict, total=False): "agentic_agent_switcher", "agentic_knowledge", "agentic_memory", + "agentic_summary", + "agentic_describe_object", } ) @@ -94,6 +98,11 @@ class _LfKw(TypedDict, total=False): # vis_agentic, agentic_visualization visualizations come back as AAC proposals # in the chat response; nothing is persisted # and neither module has cleanup code +# agentic_summary executes stored AFMs (a read) and sends the UI's own +# "Summarize" message; an item with a question of its +# own or with follow_ups runs serially +# (item_runs_in_parallel) +# agentic_describe_object one question answered from workspace lookups PARALLEL_SAFE_TEST_KINDS = frozenset( { "agentic_general_question", @@ -102,6 +111,8 @@ class _LfKw(TypedDict, total=False): "agentic_search", "vis_agentic", "agentic_visualization", + "agentic_summary", + "agentic_describe_object", } ) @@ -129,11 +140,14 @@ def item_runs_in_parallel(item: DatasetItem) -> bool: """True for an item of a cleared kind that sends nothing the clearance does not cover. ``agentic_search`` is cleared for its search. An item's ``setup_turns`` are free text sent before the question, - and nothing stops one from asking the agent to save something, so such an item runs serially. + and nothing stops one from asking the agent to save something, so such an item runs serially. The same holds + for an ``agentic_summary`` item with a ``question`` of its own or with ``follow_ups``. """ if not runs_in_parallel(item.test_kind): return False eo = item.expected_output + if item.test_kind == "agentic_summary" and item.agentic_summary_input is not None: + return not (item.agentic_summary_input.question or item.agentic_summary_input.follow_ups) return not (item.test_kind == "agentic_search" and isinstance(eo, dict) and "setup_turns" in eo) @@ -367,6 +381,37 @@ def _dispatch_agentic( agent_id=agent_id, **lf_kw, ) + elif kind == "agentic_summary": + agentic_summary_input = item.agentic_summary_input + if agentic_summary_input is None or item.user_context is None: + raise ValueError(f"agentic_summary item '{item.id}' needs both 'agentic_summary_input' and 'user_context'.") + return evaluate_agentic_summary( + host=host, + token=token, + workspace_id=workspace_id, + # The item's question is its readable scenario line, read by the judge; the text + # sent to the agent is agentic_summary_input.question or the UI's pre-filled one. + scenario=item.question, + summary_input=agentic_summary_input, + user_context=item.user_context, + expected_output=eo if isinstance(eo, dict) else {}, + k=k, + gate=gate, + agent_id=agent_id, + **lf_kw, + ) + elif kind == "agentic_describe_object": + return evaluate_agentic_describe_object( + host=host, + token=token, + workspace_id=workspace_id, + question=item.question, + expected_output=eo if isinstance(eo, dict) else {}, + k=k, + gate=gate, + agent_id=agent_id, + **lf_kw, + ) elif kind == "agentic_what_if": return evaluate_agentic_what_if( host=host, diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/chat_summary.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/chat_summary.py new file mode 100644 index 000000000..8b3cbc756 --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/chat_summary.py @@ -0,0 +1,815 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +"""Chat summary of a widget or a dashboard, sent the way the UI sends it. + +The UI's "Summarize" items (widget menu, dashboard or tab menu) open the assistant with a +fixed question and a `userContext` that describes the dashboard on screen: its definition, +the live filter bar, the active tab, and every widget with the result id it rendered and +the filters that reached it. The skills read the data through those result ids. + +A result id is a key into a result cache and expires, so an item cannot store one. It +stores the UI's `userContext` without result ids, plus each widget's execution (the AFM +and result spec the UI ran, filters included). Before each conversation the executions +run again and the fresh result ids go back into the context. Nothing here resolves +filters: the stored execution already carries the filters the widget rendered with, which +is the only way a KPI's comparison measures, a chart's dimensions and a widget that +ignores the dashboard date filter all stay as the user saw them. +""" + +from __future__ import annotations + +import copy +import time +from dataclasses import dataclass, field +from typing import Any, cast + +import httpx + +from gooddata_eval.core._retry import is_retryable_request_error, retry_transient +from gooddata_eval.core.agentic._failed_runs import build_failed_runs +from gooddata_eval.core.agentic._gate import ( + DEFAULT_GATE, + EvalGate, + gate_passed, + log_gate_scores, + stamp_gate_metadata, +) +from gooddata_eval.core.agentic._outcome import ( + agentic_detail, + agentic_success, + attach_labels, + chat_failure_exit, + failure_message_head, + label_runs, + mark_unscored_run, + raise_agentic_failure, +) +from gooddata_eval.core.agentic._trace_linker import ( + RunIdentity, + RunTraceContext, + SubmitTraceLink, + conversations_to_link, + open_trace_window, + run_trace_link_inline, + submit_trace_scoring, + utc_now, +) +from gooddata_eval.core.chat.render import render_answer_text +from gooddata_eval.core.chat.sse_client import ChatClient, ChatError +from gooddata_eval.core.config import ReasoningEffort +from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError +from gooddata_eval.core.evaluators.base import ItemEvaluation +from gooddata_eval.core.evaluators.chat_summary import ( + CODE_CHECKS, + SummaryScope, + evaluate_turn, + make_judges, + validate_expected, +) +from gooddata_eval.core.evaluators.chat_summary_figures import Table, tables_from_tool_calls +from gooddata_eval.core.models import ( + AgenticAssertionError, + AgenticEvalOutcome, + AgenticSummaryInput, + ChatResult, + LoopExit, + WidgetBaseline, + WidgetExecution, +) +from gooddata_eval.core.outcome import DATA_BASELINE_CHANGED, WIDGET_EXECUTION_FAILED, setup_error +from gooddata_eval.core.timing import PhaseTimings, log_timer, run_latency_s + +# The questions the UI pre-fills. An item's own question wins. +WIDGET_QUESTION = 'Summarize the visualization "{title}"' +DASHBOARD_QUESTION = "Summarize this dashboard" + +_EXECUTE_TIMEOUT_S = 120.0 + + +def execute_widget(client: httpx.Client, workspace_id: str, execution: WidgetExecution) -> str: + """Run one stored execution and return the id of the result it produced; a 429/5xx is retried.""" + body: dict[str, Any] = {"execution": execution.afm, "resultSpec": execution.result_spec} + + def _post() -> httpx.Response: + resp = client.post(f"/api/v1/actions/workspaces/{workspace_id}/execution/afm/execute", json=body) + resp.raise_for_status() + return resp + + resp = retry_transient(_post, is_retryable=is_retryable_request_error) + return str(resp.json()["executionResponse"]["links"]["executionResult"]) + + +def execute_widgets( + host: str, token: str, workspace_id: str, executions: dict[str, WidgetExecution] +) -> dict[str, str | None]: + """Fresh result ids per widget id; None for a widget whose execution failed. + + A failed widget is kept with None rather than raised, so the caller can name every failed + widget at once; `run_chat_summary` stops the item on any of them (`WidgetExecutionError`). + """ + result_ids: dict[str, str | None] = {} + with httpx.Client( + base_url=host.rstrip("/"), headers={"Authorization": f"Bearer {token}"}, timeout=_EXECUTE_TIMEOUT_S + ) as client: + for widget_id, execution in executions.items(): + try: + result_ids[widget_id] = execute_widget(client, workspace_id, execution) + except (httpx.HTTPError, KeyError, ValueError) as exc: # one dead widget must not lose the item + log_timer(f"[chat_summary] widget '{widget_id}' failed to execute: {exc}") + result_ids[widget_id] = None + return result_ids + + +def _has_values(data: Any) -> bool: + if isinstance(data, list): + return any(_has_values(v) for v in data) + return data is not None + + +def fetch_results( + host: str, token: str, workspace_id: str, result_ids: dict[str, str | None] +) -> dict[str, dict[str, Any] | None]: + """Each widget's result body; None for a widget without a result or whose result cannot be read.""" + results: dict[str, dict[str, Any] | None] = {} + with httpx.Client( + base_url=host.rstrip("/"), headers={"Authorization": f"Bearer {token}"}, timeout=_EXECUTE_TIMEOUT_S + ) as client: + for widget_id, result_id in result_ids.items(): + results[widget_id] = None + if not result_id: + continue + url = f"/api/v1/actions/workspaces/{workspace_id}/execution/afm/execute/result/{result_id}" + + def _get(url: str = url) -> httpx.Response: + resp = client.get(url) + resp.raise_for_status() + return resp + + try: + body = retry_transient(_get, is_retryable=is_retryable_request_error).json() + except (httpx.HTTPError, ValueError) as exc: # read the next widget anyway + log_timer(f"[chat_summary] result of widget '{widget_id}' unreadable: {exc}") + continue + results[widget_id] = body if isinstance(body, dict) else None + return results + + +def widgets_with_data(results: dict[str, dict[str, Any] | None]) -> set[str]: + """Widget ids whose result holds at least one value; a result that cannot be read counts as empty.""" + return {w for w, body in results.items() if body is not None and _has_values(body.get("data"))} + + +def _values(data: Any) -> list[float]: + if isinstance(data, list): + return [v for item in data for v in _values(item)] + if isinstance(data, (int, float)) and not isinstance(data, bool): + return [float(data)] + if isinstance(data, str): + try: + return [float(data)] + except ValueError: + return [] + return [] + + +def baseline_of(result: dict[str, Any] | None) -> WidgetBaseline: + """The baseline an item stores for a widget, from its result body (None = no result).""" + if result is None: + return WidgetBaseline(has_data=False, row_count=0, value_sum=0.0) + data = result.get("data") + paging = result.get("paging") or {} + total = paging.get("total") if isinstance(paging, dict) else None + rows = int(total[0]) if isinstance(total, list) and total else (len(data) if isinstance(data, list) else 0) + return WidgetBaseline(has_data=_has_values(data), row_count=rows, value_sum=round(sum(_values(data)), 6)) + + +def baseline_problems( + executions: dict[str, WidgetExecution], results: dict[str, dict[str, Any] | None], titles: dict[str, str] +) -> list[str]: + """One line per widget whose data differs from the baseline the item stores.""" + problems: list[str] = [] + for widget_id, execution in executions.items(): + expected = execution.baseline + if expected is None: + continue + actual = baseline_of(results.get(widget_id)) + changes = [ + f"{name} {getattr(expected, name)} → {getattr(actual, name)}" + for name in ("has_data", "row_count") + if getattr(expected, name) != getattr(actual, name) + ] + if abs(expected.value_sum - actual.value_sum) > max(1e-6, abs(expected.value_sum) * 1e-9): + changes.append(f"value_sum {expected.value_sum:,.2f} → {actual.value_sum:,.2f}") + if changes: + problems.append(f'widget "{titles.get(widget_id, widget_id)}": ' + ", ".join(changes)) + return problems + + +class SetupError(Exception): + """The item's input could not be prepared; `reason` is one of `outcome.SETUP_ERRORS`.""" + + reason = "" + headline = "" + + def __init__(self, problems: list[str]): + self.problems = problems + super().__init__("; ".join(problems)) + + +class DataBaselineError(SetupError): + """The data under the item differs from the baseline it was made with.""" + + reason = DATA_BASELINE_CHANGED + headline = "the widget data changed" + + +class WidgetExecutionError(SetupError): + """A stored execution did not run or its result could not be read: nothing can be said about its data.""" + + reason = WIDGET_EXECUTION_FAILED + headline = "a stored widget execution failed" + + +def execution_problems( + executions: dict[str, WidgetExecution], + result_ids: dict[str, str | None], + results: dict[str, dict[str, Any] | None], + titles: dict[str, str], +) -> list[str]: + """One line per widget that has no result id or whose result has no readable body.""" + problems: list[str] = [] + for widget_id in executions: + if result_ids.get(widget_id) is None: + problems.append(f'widget "{titles.get(widget_id, widget_id)}": the execution failed') + elif results.get(widget_id) is None: + problems.append(f'widget "{titles.get(widget_id, widget_id)}": the result could not be read') + return problems + + +def referenced_widget_ids(user_context: dict[str, Any]) -> list[str]: + return [ + str(o.get("id")) + for group in user_context.get("referencedObjects") or [] + if isinstance(group, dict) + for o in group.get("objects") or [] + if isinstance(o, dict) and o.get("type") == "WIDGET" + ] + + +def is_kpi(execution: WidgetExecution) -> bool: + """A KPI (headline): no attributes and one result dimension holding only the measures. + + A chart of measures only (donut, waterfall, bullet) has no attributes either, but lays the + measures out on a second dimension. Without a result spec, no attributes is all there is. + """ + if execution.afm.get("attributes"): + return False + dims = execution.result_spec.get("dimensions") + if not isinstance(dims, list) or not dims: + return True + return len(dims) == 1 and isinstance(dims[0], dict) and dims[0].get("itemIdentifiers") == ["measureGroup"] + + +def summary_scope( + summary_input: AgenticSummaryInput, user_context: dict[str, Any], with_data: set[str] +) -> SummaryScope: + """What the summarized widgets are: the referenced ones for a widget summary, all for a dashboard.""" + executions = summary_input.executions + in_scope = referenced_widget_ids(user_context) if summary_input.scope == "widget" else list(executions) + in_scope = [w for w in in_scope if w in executions] + kpi_only = bool(in_scope) and all(is_kpi(executions[w]) for w in in_scope) + return SummaryScope( + scope=summary_input.scope, + kpi_only=kpi_only, + all_empty=not any(w in with_data for w in in_scope), + ) + + +def _widgets(user_context: dict[str, Any]) -> list[dict[str, Any]]: + view = user_context.get("view") + dashboard = view.get("dashboard") if isinstance(view, dict) else None + widgets = dashboard.get("widgets") if isinstance(dashboard, dict) else None + if not isinstance(widgets, list): + return [] + return [cast(dict[str, Any], w) for w in widgets if isinstance(w, dict)] + + +def with_result_ids(user_context: dict[str, Any], result_ids: dict[str, str | None]) -> dict[str, Any]: + """A copy of the stored context with each widget's fresh result id. + + A widget with no fresh result id is sent without the key, as the UI sends a widget + that did not render. A stored result id is always dropped: it has expired. + """ + context = copy.deepcopy(user_context) + for widget in _widgets(context): + widget.pop("resultId", None) + result_id = result_ids.get(str(widget.get("widgetId", ""))) + if result_id: + widget["resultId"] = result_id + return context + + +def missing_executions(user_context: dict[str, Any], executions: dict[str, WidgetExecution]) -> list[str]: + """Insight widgets of the context with no stored execution: they would reach the agent without data.""" + return [ + str(w.get("widgetId")) + for w in _widgets(user_context) + if w.get("widgetType", "insight") != "richText" and str(w.get("widgetId")) not in executions + ] + + +def default_question(summary_input: AgenticSummaryInput, user_context: dict[str, Any]) -> str: + """The UI's pre-filled question: the referenced widget's title, or the dashboard one.""" + if summary_input.scope == "dashboard": + return DASHBOARD_QUESTION + referenced = set(referenced_widget_ids(user_context)) + titles = [str(w.get("title")) for w in _widgets(user_context) if str(w.get("widgetId")) in referenced] + if len(titles) != 1: + raise ValueError( + f"A widget summary needs exactly one referenced widget to phrase the UI question, found {len(titles)}; " + "set the item question instead." + ) + return WIDGET_QUESTION.format(title=titles[0]) + + +@dataclass +class SummaryTurn: + """One question and what the agent answered to it.""" + + question: str + result: ChatResult | None = None + error: str | None = None + agent_s: float = 0.0 + exit_reason: LoopExit | None = None # set when the chat call raised + + +@dataclass +class SummaryConversation: + """One run: the summary turn and its follow-ups, in order.""" + + conversation_id: str + turns: list[SummaryTurn] = field(default_factory=list) + widgets_total: int = 0 + widgets_executed: int = 0 + scope: SummaryScope | None = None + filter_years: set[int] = field(default_factory=set) + known_text: list[str] = field(default_factory=list) + # One verdict per answered turn, set by evaluate_chat_summary. + evaluations: list[ItemEvaluation] = field(default_factory=list) + judge_s: float = 0.0 + + @property + def chat_error(self) -> str | None: + return next((t.error for t in self.turns if t.error), None) + + @property + def exit_reason(self) -> LoopExit | None: + """How the run's chat ended when a call raised; None for a run that got every answer.""" + return next((t.exit_reason for t in self.turns if t.exit_reason is not None), None) + + @property + def judge_error(self) -> str | None: + """Why the judge left the run without a verdict, when its verdict was the one still open. + + None when a code check or a graded criterion already failed the run, or the run has no answer. + """ + if self.chat_error is not None: + return None + errors = [e.error for e in self.evaluations if not e.passed and e.error and e.error != "empty answer"] + decided = [e for e in self.evaluations if not e.passed and not (e.error and e.error != "empty answer")] + code_failed = any(e.detail.get(key) is False for e in self.evaluations for key in CODE_CHECKS) + return errors[0] if errors and not decided and not code_failed else None + + +def run_summary_conversation( + client: ChatClient, + conversation_id: str, + questions: list[str], + user_context: dict[str, Any], +) -> list[SummaryTurn]: + """Send the summary question and each follow-up in one conversation, with the same context. + + The UI keeps the dashboard context attached for every message of the conversation, so + the follow-ups carry it too. A failed turn ends the conversation: a later answer would + rest on a turn the agent never answered. + """ + turns: list[SummaryTurn] = [] + for question in questions: + started = time.monotonic() + try: + result = client.send_message(conversation_id, question, user_context=user_context) + except ChatError as exc: + turns.append( + SummaryTurn( + question, + error=f"chat failed: {exc}", + agent_s=time.monotonic() - started, + exit_reason=chat_failure_exit(exc), + ) + ) + break + turns.append(SummaryTurn(question, result=result, agent_s=time.monotonic() - started)) + return turns + + +def run_chat_summary( + host: str, + token: str, + workspace_id: str, + summary_input: AgenticSummaryInput, + user_context: dict[str, Any], + question: str | None = None, + k: int = 1, + reasoning_effort: ReasoningEffort | None = None, + agent_id: str | None = None, +) -> list[SummaryConversation]: + """Run the item K times; each run executes the widgets again and opens its own conversation. + + The executions run per run, not once per item: K runs that share result ids would all + read one cached result, and a result that expires between runs would fail the later ones + for a reason unrelated to the agent. + """ + missing = missing_executions(user_context, summary_input.executions) + if missing: + raise ValueError(f"No stored execution for widgets {missing}; capture them with the item.") + first = question or default_question(summary_input, user_context) + questions = [first] + [f.question for f in summary_input.follow_ups] + client = ChatClient( + host=host, token=token, workspace_id=workspace_id, reasoning_effort=reasoning_effort, agent_id=agent_id + ) + runs: list[SummaryConversation] = [] + try: + for _ in range(k): + result_ids = execute_widgets(host, token, workspace_id, summary_input.executions) + results = fetch_results(host, token, workspace_id, result_ids) + titles = {str(w.get("widgetId")): str(w.get("title")) for w in _widgets(user_context)} + failed = execution_problems(summary_input.executions, result_ids, results, titles) + if failed: + raise WidgetExecutionError(failed) + problems = baseline_problems(summary_input.executions, results, titles) + if problems: + raise DataBaselineError(problems) + scope = summary_scope(summary_input, user_context, widgets_with_data(results)) + context = with_result_ids(user_context, result_ids) + try: + conversation_id = client.create_conversation() + except ( + ChatError, + httpx.HTTPError, + ValueError, + ) as exc: # a lost conversation must not discard completed runs + runs.append(SummaryConversation("", [SummaryTurn(first, error=f"conversation creation failed: {exc}")])) + continue + try: + turns = run_summary_conversation(client, conversation_id, questions, context) + finally: + client.delete_conversation(conversation_id) + runs.append( + SummaryConversation( + conversation_id, + turns, + widgets_total=len(result_ids), + widgets_executed=sum(1 for r in result_ids.values() if r), + scope=scope, + filter_years=filter_years(user_context), + known_text=known_text(user_context), + ) + ) + finally: + client.close() + return runs + + +def _tool_names(result: ChatResult | None) -> list[str]: + return [e.function_name for e in (result.tool_call_events if result else [])] + + +def filter_years(user_context: dict[str, Any]) -> set[int]: + """Years of the absolute date filters on screen: the filter bar and each widget's filters.""" + view = user_context.get("view") + dashboard = view.get("dashboard") if isinstance(view, dict) else None + found: list[dict[str, Any]] = [] + if isinstance(dashboard, dict): + found += [vf.get("filter") for vf in dashboard.get("viewFilters") or [] if isinstance(vf, dict)] + for widget in _widgets(user_context): + found += [f for f in widget.get("filters") or [] if isinstance(f, dict)] + years: set[int] = set() + for f in found: + if not isinstance(f, dict): + continue + bounds = [str(f.get(k, ""))[:4] for k in ("from", "to")] + if all(b.isdigit() for b in bounds): + years |= set(range(int(bounds[0]), int(bounds[1]) + 1)) + return years + + +def known_text(user_context: dict[str, Any]) -> list[str]: + """Names on screen that may hold digits ("Top 10 Spenders", "1-3M"): never read as figures.""" + texts: list[str] = [] + view = user_context.get("view") + dashboard = view.get("dashboard") if isinstance(view, dict) else None + if isinstance(dashboard, dict): + texts.append(str(dashboard.get("title", ""))) + for vf in dashboard.get("viewFilters") or []: + flt = vf.get("filter") if isinstance(vf, dict) else None + state = flt.get("state") if isinstance(flt, dict) else None + if isinstance(state, dict): + texts += [str(v) for values in state.values() if isinstance(values, list) for v in values] + texts += [str(w.get("title", "")) for w in _widgets(user_context)] + return [t for t in texts if t] + + +def judge_input(scenario: str, turns: list[SummaryTurn], index: int) -> str: + """What the judge reads as INPUT for turn `index`. + + - summary turn: the scenario line and its question + - follow-up: also the conversation before it, in full, so a criterion can compare the + answer with what the assistant said earlier + """ + lines = [scenario] + if index: + lines.append("Conversation before this turn:") + for turn in turns[:index]: + lines.append(f"USER: {turn.question}") + lines.append(f"ASSISTANT: {render_answer_text(turn.result) if turn.result else ''}") + lines.append(f"Question of this turn: {turns[index].question}") + return "\n".join(lines) + + +def grade_conversation( + run: SummaryConversation, + *, + scenario: str, + expected_outputs: list[dict[str, Any]], + judge_model: str | None = None, +) -> bool: + """Grade every turn of one run; the run passes when every turn passes. + + `expected_outputs[0]` grades the summary, the rest the follow-ups in order. A run whose + chat failed has no verdict: its error is recorded and nothing is graded. + """ + if run.chat_error is not None: + return False + positive, violation = make_judges(judge_model) + started = time.monotonic() + tables: list[Table] = [] + for index, turn in enumerate(run.turns): + expected = expected_outputs[index] if index < len(expected_outputs) else {} + # a follow-up answers from every table read so far in the conversation + tables = tables + tables_from_tool_calls(turn.result.tool_call_events if turn.result else []) + run.evaluations.append( + evaluate_turn( + judge_input=judge_input(scenario, run.turns, index), + answer=render_answer_text(turn.result) if turn.result else "", + tool_names=_tool_names(turn.result), + expected=expected, + scope=run.scope if index == 0 else None, + positive_judge=positive, + violation_judge=violation, + tables=tables, + filter_years=run.filter_years, + known_text=run.known_text, + ) + ) + run.judge_s = time.monotonic() - started + return run_passed(run) + + +def run_passed(run: SummaryConversation) -> bool: + """Every turn answered and every turn's checks passed.""" + return run.chat_error is None and bool(run.evaluations) and all(e.passed for e in run.evaluations) + + +def _turn_detail(run: SummaryConversation, index: int) -> dict[str, Any]: + turn = run.turns[index] + entry: dict[str, Any] = {"question": turn.question} + if index < len(run.evaluations): + evaluation = run.evaluations[index] + entry.update(evaluation.detail) + if evaluation.error: + entry["error"] = evaluation.error + elif turn.error: + entry["error"] = turn.error + return entry + + +def _run_detail(run: SummaryConversation) -> dict[str, Any]: + """One run's diagnosis, flat like the other kinds' detail. + + - summary turn: its keys at the top level (`actual_output`, `shape_ok`, `must_include_0`, ...) + - follow-up i (from 1): the same keys prefixed `followup__` + """ + detail: dict[str, Any] = {} + for index in range(len(run.turns)): + prefix = f"followup_{index}_" if index else "" + detail.update({f"{prefix}{key}": value for key, value in _turn_detail(run, index).items()}) + detail["widgets_total"] = run.widgets_total + detail["widgets_executed"] = run.widgets_executed + if run.scope is not None: + detail["scope"] = {"scope": run.scope.scope, "kpi_only": run.scope.kpi_only, "all_empty": run.scope.all_empty} + if run.chat_error is not None: + detail["chat_error"] = run.chat_error + events = [ev for t in run.turns if t.result for ev in t.result.tool_call_events] + steps = [ev for t in run.turns if t.result for ev in t.result.reasoning_step_events] + return agentic_detail(events, steps, **detail) + + +def _run_latency(run: SummaryConversation) -> float: + return sum(t.agent_s for t in run.turns) + run.judge_s + + +def _last_result(run: SummaryConversation) -> ChatResult | None: + return next((t.result for t in reversed(run.turns) if t.result), None) + + +class ChatSummaryAssertionError(AgenticAssertionError): + """Raised when an agentic chat-summary evaluation fails.""" + + +def _setup_error(scenario: str, exc: SetupError) -> ChatSummaryAssertionError: + """An ERROR item: its executions failed or its data changed, so no chat ran and nothing was graded.""" + reason = "\n".join(exc.problems) + error = ChatSummaryAssertionError(f"Chat summary not run for '{scenario}': {exc.headline}.\n{reason}") + error.reasoning_steps = [] + error.conversation_id = "" + error.response_id = None + key = "data_baseline" if isinstance(exc, DataBaselineError) else "widgets_executed" + error.detail = {key: False, f"{key}_reason": reason} + error.timings = PhaseTimings() + error.runs_passed = 0 + error.runs_effective = 0 + error.failed_runs = [] + error.run_latencies_s = [] + error.harness_error = setup_error(exc.reason).as_record() + return error + + +def evaluate_agentic_summary( + host: str, + token: str, + workspace_id: str, + scenario: str, + summary_input: AgenticSummaryInput, + user_context: dict[str, Any], + expected_output: dict[str, Any], + k: int = 1, + gate: EvalGate = DEFAULT_GATE, + agent_id: str | None = None, + langfuse: object | None = None, + dataset_item_id: str = "", + dataset_name: str = "chat_summary", + run_timestamp: str | None = None, + model_version_override: str | None = None, + run_metadata_extra: dict | None = None, + reasoning_effort: ReasoningEffort | None = None, + submit_trace_link: SubmitTraceLink = run_trace_link_inline, + judge_model: str | None = None, +) -> AgenticEvalOutcome: + """Run the item K times, grade every turn, log to Langfuse, raise ChatSummaryAssertionError on failure. + + `scenario` is the item's readable line (its `question`), which the judge reads as INPUT; + the text sent to the agent is `summary_input.question` or the UI's pre-filled one. + """ + validate_expected(expected_output, "item") + for n, follow_up in enumerate(summary_input.follow_ups, start=1): + validate_expected(follow_up.expected_output, f"follow-up {n}") + langfuse, window_start = open_trace_window(langfuse) + try: + runs = run_chat_summary( + host, + token, + workspace_id, + summary_input, + user_context, + question=summary_input.question, + k=k, + reasoning_effort=reasoning_effort, + agent_id=agent_id, + ) + except SetupError as exc: + raise _setup_error(scenario, exc) from exc + expected_outputs = [expected_output] + [ + f.expected_output if isinstance(f.expected_output, dict) else {} for f in summary_input.follow_ups + ] + for run in runs: + grade_conversation(run, scenario=scenario, expected_outputs=expected_outputs, judge_model=judge_model) + + scored = [r for r in runs if r.chat_error is None and r.judge_error is None] + pass_at_k = any(run_passed(r) for r in scored) + pass_power_k = bool(runs) and all(run_passed(r) for r in runs) + # Before the Langfuse scores, so a run the judge could not grade gets its ERROR marker there. + run_labels = label_runs(runs, passed=run_passed) + + if langfuse is not None and dataset_item_id: + window_end = utc_now() + + def _write_scores(ctx: RunTraceContext) -> None: + stamp_gate_metadata(ctx.run_metadata, k=len(runs), gate=gate) + for run_idx, run in enumerate(runs): + if run.chat_error is not None or run.judge_error is not None: + # No verdict: a 0.0 would publish a failure nobody graded. + mark_unscored_run(ctx, run_idx, run.conversation_id, run_labels.error_label(run_idx)) + continue + pt = ctx.trace(run.conversation_id) + with ctx.observe(pt, run_idx) as tid: + ctx.score(tid, name="summary_pass", value=float(run_passed(run)), data_type="BOOLEAN") + ctx.quality( + tid, + strict_checks={"summary_pass": run_passed(run)}, + latency_sec=pt.latency if pt else None, + cost_usd=pt.total_cost if pt else None, + ) + log_gate_scores(ctx, tid, gate=gate, pass_at_k=pass_at_k, pass_power_k=pass_power_k) + + submit_trace_scoring( + submit_trace_link, + RunIdentity( + host, + token, + workspace_id, + dataset_name, + run_timestamp, + model_version_override, + run_metadata_extra, + reasoning_effort, + ), + langfuse=langfuse, + dataset_item_id=dataset_item_id, + conversation_ids=conversations_to_link( + [r.conversation_id for r in scored], + [r.conversation_id for r in runs if r not in scored], + ), + window_start=window_start, + window_end=window_end, + suffix_runs=len(runs) > 1, + write_scores=_write_scores, + item_input=scenario, + ) + + best = max(runs, key=lambda r: (run_passed(r), sum(e.passed for e in r.evaluations))) + best_result = _last_result(best) + timings = PhaseTimings() + for run in runs: + timings = timings + PhaseTimings(agent_s=sum(t.agent_s for t in run.turns), judge_s=run.judge_s) + runs_passed = sum(1 for r in runs if run_passed(r)) + failed_runs = build_failed_runs(runs, labels=run_labels, detail=_run_detail) + reasoning = list(best_result.reasoning_steps or []) if best_result else [] + run_latencies_s = [_run_latency(r) for r in runs] + best_latency = run_latency_s(PhaseTimings(agent_s=sum(t.agent_s for t in best.turns), judge_s=best.judge_s)) + detail = _run_detail(best) + unscored = [r.judge_error for r in runs if r.judge_error is not None] + if unscored: + detail["unscored_runs"] = len(unscored) + detail["judge_errors"] = unscored + + if unscored and not scored: + # No run got a verdict: the item is a harness error, not K failures. + error = JudgeResponseError( + f"judge returned no readable verdict for any of the {len(unscored)} graded run(s): " + " | ".join(unscored) + ) + error.reasoning_steps = reasoning + error.conversation_id = best.conversation_id + error.response_id = best_result.response_id if best_result else None + error.detail = detail + error.runs_passed = runs_passed + error.runs_effective = len(runs) + error.failed_runs = failed_runs + error.run_latencies_s = run_latencies_s + error.best_run_latency_s = best_latency + error.timings = timings + attach_labels(error, run_labels, gate) + raise error + + if not gate_passed(gate, pass_at_k=pass_at_k, pass_power_k=pass_power_k): + failing = next((e for e in best.evaluations if not e.passed), None) + reason = best.chat_error or (failing.error if failing and failing.error else "criteria not satisfied") + head = failure_message_head(gate, run_labels, runs_passed, failed_runs, len(unscored)) + raise_agentic_failure( + ChatSummaryAssertionError, + f"Chat summary failed for '{scenario}'. {head} " + f"({best.widgets_executed}/{best.widgets_total} widgets executed): {reason}", + harness_error=run_labels.harness_error_record, + shadow=run_labels.shadow(gate), + reasoning_steps=reasoning, + conversation_id=best.conversation_id, + response_id=best_result.response_id if best_result else None, + detail=detail, + runs_passed=runs_passed, + runs_effective=len(runs), + failed_runs=failed_runs, + run_latencies_s=run_latencies_s, + best_run_latency_s=best_latency, + timings=timings, + ) + return agentic_success( + shadow=run_labels.shadow(gate), + reasoning_steps=reasoning, + conversation_id=best.conversation_id, + response_id=best_result.response_id if best_result else None, + detail=detail, + runs_passed=runs_passed, + runs_effective=len(runs), + failed_runs=failed_runs, + run_latencies_s=run_latencies_s, + best_run_latency_s=best_latency, + timings=timings, + ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/describe_object.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/describe_object.py new file mode 100644 index 000000000..1e2a36bdd --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/describe_object.py @@ -0,0 +1,268 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +"""Describe or explain an analytics object in the chat, as a user asks on the Analyze page. + +One question, no `userContext`: the agent has to find the object in the workspace itself. +Each of the K runs opens its own conversation; the gate decides the item. +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field +from typing import Any + +import httpx + +from gooddata_eval.core.agentic._failed_runs import build_failed_runs +from gooddata_eval.core.agentic._gate import ( + DEFAULT_GATE, + EvalGate, + gate_passed, + log_gate_scores, + stamp_gate_metadata, +) +from gooddata_eval.core.agentic._outcome import ( + agentic_detail, + agentic_success, + attach_labels, + chat_failure_exit, + failure_message_head, + label_runs, + mark_unscored_run, + raise_agentic_failure, +) +from gooddata_eval.core.agentic._trace_linker import ( + RunIdentity, + RunTraceContext, + SubmitTraceLink, + conversations_to_link, + open_trace_window, + run_trace_link_inline, + submit_trace_scoring, + utc_now, +) +from gooddata_eval.core.chat.render import render_answer_text +from gooddata_eval.core.chat.sse_client import ChatClient, ChatError +from gooddata_eval.core.config import ReasoningEffort +from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError +from gooddata_eval.core.evaluators.base import ItemEvaluation +from gooddata_eval.core.evaluators.describe_object import evaluate_answer, make_judges +from gooddata_eval.core.models import AgenticAssertionError, AgenticEvalOutcome, ChatResult, LoopExit +from gooddata_eval.core.timing import PhaseTimings, run_latency_s + + +@dataclass +class DescribeRun: + conversation_id: str + result: ChatResult | None = None + error: str | None = None + evaluation: ItemEvaluation | None = None + agent_s: float = 0.0 + judge_s: float = 0.0 + tool_names: list[str] = field(default_factory=list) + exit_reason: LoopExit | None = None # set when a chat call raised + + @property + def passed(self) -> bool: + """Answered, and every check passed.""" + return self.error is None and self.evaluation is not None and self.evaluation.passed + + @property + def judge_error(self) -> str | None: + """Why the judge left the run without a verdict, when the lookup check had not already failed it.""" + ev = self.evaluation + if self.error is not None or ev is None or ev.passed or not ev.error or ev.error == "empty answer": + return None + return None if ev.detail.get("workspace_lookup") is False else ev.error + + +def _run_once(client: ChatClient, question: str, expected: dict[str, Any], judge_model: str | None) -> DescribeRun: + try: + conversation_id = client.create_conversation() + except (ChatError, httpx.HTTPError, ValueError) as exc: # a lost conversation must not discard completed runs + return DescribeRun("", error=f"conversation creation failed: {exc}", exit_reason=chat_failure_exit(exc)) + run = DescribeRun(conversation_id) + started = time.monotonic() + try: + run.result = client.send_message(conversation_id, question) + except ChatError as exc: + run.error = f"chat failed: {exc}" + run.exit_reason = chat_failure_exit(exc) + finally: + run.agent_s = time.monotonic() - started + client.delete_conversation(conversation_id) + if run.result is not None: + run.tool_names = [e.function_name for e in run.result.tool_call_events] + positive, violation = make_judges(judge_model) + judged = time.monotonic() + run.evaluation = evaluate_answer( + question=question, + answer=render_answer_text(run.result), + tool_names=run.tool_names, + expected=expected, + positive_judge=positive, + violation_judge=violation, + ) + run.judge_s = time.monotonic() - judged + return run + + +def _run_detail(run: DescribeRun) -> dict[str, Any]: + detail: dict[str, Any] = dict(run.evaluation.detail) if run.evaluation else {} + detail["tools"] = run.tool_names + if run.error: + detail["chat_error"] = run.error + if run.result is None: + return detail + return agentic_detail(run.result.tool_call_events, run.result.reasoning_step_events, **detail) + + +class DescribeObjectAssertionError(AgenticAssertionError): + """Raised when an agentic describe-object evaluation fails.""" + + +def evaluate_agentic_describe_object( + host: str, + token: str, + workspace_id: str, + question: str, + expected_output: dict[str, Any], + k: int = 1, + gate: EvalGate = DEFAULT_GATE, + agent_id: str | None = None, + langfuse: object | None = None, + dataset_item_id: str = "", + dataset_name: str = "describe_objects", + run_timestamp: str | None = None, + model_version_override: str | None = None, + run_metadata_extra: dict | None = None, + reasoning_effort: ReasoningEffort | None = None, + submit_trace_link: SubmitTraceLink = run_trace_link_inline, + judge_model: str | None = None, +) -> AgenticEvalOutcome: + """Ask K times, grade each answer, log to Langfuse, raise DescribeObjectAssertionError on failure.""" + langfuse, window_start = open_trace_window(langfuse) + client = ChatClient( + host=host, token=token, workspace_id=workspace_id, reasoning_effort=reasoning_effort, agent_id=agent_id + ) + try: + runs = [_run_once(client, question, expected_output, judge_model) for _ in range(k)] + finally: + client.close() + + scored = [r for r in runs if r.error is None and r.judge_error is None] + pass_at_k = any(r.passed for r in scored) + pass_power_k = bool(runs) and all(r.passed for r in runs) + run_labels = label_runs(runs, passed=lambda r: r.passed) + + if langfuse is not None and dataset_item_id: + window_end = utc_now() + + def _write_scores(ctx: RunTraceContext) -> None: + stamp_gate_metadata(ctx.run_metadata, k=len(runs), gate=gate) + for run_idx, run in enumerate(runs): + if run.error is not None or run.judge_error is not None: + mark_unscored_run(ctx, run_idx, run.conversation_id, run_labels.error_label(run_idx)) + continue + pt = ctx.trace(run.conversation_id) + with ctx.observe(pt, run_idx) as tid: + ctx.score(tid, name="describe_pass", value=float(run.passed), data_type="BOOLEAN") + ctx.quality( + tid, + strict_checks={"describe_pass": run.passed}, + latency_sec=pt.latency if pt else None, + cost_usd=pt.total_cost if pt else None, + ) + log_gate_scores(ctx, tid, gate=gate, pass_at_k=pass_at_k, pass_power_k=pass_power_k) + + submit_trace_scoring( + submit_trace_link, + RunIdentity( + host, + token, + workspace_id, + dataset_name, + run_timestamp, + model_version_override, + run_metadata_extra, + reasoning_effort, + ), + langfuse=langfuse, + dataset_item_id=dataset_item_id, + conversation_ids=conversations_to_link( + [r.conversation_id for r in scored], + [r.conversation_id for r in runs if r not in scored and r.conversation_id], + ), + window_start=window_start, + window_end=window_end, + suffix_runs=len(runs) > 1, + write_scores=_write_scores, + item_input=question, + ) + + best = max(runs, key=lambda r: (r.passed, r.evaluation.rank_key if r.evaluation else (-2, 0.0))) + timings = PhaseTimings() + for run in runs: + timings = timings + PhaseTimings(agent_s=run.agent_s, judge_s=run.judge_s) + runs_passed = sum(1 for r in runs if r.passed) + failed_runs = build_failed_runs(runs, labels=run_labels, detail=_run_detail) + reasoning = list(best.result.reasoning_steps or []) if best.result else [] + response_id = best.result.response_id if best.result else None + run_latencies_s = [r.agent_s + r.judge_s for r in runs] + best_latency = run_latency_s(PhaseTimings(agent_s=best.agent_s, judge_s=best.judge_s)) + detail = _run_detail(best) + unscored = [r.judge_error for r in runs if r.judge_error is not None] + if unscored: + detail["unscored_runs"] = len(unscored) + detail["judge_errors"] = unscored + + if unscored and not scored: + # No run got a verdict: the item is a harness error, not K failures. + error = JudgeResponseError( + f"judge returned no readable verdict for any of the {len(unscored)} graded run(s): " + " | ".join(unscored) + ) + error.reasoning_steps = reasoning + error.conversation_id = best.conversation_id + error.response_id = response_id + error.detail = detail + error.runs_passed = runs_passed + error.runs_effective = len(runs) + error.failed_runs = failed_runs + error.run_latencies_s = run_latencies_s + error.best_run_latency_s = best_latency + error.timings = timings + attach_labels(error, run_labels, gate) + raise error + + if not gate_passed(gate, pass_at_k=pass_at_k, pass_power_k=pass_power_k): + reason = best.error or (best.evaluation.error if best.evaluation and best.evaluation.error else None) + head = failure_message_head(gate, run_labels, runs_passed, failed_runs, len(unscored)) + raise_agentic_failure( + DescribeObjectAssertionError, + f"Describe object failed for {question!r}. {head} {reason or 'criteria not satisfied'}", + harness_error=run_labels.harness_error_record, + shadow=run_labels.shadow(gate), + reasoning_steps=reasoning, + conversation_id=best.conversation_id, + response_id=response_id, + detail=detail, + runs_passed=runs_passed, + runs_effective=len(runs), + failed_runs=failed_runs, + run_latencies_s=run_latencies_s, + best_run_latency_s=best_latency, + timings=timings, + ) + return agentic_success( + shadow=run_labels.shadow(gate), + reasoning_steps=reasoning, + conversation_id=best.conversation_id, + response_id=response_id, + detail=detail, + runs_passed=runs_passed, + runs_effective=len(runs), + failed_runs=failed_runs, + run_latencies_s=run_latencies_s, + best_run_latency_s=best_latency, + timings=timings, + ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py b/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py index d2a5d2aa8..47dad940f 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/dataset/langfuse_source.py @@ -19,6 +19,7 @@ from gooddata_eval.core.langfuse._env import make_http_client from gooddata_eval.core.models import ( + AgenticSummaryInput, AgentSwitcherInput, CatalogInput, DatasetItem, @@ -67,6 +68,21 @@ def _summary_input_from_raw(raw: dict, expected_output: Any) -> SummaryInput | N return SummaryInput.model_validate(candidate) if candidate is not None else None +def _agentic_summary_input_from_raw(raw: dict) -> AgenticSummaryInput | None: + """Locate an agentic_summary item's `agentic_summary_input`, from the item input or its metadata. + + Raises: + ValueError: The value found is not a valid `agentic_summary_input` object. + """ + candidate = _first_of(dict, "agentic_summary_input", raw.get("input"), raw.get("metadata")) + if candidate is None: + return None + try: + return AgenticSummaryInput.model_validate(candidate) + except ValidationError as exc: + raise ValueError(f"Item {raw.get('id')!r} has an invalid `agentic_summary_input`: {exc}") from exc + + def _catalog_input_from_raw(raw: dict, expected_output: Any) -> CatalogInput | None: """Locate a catalog_metadata item's `catalog_input`. @@ -236,6 +252,7 @@ def _item_from_raw(raw: dict, *, dataset_name: str, test_kind: str) -> DatasetIt catalog_input=catalog_input, agent_switcher_input=agent_switcher_input, memory_input=memory_input, + agentic_summary_input=_agentic_summary_input_from_raw(raw), user_context=_user_context_from_raw(raw), ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/evaluators/chat_summary.py b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/chat_summary.py new file mode 100644 index 000000000..9935d68a6 --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/chat_summary.py @@ -0,0 +1,270 @@ +# (C) 2026 GoodData Corporation +"""Checks and judge steps for `agentic_summary`: the chat summary of a widget or a dashboard. + +Each turn's `expected_output` (the item's for the summary, a follow-up's own for that turn): + + { + "format": {...} | false, + "no_tool_calls": false, + "must_include": ["...criteria the answer must satisfy..."], + "must_not_include": ["...characteristics the answer must not show..."], + "rubric": ["...soft quality dimensions..."] + } + +Every key is optional. The code checks gate the verdict and need no judge: + +- shape (summary turn only, unless `format` is false): a chart widget gets the four + headings of the visualization summary in order, a KPI widget none and at most three + sentences, a dashboard the three headings of the dashboard summary in order, and a + dashboard whose widgets all returned no data no headings; an empty + widget has no fixed shape. A `format` + object replaces the default: `max_sentences`, `no_headings`, `no_bullets`, `headings`. +- no ids (summary turn only): no `{visualization/...}` reference tag and no raw object id. A + follow-up is answered as an ordinary chat message, whose reference tags the UI renders as links. +- no figures on no data: when every widget in scope returned no data, the answer quotes no + amount, share or count. +- `no_tool_calls`: the turn answers from the conversation, without running a tool. +- `figures_grounded` (when the kind passes the tables the agent read): every figure in the + answer comes from those tables or a simple calculation on them (`chat_summary_figures`). A + summary turn that states figures and read no table fails, whatever tools it ran. + +Judge criteria are graded one by one, as for `dashboard_summary`; the INPUT the judge reads +is the item's scenario line plus the question of the turn. Criteria give a direction, never +a value. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from typing import Any + +from gooddata_eval.core.evaluators._llm_judge import LLMJudge +from gooddata_eval.core.evaluators._rubric import Criterion, grade_rubric +from gooddata_eval.core.evaluators._text_utils import count_sentences as count_text_sentences +from gooddata_eval.core.evaluators.base import ItemEvaluation +from gooddata_eval.core.evaluators.chat_summary_figures import Table, check_figures, extract_figures + +CHART_HEADINGS = ("Summary", "Key Findings", "Trends", "Areas to Watch") +DASHBOARD_HEADINGS = ("Summary", "Key Insights", "Areas to Watch") +KPI_MAX_SENTENCES = 3 + +# Tools gen-ai runs to manage the conversation, not to answer it. +_BOOKKEEPING_TOOLS = frozenset({"set_skills"}) + +_POSITIVE_STEPS = [ + "Read the INPUT: the dashboard or widget the user summarizes, its filters, and the question of this turn.", + "Read the EXPECTED OUTPUT: one criterion the answer must satisfy.", + "Read the ACTUAL OUTPUT: the assistant's answer to that question.", + "Score 1 if the actual output clearly satisfies the criterion.", + "Score 0 if the criterion is missing, contradicted, or only partially addressed.", +] + +# A presence question, inverted in code, as in summary.py: the INPUT names filters and data, +# which pulls the judge towards grading correctness; the third step keeps it on presence. +_VIOLATION_STEPS = [ + "Read the CHARACTERISTIC described in EXPECTED OUTPUT, including any exceptions it states.", + "Read the ACTUAL OUTPUT: the assistant's answer.", + "Decide only whether the actual output exhibits the characteristic, not whether it is correct or wanted.", + "Score 1 if the actual output clearly exhibits the described characteristic.", + "Score 0 if it does not exhibit it.", +] + +_HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$", re.MULTILINE) +_BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s", re.MULTILINE) +_REFERENCE_TAG = re.compile(r"\{(?:visualization|dashboard|metric|attribute|label|fact|widget)/[^}]*\}") +_RAW_ID = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b|\b[0-9a-f]{32}\b") + + +@dataclass(frozen=True) +class SummaryScope: + """What the summarized widgets returned, as the checks need it.""" + + scope: str # "widget" or "dashboard" + kpi_only: bool # the referenced widgets are single-value KPIs + all_empty: bool # every widget in scope returned no data + + +def headings(text: str) -> list[str]: + """The markdown headings of an answer, in order, without their markers.""" + return [h.strip(" *_") for h in _HEADING.findall(text)] + + +# A period after a title or a short name ends no sentence: "Mrs. Crystal Murray", "Inc. revenue". +_ABBREVIATIONS = frozenset({"mr", "mrs", "ms", "dr", "prof", "inc", "ltd", "co", "st", "vs", "etc", "e.g", "i.e"}) + + +def count_sentences(text: str) -> int: + """Sentences of an answer; a heading line is no sentence.""" + return count_text_sentences(_HEADING.sub(" ", text), _ABBREVIATIONS) + + +def shape_problem(text: str, scope: SummaryScope, fmt: dict[str, Any] | None) -> str | None: + """Why the answer's shape is wrong, or None. + + `fmt` replaces the default shape (an item where the user asked for another format). + """ + found = headings(text) + if fmt: + if fmt.get("no_headings") and found: + return f"headings {found} although the user asked for none" + if fmt.get("no_bullets") and _BULLET.search(text): + return "bullet points although the user asked for none" + limit = fmt.get("max_sentences") + if isinstance(limit, int) and count_sentences(text) > limit: + return f"{count_sentences(text)} sentences, more than the {limit} the user asked for" + wanted = fmt.get("headings") + if isinstance(wanted, list) and found != wanted: + return f"headings {found}, expected {wanted}" + return None + if scope.scope == "dashboard": + if scope.all_empty: + return f"headings {found} on a dashboard without data" if found else None + return None if found == list(DASHBOARD_HEADINGS) else f"headings {found}, expected {list(DASHBOARD_HEADINGS)}" + if scope.all_empty: + # An empty widget comes back with all four headings or with a single one: the prompt + # sets no shape for it, so only the no-figures check applies. + return None + if scope.kpi_only: + if found: + return f"headings {found} on a KPI" + n = count_sentences(text) + return f"{n} sentences on a KPI, more than {KPI_MAX_SENTENCES}" if n > KPI_MAX_SENTENCES else None + return None if found == list(CHART_HEADINGS) else f"headings {found}, expected {list(CHART_HEADINGS)}" + + +def id_problem(text: str) -> str | None: + """Why the answer shows an id or a reference tag the user cannot read, or None.""" + tag = _REFERENCE_TAG.search(text) + if tag: + return f"reference tag {tag.group(0)!r} in the answer" + raw = _RAW_ID.search(text) + return f"raw id {raw.group(0)!r} in the answer" if raw else None + + +def figures(text: str) -> list[str]: + """The amounts, shares and counts an answer states, read as `figures_grounded` reads them; a year is a date.""" + return [f.raw for f in extract_figures(text) if f.kind != "year"] + + +def answer_tools(tool_names: Sequence[str]) -> list[str]: + return [t for t in tool_names if t and t not in _BOOKKEEPING_TOOLS] + + +def _criteria(expected: dict[str, Any], key: str, prefix: str) -> list[Criterion]: + raw = expected.get(key) or [] + items = raw if isinstance(raw, list) else [raw] + return [(f"{prefix}{i}", str(c)) for i, c in enumerate(items) if str(c).strip()] + + +# Detail keys a code check sets; False = that check failed the turn. +EXPECTED_KEYS = frozenset({"format", "no_tool_calls", "must_include", "must_not_include", "rubric"}) +FORMAT_KEYS = frozenset({"max_sentences", "no_headings", "no_bullets", "headings"}) + + +def validate_expected(expected: Any, where: str) -> None: + """Reject a key the checks do not know, so a misspelt one cannot read as a pass. + + A `format` object replaces the default shape; with an unknown key in it no shape would be checked. + + Raises: + ValueError: `expected` is not an object, or it or its `format` has an unknown key. + """ + if expected is None: + return + if not isinstance(expected, dict): + raise ValueError(f"{where}: expected_output must be an object, got {type(expected).__name__}") + unknown = sorted(set(expected) - EXPECTED_KEYS) + if unknown: + raise ValueError(f"{where}: unknown expected_output keys {unknown}; known: {sorted(EXPECTED_KEYS)}") + fmt = expected.get("format") + if fmt is None or fmt is False: + return + if not isinstance(fmt, dict) or not fmt: + raise ValueError(f"{where}: `format` must be false or a non-empty object, got {fmt!r}") + unknown = sorted(set(fmt) - FORMAT_KEYS) + if unknown: + raise ValueError(f"{where}: unknown `format` keys {unknown}; known: {sorted(FORMAT_KEYS)}") + + +CODE_CHECKS = ("shape_ok", "no_ids", "no_figures_on_no_data", "figures_grounded", "no_tool_calls") + + +def evaluate_turn( + *, + judge_input: str, + answer: str, + tool_names: Sequence[str], + expected: dict[str, Any], + scope: SummaryScope | None, + positive_judge: LLMJudge, + violation_judge: LLMJudge, + tables: Sequence[Table] | None = None, + filter_years: Iterable[int] = (), + known_text: Iterable[str] = (), +) -> ItemEvaluation: + """Grade one turn. `scope` is None for a follow-up: only the summary turn has a shape and the no-ids rule.""" + detail: dict[str, Any] = {"actual_output": answer} + passed = True + if not answer.strip(): + detail["error"] = "empty answer" + return ItemEvaluation(passed=False, rank_key=(-1, 0.0), detail=detail, error="empty answer") + + fmt = expected.get("format") + if scope is not None and fmt is not False: + problem = shape_problem(answer, scope, fmt if isinstance(fmt, dict) else None) + detail["shape_ok"] = problem is None + if problem: + detail["shape_problem"] = problem + passed = False + + if scope is not None: + problem = id_problem(answer) + detail["no_ids"] = problem is None + if problem: + detail["id_problem"] = problem + passed = False + + if scope is not None and scope.all_empty: + quoted = figures(answer) + detail["no_figures_on_no_data"] = not quoted + if quoted: + detail["figures_on_no_data"] = quoted[:5] + passed = False + + if tables is not None: + grounding = check_figures(answer, tables, filter_years=filter_years, known_text=known_text) + # figures on a summary turn that read no data at all: nothing they could come from. A turn that + # only searched the workspace has run a tool and read no table. + unread = scope is not None and not scope.all_empty and not tables and bool(figures(answer)) + detail["figures_grounded"] = grounding.passed and not unread + detail["figures_grounded_reason"] = ( + f"states {len(figures(answer))} figures but read no data" if unread else grounding.reason() + ) + if not detail["figures_grounded"]: + passed = False + + if expected.get("no_tool_calls"): + ran = answer_tools(tool_names) + detail["no_tool_calls"] = not ran + if ran: + detail["tools_run"] = ran + passed = False + + return grade_rubric( + positive_judge, + violation_judge, + question=judge_input, + actual=answer, + must_include=_criteria(expected, "must_include", "must_include_"), + must_not_include=_criteria(expected, "must_not_include", "must_not_include_"), + rubric=_criteria(expected, "rubric", "rubric_"), + detail=detail, + passed=passed, + ) + + +def make_judges(model: str | None = None) -> tuple[LLMJudge, LLMJudge]: + """The positive and the violation judge, with the summary-specific steps.""" + return LLMJudge(_POSITIVE_STEPS, model=model), LLMJudge(_VIOLATION_STEPS, model=model) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/evaluators/chat_summary_figures.py b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/chat_summary_figures.py new file mode 100644 index 000000000..61c00ffa9 --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/chat_summary_figures.py @@ -0,0 +1,995 @@ +# (C) 2026 GoodData Corporation +"""`figures_grounded` for `agentic_summary`: every figure in an answer must come from the data. + +The data is what the agent read in the conversation: the tables `execute_existing_visualizations` +returned. A figure is grounded when it is close to an allowed value: + +- a cell, a column or row total, a column average, a sum of the first rows (largest, smallest or as listed) +- the difference, ratio, change or "A as % of B" between two cells of one column or one row + (a long column: its neighbours, first vs last and largest vs smallest) +- in a row or a short column (up to 6 cells): the sum of any cells, and its share of the total or of one cell +- a share: a cell, or a sum of the first rows, over its column total or its row total +- a column shown as a percentage (format with `%`), times 100 +- a row count, the rows read, any count the result states, a number inside a label or a title + (`SanDisk 128GB`, `Top 10`), a rating label as its stars (`***` = 3), a position up to the rows read +- the sum of the rows that share a label (the United States in a country/state table), its share +- across one-row results (KPIs): the difference, ratio, "A as % of B" and "A per B" of two values +- any number of another data tool's result (e.g. a change analysis), and its labels + +Figure kinds are matched to fitting values only: an amount to amounts and counts, a percentage +to shares, changes and percentage columns, a ratio (`2.5×`) to ratios. A year is checked +against the years of the active filters (plus the year before, for previous-period +comparisons) and of the date labels. + +Tolerance follows what the answer wrote: half of its last digit (`$1.3 M` covers 1.25–1.35 M), for an +amount without decimals at most 10 % of the value (a round `$100K` covers 90–110 K, `$1 M` 0.9–1.1 M), +or 0.5 % of the value, whichever is larger; twice that for a derived +value, which the agent may compute from rounded figures. A range takes its end's unit (`$1.0–$1.3 M`, +`10–15%`). Czech and German scale words and a decimal comma count (`985,3 tis.`, `1,3 Mio.`). +A bound (`above $900 K`, `below $350 K`) is not a value: it stays `unverified`. + +A figure next to a row's name is tied to that row: "Michael Parsons leads with $76.9 K" fails when +$76.9 K is Michael Baker's value. The name right before the figure counts (several names in a list +all count), and a name right after it ("2,002 in-cart"); a value about the whole data or a derived +value about rows the sentence names stays allowed. Not tied: answers in another language (labels +stay in English). Text that names a row label, a column or a filter +value (`1-3M`, `Q4 2024`) is removed before extraction, so a label is never read as a figure. + +A figure that fits no allowed value is `ungrounded` and fails the check. Nothing is +`ungrounded` when the agent read no table: its figures are `unverified`. + +Limit: the check is weak on long tables. With some hundred values in a column the 0.5 % slack is +wider than the gaps between them, so a wrong figure without a row's name next to it fits some cell. +On real answers with one figure changed by 8-15 %, about 7 in 10 changes are caught on tables of up +to 10 rows and about 3 in 10 on tables of more than 50 rows; a figure tied to a named row is +checked against that row at any size. +""" + +from __future__ import annotations + +import bisect +import dataclasses +import itertools +import json +import math +import re +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field +from typing import Any + +PAIRWISE_LIMIT = 60 # columns longer than this get adjacent pairs only +PREFIX_LIMIT = 10 +SUBSET_LIMIT = 6 # rows/short columns up to this many cells get every sum of cells +ROW_PAIR_LIMIT = 8 # cells of one row compared pairwise: current vs previous period, part vs part +_DATALESS_TOOLS = frozenset({"set_skills"}) +_RELATIVE_SLACK = 0.005 + +_SCALE = { + "k": 1e3, + "thousand": 1e3, + "m": 1e6, + "mn": 1e6, + "million": 1e6, + "b": 1e9, + "bn": 1e9, + "billion": 1e9, + "t": 1e12, + "trillion": 1e12, + # Czech, German + "tis": 1e3, + "tisíc": 1e3, + "tsd": 1e3, + "tausend": 1e3, + "mil": 1e6, + "milion": 1e6, + "milionu": 1e6, + "milionů": 1e6, + "miliony": 1e6, + "mio": 1e6, + "millionen": 1e6, + "mld": 1e9, + "miliarda": 1e9, + "miliardy": 1e9, + "mrd": 1e9, + "milliarden": 1e9, +} +# thousands separator | decimal comma (1-2 digits: never a thousands group) | plain +_NUM = r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+,\d{1,2}(?!\d)|\d+(?:\.\d+)?" +_DECIMAL_COMMA = re.compile(r"-?\d+,\d{1,2}") +_SCALE_WORD = ( + r"\s?(?:(?:thousand|million|billion|trillion|mn|bn|tisíc|tausend|millionen|milliarden|milion[uůy]?|" + r"miliard[ay]|[KMBT])\b|(?:tis|tsd|mil|mio|mld|mrd)\b\.?)" +) +_FIGURE = re.compile( + rf"(?P[$€£])\s?(?P-?(?:{_NUM}))(?P{_SCALE_WORD})?" + rf"|(?P-?(?:{_NUM}))\s?(?P%|percent\b|percentage points\b|pp\b)" + rf"|(?P\d+(?:\.\d+)?)\s?(?P×|x\b|times\b)" + rf"|(?P(?:(?{_SCALE_WORD})?", + re.IGNORECASE, +) +_MONTHS = ( + "january|february|march|april|may|june|july|august|september|october|november|december|" + "jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec" +) +_DAY_AFTER_MONTH = re.compile( # "October 16", "October 16–23" + rf"\b(?:{_MONTHS})\.?\s+\d{{1,2}}(?:st|nd|rd|th)?(?:\s?[–-]\s?\d{{1,2}}(?:st|nd|rd|th)?)?\b", re.IGNORECASE +) +_ISO_DATE = re.compile(r"\b\d{4}-\d{2}-\d{2}\b") +_QUARTER = re.compile(r"\bQ[1-4]\b|\bH[12]\b", re.IGNORECASE) +_TIME = re.compile(r"\b\d{1,2}:\d{2}\b") +_ORDINAL = re.compile(r"\b\d+(?:st|nd|rd|th)\b", re.IGNORECASE) +_BOUND = re.compile( + r"\b(?:above|over|exceed(?:s|ed|ing)?|(?:more|less|fewer|greater|higher|lower) than|below|under|at least|at most|" + r"up to|beyond|nad|pod|více než|méně než|über|unter)\s+$", + re.IGNORECASE, +) +_NUMBER_IN_TEXT = re.compile(r"\d+(?:[.,]\d+)?") +POSITION_LIMIT = 10 # "top 3", "ranks 3 and 4"; a larger count needs "N of " +WINDOW_LIMIT = 12 # consecutive rows summed: "16:00-22:00", a quarter of months +ANCHOR_GAP = 60 # chars between a row's name and the figure after it +_SEPARATOR = re.compile(r"[,;]|\b(?:and|while|but|followed|than|versus|vs|und)\b", re.IGNORECASE) +_HONORIFIC = re.compile(r"^(?:Mrs|Mr|Ms|Miss|Dr|Prof)\.?\s+", re.IGNORECASE) +ANCHOR_GAP_AFTER = 25 # a name after the figure: "2,002 are in cart" +_COUNT_OF = re.compile(r"\s+of\s+(?:the\s+|all\s+)?(\d[\d,]*)\b") +_YEAR = re.compile(r"(?[$€£]?\s?(?:{_NUM}))\s?(?:–|—|-|to|až|bis)\s?[$€£]?\s?(?:{_NUM})(?P{_SCALE_WORD}|\s?%)", + re.IGNORECASE, +) + + +@dataclass +class Table: + """One result the agent read: rows of cells, column names and formats.""" + + columns: list[str] + formats: list[str | None] + rows: list[list[float | None]] # measure cells only, one list per row + labels: list[str] # every label text of the rows + row_count: int + title: str = "" + truncated: bool = False + row_labels: list[list[str]] = field(default_factory=list) # label texts per row, when known + cache: dict[int, list[Allowed]] = field(default_factory=dict, repr=False, compare=False) + counts: list[float] = field(default_factory=list) # other counts the result states (columns, totals) + + +@dataclass(frozen=True) +class Allowed: + value: float + kinds: frozenset[str] # "amount", "percent", "ratio" + how: str + rank: int = 2 # 0 cell, 1 total or count, 2 derived: the simplest explanation is reported + rows: frozenset[tuple[int, int]] = frozenset() # (table, row) it is about; empty = the whole data + named: bool = False # only when the sentence names every one of its rows (any pair of rows) + + +@dataclass +class Figure: + raw: str + value: float + kind: str # amount | percent | ratio | year | bound + tolerance: float + sentence: str + status: str = "unverified" # grounded | ungrounded | unverified + rounded: bool = False # written with trailing zeros ("$100K"): its tolerance already covers rounding + pos: int = 0 # where it starts in the answer + match: str = "" + nearest: list[str] = field(default_factory=list) + + +# ---------- tables ---------- + + +def _num(v: Any) -> float | None: + if isinstance(v, bool): + return None + if isinstance(v, (int, float)): + return float(v) if math.isfinite(v) else None + if isinstance(v, str): + try: + return float(v.replace(",", "")) + except ValueError: + return None + return None + + +def tables_from_tool_result(result: Any) -> list[Table]: + """Tables of one `execute_existing_visualizations` result (xtab or rows format).""" + if isinstance(result, str): + try: + result = json.loads(result) + except ValueError: + return [] + if not isinstance(result, dict): + return [] + out: list[Table] = [] + for entry in result.get("results") or []: + data = entry.get("data") if isinstance(entry, dict) else None + if not isinstance(data, dict): + continue + cols = [c for c in data.get("columns") or [] if isinstance(c, dict)] + measures = [c for c in cols if c.get("type") != "attribute"] + labels: list[str] = [] + row_labels: list[list[str]] = [] + rows: list[list[float | None]] = [] + if isinstance(data.get("data"), list): # xtab + for label in data.get("row_labels") or []: + row_labels.append([str(x) for x in (label if isinstance(label, list) else [label])]) + labels += row_labels[-1] + rows = [[_num(v) for v in (r if isinstance(r, list) else [r])] for r in data["data"]] + elif isinstance(data.get("rows"), list): # rows format + names = [c.get("name") for c in measures] + for r in data["rows"]: + if isinstance(r, dict): + rows.append([_num(r.get(n)) for n in names]) + row_labels.append([str(v) for k, v in r.items() if k not in names and v is not None]) + labels += row_labels[-1] + for c in cols: + if c.get("type") == "attribute": + labels += [str(v) for v in c.get("values") or []] + out.append( + Table( + columns=[str(c.get("name", "")) for c in measures], + formats=[c.get("format") for c in measures], + rows=rows, + labels=labels, + row_count=int(_num(data.get("row_count")) or len(rows)), + title=str(entry.get("visualization_id") or ""), + truncated=bool(data.get("truncated")), + row_labels=row_labels if len(row_labels) == len(rows) else [], + counts=[ + v for v in (_num(x) for k, x in data.items() if not isinstance(x, (list, dict))) if v is not None + ], + ) + ) + return out + + +def _walk(value: Any, nums: list[float], labels: list[str], depth: int = 0) -> None: + if depth > 20: + return + if isinstance(value, dict): + for v in value.values(): + _walk(v, nums, labels, depth + 1) + elif isinstance(value, list): + for v in value: + _walk(v, nums, labels, depth + 1) + elif isinstance(value, str): + n = _num(value) + if n is not None: + nums.append(n) + elif len(value) <= 80: + labels.append(value) + else: + n = _num(value) + if n is not None: + nums.append(n) + + +def table_from_any_result(result: Any, title: str = "") -> Table | None: + """Every number of another data tool's result as one column; its texts as labels.""" + if isinstance(result, str): + try: + result = json.loads(result) + except ValueError: + return None + nums: list[float] = [] + labels: list[str] = [] + _walk(result, nums, labels) + if not nums: + return None + # a fraction may be written as a percentage: the column is read as one + return Table(["value"], ["0.0%"], [[n] for n in nums], labels, len(nums), title) + + +def tables_from_tool_calls(events: Iterable[Any]) -> list[Table]: + """The tables of one turn's tool results: visualization results, and any other data tool's numbers.""" + tables: list[Table] = [] + for ev in events: + name, result = getattr(ev, "function_name", ""), getattr(ev, "result", None) + if not result or name in _DATALESS_TOOLS: + continue + if name == "execute_existing_visualizations": + tables += tables_from_tool_result(result) + elif table := table_from_any_result(result, name): + tables.append(table) + return tables + + +# ---------- allowed values ---------- + + +def _cell(row: list[float | None], c: int) -> float | None: + return row[c] if c < len(row) else None + + +def _is_percent_format(fmt: str | None) -> bool: + return bool(fmt) and "%" in str(fmt) + + +def _table_allowed(t: Table, ti: int) -> list[Allowed]: + """The values one table allows (cached on the table: a conversation re-checks it every turn).""" + cached = t.cache.get(ti) + if cached is not None: + return cached + out: list[Allowed] = [] + amount, percent = frozenset({"amount"}), frozenset({"percent"}) + tag = f"table {ti + 1}" + out.append(Allowed(float(t.row_count), amount, f"{tag} row count", 1)) + out.append(Allowed(float(len(t.rows)), amount, f"{tag} rows read", 1)) + out += [Allowed(v, amount, f"{tag} count stated by the result", 1) for v in t.counts] + out.append(Allowed(float(len(t.columns)), amount, f"{tag} columns", 1)) + if t.row_count > len(t.rows): + out.append(Allowed(float(t.row_count - len(t.rows)), amount, f"{tag} rows not read", 1)) + width = max(len(t.rows), len(t.columns)) + out += [Allowed(float(k), amount, "a position", 1) for k in range(1, min(width, POSITION_LIMIT) + 1)] + out += _label_numbers([*t.labels, *t.columns], tag) + out += _date_groups(t, ti) + out += _group_values(t, ti) + cells_all = [v for r in t.rows for v in r if v is not None] + if len(t.columns) > 1 and cells_all: # a pivot: one measure over column labels + out.append(Allowed(sum(cells_all), amount, f"{tag} total of all cells", 1)) + ncol = max((len(r) for r in t.rows), default=0) + for c in range(ncol): + name = t.columns[c] if c < len(t.columns) else f"column {c + 1}" + fmt = t.formats[c] if c < len(t.formats) else None + col: list[tuple[int, float]] = [(i, v) for i, r in enumerate(t.rows) if (v := _cell(r, c)) is not None] + vals = [v for _, v in col] + if not vals: + continue + total = sum(vals) + for i, v in col: + at = frozenset({(ti, i)}) + out.append(Allowed(v, amount, f"{name} row {i + 1} = {v:,.2f}", 0, at)) + if _is_percent_format(fmt): + out.append(Allowed(v * 100, percent, f"{name} row {i + 1} as % = {v * 100:.2f}", 0, at)) + if total: + out.append(Allowed(v / total * 100, percent, f"{name} row {i + 1} share of column total", 2, at)) + out.append(Allowed(total, amount, f"{name} total = {total:,.2f}", 1)) + out.append(Allowed(total / len(vals), amount, f"{name} average")) + for order, seq in (("largest", sorted(vals, reverse=True)), ("smallest", sorted(vals)), ("listed", vals)): + acc = 0.0 + for k, v in enumerate(seq[:PREFIX_LIMIT], start=1): + acc += v + if k == 1: # a cell, already allowed + continue + out.append(Allowed(acc, amount, f"{name} sum of first {k} ({order})")) + if total: + out.append(Allowed(acc / total * 100, percent, f"{name} share of first {k} ({order})")) + out += _pair_values(col, name, table=ti) + for a in range(len(col) if len(col) <= PAIRWISE_LIMIT else 0): # consecutive rows: "18:00-22:00" + acc = col[a][1] + for b in range(a + 1, min(len(col), a + WINDOW_LIMIT)): + acc += col[b][1] + at = frozenset((ti, col[k][0]) for k in range(a, b + 1)) + how = f"{name} rows {col[a][0] + 1}-{col[b][0] + 1}" + out.append(Allowed(acc, amount, how, 2, at)) + if total: + out.append(Allowed(acc / total * 100, percent, f"{how} share", 2, at)) + if len(col) <= SUBSET_LIMIT: + out += _subset_values(col, name, lambda i: f"row {i + 1}") + for i, r in enumerate(t.rows): # within one row: current vs previous period, part vs whole + names = [t.columns[c] if c < len(t.columns) else f"column {c + 1}" for c in range(len(r))] + cells = [(c, v) for c, v in enumerate(r) if v is not None] + if len(cells) < 2: + continue + at = frozenset({(ti, i)}) + row_total = sum(v for _, v in cells) + row: list[Allowed] = [Allowed(row_total, amount, f"row {i + 1} total")] # the agent may add rounded cells + if row_total: + row += [ + Allowed(va / row_total * 100, percent, f"row {i + 1}: {names[ca]} share of the row") for ca, va in cells + ] + # a wide row, or a long table's row of more than current and previous: total and shares only + if len(cells) > ROW_PAIR_LIMIT or (len(t.rows) > PAIRWISE_LIMIT and len(cells) > 3): + # first vs last period, neighbours, extremes: a fixed few per row + row += _pair_values(cells, f"row {i + 1}:", lambda c: names[c], long=True) + out += [dataclasses.replace(x, rows=at) for x in row] + continue + row += _pair_values(cells, f"row {i + 1}:", lambda c: names[c]) + # percentage cells: a % format, or a fraction next to one (a previous period's margin may come unformatted) + has_pct = any(_is_percent_format(t.formats[c] if c < len(t.formats) else None) for c, _ in cells) + pct = [ + (c, v) + for c, v in cells + if _is_percent_format(t.formats[c] if c < len(t.formats) else None) or (has_pct and abs(v) <= 1.5) + ] + row += [ # "about $2,952 per order": one measure per another, in one row + Allowed(va / vb, amount, f"row {i + 1}: {names[ca]} per {names[cb]}") + for ca, va in cells + for cb, vb in cells + if ca != cb and vb + ] + row += [ # 48.3% → 47.9% = 0.35 percentage points + Allowed((va - vb) * 100, percent, f"row {i + 1}: {names[ca]} − {names[cb]} in points") + for ca, va in pct + for cb, vb in pct + if ca != cb + ] + if len(cells) <= SUBSET_LIMIT: + row += _subset_values(cells, f"row {i + 1}", lambda c: names[c]) + out += [dataclasses.replace(x, rows=at) for x in row] + t.cache[ti] = out + return out + + +def allowed_values(tables: Sequence[Table]) -> list[Allowed]: + """Every value a figure may be: per table (cells, totals, shares, pairs, ...) and across one-row tables.""" + out: list[Allowed] = [] + amount = frozenset({"amount"}) + for ti, t in enumerate(tables): + out += _table_allowed(t, ti) + kpis = [ + (f"{t.columns[c] if c < len(t.columns) else 'value'}", v) + for t in tables + if len(t.rows) == 1 + for c, v in enumerate(t.rows[0]) + if v is not None + ] + if 1 < len(kpis) <= 40: # one-row results side by side: Net Sales vs Total Sales, sales per order + for (na, va), (nb, vb) in itertools.permutations(kpis, 2): + out += _pair(va, vb, na, nb) + if vb: + out.append(Allowed(va / vb, amount, f"{na} per {nb}")) + return out + + +def _label_numbers(labels: Iterable[str], tag: str) -> list[Allowed]: + """Numbers inside labels or titles ("SanDisk 128GB", "Top 10"); a star rating label as its stars.""" + out: list[Allowed] = [] + for label in set(labels): + if _ISO_DATE.search(label) or re.fullmatch(r"[\d\s/.:-]+", label.strip()): + continue # a date or a plain number: its parts ("31" of "2024-10-31") are no figures + if re.fullmatch(r"\*{1,10}", label.strip()): + out.append(Allowed(float(len(label.strip())), frozenset({"amount"}), f"{tag} rating label {label}", 1)) + continue + out.extend( + Allowed(_to_float(n), frozenset({"amount"}), f"{tag} number in label '{label[:40]}'", 1) + for n in _NUMBER_IN_TEXT.findall(label) + ) + return out + + +def _group_values(t: Table, ti: int) -> list[Allowed]: + """Rows that share a label (a country over its states): their sum per column, its share, their count.""" + out: list[Allowed] = [] + if not t.row_labels or len(t.row_labels) != len(t.rows): + return out + depth = max((len(r) for r in t.row_labels), default=0) + for level in range(depth): + groups: dict[str, list[int]] = {} + for i, labels in enumerate(t.row_labels): + if level < len(labels): + groups.setdefault(labels[level], []).append(i) + if len(groups) > 50: + continue + for value, idx in groups.items(): + if not 1 < len(idx) < len(t.rows): + continue + at = frozenset((ti, i) for i in idx) + out.append(Allowed(float(len(idx)), frozenset({"amount"}), f"rows of {value}", 1, at)) + ncol = max(len(t.rows[i]) for i in idx) + for c in range(ncol): + vals: list[float] = [v for i in idx if (v := _cell(t.rows[i], c)) is not None] + col_total = sum(v for r in t.rows if (v := _cell(r, c)) is not None) + name = t.columns[c] if c < len(t.columns) else f"column {c + 1}" + acc = sum(vals) + out.append(Allowed(acc, frozenset({"amount"}), f"{name} of {value} (sum of its rows)", 2, at)) + if acc: + out.extend( + Allowed(v / acc * 100, frozenset({"percent"}), f"{name} row as % of {value}", 2, at) + for v in vals + ) + if col_total: + out.append( + Allowed(acc / col_total * 100, frozenset({"percent"}), f"{name} of {value} share", 2, at) + ) + return out + + +def _date_groups(t: Table, ti: int) -> list[Allowed]: + """A daily series summed by month, quarter and year of its date labels ("October: $5.3 M").""" + out: list[Allowed] = [] + keys: dict[str, list[int]] = {} + for i, labels in enumerate(t.row_labels): + m = next((_ISO_DATE.search(x) for x in labels if _ISO_DATE.search(x)), None) + if not m: + continue + y, mo = m.group(0)[:4], int(m.group(0)[5:7]) + for key in (f"{y}-{mo:02d}", f"{y}-Q{(mo - 1) // 3 + 1}", y): + keys.setdefault(key, []).append(i) + for key, idx in keys.items(): + if len(idx) < 2: + continue + at = frozenset((ti, i) for i in idx) + ncol = max(len(t.rows[i]) for i in idx) + for c in range(ncol): + vals: list[float] = [v for i in idx if (v := _cell(t.rows[i], c)) is not None] + name = t.columns[c] if c < len(t.columns) else f"column {c + 1}" + out.append(Allowed(sum(vals), frozenset({"amount"}), f"{name} in {key}", 2, at)) + if vals: + out.append(Allowed(sum(vals) / len(vals), frozenset({"amount"}), f"{name} average in {key}", 2, at)) + return out + + +def _pair(va: float, vb: float, a: str, b: str) -> list[Allowed]: + out = [Allowed(va - vb, frozenset({"amount"}), f"{a} − {b}")] + if vb: + out += [ + Allowed(va / vb, frozenset({"ratio"}), f"{a} / {b}"), + Allowed(va / vb * 100, frozenset({"percent"}), f"{a} as % of {b}"), + Allowed((va - vb) / vb * 100, frozenset({"percent"}), f"change {b} → {a}"), + ] + return out + + +def _pair_values( + col: list[tuple[int, float]], name: str, label: Any = None, table: int | None = None, long: bool = False +) -> list[Allowed]: + """Pairs of one column (`table` set) or of one row's cells. + + Always: neighbours, first vs last, largest vs smallest; up to `PAIRWISE_LIMIT` values also each + vs the largest. Any other pair of a column only when the sentence names both rows ("Tracy + Carter leads Tiffany Durham by ..."). + """ + label = label or (lambda i: f"row {i + 1}") + n = len(col) + hi = max(range(n), key=lambda k: col[k][1]) if n else 0 + lo = min(range(n), key=lambda k: col[k][1]) if n else 0 + plain = {(a, a + 1) for a in range(n - 1)} | {(0, n - 1), (hi, lo)} + long = long or n > PAIRWISE_LIMIT + if not long: # a long column or wide row: neighbours and its ends only, or every value would fit + plain |= {(k, hi) for k in range(n)} + plain = {p for p in plain | {(b, a) for a, b in plain} if p[0] != p[1]} + named = {(a, b) for a in range(n) for b in range(n) if a != b} - plain if not long else set() + if table is None: # one row's cells: few, all plain + plain, named = plain | named, set() + out: list[Allowed] = [] + for pairs, need_names in ((plain, False), (named, True)): + for a, b in sorted(pairs): + (ia, va), (ib, vb) = col[a], col[b] + at = frozenset({(table, ia), (table, ib)}) if table is not None else frozenset() + out += [ + dataclasses.replace(x, rows=at, named=need_names) + for x in _pair(va, vb, f"{name} {label(ia)}", label(ib)) + ] + return out + + +def _subset_values(cells: list[tuple[int, float]], where: str, label: Any) -> list[Allowed]: + """Every sum of 2+ cells (not all), its share of the total and of each other cell.""" + out: list[Allowed] = [] + total = sum(v for _, v in cells) + for size in range(2, len(cells)): + for combo in itertools.combinations(cells, size): + acc = sum(v for _, v in combo) + how = f"{where}: " + " + ".join(str(label(k)) for k, _ in combo) + out.append(Allowed(acc, frozenset({"amount"}), how)) + if total: + out.append(Allowed(acc / total * 100, frozenset({"percent"}), f"{how} share of the total")) + for k, v in cells: + if all(k != c for c, _ in combo): + if abs(v) > abs(acc): # "Processed exceed In Cart and Canceled combined by 28,985" + out.append(Allowed(v - acc, frozenset({"amount"}), f"{label(k)} − ({how})")) + if v: + out.append(Allowed(acc / v * 100, frozenset({"percent"}), f"{how} as % of {label(k)}")) + elif acc: + out.append(Allowed(v / acc * 100, frozenset({"percent"}), f"{label(k)} as % of ({how})")) + return out + + +# ---------- figures ---------- + + +def _strip_known_text(text: str, known: Iterable[str]) -> str: + """Blank out labels and dates; same length, so positions still point into the answer.""" + for s in sorted({_dashes(k) for k in known if k and len(k) >= 2 and re.search(r"\d", k)}, key=len, reverse=True): + # a whole label only: "03" must not cut "$295,039.98" + text = re.sub(rf"(? str: + return " " * len(m.group(0)) + + +def _dashes(text: str) -> str: + """An en dash as "-" ("1–3M" in an answer is the label "1-3M"); an em dash is a pause. Same length.""" + return text.replace("–", "-").replace("—", " ") + + +def _to_float(num: str) -> float: + if _DECIMAL_COMMA.fullmatch(num): + return float(num.replace(",", ".")) + return float(num.replace(",", "")) + + +def _scale_of(word: str | None) -> float: + return _SCALE.get((word or "").strip().rstrip(".").lower(), 1.0) + + +def _tolerance(num: str, scale: float, value: float, kind: str = "amount") -> float: + """Half of the last written digit, for an amount at most 10% of the value when it has no decimals. + + - Trailing zeros of a whole amount are not written digits: "$100K" may be a rounded 96 K (90-110 K). + - A whole amount with a scale word keeps the same limit: "$1 M" is 0.9-1.1 M, "$7 M" 6.5-7.5 M. + - A percentage is read as written: "20%" is 19.5-20.5. + """ + digits = num.lstrip("-") + if _DECIMAL_COMMA.fullmatch(digits): + unit = 10.0 ** -len(digits.split(",")[1]) + elif "." in digits: + unit = 10.0 ** -len(digits.split(".")[1]) + else: + whole = digits.replace(",", "") + unit = 10.0 ** (len(whole) - len(whole.rstrip("0"))) if whole.strip("0") and kind == "amount" else 1.0 + half = 0.5 * unit * scale + if unit > 1: + half = max(0.5 * scale, min(half, abs(value) * 0.1)) + elif unit == 1 and scale > 1 and kind == "amount": + # "$1 M": half of its only digit is 50% of the value, wide enough to match an unrelated cell + half = min(half, abs(value) * 0.1) + return max(half, abs(value) * _RELATIVE_SLACK) + + +# a period after a title ("Mrs. Crystal Murray") ends no sentence +_SENTENCE_END = re.compile(r"(? str: + """The sentence around `pos`; a decimal point does not end a sentence.""" + start = max((m.end() for m in _SENTENCE_END.finditer(text, 0, pos)), default=0) + end_match = _SENTENCE_END.search(text, pos) + end = end_match.start() + 1 if end_match else len(text) + return " ".join(text[start:end].split())[:160] + + +def extract_figures(text: str, known_text: Iterable[str] = ()) -> list[Figure]: + """Figures of an answer, labels and dates removed first; markdown bold is ignored.""" + plain = _dashes(text.replace("**", "").replace("__", "")) + cleaned = _strip_known_text(plain, known_text) + figures = [ + Figure(m.group(0), float(m.group(1)), "year", 0.0, _sentence_at(plain, m.start()), pos=m.start()) + for m in _YEAR.finditer(cleaned) + ] + cleaned_no_years = _YEAR.sub(lambda m: " " * len(m.group(0)), cleaned) + range_unit = {m.start("a"): m.group("unit") for m in _RANGE.finditer(cleaned_no_years)} + for m in _FIGURE.finditer(cleaned_no_years): + if m.group("cur"): + num, scale_word, kind = m.group("cnum"), m.group("cscale"), "amount" + elif m.group("pct"): + num, scale_word, kind = m.group("pnum"), None, "percent" + elif m.group("ratio"): + num, scale_word, kind = m.group("rnum"), None, "ratio" + else: + num, scale_word, kind = m.group("num"), m.group("nscale"), "amount" + unit = range_unit.get(m.start()) + # "$1.0–$1.3 M" yes; "from $64,610.33 to $26.0 K" is a change, not a range + if ( + unit + and not scale_word + and kind == "amount" + and len(num.lstrip("-").split(".")[0].split(",")[0]) <= 3 + and "," not in num + ): + if unit.strip() == "%": + kind = "percent" + else: + scale_word = unit + scale = _scale_of(scale_word) + value = _to_float(num) * scale + if _BOUND.search(cleaned_no_years[max(0, m.start() - 20) : m.start()]): + kind = "bound" # "above $900 K" bounds the data, it is no value of it: stays unverified + digits = num.lstrip("-").replace(",", "") + rounded = kind == "amount" and digits.isdigit() and digits.endswith("0") and bool(digits.strip("0")) + figures.append( + Figure( + m.group(0).strip(), + value, + kind, + _tolerance(num, scale, value, kind), + _sentence_at(plain, m.start()), + rounded=rounded, + pos=m.start(), + ) + ) + return figures + + +# ---------- check ---------- + + +def _fmt(v: float) -> str: + a = abs(v) + for limit, suffix in ((1e9, " B"), (1e6, " M"), (1e3, " K")): + if a >= limit: + return f"{v / limit:,.2f}{suffix}" + return f"{v:,.4g}" + + +@dataclass +class GroundingResult: + figures: list[Figure] + tables_read: int + + @property + def ungrounded(self) -> list[Figure]: + return [f for f in self.figures if f.status == "ungrounded"] + + @property + def passed(self) -> bool: + return not self.ungrounded + + def reason(self) -> str: + checked = [f for f in self.figures if f.status != "unverified"] + head = ( + f"{len(self.ungrounded)} of {len(checked)} figures not in the data" + if self.ungrounded + else f"{len(checked)} figures grounded" + ) + lines = [ + head + (f", {len(self.figures) - len(checked)} unverified" if len(checked) < len(self.figures) else "") + ] + for f in sorted(self.figures, key=lambda f: {"ungrounded": 0, "unverified": 1, "grounded": 2}[f.status]): + mark = {"ungrounded": "✗", "unverified": "?", "grounded": "✓"}[f.status] + if f.status == "ungrounded": + lines.append(f' {mark} "{f.raw}" ({f.kind}, ±{_fmt(f.tolerance)}) in "{f.sentence}"') + lines.append(f" nearest: {' · '.join(f.nearest) or '-'}") + else: + lines.append(f' {mark} "{f.raw}" {("= " + f.match) if f.match else ""}'.rstrip()) + return "\n".join(lines) + + +def _allowed_years(filter_years: Iterable[int], tables: Sequence[Table]) -> set[int]: + years = set() + for y in filter_years: + years |= {y - 1, y, y + 1} + for t in tables: + for label in [*t.labels, *t.columns]: + for y in re.findall(r"\b(19\d{2}|20\d{2})\b", label): + years |= {int(y) - 1, int(y)} + return years + + +def _row_names(tables: Sequence[Table]) -> dict[tuple[int, int], list[str]]: + """Per row, its label texts that can name it in a sentence (2+ chars, with a letter: "WD", "Ontario").""" + out: dict[tuple[int, int], list[str]] = {} + for ti, t in enumerate(tables): + for i, labels in enumerate(t.row_labels): + names = [_dashes(x).strip() for x in labels if len(x.strip()) >= 2 and re.search(r"[^\W\d_]", x)] + names += [n for x in labels for n in _date_names(x)] + if names: + out[(ti, i)] = names + # a label every row shares (one country) names no row in particular + counts: dict[str, int] = {} + for names in out.values(): + for n in set(names): + counts[n] = counts.get(n, 0) + 1 + total = len(out) + return {k: [n for n in v if counts[n] < total or total == 1] for k, v in out.items()} + + +_MONTH_NAMES = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +] + + +def _date_names(label: str) -> list[str]: + """How an answer names a day label ("2024-10-07"): "October 7" and "Oct 7".""" + m = re.fullmatch(r"\s*(\d{4})-(\d{2})-(\d{2})\s*", label) + if not m or not 1 <= int(m.group(2)) <= 12: + return [] + month, day = _MONTH_NAMES[int(m.group(2)) - 1], int(m.group(3)) + return [f"{month} {day}", f"{month[:3]} {day}"] + + +def _mentions(text: str, row_names: dict[tuple[int, int], list[str]]) -> list[tuple[int, int, frozenset]]: + """Where the answer names rows: (start, end, rows the name belongs to). + + A whole-word match in any case; a space and a hyphen match each other ("in-cart" = "In Cart"); a + name without its title ("Crystal Murray") or the start of a longer label ("OBSBOT" for + "OBSBOT Tiny PTZ 4K Webcam") names that row too. + """ + by_name: dict[str, set[tuple[int, int]]] = {} + for key, names in row_names.items(): + for n in names: + for variant in {n, _HONORIFIC.sub("", n)}: + if len(variant) >= 2: + by_name.setdefault(variant.lower(), set()).add(key) + for name in list(by_name): # a short name also names the longer labels it starts + for other, rows in by_name.items(): + if other.startswith(name + " ") and len(name) >= 4: + by_name[name] = by_name[name] | rows + out: list[tuple[int, int, frozenset]] = [] + for name, rows in by_name.items(): + pattern = r"[\s-]+".join(re.escape(w) for w in re.split(r"[\s-]+", name)) + out.extend( + (m.start(), m.end(), frozenset(rows)) for m in re.finditer(rf"(?= kept[-1][1]: + kept.append(x) + return kept + + +def _figure_row(f: Figure, figures: list[Figure], mentions: list[tuple[int, int, frozenset]], text: str) -> frozenset: + """The rows a figure is about, from the names next to it in its sentence; empty when none. + + - names before it, after the previous figure ("Tracy Carter leads with $1.3 M"); several + names there ("Clothing and Home Goods are at $3.2 M and $2.2 M") all count + - the name right after it, joined by a few words ("2,002 are in cart"), not by "and" or a comma + """ + start = max((m.end() for m in _SENTENCE_END.finditer(text, 0, f.pos)), default=0) + end_match = _SENTENCE_END.search(text, f.pos) + end = end_match.start() if end_match else len(text) + prev = [g.pos + len(g.raw) for g in figures if g is not f and start <= g.pos < f.pos] + seg = max([start, *prev]) + rows: set = set() + before = [m for m in mentions if seg <= m[0] and m[1] <= f.pos] + # the last name must be close and lead straight to the figure ("Tracy Carter leads, while the + # bottom of the list is near $1.0 M" is not about Tracy); then every name of the list counts + gap = text[before[-1][1] : f.pos] if before else "" + # "from 3 on October 1 to 19": the figure after a bare "to" is the other end of a range + led = bool(before) and not _SEPARATOR.search(gap) and gap.strip(" $€£*").lower() != "to" + if led and f.pos - before[-1][1] <= ANCHOR_GAP: + for m in before: + rows |= m[2] + after_pos = f.pos + len(f.raw) + right_after = [m for m in mentions if after_pos < m[0] <= after_pos + 2 and not text[after_pos : m[0]].strip()] + if right_after: # "2,002 in-cart": the name glued to the figure is the one meant + return right_after[0][2] + nxt = min([g.pos for g in figures if g is not f and after_pos <= g.pos < end] + [end]) + after = [m for m in mentions if after_pos <= m[0] < nxt and m[0] - after_pos <= ANCHOR_GAP_AFTER] + if after and not _SEPARATOR.search(text[after_pos : after[0][0]]): + rows |= after[0][2] + return frozenset(rows) + + +def _row_name(t: Table, r: int) -> str: + return " / ".join(t.row_labels[r]) if r < len(t.row_labels) else f"row {r + 1}" + + +def _named_pairs(tables: Sequence[Table], anchors: set[tuple[int, int]]) -> list[Allowed]: + """Pairs of rows a sentence names, in every column of their table ("February 10 was 155% above January 20").""" + if not 1 < len(anchors) <= 8: + return [] + out: list[Allowed] = [] + for (ta, ra), (tb, rb) in itertools.permutations(sorted(anchors), 2): + if ta != tb or ta >= len(tables): + continue + t = tables[ta] + for c in range(min(len(t.rows[ra]), len(t.rows[rb]))): + va, vb = t.rows[ra][c], t.rows[rb][c] + if va is None or vb is None: + continue + col = t.columns[c] if c < len(t.columns) else f"column {c + 1}" + out += [ + dataclasses.replace(x, rows=frozenset({(ta, ra), (ta, rb)})) + for x in _pair(va, vb, f"{col} {_row_name(t, ra)}", _row_name(t, rb)) + ] + return out + + +def _fits_anchors(a: Allowed, anchors: set[tuple[int, int]], own: frozenset) -> bool: + """Whether a value may explain a figure, given the rows its sentence names. + + - a pair of any two rows: only when the sentence names both + - a figure with its own row (the name next to it): a cell of that row, a value about the whole + data (totals, counts), or a derived value about rows the sentence names ("$44.1 M more than + Home Goods" after "Audio & Video Accessories") + """ + if a.named and not (anchors and a.rows <= anchors): + return False + if not own or not a.rows or a.rows & own: + return True + return a.rank == 2 and bool(anchors) and a.rows <= anchors + + +def check_figures( + answer: str, + tables: Sequence[Table], + *, + filter_years: Iterable[int] = (), + known_text: Iterable[str] = (), +) -> GroundingResult: + """Check every figure of `answer` against the values `tables` allow (see the module docstring). + + `filter_years` are the years of the active filters; `known_text` names on screen (titles, + filter values) that hold digits and are no figures. + """ + labels = [lab for t in tables for lab in t.labels] + [c for t in tables for c in t.columns] + figures = extract_figures(answer, [*known_text, *labels]) + if not tables: + return GroundingResult(figures, 0) + allowed = allowed_values(tables) + _label_numbers(known_text, "title") + by_kind: dict[str, list[Allowed]] = {"amount": [], "percent": [], "ratio": []} + for a in allowed: + for k in a.kinds: + by_kind[k].append(a) + sorted_by_kind = {k: sorted(v, key=lambda a: abs(a.value)) for k, v in by_kind.items()} + keys = {k: [abs(a.value) for a in v] for k, v in sorted_by_kind.items()} + years = _allowed_years(filter_years, tables) + plain = _dashes(answer.replace("**", "").replace("__", "")) + row_names = _row_names(tables) + # labels stay in English: in another language a name next to a figure may not be the row's name + letters = [ch for ch in plain if ch.isalpha()] + english = not letters or sum(not ch.isascii() for ch in letters) / len(letters) < 0.01 + mentions = _mentions(plain, row_names) if english else [] + counts = {float(t.row_count) for t in tables} | {float(len(t.rows)) for t in tables} + for f in figures: + if f.kind == "year": + if years and int(f.value) not in years: + f.status, f.nearest = "ungrounded", [f"years in filters/labels: {sorted(years)}"] + else: + f.status, f.match = "grounded", "a year of the filters or labels" + continue + if f.kind == "bound": + continue + c_start = max((m.end() for m in _SENTENCE_END.finditer(plain, 0, f.pos)), default=0) + c_end_match = _SENTENCE_END.search(plain, f.pos) + c_end = c_end_match.start() if c_end_match else len(plain) + anchors = {r for m in mentions if c_start <= m[0] < c_end for r in m[2]} + own = _figure_row(f, figures, mentions, plain) + of = _COUNT_OF.match(plain, f.pos + len(f.raw)) + if ( + of + and f.kind == "amount" + and float(f.value).is_integer() + and _to_float(of.group(1)) in counts + and f.value <= _to_float(of.group(1)) + ): + f.status, f.match = "grounded", f"a count of rows out of {of.group(1)}" + continue + pool, pool_keys = sorted_by_kind[f.kind], keys[f.kind] + named_pairs = [a for a in _named_pairs(tables, anchors) if f.kind in a.kinds] + if named_pairs: # rows the sentence names, compared on the fly (any two rows of a long column) + pool = sorted([*pool, *named_pairs], key=lambda a: abs(a.value)) + pool_keys = [abs(a.value) for a in pool] + target = abs(f.value) + i = bisect.bisect_left(pool_keys, target) + reach = f.tolerance if f.rounded else 2 * f.tolerance # a derived value may come from rounded figures + window = pool[ + max(0, bisect.bisect_left(pool_keys, target - reach) - 3) : bisect.bisect_right(pool_keys, target + reach) + + 3 + ] + inside = sorted( + ( + a + for a in window + if abs(abs(a.value) - target) <= (reach if a.rank == 2 else f.tolerance) * (1 + 1e-9) + 1e-9 + and _fits_anchors(a, anchors, own) + ), + key=lambda a: (a.rank, abs(abs(a.value) - target)), + ) + if inside: + f.status, f.match = "grounded", f"{inside[0].how} ({_fmt(inside[0].value)})" + else: + near = sorted(pool[max(0, i - 3) : i + 3], key=lambda a: abs(abs(a.value) - target))[:3] + cells = [a for a in pool if a.rank == 0] + cell = min(cells, key=lambda a: abs(abs(a.value) - target)) if cells else None + if cell and cell not in near: # the closest cell says most about a wrong figure + near = [cell, *near[:2]] + f.status = "ungrounded" + f.nearest = [f"{a.how} = {_fmt(a.value)}" for a in near] + if own: + f.nearest.append(f"about the row(s) named next to it: {sorted(r + 1 for _, r in own)[:5]}") + return GroundingResult(figures, len(tables)) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/evaluators/describe_object.py b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/describe_object.py new file mode 100644 index 000000000..5e67c808f --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/evaluators/describe_object.py @@ -0,0 +1,89 @@ +# (C) 2026 GoodData Corporation +"""Checks and judge steps for `agentic_describe_object`: "describe / explain " in the chat. + +`expected_output`: + + { + "search": true, + "must_include": ["...criteria the answer must satisfy..."], + "must_not_include": ["...characteristics the answer must not show..."], + "rubric": ["...soft quality dimensions..."] + } + +`search` (default true) gates the verdict without a judge: the answer must rest on a +workspace lookup (`search_objects` or `get_object_with_children`), never on general +knowledge. An item where the right answer is to ask back ("Describe this" with nothing on +screen) sets it to false. Judge criteria are graded one by one; the INPUT the judge reads +is the item's question. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from gooddata_eval.core.evaluators._llm_judge import LLMJudge +from gooddata_eval.core.evaluators._rubric import Criterion, grade_rubric +from gooddata_eval.core.evaluators.base import ItemEvaluation + +LOOKUP_TOOLS = frozenset({"search_objects", "get_object_with_children"}) + +_POSITIVE_STEPS = [ + "Read the INPUT: the user's request to describe or explain an analytics object of their workspace.", + "Read the EXPECTED OUTPUT: one criterion the answer must satisfy.", + "Read the ACTUAL OUTPUT: the assistant's answer.", + "Score 1 if the actual output clearly satisfies the criterion.", + "Score 0 if the criterion is missing, contradicted, or only partially addressed.", +] + +_VIOLATION_STEPS = [ + "Read the CHARACTERISTIC described in EXPECTED OUTPUT, including any exceptions it states.", + "Read the ACTUAL OUTPUT: the assistant's answer.", + "Decide only whether the actual output exhibits the characteristic, not whether it is correct or wanted.", + "Score 1 if the actual output clearly exhibits the described characteristic.", + "Score 0 if it does not exhibit it.", +] + + +def _criteria(expected: dict[str, Any], key: str) -> list[Criterion]: + raw = expected.get(key) or [] + items = raw if isinstance(raw, list) else [raw] + return [(f"{key}_{i}", str(c)) for i, c in enumerate(items) if str(c).strip()] + + +def evaluate_answer( + *, + question: str, + answer: str, + tool_names: Sequence[str], + expected: dict[str, Any], + positive_judge: LLMJudge, + violation_judge: LLMJudge, +) -> ItemEvaluation: + """Grade one answer: a workspace lookup ran (unless the item expects the agent to ask back), then the criteria.""" + detail: dict[str, Any] = {"actual_output": answer} + if not answer.strip(): + return ItemEvaluation(passed=False, rank_key=(-1, 0.0), detail=detail, error="empty answer") + passed = True + if expected.get("search", True): + looked_up = sorted(LOOKUP_TOOLS.intersection(tool_names)) + detail["workspace_lookup"] = bool(looked_up) + if not looked_up: + detail["lookup_problem"] = f"answered without a workspace lookup (tools: {list(tool_names)})" + passed = False + return grade_rubric( + positive_judge, + violation_judge, + question=question, + actual=answer, + must_include=_criteria(expected, "must_include"), + must_not_include=_criteria(expected, "must_not_include"), + rubric=_criteria(expected, "rubric"), + detail=detail, + passed=passed, + ) + + +def make_judges(model: str | None = None) -> tuple[LLMJudge, LLMJudge]: + """The positive and the violation judge, with the describe-specific steps.""" + return LLMJudge(_POSITIVE_STEPS, model=model), LLMJudge(_VIOLATION_STEPS, model=model) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/interaction.py b/packages/gooddata-eval/src/gooddata_eval/core/interaction.py index 49b748a09..f7ecd82d8 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/interaction.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/interaction.py @@ -30,6 +30,7 @@ "agentic_search", "agentic_dashboard_summary", "agentic_memory", + "agentic_describe_object", } ) @@ -49,6 +50,8 @@ "agentic_forecasting", "agentic_agent_switcher", "agentic_knowledge", + # One summary turn plus the item's follow-ups, in one conversation. + "agentic_summary", } ) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/models.py b/packages/gooddata-eval/src/gooddata_eval/core/models.py index 62715dc32..f6a874548 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/models.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/models.py @@ -663,6 +663,65 @@ def _check(self) -> "MemoryInput": return self +class WidgetBaseline(BaseModel): + """What a widget's data was when the item was made, checked before every run. + + Only what a verdict rests on: whether it has data, how many rows, and the sum of its + values. A difference means the data under the item changed (fixture, execution or a + relative date), so the run says nothing about the agent. + """ + + model_config = ConfigDict(extra="forbid") + + has_data: bool + row_count: int + value_sum: float + + +class WidgetExecution(BaseModel): + """The execution a dashboard widget renders with, as the UI sent it. + + `afm` and `result_spec` are the body of `POST .../execution/afm/execute`, filters + included: captured from the result the UI computed, so measures (a KPI's comparison), + dimensions and sorting match what the user sees. Executed again on every run, because + a result id expires. + """ + + model_config = ConfigDict(extra="forbid") + + afm: dict[str, Any] + result_spec: dict[str, Any] = Field(default_factory=dict) + baseline: WidgetBaseline | None = None + + +class SummaryFollowUp(BaseModel): + """A question sent after the summary, in the same conversation.""" + + model_config = ConfigDict(extra="forbid") + + question: str = Field(min_length=1) + expected_output: Any = None + + +class AgenticSummaryInput(BaseModel): + """Structured input for the `agentic_summary` test kind. + + The chat summary of a widget or a dashboard as the UI asks for it. The item's + `user_context` is the UI's `userContext` without result ids; `executions` holds one + execution per widget id, run before each conversation to put fresh result ids back. + Every widget in the context needs an execution: the kind refuses an item that misses one. + """ + + model_config = ConfigDict(extra="forbid") + + scope: Literal["widget", "dashboard"] + # The message sent to the agent. The item's `question` is a readable scenario line the + # judge reads as INPUT, so the sent text lives here; None sends the UI's pre-filled one. + question: str | None = None + executions: dict[str, WidgetExecution] = Field(default_factory=dict) + follow_ups: list[SummaryFollowUp] = Field(default_factory=list) + + class DatasetItem(BaseModel): """Common dataset envelope. `expected_output` stays raw; each evaluator parses its own shape.""" @@ -683,6 +742,8 @@ class DatasetItem(BaseModel): agent_switcher_input: AgentSwitcherInput | None = None # Only used by the `agentic_memory` test kind; ignored by all others. memory_input: MemoryInput | None = None + # Only used by the `agentic_summary` test kind; ignored by all others. + agentic_summary_input: AgenticSummaryInput | None = None # Relayed verbatim as the chat request's `userContext`. Deliberately opaque: gen-ai owns # that schema (a discriminated union of view/widget descriptors), so re-modelling it here # would only create a second copy to keep in sync. diff --git a/packages/gooddata-eval/src/gooddata_eval/core/outcome.py b/packages/gooddata-eval/src/gooddata_eval/core/outcome.py index 0d9d0df95..c77aeb78b 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/outcome.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/outcome.py @@ -16,6 +16,10 @@ proof the agent was blameless: the simulated user is also asked after an answer that was already final, so an ERROR run still lists the checks it failed. Anything else, including a chat API error and an unknown exit, is FAIL. + +An item can also be ERROR before its first run: a kind that prepares its own input (it runs the +stored executions of a dashboard's widgets) could not prepare it, for a cause on ``SETUP_ERRORS``. +No chat is sent then, so there is no run to label; ``setup_error`` is that item's outcome. """ from __future__ import annotations @@ -35,10 +39,12 @@ "JUDGE_FAILED", "Outcome", "OutcomeStatus", + "SETUP_ERRORS", "SHADOW_MIN_SCORED_SHARE", "UNKNOWN_REASON", "classify_run", "item_outcome", + "setup_error", "shadow_verdict", ] @@ -87,6 +93,16 @@ def as_record(self) -> dict[str, Any]: JUDGE_FAILED = "judge_failed" """The reason of a run the judge or scorer could not grade.""" +DATA_BASELINE_CHANGED = "data_baseline_changed" +"""The data under the item differs from the baseline the item stores.""" + +WIDGET_EXECUTION_FAILED = "widget_execution_failed" +"""A stored widget execution of the item could not be run, or its result could not be read.""" + +SETUP_ERRORS: frozenset[str] = frozenset({DATA_BASELINE_CHANGED, WIDGET_EXECUTION_FAILED}) +"""The only causes that make an item an ERROR before any run. Like ``_ERROR_EXITS`` they are on the +harness path: the agent was never asked.""" + UNKNOWN_REASON = "unknown" """The reason shown for an ERROR that carries none.""" @@ -127,6 +143,17 @@ def classify_run(exit_reason: LoopExit | str | None, *, passed: bool, judge_erro return Outcome.failed(loop_exit.value if loop_exit is not None else None) +def setup_error(reason: str) -> Outcome: + """The outcome of an item whose input could not be prepared, so that no run happened. + + Raises: + ValueError: ``reason`` is not on ``SETUP_ERRORS``: a new cause is added there on purpose. + """ + if reason not in SETUP_ERRORS: + raise ValueError(f"{reason!r} is not a setup error; known: {sorted(SETUP_ERRORS)}") + return Outcome.error(reason) + + def item_outcome(outcomes: Sequence[Outcome]) -> Outcome | None: """ERROR when every run of the item is ERROR, with the most frequent reason; else None. diff --git a/packages/gooddata-eval/tests/test_agentic_chat_summary.py b/packages/gooddata-eval/tests/test_agentic_chat_summary.py new file mode 100644 index 000000000..fef2dcf7b --- /dev/null +++ b/packages/gooddata-eval/tests/test_agentic_chat_summary.py @@ -0,0 +1,373 @@ +# (C) 2026 GoodData Corporation +from __future__ import annotations + +import json +from typing import Any, cast + +import httpx +import pytest +from gooddata_eval.cli.agentic_runner import item_runs_in_parallel +from gooddata_eval.core.agentic import chat_summary +from gooddata_eval.core.dataset.langfuse_source import _item_from_raw +from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError +from gooddata_eval.core.models import AgenticSummaryInput, ChatResult, DatasetItem, WidgetBaseline, WidgetExecution + +_AFM = { + "attributes": [], + "measures": [{"localIdentifier": "m", "definition": {"measure": {"item": {}}}}], + "filters": [], +} +_SPEC = {"dimensions": [{"localIdentifier": "dim_0", "itemIdentifiers": ["measureGroup"]}]} + + +def _context(*widget_ids: str, referenced: list[str] | None = None) -> dict[str, Any]: + widgets: list[dict[str, Any]] = [ + {"widgetId": w, "title": f"Title {w}", "widgetType": "insight", "resultId": f"stale-{w}"} for w in widget_ids + ] + context: dict[str, Any] = {"view": {"dashboard": {"id": "d", "widgets": widgets}}} + if referenced is not None: + context["referencedObjects"] = [ + {"context": {"type": "DASHBOARD", "id": "d"}, "objects": [{"type": "WIDGET", "id": r} for r in referenced]} + ] + return context + + +def _input(scope: str = "dashboard", *widget_ids: str) -> AgenticSummaryInput: + return AgenticSummaryInput.model_validate( + {"scope": scope, "executions": {w: {"afm": _AFM, "result_spec": _SPEC} for w in widget_ids}} + ) + + +def test_fresh_result_ids_replace_the_stored_ones_and_a_failed_widget_has_none() -> None: + stored = _context("a", "b") + sent = chat_summary.with_result_ids(stored, {"a": "fresh-a", "b": None}) + widgets = sent["view"]["dashboard"]["widgets"] + assert widgets[0]["resultId"] == "fresh-a" + assert "resultId" not in widgets[1] + # the stored item is not changed: the next run starts from it again + assert stored["view"]["dashboard"]["widgets"][0]["resultId"] == "stale-a" + + +def test_a_widget_without_a_stored_execution_is_reported() -> None: + context = _context("a", "b") + context["view"]["dashboard"]["widgets"].append({"widgetId": "note", "widgetType": "richText"}) + assert chat_summary.missing_executions(context, _input("dashboard", "a").executions) == ["b"] + + +def test_the_ui_question_names_the_referenced_widget() -> None: + context = _context("a", "b", referenced=["b"]) + assert chat_summary.default_question(_input("widget", "a", "b"), context) == 'Summarize the visualization "Title b"' + assert chat_summary.default_question(_input("dashboard", "a", "b"), context) == "Summarize this dashboard" + + +@pytest.mark.parametrize("referenced", [[], ["a", "b"]]) +def test_a_widget_summary_without_exactly_one_referenced_widget_needs_a_question(referenced: list[str]) -> None: + with pytest.raises(ValueError, match="exactly one referenced widget"): + chat_summary.default_question(_input("widget", "a", "b"), _context("a", "b", referenced=referenced)) + + +def test_execute_widget_posts_the_stored_execution_and_returns_the_result_id() -> None: + seen: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.path == "/api/v1/actions/workspaces/ws/execution/afm/execute" + seen.append(json.loads(request.content)) + return httpx.Response(200, json={"executionResponse": {"links": {"executionResult": "rid-1"}}}) + + with httpx.Client(base_url="https://h", transport=httpx.MockTransport(handler)) as client: + rid = chat_summary.execute_widget(client, "ws", WidgetExecution(afm=_AFM, result_spec=_SPEC)) + assert rid == "rid-1" + assert seen == [{"execution": _AFM, "resultSpec": _SPEC}] + + +def test_execute_widgets_keeps_a_failed_widget_as_none(monkeypatch: pytest.MonkeyPatch) -> None: + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + if body["execution"]["measures"][0]["localIdentifier"] == "bad": + return httpx.Response(400, json={"detail": "bad filter"}) + return httpx.Response(200, json={"executionResponse": {"links": {"executionResult": "rid-ok"}}}) + + real_client = httpx.Client + monkeypatch.setattr( + chat_summary.httpx, "Client", lambda **kw: real_client(transport=httpx.MockTransport(handler), **kw) + ) + bad = {**_AFM, "measures": [{"localIdentifier": "bad", "definition": {}}]} + executions = {"ok": WidgetExecution(afm=_AFM), "bad": WidgetExecution(afm=bad)} + assert chat_summary.execute_widgets("https://h", "t", "ws", executions) == {"ok": "rid-ok", "bad": None} + + +def test_a_failed_turn_ends_the_conversation() -> None: + class _Client: + def __init__(self) -> None: + self.sent: list[str] = [] + + def send_message(self, conversation_id: str, question: str, *, user_context: dict) -> Any: + self.sent.append(question) + if question == "second": + raise chat_summary.ChatError("boom") + return object() + + client = _Client() + turns = chat_summary.run_summary_conversation( + cast(chat_summary.ChatClient, client), "c", ["first", "second", "third"], {} + ) + assert client.sent == ["first", "second"] + assert [t.error is None for t in turns] == [True, False] + + +def test_the_langfuse_item_carries_the_summary_input_from_its_metadata() -> None: + raw = { + "id": "i1", + "input": "[dashboard] 2. Sales · all time", + "expectedOutput": {"must_include": ["x"]}, + "metadata": { + "test_kind": "agentic_summary", + "user_context": _context("a"), + "agentic_summary_input": { + "scope": "dashboard", + "executions": {"a": {"afm": _AFM, "result_spec": _SPEC}}, + "follow_ups": [{"question": "Why?", "expected_output": {"must_not_include": ["a cause"]}}], + }, + }, + } + item = _item_from_raw(raw, dataset_name="chat_summary", test_kind="visualization") + assert item.test_kind == "agentic_summary" + assert item.agentic_summary_input is not None + assert item.agentic_summary_input.follow_ups[0].question == "Why?" + assert item.user_context == _context("a") + + +def test_an_invalid_summary_input_fails_loudly() -> None: + raw = {"id": "i2", "input": "q", "expectedOutput": {}, "metadata": {"agentic_summary_input": {"scope": "page"}}} + with pytest.raises(ValueError, match="invalid `agentic_summary_input`"): + _item_from_raw(raw, dataset_name="chat_summary", test_kind="visualization") + + +# ---------- baseline ---------- + + +def _result(data: list, total: int) -> dict[str, Any]: + return {"data": data, "paging": {"total": [total, 1]}} + + +def test_the_baseline_reads_data_rows_and_sum() -> None: + assert chat_summary.baseline_of(_result([[1.0], [2.5]], 2)) == WidgetBaseline( + has_data=True, row_count=2, value_sum=3.5 + ) + assert chat_summary.baseline_of(None) == WidgetBaseline(has_data=False, row_count=0, value_sum=0.0) + + +def test_a_changed_widget_is_named_with_old_and_new_values() -> None: + inp = AgenticSummaryInput.model_validate( + { + "scope": "widget", + "executions": { + "w": {"afm": {}, "baseline": {"has_data": True, "row_count": 92, "value_sum": 1000.0}}, + "x": {"afm": {}}, + }, + } + ) + problems = chat_summary.baseline_problems( + inp.executions, {"w": _result([], 0), "x": None}, {"w": "Net sales over time"} + ) + assert problems == [ + 'widget "Net sales over time": has_data True → False, row_count 92 → 0, value_sum 1,000.00 → 0.00' + ] + same = {"w": _result([[400.0], [600.0]], 92)} + assert chat_summary.baseline_problems(inp.executions, same, {}) == [] + + +def test_changed_data_stops_the_run_before_any_conversation(monkeypatch: pytest.MonkeyPatch) -> None: + opened: list[str] = [] + + class _Client: + def __init__(self, **_kwargs: Any) -> None: + pass + + def create_conversation(self) -> str: + opened.append("conversation") + return "c1" + + def close(self) -> None: + pass + + inp = AgenticSummaryInput.model_validate( + { + "scope": "dashboard", + "executions": {"w": {"afm": _AFM, "baseline": {"has_data": True, "row_count": 92, "value_sum": 1000.0}}}, + } + ) + monkeypatch.setattr(chat_summary, "ChatClient", _Client) + monkeypatch.setattr(chat_summary, "execute_widgets", lambda *_a, **_k: {"w": "r1"}) + monkeypatch.setattr(chat_summary, "fetch_results", lambda *_a, **_k: {"w": _result([], 0)}) + + with pytest.raises(chat_summary.DataBaselineError, match="row_count 92 → 0"): + chat_summary.run_chat_summary("h", "t", "ws", inp, _context("w")) + assert opened == [] + + +@pytest.mark.parametrize( + ("question", "follow_ups", "parallel"), + [ + (None, [], True), + (None, [{"question": "Which one is the largest?"}], False), + ("Give me a brief executive summary", [], False), + ], +) +def test_a_summary_item_with_free_text_runs_serially(question: str | None, follow_ups: list, parallel: bool) -> None: + item = DatasetItem( + id="i1", + dataset_name="d", + test_kind="agentic_summary", + question="[widget] Sales", + expected_output={}, + agentic_summary_input=AgenticSummaryInput.model_validate( + {"scope": "widget", "question": question, "follow_ups": follow_ups} + ), + ) + assert item_runs_in_parallel(item) is parallel + + +def test_a_failed_execution_stops_the_run_and_is_not_called_a_data_change(monkeypatch: pytest.MonkeyPatch) -> None: + opened: list[str] = [] + + class _Client: + def __init__(self, **_kwargs: Any) -> None: + pass + + def create_conversation(self) -> str: + opened.append("conversation") + return "c1" + + def close(self) -> None: + pass + + baseline = {"has_data": True, "row_count": 1, "value_sum": 10.0} + inp = AgenticSummaryInput.model_validate( + {"scope": "dashboard", "executions": {w: {"afm": _AFM, "baseline": baseline} for w in ("a", "b", "c")}} + ) + monkeypatch.setattr(chat_summary, "ChatClient", _Client) + monkeypatch.setattr(chat_summary, "execute_widgets", lambda *_a, **_k: {"a": "r1", "b": None, "c": "r3"}) + monkeypatch.setattr( + chat_summary, "fetch_results", lambda *_a, **_k: {"a": _result([[10.0]], 1), "b": None, "c": None} + ) + + with pytest.raises(chat_summary.WidgetExecutionError) as info: + chat_summary.run_chat_summary("h", "t", "ws", inp, _context("a", "b", "c")) + assert info.value.problems == [ + 'widget "Title b": the execution failed', + 'widget "Title c": the result could not be read', + ] + assert opened == [] + + def failed(*_args: Any, **_kwargs: Any) -> list: + raise info.value + + monkeypatch.setattr(chat_summary, "run_chat_summary", failed) + with pytest.raises(chat_summary.ChatSummaryAssertionError, match="a stored widget execution failed") as item: + chat_summary.evaluate_agentic_summary("h", "t", "ws", "[dashboard] Sales", inp, _context("a", "b", "c"), {}) + assert item.value.harness_error == {"status": "error", "reason": "widget_execution_failed"} + assert item.value.detail["widgets_executed"] is False + + +def test_a_misspelt_format_key_fails_before_any_execution(monkeypatch: pytest.MonkeyPatch) -> None: + def never(*_args: Any, **_kwargs: Any) -> list: + raise AssertionError("the item must not run") + + monkeypatch.setattr(chat_summary, "run_chat_summary", never) + with pytest.raises(ValueError, match="item: unknown `format` keys"): + chat_summary.evaluate_agentic_summary( + "h", "t", "ws", "[widget] Sales", AgenticSummaryInput(scope="widget"), {}, {"format": {"no_heading": True}} + ) + follow_up = AgenticSummaryInput.model_validate( + {"scope": "widget", "follow_ups": [{"question": "Which?", "expected_output": {"no_tool_call": True}}]} + ) + with pytest.raises(ValueError, match="follow-up 1: unknown expected_output keys"): + chat_summary.evaluate_agentic_summary("h", "t", "ws", "[widget] Sales", follow_up, {}, {}) + + +def test_a_changed_baseline_is_an_error_item_without_a_chat(monkeypatch: pytest.MonkeyPatch) -> None: + def changed(*_args: Any, **_kwargs: Any) -> list: + raise chat_summary.DataBaselineError(['widget "Sales": row_count 92 → 0']) + + monkeypatch.setattr(chat_summary, "run_chat_summary", changed) + with pytest.raises(chat_summary.ChatSummaryAssertionError) as info: + chat_summary.evaluate_agentic_summary( + "h", "t", "ws", "[widget] Sales", AgenticSummaryInput(scope="widget"), {}, {}, k=2 + ) + exc = info.value + assert exc.harness_error == {"status": "error", "reason": "data_baseline_changed"} + assert exc.detail == {"data_baseline": False, "data_baseline_reason": 'widget "Sales": row_count 92 → 0'} + assert exc.runs_effective == 0 + + +class _Judge: + model = "stub" + + def __init__(self, verdict: bool | None) -> None: + self.verdict = verdict + + def score(self, input: str, expected_output: str, actual_output: str) -> tuple[bool, str]: + if self.verdict is None: + raise JudgeResponseError("unreadable") + return self.verdict, "stub" + + +def _conversation(answer: str) -> chat_summary.SummaryConversation: + table = json.dumps( + { + "results": [ + { + "data": { + "columns": [{"name": "Customer", "type": "attribute"}, {"name": "Net Sales", "type": "metric"}], + "row_labels": [["Tracy Carter"], ["Tammy Long"]], + "data": [[1317241.93], [1301535.2]], + "row_count": 2, + } + } + ] + } + ) + result = ChatResult.model_validate( + { + "textResponse": answer, + "toolCallEvents": [ + {"functionName": "execute_existing_visualizations", "functionArguments": "{}", "result": table} + ], + } + ) + return chat_summary.SummaryConversation( + "c", turns=[chat_summary.SummaryTurn("Summarize", result=result)], scope=None, widgets_total=1 + ) + + +@pytest.mark.parametrize( + ("answer", "verdict", "outcome"), + [ + ("Tracy Carter leads with $1.3 M.", True, "pass"), + ("Tammy Long leads with $1.5 M.", True, "fail"), # an invented figure + ("Tracy Carter leads with $1.3 M.", None, "error"), # no run got a verdict + ], +) +def test_the_item_gates_on_its_runs( + monkeypatch: pytest.MonkeyPatch, answer: str, verdict: bool | None, outcome: str +) -> None: + monkeypatch.setattr( + chat_summary, "run_chat_summary", lambda *a, **k: [_conversation(answer), _conversation(answer)] + ) + monkeypatch.setattr(chat_summary, "make_judges", lambda model=None: (_Judge(verdict), _Judge(False))) + args = ("h", "t", "ws", "[widget] Top Spenders", AgenticSummaryInput(scope="widget"), {}, {"must_include": ["x"]}) + if outcome == "pass": + result = chat_summary.evaluate_agentic_summary(*args, k=2) + assert result.runs_passed == 2 + assert result.best_run_latency_s is not None + assert "tool_calls" in result.detail + return + error_cls = chat_summary.ChatSummaryAssertionError if outcome == "fail" else JudgeResponseError + with pytest.raises(error_cls) as info: + chat_summary.evaluate_agentic_summary(*args, k=2) + assert info.value.runs_passed == 0 + if outcome == "error": + assert info.value.harness_error is not None + else: + assert info.value.detail["figures_grounded"] is False diff --git a/packages/gooddata-eval/tests/test_agentic_describe_object.py b/packages/gooddata-eval/tests/test_agentic_describe_object.py new file mode 100644 index 000000000..b000b0a9f --- /dev/null +++ b/packages/gooddata-eval/tests/test_agentic_describe_object.py @@ -0,0 +1,85 @@ +# (C) 2026 GoodData Corporation +from __future__ import annotations + +from typing import Any, cast + +import pytest +from gooddata_eval.core.agentic import describe_object as kind +from gooddata_eval.core.evaluators import describe_object as do +from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError, LLMJudge +from gooddata_eval.core.models import ChatResult + + +class _Judge: + model = "stub" + + def __init__(self, verdict: bool | None) -> None: + self.verdict = verdict + + def score(self, input: str, expected_output: str, actual_output: str) -> tuple[bool, str]: + if self.verdict is None: + raise JudgeResponseError("unreadable") + return self.verdict, "stub" + + +def test_a_describe_answer_must_rest_on_a_workspace_lookup() -> None: + def grade(tools: list[str], expected: dict[str, Any]): + return do.evaluate_answer( + question="Explain the ARPU metric", + answer="ARPU is Net Sales divided by Active Customers.", + tool_names=tools, + expected=expected, + positive_judge=cast(LLMJudge, _Judge(True)), + violation_judge=cast(LLMJudge, _Judge(False)), + ) + + assert grade(["set_skills", "search_objects"], {}).passed + no_lookup = grade([], {}) + assert not no_lookup.passed + assert no_lookup.detail["workspace_lookup"] is False + # an item whose right answer is to ask back needs no lookup + assert grade([], {"search": False}).passed + + +class _Client: + """A chat client that answers every question with one lookup and one sentence.""" + + def __init__(self, **_kwargs: Any) -> None: + self.deleted: list[str] = [] + + def create_conversation(self) -> str: + return "conv" + + def send_message(self, conversation_id: str, question: str) -> ChatResult: + return ChatResult.model_validate( + { + "textResponse": "ARPU is Net Sales divided by Active Customers.", + "toolCallEvents": [{"functionName": "search_objects", "functionArguments": "{}", "result": "{}"}], + } + ) + + def delete_conversation(self, conversation_id: str) -> None: + self.deleted.append(conversation_id) + + def close(self) -> None: + pass + + +@pytest.mark.parametrize(("verdict", "outcome"), [(True, "pass"), (False, "fail"), (None, "error")]) +def test_the_item_passes_fails_or_errors_with_the_judge( + monkeypatch: pytest.MonkeyPatch, verdict: bool | None, outcome: str +) -> None: + monkeypatch.setattr(kind, "ChatClient", _Client) + monkeypatch.setattr(kind, "make_judges", lambda model=None: (_Judge(verdict), _Judge(False))) + expected = {"must_include": ["Names the formula."]} + if outcome == "pass": + result = kind.evaluate_agentic_describe_object("h", "t", "ws", "Explain ARPU", expected, k=2) + assert result.runs_passed == 2 + assert result.best_run_latency_s is not None + return + error_cls = kind.DescribeObjectAssertionError if outcome == "fail" else JudgeResponseError + with pytest.raises(error_cls) as info: + kind.evaluate_agentic_describe_object("h", "t", "ws", "Explain ARPU", expected, k=2) + assert info.value.runs_passed == 0 + if outcome == "error": # no run got a verdict: a harness error, not two failures + assert info.value.harness_error is not None diff --git a/packages/gooddata-eval/tests/test_agentic_runner.py b/packages/gooddata-eval/tests/test_agentic_runner.py index 9919e37f2..acb8f7f3c 100644 --- a/packages/gooddata-eval/tests/test_agentic_runner.py +++ b/packages/gooddata-eval/tests/test_agentic_runner.py @@ -110,6 +110,8 @@ def test_dispatch_agentic_omits_agent_id_by_default(): ("agentic_agent_switcher", {}, "evaluate_agentic_agent_switcher"), ("agentic_knowledge", {"expected_documents": ["Discount Policy"]}, "evaluate_agentic_knowledge"), ("agentic_memory", "Ends with the help line.", "evaluate_agentic_memory"), + ("agentic_summary", {"must_include": ["Names the period."]}, "evaluate_agentic_summary"), + ("agentic_describe_object", {"must_include": ["Names the chart type."]}, "evaluate_agentic_describe_object"), ] # Kinds whose item names its own agents, so the CLI's --agent-id does not reach them. @@ -119,6 +121,19 @@ def test_dispatch_agentic_omits_agent_id_by_default(): # summarize is named in summary_input, exactly as for the single-shot dashboard_summary. _SUMMARY_INPUT_KINDS = {"agentic_dashboard_summary"} +# agentic_summary needs its stored executions and the UI's context: without either the item +# cannot be sent the way the UI sends it. +_AGENTIC_SUMMARY_FIELDS: dict[str, Any] = { + "agentic_summary_input": {"scope": "widget"}, + "user_context": {"view": {"dashboard": {"widgets": []}}}, +} + + +def _kind_fields(kind: str) -> dict[str, Any]: + if kind in _SUMMARY_INPUT_KINDS: + return {"summary_input": {"dashboard_id": "dash-1"}} + return _AGENTIC_SUMMARY_FIELDS if kind == "agentic_summary" else {} + def test_all_agentic_kind_cases_covers_every_registered_kind(): """Guards the two parametrized tests below against silently going stale: a kind added @@ -136,7 +151,7 @@ def test_dispatch_agentic_passes_agent_id_through_for_every_kind(kind, expected_ test_kind=kind, question="q", expected_output=expected_output, - summary_input={"dashboard_id": "dash-1"} if kind in _SUMMARY_INPUT_KINDS else None, + **_kind_fields(kind), ) with patch(f"gooddata_eval.cli.agentic_runner.{target}") as mock_eval: _dispatch_agentic( @@ -281,7 +296,7 @@ def test_dispatch_agentic_returns_a_real_outcome_for_every_kind(kind, expected_o test_kind=kind, question="q", expected_output=expected_output, - summary_input={"dashboard_id": "dash-1"} if kind in _SUMMARY_INPUT_KINDS else None, + **_kind_fields(kind), ) canned = AgenticEvalOutcome(reasoning_steps=["x"], conversation_id="c1", response_id="r1", detail={"k": "v"}) with patch(f"gooddata_eval.cli.agentic_runner.{target}", return_value=canned) as mock_eval: @@ -907,6 +922,8 @@ def test_an_errored_item_without_timings_keeps_its_zero_defaults(): ("agentic_conversation", "evaluate_agentic_conversation", {"id": "c1", "expected_skills": [], "turns": []}), ("agentic_agent_switcher", "evaluate_agentic_agent_switcher", {}), ("agentic_memory", "evaluate_agentic_memory", "Ends with the help line."), + ("agentic_summary", "evaluate_agentic_summary", {}), + ("agentic_describe_object", "evaluate_agentic_describe_object", {}), ] @@ -929,7 +946,21 @@ def test_dispatch_agentic_passes_user_context_through_to_every_kind( expected_output=expected_output, user_context=user_context, summary_input={"dashboard_id": "dash-1"} if kind in _SUMMARY_INPUT_KINDS else None, + agentic_summary_input={"scope": "widget"} if kind == "agentic_summary" else None, ) + if kind == "agentic_summary" and user_context is None: + with pytest.raises(ValueError, match="needs both"): + _dispatch_agentic( + item, + host="https://h", + token="tok", + workspace_id="ws1", + k=1, + langfuse=None, + run_ts="2026-01-01", + model_version_override=None, + ) + return with patch(f"gooddata_eval.cli.agentic_runner.{evaluator}") as mock_eval: _dispatch_agentic( item, @@ -949,9 +980,15 @@ def test_dispatch_agentic_passes_user_context_through_to_every_kind( # agentic_dashboard_summary builds its own context from the dashboard it summarises and # takes its scope from summary_input, so relaying the item's context would override the -# thing under test rather than add to it. Excluded on purpose, not by omission. -# agentic_agent_switcher and agentic_memory get the whole item and read user_context off it. -_KINDS_WITHOUT_USER_CONTEXT = {"agentic_dashboard_summary", "agentic_agent_switcher", "agentic_memory"} +# thing under test rather than add to it. agentic_describe_object asks with no context, as +# the Analyze-page chat does; agentic_agent_switcher and agentic_memory get the whole item and +# read user_context off it. Excluded on purpose, not by omission. +_KINDS_WITHOUT_USER_CONTEXT = { + "agentic_dashboard_summary", + "agentic_agent_switcher", + "agentic_memory", + "agentic_describe_object", +} class _Stop(Exception): @@ -1134,7 +1171,7 @@ def test_failed_runs_reaches_the_report_for_every_kind(kind, expected_output, ta test_kind=kind, question="q", expected_output=expected_output, - summary_input={"dashboard_id": "dash-1"} if kind in _SUMMARY_INPUT_KINDS else None, + **_kind_fields(kind), ) canned = AgenticEvalOutcome(reasoning_steps=["x"], detail={"k": "v"}, failed_runs=[_A_FAILED_RUN]) with patch(f"gooddata_eval.cli.agentic_runner.{target}", return_value=canned): @@ -1283,7 +1320,7 @@ def test_run_latencies_reach_the_report_for_every_kind(kind, expected_output, ta test_kind=kind, question="q", expected_output=expected_output, - summary_input={"dashboard_id": "dash-1"} if kind in _SUMMARY_INPUT_KINDS else None, + **_kind_fields(kind), ) canned = AgenticEvalOutcome(reasoning_steps=["x"], detail={"k": "v"}, run_latencies_s=[4.5, 6.0]) with patch(f"gooddata_eval.cli.agentic_runner.{target}", return_value=canned): @@ -1354,7 +1391,7 @@ def test_every_kind_gets_its_chat_turns_recorded_as_trace_latencies(kind, expect test_kind=kind, question="q", expected_output=expected_output, - summary_input={"dashboard_id": "dash-1"} if kind in _SUMMARY_INPUT_KINDS else None, + **_kind_fields(kind), ) with patch(f"gooddata_eval.cli.agentic_runner.{target}", side_effect=_noting(1.5, 2.5, 0.5)): report = run_agentic_items([item], host="http://host", token="tok", workspace_id="ws1", run_ts="2026-01-01") diff --git a/packages/gooddata-eval/tests/test_chat_summary_evaluator.py b/packages/gooddata-eval/tests/test_chat_summary_evaluator.py new file mode 100644 index 000000000..990f0f57e --- /dev/null +++ b/packages/gooddata-eval/tests/test_chat_summary_evaluator.py @@ -0,0 +1,272 @@ +# (C) 2026 GoodData Corporation +from __future__ import annotations + +from typing import Any, cast + +import pytest +from gooddata_eval.core.agentic import chat_summary as kind +from gooddata_eval.core.evaluators import chat_summary as cs +from gooddata_eval.core.evaluators._llm_judge import LLMJudge +from gooddata_eval.core.models import AgenticSummaryInput, ChatResult + +CHART = """## Summary +Net sales grew in 2024. + +## Key Findings +- Audio & Video Accessories led with **$19.5 M**. + +## Trends +- Sales rose through the year. + +## Areas to Watch +- Furniture declined by **21.9%**.""" + +DASHBOARD = """## Summary +For **2024**, total sales reached **$67.5 M**. + +## Key Insights +- Gross profit fell **0.7%**. + +## Areas to Watch +- Orders declined slightly.""" + +CHART_SCOPE = cs.SummaryScope("widget", kpi_only=False, all_empty=False) +KPI_SCOPE = cs.SummaryScope("widget", kpi_only=True, all_empty=False) +DASHBOARD_SCOPE = cs.SummaryScope("dashboard", kpi_only=False, all_empty=False) + + +class _Judge: + """Answers every criterion with the verdict it was built with, and records the criteria it saw.""" + + def __init__(self, verdict: bool) -> None: + self.verdict = verdict + self.seen: list[tuple[str, str]] = [] + + def score(self, input: str, expected_output: str, actual_output: str) -> tuple[bool, str]: + self.seen.append((input, expected_output)) + return self.verdict, "stub" + + +def _grade(answer: str, expected: dict[str, Any], scope: cs.SummaryScope | None, tools: list[str] | None = None): + positive, violation = _Judge(True), _Judge(False) + return cs.evaluate_turn( + judge_input="[widget] 2. Sales", + answer=answer, + tool_names=tools or [], + expected=expected, + scope=scope, + positive_judge=cast(LLMJudge, positive), + violation_judge=cast(LLMJudge, violation), + ) + + +def test_a_chart_summary_needs_the_four_headings_in_order() -> None: + assert _grade(CHART, {}, CHART_SCOPE).passed + swapped = ( + CHART.replace("## Trends", "## Tmp") + .replace("## Key Findings", "## Trends") + .replace("## Tmp", "## Key Findings") + ) + result = _grade(swapped, {}, CHART_SCOPE) + assert not result.passed + assert "expected ['Summary', 'Key Findings', 'Trends', 'Areas to Watch']" in result.detail["shape_problem"] + + +def test_a_dashboard_summary_needs_its_three_headings() -> None: + assert _grade(DASHBOARD, {}, DASHBOARD_SCOPE).passed + assert not _grade(CHART, {}, DASHBOARD_SCOPE).passed + + +def test_a_kpi_summary_has_no_headings_and_few_sentences() -> None: + kpi = "For **2024**, Total Sales was **$67.5 M**, up **0.27%** from the previous period." + assert _grade(kpi, {}, KPI_SCOPE).passed + assert not _grade(DASHBOARD, {}, KPI_SCOPE).passed + long_kpi = " ".join(["Sales grew."] * 4) + assert "4 sentences on a KPI" in _grade(long_kpi, {}, KPI_SCOPE).detail["shape_problem"] + + +def test_a_dashboard_without_data_has_no_headings_and_no_figures() -> None: + empty = cs.SummaryScope("dashboard", kpi_only=False, all_empty=True) + no_data = "No data is available for the current dashboard filters. Please check the filter configuration." + assert _grade(no_data, {}, empty).passed + with_figures = "No data for 2020, but last year sales were $1.9 M and grew 12%." + result = _grade(with_figures, {}, empty) + assert not result.passed + assert result.detail["figures_on_no_data"] == ["$1.9 M", "12%"] + + +def test_an_empty_widget_has_no_fixed_shape() -> None: + empty = cs.SummaryScope("widget", kpi_only=False, all_empty=True) + assert _grade("## Summary\n- The visualization returned no data for January 1–December 31, 2020.", {}, empty).passed + + +def test_a_users_own_format_replaces_the_default_shape() -> None: + brief = {"format": {"max_sentences": 3, "no_headings": True, "no_bullets": True}} + three = "Tracy Carter leads at $1.3 M. The top three are close. The tenth is at $985.3 K." + assert _grade(three, brief, CHART_SCOPE).passed + assert "headings" in _grade(CHART, brief, CHART_SCOPE).detail["shape_problem"] + four = three + " Spending is concentrated." + assert "4 sentences" in _grade(four, brief, CHART_SCOPE).detail["shape_problem"] + assert _grade(CHART, {"format": False}, CHART_SCOPE).detail.get("shape_ok") is None + titled = "Tracy Carter leads at $1.3 M. Mrs. Crystal Murray is third. The tenth is at $985.3 K." + assert _grade(titled, brief, CHART_SCOPE).passed + + +@pytest.mark.parametrize( + "leak", + ["See {visualization/top_10_spenders} for details.", "Widget 0f1e2d3c-4b5a-6978-8a9b-0c1d2e3f4a5b is empty."], +) +def test_ids_never_reach_the_answer(leak: str) -> None: + result = _grade(f"{CHART}\n{leak}", {}, CHART_SCOPE) + assert not result.passed + assert result.detail["no_ids"] is False + + +def test_a_follow_up_without_tool_calls_has_no_default_shape() -> None: + answer = "Tracy Carter leads, about $15.7 K ahead of the second place." + assert _grade(answer, {"no_tool_calls": True}, None, tools=["set_skills"]).passed + # a follow-up may link objects: the UI renders its reference tags + assert _grade("Driven by {metric/active_customers}.", {}, None).detail.get("no_ids") is None + ran = _grade(answer, {"no_tool_calls": True}, None, tools=["execute_existing_visualizations"]) + assert not ran.passed + assert ran.detail["tools_run"] == ["execute_existing_visualizations"] + + +def test_judge_criteria_gate_the_verdict() -> None: + result = _grade(CHART, {"must_include": ["names the period"], "must_not_include": ["invents a cause"]}, CHART_SCOPE) + assert result.passed + assert result.detail["must_include_0"] is True + assert result.detail["must_not_include_0"] is True + + +def _turn(answer: str, tools: list[str]) -> kind.SummaryTurn: + result = ChatResult.model_validate( + { + "textResponse": answer, + "toolCallEvents": [{"functionName": t, "functionArguments": "{}"} for t in tools], + } + ) + return kind.SummaryTurn("q", result=result) + + +def test_each_turn_is_graded_with_its_own_expectation(monkeypatch: pytest.MonkeyPatch) -> None: + # no figures: this run's turns carry tool names only, so there is no table to ground a figure on + summary = "## Summary\nSales grew.\n\n## Key Findings\n- Clothing leads.\n\n## Trends\n- Up.\n\n## Areas to Watch\n- None." + judges = (_Judge(True), _Judge(False)) + monkeypatch.setattr(kind, "make_judges", lambda model=None: judges) + run = kind.SummaryConversation( + "c", + turns=[_turn(summary, ["execute_existing_visualizations"]), _turn("Tracy Carter leads.", [])], + scope=CHART_SCOPE, + ) + passed = kind.grade_conversation( + run, + scenario="[widget] Top 10 Spenders", + expected_outputs=[ + {"must_include": ["summary criterion"]}, + {"no_tool_calls": True, "must_include": ["follow-up"]}, + ], + ) + assert passed + assert [e.passed for e in run.evaluations] == [True, True] + assert [c for _, c in judges[0].seen] == ["summary criterion", "follow-up"] + # the follow-up's judge reads the summary it follows; the summary turn reads no history + summary_input, follow_up_input = (i for i, _ in judges[0].seen) + assert "Conversation before" not in summary_input + assert f"USER: q\nASSISTANT: {summary}\nQuestion of this turn: q" in follow_up_input + # the follow-up keeps no default shape: only the summary turn is shape-checked + assert "shape_ok" not in run.evaluations[1].detail + # the run detail is flat: the summary turn at the top, follow-ups prefixed + detail = kind._run_detail(run) + assert detail["actual_output"] == summary + assert detail["must_include_0"] is True + assert detail["followup_1_actual_output"] == "Tracy Carter leads." + assert detail["followup_1_no_tool_calls"] is True + assert "followup_1_shape_ok" not in detail + + +def test_the_scope_reads_kpis_and_empty_results_from_the_referenced_widgets() -> None: + kpi_afm = {"attributes": [], "measures": [{"localIdentifier": "m"}], "filters": []} + chart_afm = {"attributes": [{"localIdentifier": "a"}], "measures": [{"localIdentifier": "m"}], "filters": []} + inp = AgenticSummaryInput.model_validate( + {"scope": "widget", "executions": {"k": {"afm": kpi_afm}, "c": {"afm": chart_afm}}} + ) + context = {"referencedObjects": [{"objects": [{"type": "WIDGET", "id": "k"}]}]} + assert kind.summary_scope(inp, context, with_data={"k"}) == cs.SummaryScope("widget", True, False) + assert kind.summary_scope(inp, context, with_data={"c"}).all_empty + # a chart of measures only (donut, waterfall) puts the measures on a second dimension: not a KPI + breakdown = { + "afm": {"attributes": [], "measures": [{"localIdentifier": "m"}, {"localIdentifier": "n"}], "filters": []}, + "result_spec": {"dimensions": [{"itemIdentifiers": []}, {"itemIdentifiers": ["measureGroup"]}]}, + } + headline = {"afm": kpi_afm, "result_spec": {"dimensions": [{"itemIdentifiers": ["measureGroup"]}]}} + shapes = AgenticSummaryInput.model_validate({"scope": "widget", "executions": {"k": headline, "b": breakdown}}) + assert kind.summary_scope(shapes, context, with_data={"k"}).kpi_only + donut = {"referencedObjects": [{"objects": [{"type": "WIDGET", "id": "b"}]}]} + assert not kind.summary_scope(shapes, donut, with_data={"b"}).kpi_only + dashboard = inp.model_copy(update={"scope": "dashboard"}) + assert kind.summary_scope(dashboard, {}, with_data={"c"}) == cs.SummaryScope("dashboard", False, False) + + +@pytest.mark.parametrize("tools", [["set_skills"], ["set_skills", "search_objects"]]) +def test_figures_on_a_summary_turn_that_read_no_data_fail(tools: list[str]) -> None: + """A workspace search is a tool call and reads no table: its turn has nothing a figure could come from.""" + result = cs.evaluate_turn( + judge_input="[widget] 2. Sales", + answer=CHART, + tool_names=tools, + expected={}, + scope=CHART_SCOPE, + positive_judge=cast(LLMJudge, _Judge(True)), + violation_judge=cast(LLMJudge, _Judge(False)), + tables=[], + ) + assert not result.passed + assert "read no data" in result.detail["figures_grounded_reason"] + + +def test_the_no_data_check_reads_figures_as_the_grounding_check_does() -> None: + empty = cs.SummaryScope("dashboard", kpi_only=False, all_empty=True) + # a plain count and a scale word: figures for `figures_grounded`, so figures here too + for text in ("No data, although 345 orders were placed.", "No data for 2020, earlier sales were 1.3 million."): + assert not _grade(text, {}, empty).passed, text + assert _grade("No data is available for 2020 or 2021.", {}, empty).passed + + +def test_a_heading_and_an_abbreviation_are_no_sentences() -> None: + assert cs.count_sentences("## Summary\nNet sales are **$1.2 M** vs. last year. Mrs. Crystal Murray leads.") == 2 + + +@pytest.mark.parametrize( + ("expected", "message"), + [ + ({"format": {"no_heading": True}}, "unknown `format` keys \\['no_heading'\\]"), + ({"format": {}}, "`format` must be false or a non-empty object"), + ({"format": True}, "`format` must be false or a non-empty object"), + ({"must_includes": ["x"]}, "unknown expected_output keys \\['must_includes'\\]"), + (["x"], "expected_output must be an object"), + ], +) +def test_an_unknown_expectation_key_is_rejected(expected: Any, message: str) -> None: + with pytest.raises(ValueError, match=f"follow-up 2: {message}"): + cs.validate_expected(expected, "follow-up 2") + + +@pytest.mark.parametrize( + "expected", + [ + None, + {}, + {"format": False}, + {"format": {"max_sentences": 3, "no_headings": True, "no_bullets": True}}, + { + "no_tool_calls": True, + "must_include": ["x"], + "must_not_include": ["y"], + "rubric": ["z"], + "format": {"headings": []}, + }, + ], +) +def test_every_known_expectation_key_is_accepted(expected: Any) -> None: + cs.validate_expected(expected, "item") diff --git a/packages/gooddata-eval/tests/test_chat_summary_figures.py b/packages/gooddata-eval/tests/test_chat_summary_figures.py new file mode 100644 index 000000000..d0eecf860 --- /dev/null +++ b/packages/gooddata-eval/tests/test_chat_summary_figures.py @@ -0,0 +1,359 @@ +# (C) 2026 GoodData Corporation +from __future__ import annotations + +import json +from typing import Any + +import pytest +from gooddata_eval.core.agentic import chat_summary as kind +from gooddata_eval.core.evaluators.chat_summary_figures import ( + check_figures, + tables_from_tool_calls, + tables_from_tool_result, +) +from gooddata_eval.core.models import ChatResult, ToolCallEvent + +MONEY = "[>=1000000]$#,,.0 M;[>=1000]$#,.0 K;$#,##0" + + +def _xtab(columns: list[tuple[str, str]], labels: list[list[str]], data: list[list[float]], **extra: Any) -> str: + """A tool result as `execute_existing_visualizations` returns it.""" + cols = [{"name": n, "type": t, **({"format": MONEY} if t == "metric" else {})} for n, t in columns] + body = {"output_format": "xtab", "columns": cols, "row_labels": labels, "data": data, "row_count": len(data)} + return json.dumps({"success": True, "results": [{"visualization_id": "v", "data": {**body, **extra}}]}) + + +BREAKDOWN = tables_from_tool_result( + _xtab( + [("Total Discounts", "metric"), ("Total Returns", "metric"), ("COGS", "metric"), ("Gross Profit", "metric")], + [], + [[2770402.0, 1103551.0, 33081914.0, 30512880.0]], + ) +) +SPENDERS = tables_from_tool_result( + _xtab( + [("Customer name", "attribute"), ("Net Sales", "metric")], + [["Michael Baker"], ["Michael Parsons"], ["Rebecca Webb"]], + [[76900.0], [73700.0], [71400.0]], + ) +) + +# A real answer to "Summarize the visualization Total sales breakdown" (2024). +REAL = ( + "## Summary\nFor **2024**, COGS was the largest value at **$33.1 M**, exceeding gross profit by approximately " + "**$2.6 M**. Gross profit reached **$30.5 M**.\n\n## Key Findings\n- Discounts were roughly **2.5×** returns, " + "with **$2.8 M** versus **$1.1 M**.\n- COGS was **49.0%** of the four values." +) + + +def test_a_real_answer_is_grounded() -> None: + result = check_figures(REAL, BREAKDOWN, filter_years=[2024]) + assert result.passed + assert "figures grounded" in result.reason() + + +def test_one_invented_figure_fails_and_says_where() -> None: + result = check_figures(REAL.replace("$33.1 M", "$35.0 M"), BREAKDOWN, filter_years=[2024]) + assert not result.passed + assert [f.raw for f in result.ungrounded] == ["$35.0 M"] + reason = result.reason() + assert "1 of" in reason + assert "COGS was the largest value at $35.0 M" in reason + assert "nearest:" in reason + assert "33.08 M" in reason + + +@pytest.mark.parametrize( + ("text", "kind_"), + [ + ("Discounts were 4× returns.", "ratio"), + ("COGS was 75% of the values.", "percent"), + ("Returns were 1,500.", "amount"), + ], +) +def test_each_kind_is_matched_to_fitting_values(text: str, kind_: str) -> None: + result = check_figures(text, BREAKDOWN) + assert [(f.raw.split()[0], f.kind) for f in result.ungrounded][0][1] == kind_ + + +def test_labels_dates_and_names_are_never_figures() -> None: + text = ( + "In the Top 10 Spenders chart for Q4 2024, Michael Baker leads at $76.9 K on October 23, ahead of the " + "1-3M age group; daily data from 2024-10-01 covers the top 3 customers." + ) + result = check_figures(text, SPENDERS, filter_years=[2024], known_text=["Top 10 Spenders", "1-3M"]) + assert result.passed, result.reason() + assert {f.raw for f in result.figures} == {"2024", "$76.9 K", "3"} + + +def test_shares_differences_and_first_rows_are_allowed() -> None: + text = "The top two spent $150.6 K, 67.8% of the three; the leader is $3.2 K ahead of the second." + assert check_figures(text, SPENDERS).passed + + +def test_a_year_outside_the_filters_fails() -> None: + assert check_figures("Sales in 2024 rose versus 2023.", BREAKDOWN, filter_years=[2024]).passed + wrong = check_figures("Sales in 2020 were flat.", BREAKDOWN, filter_years=[2024]) + assert [f.raw for f in wrong.ungrounded] == ["2020"] + + +def test_without_a_table_nothing_is_judged() -> None: + result = check_figures(REAL, []) + assert result.passed + assert all(f.status == "unverified" for f in result.figures) + + +def test_a_percentage_column_counts_as_percent() -> None: + margin = tables_from_tool_result( + json.dumps( + { + "results": [ + { + "data": { + "columns": [{"name": "Gross Profit Margin", "type": "metric", "format": "#,##0.0%"}], + "row_labels": [], + "data": [[0.4794]], + "row_count": 1, + } + } + ] + } + ) + ) + assert check_figures("The margin was 47.9%.", margin).passed + + +def test_a_range_takes_the_unit_of_its_end() -> None: + assert check_figures("The top three spent $71.4–$76.9 K each.", SPENDERS).passed + wrong = check_figures("The top three spent $1.0–$76.9 K each.", SPENDERS) + assert [f.raw for f in wrong.ungrounded] == ["$1.0"] + + +def test_czech_scale_words_and_a_decimal_comma_count() -> None: + text = "Vede Michael Baker s 76,9 tis. USD, třetí je Rebecca Webb se 71,4 tis." + assert check_figures(text, SPENDERS).passed + assert not check_figures("Vede Michael Baker s 96,9 tis. USD.", SPENDERS).passed + assert check_figures("Všichni tři utratili nad 70 tis. USD.", SPENDERS).passed # "nad" = above: a bound + + +def test_a_round_figure_is_read_as_rounded() -> None: + assert check_figures("Each of the three spent about $70K or more.", SPENDERS).passed + assert not check_figures("Each of the three spent about $90K.", SPENDERS).passed + + +def test_a_value_derived_from_rounded_figures_is_allowed() -> None: + # 33.1 M - 30.5 M from the rounded display values = 2.6 M; the exact gap is 2.57 M + assert check_figures("COGS exceeded gross profit by $2.6 M.", BREAKDOWN).passed + # discounts + returns as a share of COGS: (2.77 M + 1.10 M) / 33.08 M + assert check_figures("Discounts and returns, $3.9 M together, were 11.7% of COGS.", BREAKDOWN).passed + + +def test_another_data_tools_numbers_and_labels_count() -> None: + analysis = json.dumps({"drivers": [{"attribute": "Customer age", "value": "7M+", "before": 508, "after": 543}]}) + events = [ToolCallEvent(functionName="analyze_change", functionArguments="{}", result=analysis)] + tables = tables_from_tool_calls(events) + text = "Active customers aged 7M+ grew from 508 to 543, up 6.9%." + assert check_figures(text, tables).passed + assert not check_figures("Active customers aged 7M+ grew from 508 to 600.", tables).passed + + +GEO = tables_from_tool_result( + _xtab( + [("Country", "attribute"), ("State", "attribute"), ("Active Customers", "metric")], + [["United States", "California"], ["United States", "Texas"], ["Canada", "Ontario"]], + [[106.0], [44.0], [60.0]], + ) +) + + +def test_rows_that_share_a_label_add_up() -> None: + assert check_figures("The United States has 150 active customers, 71.4% of the total.", GEO).passed + + +def test_a_bound_and_a_count_of_rows_are_no_values() -> None: + assert check_figures("All three customers spent more than $70 K; 2 of 3 spent over $73 K.", SPENDERS).passed + + +def test_any_two_rows_compare_only_when_the_sentence_names_both() -> None: + five = tables_from_tool_result( + _xtab( + [("Customer name", "attribute"), ("Net Sales", "metric")], + [["Ann Lee"], ["Bob Ray"], ["Cy Fox"], ["Dee Orr"], ["Eve Poe"]], + [[76900.0], [73700.0], [71400.0], [70000.0], [65000.0]], + ) + ) + assert check_figures("Bob Ray spent $3.7 K more than Dee Orr.", five).passed + assert not check_figures("One customer spent $3.7 K more than another.", five).passed + + +def test_a_daily_series_sums_by_month_and_points_between_percentages() -> None: + daily = tables_from_tool_result( + _xtab( + [("Date", "attribute"), ("Net Sales", "metric")], + [["2024-10-01"], ["2024-10-02"], ["2024-11-01"], ["2024-11-02"]], + [[100000.0], [150000.0], [200000.0], [100000.0]], + row_count=92, + ) + ) + assert check_figures("October brought $250.0 K and November $300.0 K; 88 days were not read.", daily).passed + margin = tables_from_tool_result( + json.dumps( + { + "results": [ + { + "data": { + "columns": [ + {"name": "Margin", "type": "metric", "format": "#,##0.0%"}, + {"name": "Margin - previous period", "type": "metric", "format": "#,##0.0%"}, + ], + "row_labels": [], + "data": [[0.4791, 0.4826]], + "row_count": 1, + } + } + ] + } + ) + ) + assert check_figures("The margin fell from 48.3% to 47.9%, about 0.35 percentage points.", margin).passed + orders = tables_from_tool_result( + _xtab( + [("Brand", "attribute"), ("Net Orders", "metric"), ("Net Sales", "metric")], + [["Corsair"]], + [[8329.0, 24591441.88]], + ) + ) + assert check_figures("Corsair averages about $2,952 per order.", orders).passed + + +STATUS = tables_from_tool_result( + _xtab( + [("Order status", "attribute"), ("# of Orders", "metric")], + [["Processed"], ["In Cart"], ["Canceled"]], + [[32483.0], [2002.0], [1496.0]], + ) +) +TITLED = tables_from_tool_result( + _xtab( + [("Customer name", "attribute"), ("Net Sales", "metric")], + [["Tracy Carter"], ["Tammy Long"], ["Mrs. Crystal Murray"], ["Jennifer Mejia"]], + [[1317241.93], [1301535.20], [1277207.42], [1226626.87]], + ) +) + + +def test_a_value_named_with_the_wrong_row_fails() -> None: + assert check_figures("Michael Baker leads with $76.9 K, ahead of Michael Parsons at $73.7 K.", SPENDERS).passed + swapped = check_figures("Michael Parsons leads with $76.9 K.", SPENDERS) + assert [f.raw for f in swapped.ungrounded] == ["$76.9 K"] + assert "named next to it" in swapped.reason() + + +def test_small_words_between_a_name_and_its_figure_keep_them_tied() -> None: + assert check_figures("Michael Baker leads with a total of $76.9 K.", SPENDERS).passed + for text in ( + "Michael Parsons leads with a total of $76.9 K.", + "Sales of Michael Parsons rose to $76.9 K.", + ): + wrong = check_figures(text, SPENDERS) + assert [f.raw for f in wrong.ungrounded] == ["$76.9 K"], text + # a bare "to" between a name and a figure ends a range: the figure belongs to what follows + assert check_figures("Net sales fall from $76.9 K for Michael Baker to $71.4 K for Rebecca Webb.", SPENDERS).passed + + +def test_a_one_digit_amount_is_no_wider_than_a_tenth_of_its_value() -> None: + table = tables_from_tool_result( + _xtab([("Net Sales", "metric"), ("Net Orders", "metric")], [], [[1300000.0, 6600000.0]]) + ) + assert not check_figures("Net sales are about $1 M.", table).passed + assert check_figures("Net orders are about $7 M.", table).passed + + +def test_names_in_lists_before_or_glued_after_a_figure_count() -> None: + assert check_figures("Michael Baker and Michael Parsons spent $76.9 K and $73.7 K.", SPENDERS).passed + assert check_figures( + "The breakdown shows 32,483 processed, 2,002 in-cart, and 1,496 canceled orders.", STATUS + ).passed + assert check_figures("Processed orders dominate at 32,483, while 2,002 are in cart.", STATUS).passed + + +def test_a_name_without_its_title_names_the_row() -> None: + assert check_figures("Crystal Murray is third at $1.28 M.", TITLED).passed + assert check_figures("Mrs. Crystal Murray and Jennifer Mejia follow at $1.3 M and $1.2 M.", TITLED).passed + assert not check_figures("Crystal Murray is third at $1.23 M.", TITLED).passed + + +def test_a_derived_value_may_use_rows_the_sentence_names() -> None: + assert check_figures("Michael Baker leads, $5.5 K more than Rebecca Webb.", SPENDERS).passed + + +def test_an_invented_figure_named_with_its_row_fails_on_a_long_table() -> None: + days = [f"2024-{m:02d}-{d:02d}" for m in (10, 11) for d in range(1, 31)][:60] + values = [100000.0 + 1000.0 * i for i in range(60)] + long = tables_from_tool_result( + _xtab([("Date", "attribute"), ("Net Sales", "metric")], [[d] for d in days], [[v] for v in values]) + ) + assert check_figures("Net sales reached $106.0 K on October 7.", long).passed + assert not check_figures("Net sales reached $120.0 K on October 7.", long).passed + # two named days of a long series compare on the fly; the month averages too + assert check_figures("November 10 was $33.0 K above October 7.", long).passed + assert check_figures("October averaged about $114.5 K per day.", long).passed + + +def test_a_rows_format_result_names_its_rows_too() -> None: + rows = tables_from_tool_result( + json.dumps( + { + "results": [ + { + "data": { + "columns": [ + {"name": "Customer", "type": "attribute"}, + {"name": "Net Sales", "type": "metric"}, + ], + "rows": [ + {"Customer": "Alice Smith", "Net Sales": 700}, + {"Customer": "Bob Jones", "Net Sales": 900}, + ], + } + } + ] + } + ) + ) + assert check_figures("Bob Jones leads with 900.", rows).passed + assert not check_figures("Alice Smith leads with 900.", rows).passed + + +class _Judge: + def score(self, input: str, expected_output: str, actual_output: str) -> tuple[bool, str]: + return True, "stub" + + +def test_a_follow_up_is_checked_against_the_tables_read_earlier(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(kind, "make_judges", lambda model=None: (_Judge(), _Judge())) + table = _xtab( + [("Customer name", "attribute"), ("Net Sales", "metric")], + [["Michael Baker"], ["Michael Parsons"]], + [[76900.0], [73700.0]], + ) + summary = ChatResult.model_validate( + { + "textResponse": "Michael Baker leads with $76.9 K.", + "toolCallEvents": [ + {"functionName": "execute_existing_visualizations", "functionArguments": "{}", "result": table} + ], + } + ) + run = kind.SummaryConversation( + "c", + turns=[ + kind.SummaryTurn("Summarize", result=summary), + kind.SummaryTurn("By how much?", result=ChatResult.model_validate({"textResponse": "By $3.2 K."})), + kind.SummaryTurn("And the total?", result=ChatResult.model_validate({"textResponse": "About $200.0 K."})), + ], + scope=None, + ) + kind.grade_conversation(run, scenario="[widget] Top Spenders", expected_outputs=[{}, {}, {}]) + assert [e.detail["figures_grounded"] for e in run.evaluations] == [True, True, False] + assert "$200.0 K" in run.evaluations[2].detail["figures_grounded_reason"] diff --git a/packages/gooddata-eval/tests/test_outcome.py b/packages/gooddata-eval/tests/test_outcome.py index 0fb00a545..821bbddd1 100644 --- a/packages/gooddata-eval/tests/test_outcome.py +++ b/packages/gooddata-eval/tests/test_outcome.py @@ -36,10 +36,12 @@ ) from gooddata_eval.core.outcome import ( JUDGE_FAILED, + SETUP_ERRORS, Outcome, OutcomeStatus, classify_run, item_outcome, + setup_error, shadow_verdict, ) @@ -537,3 +539,13 @@ def test_the_agentic_message_is_the_gate_note_the_failing_runs_and_the_best_run( # so the item is still unstable. assert head == "Gate pass^3 failed: 1/3 runs passed, 1 harness error(s) — unstable, not a clean failure." assert message.replace(gate_line, head, 1) == _MESSAGE_WITHOUT_FAILING_RUNS + + +def test_a_setup_error_is_an_error_only_for_a_known_cause() -> None: + assert sorted(SETUP_ERRORS) == ["data_baseline_changed", "widget_execution_failed"] + assert setup_error("widget_execution_failed").as_record() == { + "status": "error", + "reason": "widget_execution_failed", + } + with pytest.raises(ValueError, match="not a setup error"): + setup_error("chat_error") diff --git a/packages/gooddata-eval/tests/test_trace_linker.py b/packages/gooddata-eval/tests/test_trace_linker.py index 724e0eea6..12c4fe63c 100644 --- a/packages/gooddata-eval/tests/test_trace_linker.py +++ b/packages/gooddata-eval/tests/test_trace_linker.py @@ -127,6 +127,8 @@ def test_run_trace_link_inline_runs_the_task_on_the_calling_thread(): ("what_if", "evaluate_agentic_what_if"), ("agent_switcher", "evaluate_agentic_agent_switcher"), ("memory", "evaluate_agentic_memory"), + ("chat_summary", "evaluate_agentic_summary"), + ("describe_object", "evaluate_agentic_describe_object"), ]