From 919dcee089b61100baa1f41a03c1102264139198 Mon Sep 17 00:00:00 2001 From: huyenthanh09 Date: Fri, 4 Dec 2026 09:36:06 +0700 Subject: [PATCH] feat(gooddata-eval): judge KDA suggestions and resolve object refs - check_suggestions: an LLM judge reads every suggested action of the turn that ran the analysis against a fixed rubric, and fails one that is off topic, generic, overrides the analysed period or needs the chat to make sense. Any action type the KDA prompt and the agent's general suggestion rules allow passes, so does a comparison with another period. It replaces the check that the first action names a driver of the answer, which failed comparisons, breakdowns and re-runs the suggestion rules allow. No analysis fails, no actions pass, as before. The judge is gpt-5.2 unless GD_EVAL_JUDGE_MODEL is set: gpt-4o applied the five rules unevenly - before a judge reads the conversation, a reference such as {metric/} is written out as " (metric/<id>)" from the workspace's entity API, and an id the workspace does not have as "[unknown metric: <id>]". A reference stays raw when the metadata cannot be read. Lookups run only when a judge is called - the judge's reasoning is the comment of kda_rubric and kda_suggestions - a turn whose every create the tool answered without success, with no analysis run, no longer ends the run: the simulated user answers the agent's question and a later analysis is scored. A rejected create retried in the same turn, an expect_no_create item and a silent turn end the run as before jira: QA-29906 risk: low Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/gooddata-eval/README.md | 11 +- .../gooddata_eval/core/agentic/_kda_answer.py | 31 +- .../core/agentic/_kda_expectation.py | 4 +- .../core/agentic/_object_titles.py | 112 +++++++ .../gooddata_eval/core/agentic/kda_skill.py | 147 +++++++-- .../tests/test_agentic_kda_skill_behaviour.py | 288 ++++++++++++++++-- .../tests/test_agentic_object_titles.py | 117 +++++++ 7 files changed, 637 insertions(+), 73 deletions(-) create mode 100644 packages/gooddata-eval/src/gooddata_eval/core/agentic/_object_titles.py create mode 100644 packages/gooddata-eval/tests/test_agentic_object_titles.py diff --git a/packages/gooddata-eval/README.md b/packages/gooddata-eval/README.md index 4cd0574ef..9c60076ca 100644 --- a/packages/gooddata-eval/README.md +++ b/packages/gooddata-eval/README.md @@ -1207,7 +1207,7 @@ Each key below is opt-in and adds one score, which gates `strict_pass` like the | `"expect_clarification": true` | `kda_clarified` | the first turn asks a question and creates no analysis | | `"rubric": "<criteria>"` | `kda_rubric` | an LLM judge reads the whole conversation and finds every criterion met | | `"check_answer": true` | `kda_answer_grounded` | an analysis ran, and the answer of the turn that ran it names one of its `significant_drivers` | -| `"check_suggestions": true` | `kda_suggestions` | an analysis ran, and when its answer names a driver, the first suggested action of that turn names one of those drivers | +| `"check_suggestions": true` | `kda_suggestions` | an analysis ran, and an LLM judge finds no suggested action of that turn off topic (about a metric, driver or scope the answer does not discuss), generic (naming nothing to act on), overriding the analysed period (an unrelated period or an arbitrary short window; a comparison with another period and a driver's trend are allowed), or needing the chat to make sense. A turn without suggested actions passes | `"user_replies": ["...", ...]` sends scripted messages after the question, one per turn, in the same conversation, whatever the agent did. The analysis is scored from the last scripted turn on; @@ -1216,6 +1216,15 @@ from the question of an item without replies: with the default 4, three simulate With `"expect_clarification": true`, the first turn is the one that must ask, and the replies answer that question. A clarification asked on a later turn cannot be expressed. +Before a judge reads the conversation, an object reference such as `{metric/<id>}` is written out as +`<title> (metric/<id>)` from the workspace metadata, and an id the workspace does not have as +`[unknown metric: <id>]`. When the metadata cannot be read, the reference stays as it is. The judge's +reasoning is the comment of `kda_rubric` and `kda_suggestions`. The suggestion judge is gpt-5.2 unless +`GD_EVAL_JUDGE_MODEL` is set. + +A turn whose every create the tool rejected, with no analysis run, does not end the run: the simulated +user answers it, and a later turn that runs the analysis is the one scored. + A driver counts as named when its value appears as a whole word, plural allowed. Date values and values shorter than three characters are skipped, and `10,769` matches `10769`. diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_answer.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_answer.py index 58011e2cc..287628d02 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_answer.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_answer.py @@ -1,5 +1,5 @@ # (C) 2026 GoodData Corporation. All rights reserved. -"""Whether a KDA answer, and the suggestions after it, name the drivers the analysis returned. +"""Whether a KDA answer names the drivers the analysis returned, and the suggestions offered after it. The execute tool returns ``data.significant_drivers``: one row per attribute value, with its own ``delta`` between the periods. The answer is read as text, so a driver counts as named when its @@ -111,27 +111,14 @@ def suggested_actions(suggestions: Any) -> list[dict[str, Any]]: return actions -def check_suggestions_name_driver(execute_result: Any, answer: str, suggestions: Any) -> tuple[bool, dict[str, Any]]: - """Whether the first suggested action names a driver the answer named. - - True when there are no actions, or the answer names no driver: the rule binds only an answer - that highlights drivers by name. False when no analysis ran. - - Raises: - ValueError: The suggestions have a shape this check cannot read. - """ - actions = suggested_actions(suggestions) - if not _ran(execute_result): - return False, {"reason": "no analysis ran"} - if not actions: - return True, {"first_action": None} - first = actions[0] - in_answer = named_values(answer, driver_values(execute_result)) - if not in_answer: - return True, {"first_action": first, "drivers_in_answer": []} - action_text = f"{first.get('query') or ''} {first.get('label') or ''}" - named = named_values(action_text, in_answer) - return bool(named), {"first_action": first, "drivers_in_answer": in_answer, "named": named} +def render_actions(actions: list[dict[str, Any]]) -> str: + """The suggested actions as numbered lines a judge can read: the label, then the query it sends.""" + lines: list[str] = [] + for i, action in enumerate(actions, 1): + label = str(action.get("label") or "").strip() + query = str(action.get("query") or "").strip() + lines.append(f"{i}. {label}: {query}" if label and query else f"{i}. {label or query}") + return "\n".join(lines) def suggestions_from_turn(items: list[dict[str, Any]], turn: int) -> Any: diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py index e115916d9..a356afdee 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_kda_expectation.py @@ -18,8 +18,8 @@ analysis of the last scripted turn, or of a later one, is the one scored. - ``rubric``: an LLM judge grades the conversation against it (``kda_rubric``). - ``check_answer: true``: the answer names a driver the analysis returned (``kda_answer_grounded``). -- ``check_suggestions: true``: when the answer names a driver, the first suggested action names one - too (``kda_suggestions``). +- ``check_suggestions: true``: an LLM judge finds every suggested action after the analysis valid under + the KDA suggestion rules (``kda_suggestions``). """ from __future__ import annotations diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/_object_titles.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_object_titles.py new file mode 100644 index 000000000..37bf7cb43 --- /dev/null +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/_object_titles.py @@ -0,0 +1,112 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +"""Object references in an answer, written out with their titles for an LLM judge. + +The agent writes a workspace object as ``{metric/<id>}`` and the UI shows the object's title in its +place. A judge reading the raw token cannot tell a real metric from a made-up one, so each token is +replaced with ``<title> (<type>/<id>)`` from the workspace metadata. An id the workspace does not have +becomes ``[unknown <type>: <id>]``. When the metadata cannot be read, the token stays as it is: the +judge then grades what the user would have seen without the lookup. +""" + +from __future__ import annotations + +import logging +import re + +import httpx + +_log = logging.getLogger(__name__) + +# The reference types gen-ai writes (its ObjectType) that have an entity collection to read the title from. +# A date dataset is a dataset and a date attribute an attribute there. +_COLLECTIONS = { + "metric": "metrics", + "fact": "facts", + "attribute": "attributes", + "date_attribute": "attributes", + "label": "labels", + "dataset": "datasets", + "date": "datasets", + "visualization": "visualizationObjects", + "dashboard": "analyticalDashboards", + "filter_context": "filterContexts", +} +# Ids follow the entity API's id pattern, so a malformed one never becomes a different request. +_TOKEN = re.compile(r"\{(" + "|".join(_COLLECTIONS) + r")/((?!\.)[.A-Za-z0-9_-]{1,255})\}") +# Sentinel for an id the workspace does not have. +_MISSING = "" + + +class ObjectTitles: + """Looks up the titles of one workspace's objects. + + A title and an id the workspace does not have are kept for later runs; a lookup that failed is tried again. + """ + + def __init__( + self, + host: str, + token: str, + workspace_id: str, + *, + timeout: float = 30.0, + transport: httpx.BaseTransport | None = None, + ) -> None: + self._transport = transport + self._base = f"{host.rstrip('/')}/api/v1/entities/workspaces/{workspace_id}" + self._auth = {"Authorization": f"Bearer {token}"} + self._timeout = timeout + self._client: httpx.Client | None = None + self._titles: dict[tuple[str, str], str] = {} + + def close(self) -> None: + if self._client is not None: + self._client.close() + self._client = None + + def _title(self, kind: str, object_id: str) -> str | None: + """The object's title, ``_MISSING`` when the workspace has no such object, None when it cannot be read.""" + key = (kind, object_id) + if key in self._titles: + return self._titles[key] + title = self._fetch(kind, object_id) + if title is not None: + self._titles[key] = title + return title + + def _fetch(self, kind: str, object_id: str) -> str | None: + if self._client is None: + self._client = httpx.Client(timeout=self._timeout, transport=self._transport) + url = f"{self._base}/{_COLLECTIONS[kind]}/{object_id}" + try: + resp = self._client.get(url, headers=self._auth) + except (httpx.HTTPError, httpx.InvalidURL) as exc: + _log.warning("Could not read the title of %s/%s: %s", kind, object_id, exc) + return None + if resp.status_code == 404: + return _MISSING + if resp.status_code != 200: + _log.warning("Could not read the title of %s/%s: HTTP %s", kind, object_id, resp.status_code) + return None + try: + body = resp.json() + except ValueError: + return None + data = body.get("data") if isinstance(body, dict) else None + attributes = data.get("attributes") if isinstance(data, dict) else None + title = attributes.get("title") if isinstance(attributes, dict) else None + return title.strip() if isinstance(title, str) and title.strip() else None + + def resolve(self, text: str) -> str: + """``text`` with every object reference written out as its title.""" + + def _replace(match: re.Match[str]) -> str: + kind, object_id = match.group(1), match.group(2) + title = self._title(kind, object_id) + if title is None: + return match.group(0) + if title == _MISSING: + return f"[unknown {kind}: {object_id}]" + return f"{title} ({kind}/{object_id})" + + return _TOKEN.sub(_replace, text) diff --git a/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py b/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py index f958e8770..f3a4c5ff1 100644 --- a/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py +++ b/packages/gooddata-eval/src/gooddata_eval/core/agentic/kda_skill.py @@ -25,7 +25,8 @@ ) from gooddata_eval.core.agentic._kda_answer import ( check_answer_grounded, - check_suggestions_name_driver, + render_actions, + suggested_actions, suggestions_from_turn, ) from gooddata_eval.core.agentic._kda_expectation import ( @@ -36,6 +37,7 @@ check_kda_fields, parse_kda_expectation, ) +from gooddata_eval.core.agentic._object_titles import ObjectTitles from gooddata_eval.core.agentic._outcome import ( CHAT_FAILURE_EXITS, agentic_detail, @@ -58,7 +60,7 @@ from gooddata_eval.core.agentic.metric_skill import _judge_provider_errors 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.config import JUDGE_MODEL_ENV_VAR, ReasoningEffort from gooddata_eval.core.evaluators._llm_judge import JudgeVerdict, LLMJudge, score_run from gooddata_eval.core.langfuse.item_scope import item_scope from gooddata_eval.core.models import ( @@ -95,6 +97,27 @@ "ACTUAL OUTPUT holds the conversation, user and assistant turns in order.", "Pass only when the assistant's replies meet every criterion. Fail when any reply breaks one.", ] +# The suggestion judge when GD_EVAL_JUDGE_MODEL is not set. It applies four rules to every action, and gpt-4o, +# the default judge, applied them unevenly: the same vague action passed one run and failed the next. +_SUGGESTION_JUDGE_MODEL = "gpt-5.2" +_SUGGESTION_STEPS = [ + "EXPECTED OUTPUT states what makes a suggested action fail.", + "ACTUAL OUTPUT holds the conversation, user and assistant turns in order, then the SUGGESTED ACTIONS " + "offered after the last answer.", + "Fail when any suggested action clearly breaks a rule. Pass otherwise, also when an action could be worded better.", +] +# The suggestion rules of the KDA skill prompt and of the agent's general suggestion rules, which a KDA +# answer may also follow, as the four failures they guard against: off topic, generic, a period overridden, +# not standalone. +# Any action type those rules allow passes; a count is not required. +_SUGGESTION_RUBRIC = """\ +The assistant ran a key driver analysis and offered the SUGGESTED ACTIONS below. An action fails only when it clearly does one of these: +1. Off topic: it is about a metric, driver or scope the last assistant answer does not discuss. Only the last answer counts: a driver that only an earlier answer named is off topic (the last answer analyses Training hours, and the action breaks down Sick Leave, a driver of an earlier answer about Total hours). A driver the last answer names, a dimension of the same metric, a closely related metric, and a comparison of the same metric are on topic. +2. Generic: it names nothing to act on, such as "Break it down further", "Explore more" or "Compare with a different period" without naming one. An action that names the metric, a driver, a dimension or a period is concrete; it need not name all of them, and a short name the answer used ("sales", "West") is fine. +3. Period overridden: it moves the analysis to an unrelated analysed period (the user asked about Q1 2025 and the action analyses Q4 2025), or puts an arbitrary short window such as "last 30 days" or "past few weeks" on a question about specific periods. Comparing the analysed period with another one (year over year, a different reference period), and showing a driver's trend over time, are allowed. +4. Not standalone: its query points back to the chat with a word such as "that", "it" or "this" in place of what it acts on ("Break that down by region", "Compare it with last year"). An action that names its metric or subject and a period stands on its own, even when it leaves out the reference period. + +An object written as "<title> (<type>/<id>)" is a valid reference to that workspace object; "[unknown <type>: <id>]" names an object the workspace does not have. Name each action that fails and the rule it breaks.""" def _hint_source(expected_output: dict) -> dict: @@ -390,6 +413,16 @@ def _ran_analysis(events: list[ToolCallEvent]) -> bool: ) +def _only_rejected(events: list[ToolCallEvent]) -> bool: + """Whether ``events`` hold a create the tool answered without success, and none it accepted. + + A create with no result at all is neither: the turn was cut off, not answered. + """ + answered = [tc for tc in events if tc.function_name == "create_key_driver_analysis" and tc.result] + accepted = [tc for tc in answered if (_json_object(tc.parsed_result()) or {}).get("success") is True] + return bool(answered) and not accepted + + def _created(events: list[ToolCallEvent]) -> bool: """Whether a create call in ``events`` succeeded.""" return any( @@ -411,6 +444,8 @@ def _behaviour_checks( spec: KdaExpectation, *, judge: LLMJudge | None, + suggestion_judge: LLMJudge | None, + resolve: Callable[[str], str], question: str, turns: list[ChatResult], texts: list[str], @@ -427,7 +462,8 @@ def _behaviour_checks( ``asked_turn`` is the index of the turn that asked for the analysis: the last scripted one. ``scored_turn`` is the index of the turn whose analysis is scored, None when no turn ran one. The answer and suggestion checks read that turn alone: an earlier clarification may name a - driver the analysis answer does not. + driver the analysis answer does not. The judges read the conversation with ``resolve`` applied, + which writes object references out as their titles. """ result = _BehaviourResult() checks = result.checks @@ -443,8 +479,16 @@ def _behaviour_checks( asked = first is not None and read_first_reply(first, asked_in_text=asks_in_text(first, texts[0])).asked created = first is not None and _created(first.tool_call_events or []) checks["clarified"] = (asked and not created, {"asked": asked, "created_in_first_turn": created}) + resolved: list[tuple[str, str]] = [] + + def _resolved() -> list[tuple[str, str]]: + # Looked up only when a judge reads it: each reference costs a metadata request. + if not resolved: + resolved.extend((role, resolve(text) if role == "Assistant" else text) for role, text in transcript) + return resolved + if spec.rubric and judge is not None: - verdict = _judge(judge, spec.rubric, question, transcript) + verdict = _judge(judge, spec.rubric, question, _resolved()) if verdict.error is not None: result.unscored_check("rubric", f"judge gave no verdict: {verdict.error}") else: @@ -452,15 +496,47 @@ def _behaviour_checks( answer = texts[scored_turn] if scored_turn is not None and scored_turn < len(texts) else "" if spec.check_answer: checks["answer_grounded"] = check_answer_grounded(execute_result, answer) - if spec.check_suggestions: - try: - suggestions = read_suggestions(scored_turn) if scored_turn is not None else None - checks["suggestions"] = check_suggestions_name_driver(execute_result, answer, suggestions) - except (httpx.HTTPError, ValueError) as exc: - result.unscored_check("suggestions", f"{type(exc).__name__}: {exc}") + if spec.check_suggestions and suggestion_judge is not None: + _check_suggestions( + result, suggestion_judge, question, _resolved, scored_turn, execute_result, read_suggestions, resolve + ) return result +def _check_suggestions( + result: _BehaviourResult, + judge: LLMJudge, + question: str, + transcript: Callable[[], list[tuple[str, str]]], + scored_turn: int | None, + execute_result: dict | None, + read_suggestions: Callable[[int], Any], + resolve: Callable[[str], str], +) -> None: + """Whether every action suggested after the analysis meets the KDA suggestion rules. + + No analysis fails; no actions pass: suggestions are optional. The judge reads the whole conversation, + so an action that reuses an earlier turn's drivers can be told from one about this answer. + """ + if not (isinstance(execute_result, dict) and execute_result.get("success") is True): + result.checks["suggestions"] = (False, {"reason": "no analysis ran"}) + return + try: + actions = suggested_actions(read_suggestions(scored_turn) if scored_turn is not None else None) + except (httpx.HTTPError, ValueError) as exc: + result.unscored_check("suggestions", f"{type(exc).__name__}: {exc}") + return + if not actions: + result.checks["suggestions"] = (True, {"actions": []}) + return + listed = resolve(render_actions(actions)) + verdict = _judge(judge, _SUGGESTION_RUBRIC, question, [*transcript(), ("SUGGESTED ACTIONS", listed)]) + if verdict.error is not None: + result.unscored_check("suggestions", f"judge gave no verdict: {verdict.error}") + return + result.checks["suggestions"] = (verdict.passed, {"actions": actions, "reasoning": verdict.reasoning}) + + def run_agentic_kda_skill( host: str, token: str, @@ -490,9 +566,13 @@ def run_agentic_kda_skill( takes over only after it, and ``max_iterations`` counts from the last scripted turn. An item with ``expect_no_create`` gets no simulated reply. + A turn whose every create the tool rejected, with no analysis run, does not end the run: the + agent may ask how to go on, and the simulated user answers. A later turn that runs the analysis + is the one scored. + Raises: ValueError: The item is malformed. Raised before any request. - ImportError, OSError: The item has a rubric and the LLM judge cannot be built. + ImportError, OSError: The item has a rubric or ``check_suggestions`` and the LLM judge cannot be built. """ if k < 1: # k=0 or negative would otherwise silently run once, indistinguishable from k=1. @@ -500,6 +580,12 @@ def run_agentic_kda_skill( spec = parse_kda_expectation(expected_output) # Built before the first request: a missing judge is a setup error, not one to find after every run. judge = LLMJudge(_RUBRIC_STEPS) if spec.rubric else None + suggestion_judge = ( + LLMJudge(_SUGGESTION_STEPS, model=os.environ.get(JUDGE_MODEL_ENV_VAR, "").strip() or _SUGGESTION_JUDGE_MODEL) + if spec.check_suggestions + else None + ) + titles = ObjectTitles(host, token, workspace_id) scripted = [question, *spec.user_replies] asked_turn = len(scripted) - 1 # max_iterations counts from the last scripted turn, as it counts from the question without replies. @@ -575,9 +661,12 @@ def _accumulate(result: ChatResult) -> None: response_id = partial.response_id or response_id _accumulate(partial) if scored: - create_args, execute_result = _extract_kda_calls(partial.tool_call_events or []) - if create_args is not None: + partial_create, partial_execute = _extract_kda_calls(partial.tool_call_events or []) + # A turn cut off before any create keeps the create an earlier turn had rejected. + if partial_create is not None: + create_args, execute_result = partial_create, partial_execute turn_wall_clock_sec = partial.turn_wall_clock_sec + scored_turn = iteration turn_completed = False exit_reason = chat_failure_exit(exc) break @@ -597,17 +686,19 @@ def _accumulate(result: ChatResult) -> None: exit_reason = LoopExit.AGENT_SILENT break continue - create_args, execute_result = _extract_kda_calls(chat_result.tool_call_events or []) - if create_args is not None: + turn_create, turn_execute = _extract_kda_calls(chat_result.tool_call_events or []) + if turn_create is not None: # This turn's own time -- the turn that called create, not any earlier # disambiguation turn or the simulated-reply generation. create and execute # are always called together in the same turn (or not at all), so this is # final either way -- execute_result may still be None (e.g. the skill's # execute tool isn't available at all when data-sharing is off for the org). + create_args, execute_result = turn_create, turn_execute turn_wall_clock_sec = chat_result.turn_wall_clock_sec scored_turn = iteration - exit_reason = LoopExit.SUCCESS - break + if turn_execute is not None or not _only_rejected(chat_result.tool_call_events or []): + exit_reason = LoopExit.SUCCESS + break if not response_text: exit_reason = LoopExit.AGENT_SILENT break @@ -636,6 +727,8 @@ def _accumulate(result: ChatResult) -> None: behaviour = _behaviour_checks( spec, judge=judge, + suggestion_judge=suggestion_judge, + resolve=titles.resolve, question=question, turns=turn_results, texts=texts, @@ -680,7 +773,10 @@ def _accumulate(result: ChatResult) -> None: finally: client.delete_conversation(conv_id) finally: - client.close() + try: + client.close() + finally: + titles.close() pass_at_k = any(r.evaluation.strict_pass for r in run_results) pass_power_k = all(r.evaluation.strict_pass for r in run_results) @@ -737,6 +833,13 @@ def _behaviour_detail(ev: KdaEvaluation) -> dict: return {**ev.behaviour, "behaviour_detail": ev.behaviour_detail} +def _judge_reasoning(ev: KdaEvaluation, check: str) -> str | None: + """Why the judge passed or failed a judged check, for its score's comment; None for other checks.""" + detail = ev.behaviour_detail.get(check) if check in ev.behaviour else None + reasoning = detail.get("reasoning") if isinstance(detail, dict) else None + return reasoning if isinstance(reasoning, str) and reasoning else None + + def _harness_error_of(run: KdaRunResult) -> str | None: """The harness error, for the run's label, only when it is what left the run without a verdict. @@ -857,7 +960,13 @@ def _write_scores(ctx: RunTraceContext) -> None: if (run_error := run_labels.error_label(run_idx)) is not None: log_eval_error_score(ctx, tid, run_error) for score_name, value in strict_checks.items(): - ctx.score(tid, name=score_name, value=float(value), data_type="BOOLEAN") + ctx.score( + tid, + name=score_name, + value=float(value), + data_type="BOOLEAN", + comment=_judge_reasoning(ev, score_name.removeprefix("kda_")), + ) ctx.score(tid, name="kda_disambiguated", value=float(ev.disambiguated), data_type="BOOLEAN") ctx.score(tid, name="turns", value=run.total_turns, data_type="NUMERIC") ctx.score(tid, name="steps", value=run.total_steps, data_type="NUMERIC") diff --git a/packages/gooddata-eval/tests/test_agentic_kda_skill_behaviour.py b/packages/gooddata-eval/tests/test_agentic_kda_skill_behaviour.py index 14376e9ca..ee9a33617 100644 --- a/packages/gooddata-eval/tests/test_agentic_kda_skill_behaviour.py +++ b/packages/gooddata-eval/tests/test_agentic_kda_skill_behaviour.py @@ -7,8 +7,9 @@ import pytest from gooddata_eval.core.agentic._kda_answer import ( check_answer_grounded, - check_suggestions_name_driver, driver_values, + render_actions, + suggested_actions, suggestions_from_turn, ) from gooddata_eval.core.agentic._kda_expectation import ( @@ -22,6 +23,7 @@ evaluate_agentic_kda_skill, run_agentic_kda_skill, ) +from gooddata_eval.core.chat.sse_client import ChatError from gooddata_eval.core.evaluators._llm_judge import JudgeVerdict from gooddata_eval.core.models import ChatResult @@ -286,7 +288,6 @@ def test_an_analysis_with_no_driver_to_name_passes(execute_result: Any) -> None: @pytest.mark.parametrize("execute_result", [None, {}, {"success": False, "error": "AFM 400"}]) def test_no_analysis_means_nothing_grounded(execute_result: Any) -> None: assert check_answer_grounded(execute_result, "Outlet fell.") == (False, {"reason": "no analysis ran"}) - assert check_suggestions_name_driver(execute_result, "Outlet fell.", None)[0] is False def test_an_answer_naming_a_top_driver_is_grounded() -> None: @@ -391,14 +392,19 @@ def test_a_four_digit_number_is_a_value_not_a_year() -> None: @pytest.mark.parametrize("suggestions", [None, {}, {"actions": []}, {"actions": None}]) -def test_no_suggested_actions_pass(suggestions: Any) -> None: - assert check_suggestions_name_driver(_EXECUTE, _ANSWER, suggestions)[0] is True +def test_no_suggested_actions_read_as_none(suggestions: Any) -> None: + assert suggested_actions(suggestions) == [] @pytest.mark.parametrize("suggestions", [{"actions": "x"}, {"actions": {"items": []}}, {"actions": ["Outlet trend"]}]) def test_unreadable_suggestions_raise(suggestions: Any) -> None: with pytest.raises(ValueError, match="unreadable suggestion actions"): - check_suggestions_name_driver(_EXECUTE, _ANSWER, suggestions) + suggested_actions(suggestions) + + +def test_actions_are_listed_with_label_and_query() -> None: + actions = [{"label": "Outlet trend", "query": "Show Outlet sales by month"}, {"query": "Compare with June 2023"}] + assert render_actions(actions) == "1. Outlet trend: Show Outlet sales by month\n2. Compare with June 2023" def test_suggestions_are_read_from_the_asked_turn_on() -> None: @@ -426,20 +432,6 @@ def test_an_earlier_turns_suggestions_are_not_the_last_turns() -> None: assert suggestions_from_turn(items, 0) is None -def test_an_answer_naming_no_driver_binds_no_suggestion() -> None: - suggestions = {"actions": [{"query": "Break it down further", "label": "Break down"}]} - assert check_suggestions_name_driver(_EXECUTE, "Sales fell.", suggestions)[0] is True - - -def test_the_first_action_must_name_a_driver_from_the_answer() -> None: - good = {"actions": [{"query": "Show Outlet sales by month", "label": "Outlet trend"}]} - generic = {"actions": [{"query": "Break it down further", "label": "Break down"}, {"query": "Outlet trend"}]} - assert check_suggestions_name_driver(_EXECUTE, _ANSWER, good)[0] is True - ok, detail = check_suggestions_name_driver(_EXECUTE, _ANSWER, generic) - assert not ok - assert detail["drivers_in_answer"] == ["outlet"] - - # --------------------------------------------------------------------------- # # run_agentic_kda_skill @@ -619,6 +611,38 @@ def test_check_answer_reads_the_turn_that_ran_the_analysis_not_an_earlier_questi assert ev.behaviour_detail["answer_grounded"]["named"] == [] +def _judged(verdict: JudgeVerdict | Exception) -> Any: + """Patch both judges to return ``verdict``, or raise it; yields the score_run mock.""" + kwargs = {"side_effect": verdict} if isinstance(verdict, Exception) else {"return_value": verdict} + return _Patches( + patch("gooddata_eval.core.agentic.kda_skill.LLMJudge"), + patch("gooddata_eval.core.agentic.kda_skill.score_run", **kwargs), + ) + + +class _Patches: + def __init__(self, judge: Any, score: Any) -> None: + self._judge, self._score = judge, score + + def __enter__(self) -> MagicMock: + self._judge.__enter__() + return self._score.__enter__() + + def __exit__(self, *exc: Any) -> None: + self._score.__exit__(*exc) + self._judge.__exit__(*exc) + + +_PASS = JudgeVerdict(passed=True, reasoning="every action drills into Outlet") +_SUGGESTED = [ + {"role": "user", "content": {"text": "Why did it drop?"}}, + { + "role": "assistant", + "content": {"suggestions": {"actions": [{"label": "Outlet trend", "query": "Show Outlet sales by month"}]}}, + }, +] + + def test_suggestions_are_read_for_the_turn_that_ran_the_analysis() -> None: items = [ {"role": "user", "content": {"text": "Why did it drop?"}}, @@ -627,32 +651,214 @@ def test_suggestions_are_read_for_the_turn_that_ran_the_analysis() -> None: {"role": "assistant", "content": {"suggestions": {"actions": [{"query": "Show Outlet sales by month"}]}}}, ] client = _client(_text_turn("Which period do you mean?"), _kda_turn(), items=items) - ev = _run(client, _with(_FIELDS, check_suggestions=True)).best.evaluation + with _judged(_PASS) as judge: + ev = _run(client, _with(_FIELDS, check_suggestions=True)).best.evaluation assert ev.strict_checks["suggestions"] is True - assert ev.behaviour_detail["suggestions"]["first_action"] == {"query": "Show Outlet sales by month"} + assert ev.behaviour_detail["suggestions"]["actions"] == [{"query": "Show Outlet sales by month"}] + conversation = judge.call_args.kwargs["actual_output"] + assert conversation.endswith("SUGGESTED ACTIONS: 1. Show Outlet sales by month") + assert f"Assistant: {_ANSWER}" in conversation + assert "1. June" not in conversation + + +def test_the_suggestion_judge_gets_the_suggestion_rules_and_its_reasoning_is_kept() -> None: + fail = JudgeVerdict(passed=False, reasoning="action 1 is generic (rule 3)") + client = _client(_kda_turn(), items=_SUGGESTED) + with _judged(fail) as judge: + ev = _run(client, _with(_FIELDS, check_suggestions=True)).best.evaluation + assert ev.strict_checks["suggestions"] is False + assert ev.behaviour_detail["suggestions"]["reasoning"] == "action 1 is generic (rule 3)" + assert "An action fails only when it clearly does one of these" in judge.call_args.kwargs["expected_output"] + assert judge.call_args.kwargs["input"] == "Why did it drop?" def test_check_suggestions_reads_the_conversation_before_it_is_deleted() -> None: - items = [ - {"role": "user", "content": {"text": "Why did it drop?"}}, - {"role": "assistant", "content": {"suggestions": {"actions": [{"query": "Break it down further"}]}}}, - ] - client = _client(_kda_turn(), items=items) - ev = _run(client, _with(_FIELDS, check_suggestions=True)).best.evaluation - assert ev.strict_checks["suggestions"] is False + client = _client(_kda_turn(), items=_SUGGESTED) + with _judged(_PASS): + _run(client, _with(_FIELDS, check_suggestions=True)) client.list_items.assert_called_once_with("conv-1") +@pytest.mark.parametrize( + "items", + [ + [], + [ + {"role": "user", "content": {"text": "Why?"}}, + {"role": "assistant", "content": {"suggestions": {"actions": []}}}, + ], + ], +) +def test_no_suggested_actions_pass_without_the_judge(items: list) -> None: + with _judged(_PASS) as judge: + ev = _run(_client(_kda_turn(), items=items), _with(_FIELDS, check_suggestions=True)).best.evaluation + assert ev.strict_checks["suggestions"] is True + assert ev.behaviour_detail["suggestions"] == {"actions": []} + judge.assert_not_called() + + +def test_suggestions_fail_when_no_analysis_ran() -> None: + failed = _kda_turn(execute={"success": False, "error": "AFM 400"}) + with _judged(_PASS) as judge: + ev = _run(_client(failed, items=_SUGGESTED), _with(_FIELDS, check_suggestions=True)).best.evaluation + assert ev.strict_checks["suggestions"] is False + assert ev.behaviour_detail["suggestions"] == {"reason": "no analysis ran"} + judge.assert_not_called() + + +def test_a_suggestion_judge_without_a_verdict_leaves_the_check_unscored() -> None: + with _judged(TimeoutError("judge timed out")): + ev = _run(_client(_kda_turn(), items=_SUGGESTED), _with(_FIELDS, check_suggestions=True)).best.evaluation + assert ev.unscored == ("suggestions",) + assert ev.harness_error == "suggestions: judge gave no verdict: TimeoutError: judge timed out" + + def test_an_unreadable_conversation_fails_only_the_suggestions_check() -> None: client = _client(_kda_turn()) client.list_items.side_effect = ValueError("no items list") - ev = _run(client, _with(_FIELDS, check_suggestions=True)).best.evaluation + with _judged(_PASS): + ev = _run(client, _with(_FIELDS, check_suggestions=True)).best.evaluation assert ev.strict_checks["suggestions"] is False assert ev.strict_checks["summary_correct"] is True assert ev.unscored == ("suggestions",) assert ev.harness_error == "suggestions: ValueError: no items list" +def test_the_judges_read_object_references_as_titles() -> None: + answer = "{metric/total_sales_amount_daily_store} fell. {label/dim_store.store_format} Outlet led." + items = [ + {"role": "user", "content": {"text": "Why did it drop?"}}, + {"role": "assistant", "content": {"suggestions": {"actions": [{"query": "Show {metric/x} by month"}]}}}, + ] + titles = MagicMock() + titles.resolve.side_effect = lambda text: text.replace( + "{metric/total_sales_amount_daily_store}", "Sales (metric/s)" + ) + expected = _with(_FIELDS, rubric="Says which metric fell.", check_suggestions=True) + with ( + _judged(_PASS) as judge, + patch("gooddata_eval.core.agentic.kda_skill.ObjectTitles", return_value=titles) as built, + ): + _run(_client(_kda_turn(text=answer), items=items), expected) + built.assert_called_once_with("http://host", "tok", "ws1") + rubric_call, suggestion_call = judge.call_args_list + assert "Assistant: Sales (metric/s) fell." in rubric_call.kwargs["actual_output"] + assert "Assistant: Sales (metric/s) fell." in suggestion_call.kwargs["actual_output"] + titles.resolve.assert_any_call("1. Show {metric/x} by month") + titles.close.assert_called_once() + + +# --------------------------------------------------------------------------- # +# A create the tool rejected + + +def _rejected(text: str) -> ChatResult: + return _text_turn(text, [_tool("create_key_driver_analysis", _CREATE, {"success": False, "error": "not linked"})]) + + +def test_a_rejected_create_followed_by_a_question_gets_a_reply_and_the_next_analysis_is_scored() -> None: + client = _client(_rejected("Ship Date is not linked. Use Transaction Date instead?"), _kda_turn()) + summary, simulate = _run_and_simulate(client, _FIELDS) + assert _sent(client) == ["Why did it drop?", "Use June 2024."] + simulate.assert_called_once() + assert summary.best.exit_reason.value == "success" + assert summary.best.evaluation.strict_pass + + +def test_a_rejected_create_retried_in_the_same_turn_ends_the_run() -> None: + retried = ChatResult.model_validate( + { + "textResponse": _ANSWER, + "toolCallEvents": [ + _tool("create_key_driver_analysis", _CREATE, {"success": False, "error": "not linked"}), + _tool("create_key_driver_analysis", _CREATE, {"success": True, "kda_ref": "kda_1"}), + _tool("execute_key_driver_analysis", {"kda_ref": "kda_1"}, _EXECUTE), + ], + "reasoningStepCount": 1, + "reasoningSteps": [], + "stream_ended": True, + } + ) + client = _client(retried) + summary, simulate = _run_and_simulate(client, _FIELDS) + assert client.send_message.call_count == 1 + simulate.assert_not_called() + assert summary.best.evaluation.strict_pass + + +def test_a_rejected_create_on_a_no_create_item_ends_the_run_without_a_reply() -> None: + client = _client(_rejected("This metric cannot be used for Key Driver Analysis.")) + summary, simulate = _run_and_simulate(client, {"expect_no_create": True}) + assert client.send_message.call_count == 1 + simulate.assert_not_called() + assert summary.best.exit_reason.value == "success" + + +def test_a_silent_rejected_create_ends_the_run() -> None: + client = _client(_rejected(""), _kda_turn()) + summary, simulate = _run_and_simulate(client, _FIELDS) + assert client.send_message.call_count == 1 + simulate.assert_not_called() + assert summary.best.exit_reason.value == "agent_silent" + assert summary.best.evaluation.triggered and not summary.best.evaluation.executed + + +def test_an_accepted_create_without_an_execute_ends_the_run() -> None: + accepted = _text_turn( + "The analysis is ready. Open it above to review the results.", + [_tool("create_key_driver_analysis", _CREATE, {"success": True, "kda_ref": "kda_1"})], + ) + client = _client(accepted, _kda_turn()) + summary, simulate = _run_and_simulate(client, _FIELDS) + assert client.send_message.call_count == 1 + simulate.assert_not_called() + assert summary.best.exit_reason.value == "success" + ev = summary.best.evaluation + assert ev.triggered and not ev.executed + + +def test_a_chat_failure_after_a_rejected_create_scores_the_turn_that_failed() -> None: + rejected = _rejected("Outlet stores look like the cause. Ship Date is not linked; use Transaction Date?") + cut_off = ChatError("stream died", partial_result=_kda_turn(text="")) + summary = _run(_client(rejected, cut_off), _with(_FIELDS, check_answer=True)) + ev = summary.best.evaluation + assert ev.executed + assert ev.behaviour_detail["answer_grounded"]["named"] == [] + + +def test_a_create_answered_with_a_plain_error_counts_as_rejected() -> None: + error = _text_turn("Which date should I use?", [_tool("create_key_driver_analysis", _CREATE, "Error: not linked")]) + client = _client(error, _kda_turn()) + summary, simulate = _run_and_simulate(client, _FIELDS) + simulate.assert_called_once() + assert summary.best.evaluation.strict_pass + + +def test_a_chat_failure_after_a_rejected_create_keeps_that_create() -> None: + cut_off = ChatError("stream died", partial_result=_text_turn("")) + client = _client(_rejected("Ship Date is not linked. Use Transaction Date?"), cut_off) + summary = _run(client, _FIELDS) + ev = summary.best.evaluation + assert ev.triggered and not ev.executed + assert summary.best.actual_create_args == _CREATE + + +def test_no_title_is_looked_up_when_no_judge_reads_the_conversation() -> None: + failed = _kda_turn(text="{metric/x} fell.", execute={"success": False, "error": "AFM 400"}) + titles = MagicMock() + with _judged(_PASS), patch("gooddata_eval.core.agentic.kda_skill.ObjectTitles", return_value=titles): + _run(_client(failed, items=_SUGGESTED), _with(_FIELDS, check_suggestions=True)) + titles.resolve.assert_not_called() + + +def test_a_rejected_create_until_the_budget_runs_out_is_scored_as_not_executed() -> None: + client = _client(_rejected("Which date should I use?"), _rejected("Which date should I use?")) + summary = _run(client, _FIELDS, max_iterations=2) + assert summary.best.exit_reason.value == "budget_exhausted" + ev = summary.best.evaluation + assert ev.triggered and not ev.executed and not ev.strict_pass + + def test_the_simulated_user_keeps_its_turns_after_the_scripted_replies() -> None: replies = ["Show it by month.", "Only 2024.", "Explain the change in June."] client = _client( @@ -780,3 +986,27 @@ def test_a_failing_behaviour_check_is_reported_with_what_it_compared() -> None: (failed_run,) = exc_info.value.failed_runs assert {"name": "not_created", "actual": {"analysis_ran": True, "answered": True}} in failed_run["failed_checks"] assert exc_info.value.detail["not_created"] is False + + +def test_the_judges_reasoning_is_the_comment_of_its_score() -> None: + capture: dict = {} + verdict = JudgeVerdict(passed=True, reasoning="it names Outlet as the driver") + with _judged(verdict): + _evaluate(_client(_kda_turn(), items=_SUGGESTED), _with(_FIELDS, rubric="x", check_suggestions=True), capture) + ctx = MagicMock() + capture["write_scores"](ctx) + comments = {c.kwargs["name"]: c.kwargs.get("comment") for c in ctx.score.call_args_list} + assert comments["kda_rubric"] == "it names Outlet as the driver" + assert comments["kda_suggestions"] == "it names Outlet as the driver" + assert comments["kda_summary_correct"] is None + + +def test_the_suggestion_judge_is_gpt_5_2_unless_the_judge_model_is_set(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GD_EVAL_JUDGE_MODEL", raising=False) + with _judged(_PASS), patch("gooddata_eval.core.agentic.kda_skill.LLMJudge") as built: + _run(_client(_kda_turn(), items=_SUGGESTED), _with(_FIELDS, check_suggestions=True)) + assert built.call_args.kwargs["model"] == "gpt-5.2" + monkeypatch.setenv("GD_EVAL_JUDGE_MODEL", "gpt-4.1") + with _judged(_PASS), patch("gooddata_eval.core.agentic.kda_skill.LLMJudge") as built: + _run(_client(_kda_turn(), items=_SUGGESTED), _with(_FIELDS, check_suggestions=True)) + assert built.call_args.kwargs["model"] == "gpt-4.1" diff --git a/packages/gooddata-eval/tests/test_agentic_object_titles.py b/packages/gooddata-eval/tests/test_agentic_object_titles.py new file mode 100644 index 000000000..54675e3ae --- /dev/null +++ b/packages/gooddata-eval/tests/test_agentic_object_titles.py @@ -0,0 +1,117 @@ +# (C) 2026 GoodData Corporation. All rights reserved. +# SPDX-License-Identifier: LicenseRef-GoodData-Enterprise +from collections.abc import Callable + +import httpx +from gooddata_eval.core.agentic._object_titles import ObjectTitles + +# Shapes trimmed from the globalmart fixture's entity API. +_TITLES = { + "/api/v1/entities/workspaces/ws1/metrics/total_sales_amount_daily_store": "Total Sales Amount (Daily Store Sales)", + "/api/v1/entities/workspaces/ws1/labels/dim_store.store_format": "Store Format", + "/api/v1/entities/workspaces/ws1/datasets/transaction_date": "Transaction Date", + "/api/v1/entities/workspaces/ws1/attributes/transaction_date.quarter": "Transaction Date - Quarter/Year", +} + + +def _titles( + handler: Callable[[httpx.Request], httpx.Response] | None = None, +) -> tuple[ObjectTitles, list[str]]: + requested: list[str] = [] + + def _default(request: httpx.Request) -> httpx.Response: + requested.append(request.url.path) + assert request.headers["Authorization"] == "Bearer tok" + title = _TITLES.get(request.url.path) + if title is None: + return httpx.Response(404, json={"title": "Not Found"}) + return httpx.Response(200, json={"data": {"id": "x", "attributes": {"title": title}}}) + + transport = httpx.MockTransport(handler or _default) + return ObjectTitles("http://host/", "tok", "ws1", transport=transport), requested + + +def test_a_reference_is_written_out_with_its_title() -> None: + titles, _ = _titles() + text = "{metric/total_sales_amount_daily_store} fell, led by {label/dim_store.store_format} Outlet." + assert titles.resolve(text) == ( + "Total Sales Amount (Daily Store Sales) (metric/total_sales_amount_daily_store) fell, " + "led by Store Format (label/dim_store.store_format) Outlet." + ) + + +def test_an_id_the_workspace_does_not_have_is_marked_unknown() -> None: + titles, _ = _titles() + assert titles.resolve("See {metric/made_up}.") == "See [unknown metric: made_up]." + + +def test_each_object_is_looked_up_once() -> None: + titles, requested = _titles() + titles.resolve("{metric/total_sales_amount_daily_store} and {metric/total_sales_amount_daily_store}") + titles.resolve("{metric/total_sales_amount_daily_store}") + assert requested == ["/api/v1/entities/workspaces/ws1/metrics/total_sales_amount_daily_store"] + + +def test_a_reference_stays_as_it_is_when_the_metadata_cannot_be_read() -> None: + titles, _ = _titles(lambda _request: httpx.Response(503)) + assert titles.resolve("{metric/a} fell.") == "{metric/a} fell." + + def _down(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("down", request=request) + + titles, _ = _titles(_down) + assert titles.resolve("{fact/rating} fell.") == "{fact/rating} fell." + + +def test_an_object_without_a_title_keeps_its_reference() -> None: + titles, _ = _titles(lambda _request: httpx.Response(200, json={"data": {"attributes": {}}})) + assert titles.resolve("{dashboard/d1}") == "{dashboard/d1}" + + +def test_text_without_references_needs_no_request() -> None: + titles, requested = _titles() + assert titles.resolve("Sales fell {by} 20% in metric/x.") == "Sales fell {by} 20% in metric/x." + assert requested == [] + titles.close() + + +def test_date_references_are_read_as_datasets_and_attributes() -> None: + titles, _ = _titles() + text = "By {date/transaction_date}, per {date_attribute/transaction_date.quarter}." + assert titles.resolve(text) == ( + "By Transaction Date (date/transaction_date), per " + "Transaction Date - Quarter/Year (date_attribute/transaction_date.quarter)." + ) + + +def test_an_id_may_start_with_a_hyphen() -> None: + titles, requested = _titles() + assert titles.resolve("{metric/-sales}") == "[unknown metric: -sales]" + assert requested == ["/api/v1/entities/workspaces/ws1/metrics/-sales"] + + +def test_a_body_that_is_not_json_keeps_the_reference() -> None: + titles, _ = _titles(lambda _request: httpx.Response(200, text="<html>")) + assert titles.resolve("{metric/a}") == "{metric/a}" + + +def test_a_malformed_id_is_left_alone_without_a_request() -> None: + titles, requested = _titles() + text = "{metric/../../users} {metric/.hidden} {metric/a?b} {metric/a:b} {metric/rev\x01} {parameter/p1}" + assert titles.resolve(text) == text + assert requested == [] + + +def test_a_closed_lookup_can_resolve_again() -> None: + titles, requested = _titles() + titles.resolve("{metric/made_up}") + titles.close() + assert titles.resolve("{fact/rating}") == "[unknown fact: rating]" + assert len(requested) == 2 + + +def test_a_failed_lookup_is_tried_again() -> None: + answers = [httpx.Response(503), httpx.Response(200, json={"data": {"attributes": {"title": "Revenue"}}})] + titles, _ = _titles(lambda _request: answers.pop(0)) + assert titles.resolve("{metric/revenue}") == "{metric/revenue}" + assert titles.resolve("{metric/revenue}") == "Revenue (metric/revenue)"