Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/gooddata-eval/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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`.

Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading