gooddata-eval 1.80.1.dev12__py3-none-any.whl → 1.81.1.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,365 @@
1
+ # (C) 2026 GoodData Corporation. All rights reserved.
2
+ """The KDA item's field checks: what ``create_key_driver_analysis`` and its execution must match.
3
+
4
+ An item opts in with ``check_fields: true``. Its expected output then names the measure, the date
5
+ attribute, both periods, the non-date filters and the summary the execution must return. Without
6
+ the key, nothing here runs and the item is scored on completion only.
7
+
8
+ ``any_of`` lists complete alternatives. Each option replaces some fields of the item, and a run
9
+ passes when one option matches every field. The summary goes with the date attribute, so an
10
+ option that changes one usually states both.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ import re
18
+ from collections.abc import Mapping
19
+ from dataclasses import dataclass
20
+ from decimal import Decimal
21
+ from typing import Any
22
+
23
+ # The fields in the order they are checked and published. Score ``kda_<field>_correct`` each.
24
+ KDA_FIELDS = ("measure", "date_attribute", "analyzed_period", "reference_period", "filters", "summary")
25
+ KDA_FIELD_SCORES = tuple(f"kda_{name}_correct" for name in KDA_FIELDS)
26
+
27
+ _FIELD_KEYS = {
28
+ "measure": "Measure",
29
+ "date_attribute": "Date Attribute",
30
+ "analyzed_period": "Analyzed Period",
31
+ "reference_period": "Reference Period",
32
+ "filters": "Filters",
33
+ "summary": "Summary",
34
+ }
35
+ _OPTION_KEYS = frozenset(_FIELD_KEYS.values())
36
+ _ITEM_KEYS = _OPTION_KEYS | {"check_fields", "any_of"}
37
+ _SUMMARY_VALUES = ("analyzed_value", "reference_value", "change")
38
+ _SUMMARY_KEYS = frozenset({*_SUMMARY_VALUES, "absolute_tolerance"})
39
+ _DEFAULT_TOLERANCE = 0.01
40
+ _MEASURE_KEYS = frozenset({"id", "type", "aggregation"})
41
+ # The values create_key_driver_analysis accepts. It upper-cases the aggregation itself.
42
+ _MEASURE_TYPES = ("metric", "fact", "attribute")
43
+ _AGGREGATIONS = ("SUM", "AVG", "MIN", "MAX", "MEDIAN", "COUNT")
44
+ _FILTER_STATES = ("include", "exclude")
45
+ # Spelled like the item's other keys, these would leave the checks off without a word.
46
+ _OPT_IN_KEYS = ("check_fields", "any_of")
47
+ _DATE_FILTER = "date_filter"
48
+ # The agent's tools take an attribute by its label or its attribute id. Both ids are equal in the
49
+ # eval workspaces, so a filter is matched on the id alone.
50
+ _TYPE_PREFIXES = ("label/", "attribute/")
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class KdaFieldOption:
55
+ """One complete set of expected fields."""
56
+
57
+ measures: tuple[dict[str, Any], ...]
58
+ date_attribute: str
59
+ analyzed_period: str
60
+ reference_period: str
61
+ filters: tuple[Any, ...]
62
+ filter_entries: tuple[dict[str, Any], ...]
63
+ summary: dict[str, float]
64
+ tolerance: float
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class KdaExpectation:
69
+ """The item's field checks. ``options`` is empty when the item does not opt in."""
70
+
71
+ options: tuple[KdaFieldOption, ...] = ()
72
+
73
+ @property
74
+ def check_fields(self) -> bool:
75
+ return bool(self.options)
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class KdaFieldResult:
80
+ """The fields of one run, checked against the option that matched most of them."""
81
+
82
+ checks: dict[str, bool]
83
+ option_index: int
84
+ expected: dict[str, Any]
85
+ actual: dict[str, Any]
86
+
87
+ @property
88
+ def passed(self) -> bool:
89
+ return all(self.checks.values())
90
+
91
+
92
+ def _to_float(value: Any) -> float | None:
93
+ """A finite number from an int, float or numeric string, else None. A bool is not a number."""
94
+ if isinstance(value, bool) or value is None:
95
+ return None
96
+ try:
97
+ number = float(str(value))
98
+ except ValueError:
99
+ return None
100
+ return number if math.isfinite(number) else None
101
+
102
+
103
+ def _measures(value: Any) -> tuple[dict[str, Any], ...]:
104
+ candidates = value if isinstance(value, list) else [value]
105
+ if not candidates:
106
+ raise ValueError("Measure must name at least one candidate")
107
+ for candidate in candidates:
108
+ if not isinstance(candidate, dict) or not isinstance(candidate.get("id"), str) or not candidate["id"]:
109
+ raise ValueError(f"Measure candidate needs a non-empty string id, got {candidate!r}")
110
+ if candidate.get("type") not in _MEASURE_TYPES:
111
+ raise ValueError(f"Measure candidate type must be one of {', '.join(_MEASURE_TYPES)}, got {candidate!r}")
112
+ aggregation = candidate.get("aggregation")
113
+ if aggregation is not None and str(aggregation).upper() not in _AGGREGATIONS:
114
+ raise ValueError(f"Measure aggregation must be one of {', '.join(_AGGREGATIONS)}, got {candidate!r}")
115
+ if unknown := set(candidate) - _MEASURE_KEYS:
116
+ raise ValueError(f"Measure candidate has unknown keys {sorted(unknown)}, got {candidate!r}")
117
+ return tuple(candidates)
118
+
119
+
120
+ def _text(key: str, value: Any, *, allow_int: bool = False) -> str:
121
+ # A year period may be an int ("Analyzed Period": 2024); a date attribute id never is, and a bool is neither.
122
+ allowed = (str, int) if allow_int else str
123
+ if isinstance(value, bool) or not isinstance(value, allowed) or not str(value).strip():
124
+ raise ValueError(f"{key} must be a non-empty string, got {value!r}")
125
+ return str(value).strip()
126
+
127
+
128
+ def _period_key(value: Any) -> tuple[int | str, ...]:
129
+ """A period by its parts, numbers as numbers: the tool reads ``2024-1`` and ``2024-01`` as one month."""
130
+ return tuple(int(part) if part.isdigit() else part for part in re.split(r"[-\s:]+", str(value).strip()))
131
+
132
+
133
+ def _check_attribute_filter(entry: dict[str, Any]) -> None:
134
+ using, state = entry.get("using"), entry.get("state")
135
+ if not isinstance(using, str) or not using.strip():
136
+ raise ValueError(f"attribute_filter needs a non-empty using, got {entry!r}")
137
+ if not isinstance(state, dict) or len(state) != 1 or next(iter(state)) not in _FILTER_STATES:
138
+ raise ValueError(f"attribute_filter state needs exactly one of include, exclude, got {entry!r}")
139
+ values = next(iter(state.values()))
140
+ if not isinstance(values, list) or not values or not all(isinstance(v, str) for v in values):
141
+ raise ValueError(f"attribute_filter {next(iter(state))} must be a non-empty list of strings, got {entry!r}")
142
+
143
+
144
+ def _filters(value: Any) -> tuple[Any, ...]:
145
+ if not isinstance(value, list):
146
+ raise ValueError(f"Filters must be a list, [] for none, got {value!r}")
147
+ for entry in value:
148
+ if not isinstance(entry, dict):
149
+ raise ValueError(f"Filters must hold objects, got {entry!r}")
150
+ if entry.get("type") == _DATE_FILTER:
151
+ raise ValueError("Filters must not hold a date_filter: date filters are not checked, the periods are")
152
+ if entry.get("type") == "attribute_filter":
153
+ _check_attribute_filter(entry)
154
+ return tuple(_filter_key(entry) for entry in value)
155
+
156
+
157
+ def _summary(value: Any) -> tuple[dict[str, float], float]:
158
+ if not isinstance(value, dict):
159
+ raise ValueError(f"Summary must be an object, got {value!r}")
160
+ if unknown := set(value) - _SUMMARY_KEYS:
161
+ raise ValueError(f"Summary has unknown keys {sorted(unknown)}")
162
+ numbers: dict[str, float] = {}
163
+ for key in _SUMMARY_VALUES:
164
+ if key in value:
165
+ number = _to_float(value[key])
166
+ if number is None:
167
+ raise ValueError(f"Summary {key} must be a number, got {value[key]!r}")
168
+ numbers[key] = number
169
+ if not numbers:
170
+ raise ValueError(f"Summary must state at least one of {', '.join(_SUMMARY_VALUES)}")
171
+ tolerance = _to_float(value.get("absolute_tolerance", _DEFAULT_TOLERANCE))
172
+ if tolerance is None or tolerance < 0:
173
+ raise ValueError(f"Summary absolute_tolerance must be a number >= 0, got {value.get('absolute_tolerance')!r}")
174
+ return numbers, tolerance
175
+
176
+
177
+ def _option(fields: Mapping[str, Any], label: str) -> KdaFieldOption:
178
+ if missing := [key for key in _FIELD_KEYS.values() if key not in fields]:
179
+ raise ValueError(f"{label} lacks {', '.join(missing)}: check_fields needs every field, Filters [] for none")
180
+ summary, tolerance = _summary(fields["Summary"])
181
+ return KdaFieldOption(
182
+ measures=_measures(fields["Measure"]),
183
+ date_attribute=_text("Date Attribute", fields["Date Attribute"]),
184
+ analyzed_period=_text("Analyzed Period", fields["Analyzed Period"], allow_int=True),
185
+ reference_period=_text("Reference Period", fields["Reference Period"], allow_int=True),
186
+ filters=_filters(fields["Filters"]),
187
+ filter_entries=tuple(fields["Filters"]),
188
+ summary=summary,
189
+ tolerance=tolerance,
190
+ )
191
+
192
+
193
+ def _reject_respelt_keys(expected: dict[str, Any]) -> None:
194
+ for key in expected:
195
+ canonical = re.sub(r"[\s-]+", "_", key.strip()).lower() if isinstance(key, str) else key
196
+ if canonical in _OPT_IN_KEYS and key != canonical:
197
+ raise ValueError(f"write {canonical!r}, not {key!r}")
198
+
199
+
200
+ def parse_kda_expectation(expected: Any) -> KdaExpectation:
201
+ """Read the item's field checks, raising ValueError on a malformed one before any request is sent."""
202
+ if isinstance(expected, dict):
203
+ _reject_respelt_keys(expected)
204
+ if not isinstance(expected, dict) or "check_fields" not in expected:
205
+ if isinstance(expected, dict) and "any_of" in expected:
206
+ raise ValueError("any_of is read only with check_fields: true")
207
+ return KdaExpectation()
208
+ flag = expected["check_fields"]
209
+ if not isinstance(flag, bool):
210
+ raise ValueError(f"check_fields must be true or false, got {flag!r}")
211
+ if not flag:
212
+ if "any_of" in expected:
213
+ raise ValueError("any_of is read only with check_fields: true")
214
+ return KdaExpectation()
215
+ if unknown := set(expected) - _ITEM_KEYS:
216
+ raise ValueError(f"expected_output has unknown keys {sorted(unknown)}")
217
+ base = {key: value for key, value in expected.items() if key in _OPTION_KEYS}
218
+ if "any_of" not in expected:
219
+ return KdaExpectation(options=(_option(base, "expected_output"),))
220
+ options = expected["any_of"]
221
+ if not isinstance(options, list) or len(options) < 2 or not all(isinstance(o, dict) and o for o in options):
222
+ raise ValueError(f"any_of must list at least two non-empty objects, got {options!r}")
223
+ parsed: list[KdaFieldOption] = []
224
+ for index, option in enumerate(options):
225
+ if unknown := set(option) - _OPTION_KEYS:
226
+ raise ValueError(
227
+ f"any_of[{index}] has keys {sorted(unknown)}; an option may state only {sorted(_OPTION_KEYS)}"
228
+ )
229
+ parsed.append(_option({**base, **option}, f"any_of[{index}]"))
230
+ return KdaExpectation(options=tuple(parsed))
231
+
232
+
233
+ def _bare_id(using: Any) -> Any:
234
+ if isinstance(using, str):
235
+ for prefix in _TYPE_PREFIXES:
236
+ if using.startswith(prefix):
237
+ return using[len(prefix) :]
238
+ return using
239
+
240
+
241
+ def _filter_key(entry: dict[str, Any]) -> Any:
242
+ """A comparable form of one filter: an attribute filter by its id and values, any other as its JSON."""
243
+ state = entry.get("state")
244
+ if (
245
+ entry.get("type") == "attribute_filter"
246
+ and isinstance(state, dict)
247
+ and set(state) <= set(_FILTER_STATES)
248
+ and all(isinstance(values, list) and all(isinstance(v, str) for v in values) for values in state.values())
249
+ ):
250
+ return (
251
+ "attribute_filter",
252
+ _bare_id(entry.get("using")),
253
+ tuple(sorted(state.get("include") or [])),
254
+ tuple(sorted(state.get("exclude") or [])),
255
+ )
256
+ return json.dumps(entry, sort_keys=True, default=str)
257
+
258
+
259
+ def _measure_matches(candidate: dict[str, Any], actual: Any) -> bool:
260
+ if not isinstance(actual, dict):
261
+ return False
262
+ if candidate["id"] != actual.get("id") or candidate["type"] != actual.get("type"):
263
+ return False
264
+ expected_aggregation = candidate.get("aggregation")
265
+ if expected_aggregation is None:
266
+ return True
267
+ return str(expected_aggregation).upper() == str(actual.get("aggregation") or "").upper()
268
+
269
+
270
+ def _actual_summary(execute_result: Any) -> dict | None:
271
+ if not isinstance(execute_result, dict) or execute_result.get("success") is not True:
272
+ return None
273
+ data = execute_result.get("data")
274
+ summary = data.get("summary") if isinstance(data, dict) else None
275
+ return summary if isinstance(summary, dict) else None
276
+
277
+
278
+ def _within(actual: float, expected: float, tolerance: float) -> bool:
279
+ # In decimal, so 100.01 against 100 is a difference of exactly 0.01, not 0.010000000000005116.
280
+ return abs(Decimal(repr(actual)) - Decimal(repr(expected))) <= Decimal(repr(tolerance))
281
+
282
+
283
+ def _summary_matches(option: KdaFieldOption, actual: dict | None) -> bool:
284
+ if actual is None:
285
+ return False
286
+ for key, expected in option.summary.items():
287
+ number = _to_float(actual.get(key))
288
+ if number is None or not _within(number, expected, option.tolerance):
289
+ return False
290
+ return True
291
+
292
+
293
+ def _non_date_filters(filters: Any) -> list[Any]:
294
+ entries = filters if isinstance(filters, list) else []
295
+ return [entry for entry in entries if not (isinstance(entry, dict) and entry.get("type") == _DATE_FILTER)]
296
+
297
+
298
+ def _actual_filters(create_args: dict) -> Any:
299
+ """The non-date filters the agent sent, or the malformed value itself so a failed check shows it."""
300
+ filters = create_args.get("filters", [])
301
+ return _non_date_filters(filters) if isinstance(filters, list) else filters
302
+
303
+
304
+ def _check_option(option: KdaFieldOption, create_args: dict, summary: dict | None) -> dict[str, bool]:
305
+ filters = create_args.get("filters", [])
306
+ # Omitted filters are no filters. Anything but a list, null included, is malformed: the tool takes a list.
307
+ filters_shaped = isinstance(filters, list)
308
+ actual_filters = sorted(
309
+ (_filter_key(f) if isinstance(f, dict) else repr(f) for f in _non_date_filters(filters)),
310
+ key=repr,
311
+ )
312
+ return {
313
+ "measure": any(_measure_matches(c, create_args.get("measure")) for c in option.measures),
314
+ "date_attribute": str(create_args.get("date_attribute_id") or "").strip() == option.date_attribute,
315
+ "analyzed_period": _period_key(create_args.get("analyzed_period") or "") == _period_key(option.analyzed_period),
316
+ "reference_period": _period_key(create_args.get("reference_period") or "")
317
+ == _period_key(option.reference_period),
318
+ "filters": filters_shaped and actual_filters == sorted(option.filters, key=repr),
319
+ "summary": _summary_matches(option, summary),
320
+ }
321
+
322
+
323
+ def _expected_view(option: KdaFieldOption) -> dict[str, Any]:
324
+ return {
325
+ "measure": list(option.measures) if len(option.measures) > 1 else option.measures[0],
326
+ "date_attribute": option.date_attribute,
327
+ "analyzed_period": option.analyzed_period,
328
+ "reference_period": option.reference_period,
329
+ "filters": list(option.filter_entries),
330
+ "summary": {**option.summary, "absolute_tolerance": option.tolerance},
331
+ }
332
+
333
+
334
+ def check_kda_fields(spec: KdaExpectation, create_args: Any, execute_result: Any) -> KdaFieldResult | None:
335
+ """The run's field checks against the option that matched most fields, the first one on a tie.
336
+
337
+ None when the item does not opt in or the run never called create: there was nothing to check, and
338
+ the completion checks already fail that run. Arguments that are not an object fail every field.
339
+ """
340
+ if not spec.check_fields or create_args is None:
341
+ return None
342
+ summary = _actual_summary(execute_result)
343
+ if not isinstance(create_args, dict):
344
+ return KdaFieldResult(
345
+ checks=dict.fromkeys(KDA_FIELDS, False),
346
+ option_index=0,
347
+ expected=_expected_view(spec.options[0]),
348
+ actual=dict.fromkeys(KDA_FIELDS) | {"summary": summary},
349
+ )
350
+ results = [_check_option(option, create_args, summary) for option in spec.options]
351
+ best = max(range(len(results)), key=lambda i: sum(results[i].values()))
352
+ actual = {
353
+ "measure": create_args.get("measure"),
354
+ "date_attribute": create_args.get("date_attribute_id"),
355
+ "analyzed_period": create_args.get("analyzed_period"),
356
+ "reference_period": create_args.get("reference_period"),
357
+ "filters": _actual_filters(create_args),
358
+ "summary": summary,
359
+ }
360
+ return KdaFieldResult(
361
+ checks=results[best],
362
+ option_index=best,
363
+ expected=_expected_view(spec.options[best]),
364
+ actual=actual,
365
+ )
@@ -7,11 +7,12 @@ import logging
7
7
  import os
8
8
  import time
9
9
  from dataclasses import dataclass, field
10
+ from typing import Any
10
11
 
11
12
  import httpx
12
13
 
13
14
  from gooddata_eval.core.agentic._failed_runs import build_failed_runs
14
- from gooddata_eval.core.agentic._failure_message import failed_checks_from
15
+ from gooddata_eval.core.agentic._failure_message import FailedCheck, failed_check_records, failed_checks_from
15
16
  from gooddata_eval.core.agentic._gate import (
16
17
  DEFAULT_GATE,
17
18
  EvalGate,
@@ -19,6 +20,13 @@ from gooddata_eval.core.agentic._gate import (
19
20
  log_gate_scores,
20
21
  stamp_gate_metadata,
21
22
  )
23
+ from gooddata_eval.core.agentic._kda_expectation import (
24
+ KDA_FIELD_SCORES,
25
+ KdaExpectation,
26
+ KdaFieldResult,
27
+ check_kda_fields,
28
+ parse_kda_expectation,
29
+ )
22
30
  from gooddata_eval.core.agentic._outcome import (
23
31
  agentic_detail,
24
32
  agentic_success,
@@ -54,6 +62,16 @@ from gooddata_eval.core.models import (
54
62
 
55
63
  _log = logging.getLogger(__name__)
56
64
 
65
+ __all__ = [
66
+ "KDA_FIELD_SCORES",
67
+ "AgenticKdaSummary",
68
+ "KdaEvaluation",
69
+ "KdaRunResult",
70
+ "KdaSkillAssertionError",
71
+ "evaluate_agentic_kda_skill",
72
+ "run_agentic_kda_skill",
73
+ ]
74
+
57
75
  _DEFAULT_K = 1
58
76
  # Disambiguation safety net only (create+execute always run together in the same turn) --
59
77
  # 3 real questions' worth (metric, period, +1 slack) since a simulated reply is now sent on
@@ -61,6 +79,18 @@ _DEFAULT_K = 1
61
79
  _DEFAULT_MAX_ITERATIONS = 4
62
80
 
63
81
 
82
+ def _hint_source(expected_output: dict) -> dict:
83
+ """The fields the simulated user answers from: the item's own, or with ``any_of`` its first option.
84
+
85
+ One whole option, so the measure, date attribute and periods it names form an answer the
86
+ field checks accept. Values mixed from two options might match neither.
87
+ """
88
+ options = expected_output.get("any_of")
89
+ if isinstance(options, list) and options and isinstance(options[0], dict):
90
+ return {**expected_output, **options[0]}
91
+ return expected_output
92
+
93
+
64
94
  def _build_period_hint(expected_output: dict) -> str | None:
65
95
  """Build a period hint from whichever of expected_output's Date Attribute/Analyzed
66
96
  Period/Reference Period are present -- a question about only one of them (e.g. "which
@@ -74,7 +104,7 @@ def _build_period_hint(expected_output: dict) -> str | None:
74
104
  return None
75
105
  parts = []
76
106
  if date_attr:
77
- parts.append(date_attr)
107
+ parts.append(str(date_attr))
78
108
  if analyzed and reference_period:
79
109
  parts.append(f"comparing {analyzed} to {reference_period}")
80
110
  elif analyzed:
@@ -155,27 +185,60 @@ def _extract_kda_calls(tool_call_events: list[ToolCallEvent]) -> tuple[dict | No
155
185
  tool calls -- not the last create and last execute picked independently. A new create
156
186
  call clears any earlier execute_result -- it belongs to the create it followed, not to
157
187
  this one.
188
+
189
+ An execute names the spec it runs by ``kda_ref``, so it is paired with the create that
190
+ returned that ref, even when another create came between them. Once the turn's creates
191
+ returned refs, an execute naming any other ref, or no string ref, is ignored: its result
192
+ belongs to no arguments the run can score. Only a create that carried no result at all
193
+ lets the next execute pair without a ref. A create the tool rejected does not replace an
194
+ analysis that already ran. Create arguments that are not a JSON object count as empty
195
+ arguments; an execute whose arguments or result are not a JSON object is no execution.
158
196
  """
197
+ created: dict[str, dict] = {}
159
198
  create_args: dict | None = None
160
199
  execute_result: dict | None = None
200
+ pairs_without_ref = False
161
201
  for tc in tool_call_events:
162
202
  if tc.function_name == "create_key_driver_analysis":
163
- create_args = tc.parsed_arguments()
203
+ args = _json_object(tc.parsed_arguments()) or {}
204
+ result = _json_object(tc.parsed_result())
205
+ if result is not None and result.get("success") is True and isinstance(result.get("kda_ref"), str):
206
+ created[result["kda_ref"]] = args
207
+ if result is not None and result.get("success") is False and execute_result is not None:
208
+ continue
209
+ create_args = args
164
210
  execute_result = None
211
+ pairs_without_ref = not tc.result
165
212
  elif tc.function_name == "execute_key_driver_analysis" and tc.result:
166
- execute_result = tc.parsed_result()
213
+ execute_args = _json_object(tc.parsed_arguments())
214
+ ref = execute_args.get("kda_ref") if execute_args is not None else None
215
+ if created:
216
+ if not isinstance(ref, str) or ref not in created:
217
+ continue
218
+ create_args = created[ref]
219
+ elif not pairs_without_ref or execute_args is None:
220
+ continue
221
+ execute_result = _json_object(tc.parsed_result())
167
222
  return create_args, execute_result
168
223
 
169
224
 
225
+ def _json_object(value: Any) -> dict | None:
226
+ """``value`` when the tool call carried a JSON object, else None. A model can send any JSON."""
227
+ return value if isinstance(value, dict) else None
228
+
229
+
170
230
  @dataclass
171
231
  class KdaEvaluation:
172
232
  """Evaluation scores for a single KDA-skill run.
173
233
 
174
- Scope: asserts only that the KDA process runs to completion -- the tool chain
175
- triggers, executes successfully, and the chat turn ends cleanly with a non-empty
176
- response (``turn_completed`` requires both gen-ai's stream-ended signal and a
177
- non-empty ``text_response`` -- a stream that ends cleanly but delivers nothing to the
178
- user isn't a completed turn either).
234
+ Every run is checked for completion: the tool chain triggers, executes successfully, and
235
+ the chat turn ends cleanly with a non-empty response (``turn_completed`` requires both
236
+ gen-ai's stream-ended signal and a non-empty ``text_response`` -- a stream that ends
237
+ cleanly but delivers nothing to the user isn't a completed turn either).
238
+
239
+ An item with ``check_fields: true`` also gates on ``fields``: the measure, date attribute,
240
+ periods, non-date filters and summary of the create call and its execution. ``fields`` is
241
+ None when the item does not opt in or the run never called create.
179
242
  """
180
243
 
181
244
  triggered: bool
@@ -183,16 +246,20 @@ class KdaEvaluation:
183
246
  success: bool
184
247
  turn_completed: bool
185
248
  disambiguated: bool = False
249
+ fields: KdaFieldResult | None = None
186
250
 
187
251
  @property
188
252
  def strict_checks(self) -> dict[str, bool]:
189
253
  """Every check strict_pass requires, by name."""
190
- return {
254
+ checks = {
191
255
  "triggered": self.triggered,
192
256
  "executed": self.executed,
193
257
  "success": self.success,
194
258
  "turn_completed": self.turn_completed,
195
259
  }
260
+ if self.fields is not None:
261
+ checks.update({f"{name}_correct": ok for name, ok in self.fields.checks.items()})
262
+ return checks
196
263
 
197
264
  @property
198
265
  def strict_pass(self) -> bool:
@@ -241,6 +308,7 @@ def _evaluate_run(
241
308
  execute_result: dict | None,
242
309
  turn_completed: bool,
243
310
  disambiguated: bool = False,
311
+ spec: KdaExpectation | None = None,
244
312
  ) -> KdaEvaluation:
245
313
  triggered = create_args is not None
246
314
  executed = execute_result is not None
@@ -251,6 +319,7 @@ def _evaluate_run(
251
319
  success=success,
252
320
  turn_completed=turn_completed,
253
321
  disambiguated=disambiguated,
322
+ fields=check_kda_fields(spec, create_args, execute_result) if spec is not None else None,
254
323
  )
255
324
 
256
325
 
@@ -281,6 +350,7 @@ def run_agentic_kda_skill(
281
350
  if k < 1:
282
351
  # k=0 or negative would otherwise silently run once, indistinguishable from k=1.
283
352
  raise ValueError(f"k must be >= 1, got {k}")
353
+ spec = parse_kda_expectation(expected_output)
284
354
  run_results: list[KdaRunResult] = []
285
355
  client = ChatClient(
286
356
  host=host,
@@ -376,8 +446,9 @@ def run_agentic_kda_skill(
376
446
  # simulated reply. A false positive (agent had already given a final answer) costs
377
447
  # one harmless extra turn; a false negative (missing a genuine clarifying question)
378
448
  # would hard-fail the run, so the asymmetry favors never trying to tell them apart.
379
- measure_candidates = expected_output.get("Measure") if isinstance(expected_output, dict) else None
380
- period_hint = _build_period_hint(expected_output) if isinstance(expected_output, dict) else None
449
+ hint_source = _hint_source(expected_output) if isinstance(expected_output, dict) else None
450
+ measure_candidates = hint_source.get("Measure") if hint_source is not None else None
451
+ period_hint = _build_period_hint(hint_source) if hint_source is not None else None
381
452
  try:
382
453
  current_question = generate_simulated_kda_response(response_text, measure_candidates, period_hint)
383
454
  disambiguated = True
@@ -386,7 +457,7 @@ def run_agentic_kda_skill(
386
457
  exit_reason = LoopExit.SIMULATED_USER_FAILED
387
458
  break
388
459
 
389
- ev = _evaluate_run(create_args, execute_result, turn_completed, disambiguated)
460
+ ev = _evaluate_run(create_args, execute_result, turn_completed, disambiguated, spec)
390
461
  return KdaRunResult(
391
462
  conversation_id=conv_id,
392
463
  evaluation=ev,
@@ -423,12 +494,7 @@ def run_agentic_kda_skill(
423
494
 
424
495
  pass_at_k = any(r.evaluation.strict_pass for r in run_results)
425
496
  pass_power_k = all(r.evaluation.strict_pass for r in run_results)
426
- best = max(
427
- run_results,
428
- key=lambda r: sum(
429
- [r.evaluation.triggered, r.evaluation.executed, r.evaluation.success, r.evaluation.turn_completed]
430
- ),
431
- )
497
+ best = max(run_results, key=lambda r: sum(r.evaluation.strict_checks.values()))
432
498
  return AgenticKdaSummary(
433
499
  run_results=run_results,
434
500
  pass_at_k=pass_at_k,
@@ -456,6 +522,7 @@ def _run_detail(run: KdaRunResult) -> dict:
456
522
  "disambiguated": ev.disambiguated,
457
523
  "actual_create_args": run.actual_create_args,
458
524
  "actual_execute_result": run.actual_execute_result,
525
+ **_field_detail(ev),
459
526
  # Why the loop stopped -- see LoopExit. Per-run rather than best-only: on a failing
460
527
  # run it is the first thing worth reading.
461
528
  "exit_reason": run.exit_reason.value,
@@ -464,9 +531,29 @@ def _run_detail(run: KdaRunResult) -> dict:
464
531
  }
465
532
 
466
533
 
534
+ def _field_detail(ev: KdaEvaluation) -> dict:
535
+ """The field verdicts as top-level booleans, which the report's quality score counts, plus what they compared."""
536
+ if ev.fields is None:
537
+ return {}
538
+ return {
539
+ **{f"{name}_correct": ok for name, ok in ev.fields.checks.items()},
540
+ "field_option": ev.fields.option_index,
541
+ "expected_fields": ev.fields.expected,
542
+ }
543
+
544
+
467
545
  def _failed_checks(run: KdaRunResult) -> list[dict]:
468
- """The checks this run failed, by name. What the agent sent is in the run's detail."""
469
- return failed_checks_from(run.evaluation.strict_checks)
546
+ """The checks this run failed, by name, a field check with its expected and actual value."""
547
+ ev = run.evaluation
548
+ completion = {name: ok for name, ok in ev.strict_checks.items() if not name.endswith("_correct")}
549
+ records = failed_checks_from(completion)
550
+ if ev.fields is not None:
551
+ records += failed_check_records(
552
+ FailedCheck(f"{name}_correct", expected=ev.fields.expected[name], actual=ev.fields.actual[name])
553
+ for name, ok in ev.fields.checks.items()
554
+ if not ok
555
+ )
556
+ return records
470
557
 
471
558
 
472
559
  def evaluate_agentic_kda_skill(
@@ -496,6 +583,8 @@ def evaluate_agentic_kda_skill(
496
583
  AgenticEvalOutcome on success; on failure the same three values are attached to the
497
584
  raised exception as ``.reasoning_steps``/``.conversation_id``/``.response_id``.
498
585
  """
586
+ # Before the trace opens: a malformed item must fail without a request or an empty trace.
587
+ parse_kda_expectation(expected_output)
499
588
  identity = RunIdentity(
500
589
  host,
501
590
  token,
@@ -538,13 +627,8 @@ def evaluate_agentic_kda_skill(
538
627
  pt = ctx.trace(run.conversation_id)
539
628
  run_name = ctx.run_name(run_idx)
540
629
  ev = run.evaluation
541
- # Gates strict_pass -- current scope is completion only (see KdaEvaluation docstring).
542
- strict_checks = {
543
- "kda_triggered": ev.triggered,
544
- "kda_executed": ev.executed,
545
- "kda_success": ev.success,
546
- "kda_turn_completed": ev.turn_completed,
547
- }
630
+ # Gates strict_pass: completion, plus the kda_*_correct field checks of an item that opts in.
631
+ strict_checks = {f"kda_{name}": ok for name, ok in ev.strict_checks.items()}
548
632
  # Not pt.latency: pt can be any trace of the conversation, not necessarily the KDA turn.
549
633
  turn_wall_clock_sec = run.turn_wall_clock_sec
550
634
  _log.info(
@@ -604,6 +688,7 @@ def evaluate_agentic_kda_skill(
604
688
  disambiguated=ev.disambiguated,
605
689
  actual_create_args=best.actual_create_args,
606
690
  actual_execute_result=best.actual_execute_result,
691
+ **_field_detail(ev),
607
692
  # Why the loop stopped -- see LoopExit.
608
693
  exit_reason=best.exit_reason.value,
609
694
  turns_used=best.turns_used,
@@ -623,7 +708,9 @@ def evaluate_agentic_kda_skill(
623
708
  message = (
624
709
  f"KDA skill assertion failed. {gate_note} strict_pass={ev.strict_pass} "
625
710
  f"(triggered={ev.triggered}, executed={ev.executed}, "
626
- f"success={ev.success}, turn_completed={ev.turn_completed}). "
711
+ f"success={ev.success}, turn_completed={ev.turn_completed}"
712
+ + (f", fields={ev.fields.checks}" if ev.fields is not None else "")
713
+ + "). "
627
714
  f"Actual create args: {best.actual_create_args}. "
628
715
  f"Actual execute result: {best.actual_execute_result}."
629
716
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: gooddata-eval
3
- Version: 1.80.1.dev12
3
+ Version: 1.81.1.dev1
4
4
  Summary: Evaluate the GoodData AI agent against your own questions and models.
5
5
  Project-URL: Source, https://github.com/gooddata/gooddata-python-sdk
6
6
  Author-email: GoodData <support@gooddata.com>
@@ -18,7 +18,7 @@ Classifier: Topic :: Scientific/Engineering
18
18
  Classifier: Topic :: Software Development
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.11
21
- Requires-Dist: gooddata-sdk~=1.80.1.dev12
21
+ Requires-Dist: gooddata-sdk~=1.81.1.dev1
22
22
  Requires-Dist: httpx<1.0,>=0.27
23
23
  Requires-Dist: jsonpatch<2.0,>=1.33
24
24
  Requires-Dist: orjson<4.0.0,>=3.9.15
@@ -1129,6 +1129,58 @@ the editors and the generated `description` are not compared) and `alert_not_rec
1129
1129
  (the alert still exists and the agent created none). A failing run reports the update
1130
1130
  arguments and every field that changed unasked.
1131
1131
 
1132
+ ### `agentic_kda_skill` field checks
1133
+
1134
+ A KDA item is scored on completion: `kda_triggered`, `kda_executed`, `kda_success` and
1135
+ `kda_turn_completed`. With `"check_fields": true` the run must also match every field of the
1136
+ `create_key_driver_analysis` call and the summary its execution returns:
1137
+
1138
+ ```json
1139
+ {
1140
+ "question": "What drove the change in Total Sales Amount in Q4 2024 versus Q3 2024, excluding the United States East region?",
1141
+ "expected_output": {
1142
+ "check_fields": true,
1143
+ "Measure": {"id": "total_sales_amount_daily_store", "type": "metric"},
1144
+ "Date Attribute": "transaction_date.quarter",
1145
+ "Analyzed Period": "2024-4",
1146
+ "Reference Period": "2024-3",
1147
+ "Filters": [
1148
+ {"type": "attribute_filter", "using": "label/dim_geography_region.region_name", "state": {"exclude": ["United States East"]}}
1149
+ ],
1150
+ "Summary": {"analyzed_value": 13868253.55, "reference_value": 15142121.31, "change": -1273867.76, "absolute_tolerance": 0.01}
1151
+ }
1152
+ }
1153
+ ```
1154
+
1155
+ | Score | Passes when |
1156
+ |---|---|
1157
+ | `kda_measure_correct` | the measure has the id and type of a `Measure` candidate (one object or a list), and its aggregation when the candidate states one |
1158
+ | `kda_date_attribute_correct` | `date_attribute_id` equals `Date Attribute` |
1159
+ | `kda_analyzed_period_correct`, `kda_reference_period_correct` | the period has the expected parts, numbers compared as numbers (`2024-1` is `2024-01`, `2024-Q3` is not `2024-3`) |
1160
+ | `kda_filters_correct` | the non-date filters equal `Filters` in any order (`[]` for none). Date filters are not compared: the periods set the scope, and a date filter that changes the numbers fails the summary |
1161
+ | `kda_summary_correct` | the execution succeeded and each of `analyzed_value`, `reference_value` and `change` the item states is within `absolute_tolerance` (default 0.01) |
1162
+
1163
+ `any_of` lists complete alternatives for a question two answers fit. Each option replaces some
1164
+ of the fields, and a run passes when one option matches all six. The summary depends on the
1165
+ date attribute, so an option that changes one states both:
1166
+
1167
+ ```json
1168
+ "any_of": [
1169
+ {"Date Attribute": "transaction_date.quarter", "Summary": {"analyzed_value": 184, "reference_value": 163}},
1170
+ {"Date Attribute": "return_date.quarter", "Summary": {"analyzed_value": 191, "reference_value": 156}}
1171
+ ]
1172
+ ```
1173
+
1174
+ A missing field, an unknown key, `check fields` or `any of` spelled with a space or capitals, a
1175
+ measure type or aggregation the tool does not take, an attribute filter without one non-empty
1176
+ `include` or `exclude` list of strings, a date filter in `Filters` or `any_of` without
1177
+ `check_fields` is rejected before any request. The execute call is paired with the create whose
1178
+ `kda_ref` it names; an execute naming a ref no create of the turn returned is not counted, and a
1179
+ create the tool rejected after an analysis ran does not replace it. `filters` that are not a list
1180
+ fail `kda_filters_correct`; omitted ones are no filters. The six names are `KDA_FIELD_SCORES`; a run that never called
1181
+ create publishes none of them. A failing run reports the expected and the actual value of each
1182
+ field it failed.
1183
+
1132
1184
  ### Items asked in a dashboard context (`user_context`)
1133
1185
 
1134
1186
  An item can be asked the way a user asks from an open dashboard or an attached widget.
@@ -27,6 +27,7 @@ gooddata_eval/core/agentic/_failed_runs.py,sha256=1D3vFCKG4TUnNUdci6NO1yJlBFZ8GQ
27
27
  gooddata_eval/core/agentic/_failure_message.py,sha256=PvjDyyBHni-m69UskjSs6oXEJcQVKAfcKkNJ5R-Xjm4,8036
28
28
  gooddata_eval/core/agentic/_filters.py,sha256=arAesTihu67a-1xccREfN1KBj46Jm-dOJrBfajz67Lc,2009
29
29
  gooddata_eval/core/agentic/_gate.py,sha256=9hwdjSm8RFPw9I-NF4s4hTUcVl1aD9RWp8RcRvLdp7U,3074
30
+ gooddata_eval/core/agentic/_kda_expectation.py,sha256=WvLuYLg0hoJitp_9rTR_IcJBI1Qbfg4N3I36KGXJUX0,16317
30
31
  gooddata_eval/core/agentic/_langfuse.py,sha256=74_pf1XU6fQG6qrgRB18XYrMlO69tnH1uNi5TJWPt-o,29706
31
32
  gooddata_eval/core/agentic/_metric_expectation.py,sha256=mlhmVDEDgg4pkfOXmPSjwa7i8D6p3fYaEoMisGLVdVw,20520
32
33
  gooddata_eval/core/agentic/_metric_workspace.py,sha256=5qQAdWtneniFqFtZoc4K7vQlrGD7cj8ErruQNgdu-po,11878
@@ -43,7 +44,7 @@ gooddata_eval/core/agentic/document_skill.py,sha256=L8q5sZmQJ-DJ5lk8MoJ6AzMer8PU
43
44
  gooddata_eval/core/agentic/forecasting.py,sha256=vpq0BOuXNaMqlbPOt_MQi6avw6eqkbqcQ7Ql28KEZME,26965
44
45
  gooddata_eval/core/agentic/general_question.py,sha256=YPaz7tbeV0lTHlfmUPNvJ5FD6y-nh5ZqpwLSQqpJI4Y,20480
45
46
  gooddata_eval/core/agentic/guardrail.py,sha256=_7-nlBNVnGaYJx9Oq8V08npe1IunxgwH1bqKs0yplhY,17904
46
- gooddata_eval/core/agentic/kda_skill.py,sha256=L89qH8-cUzJxr105GsGC7WK4Cpg6i_M8wbUca8Wf-2Y,27881
47
+ gooddata_eval/core/agentic/kda_skill.py,sha256=9ovRTW9Bawg4fiExgKPXmvc0cb5XTx73Fnd0sP32d5I,32116
47
48
  gooddata_eval/core/agentic/knowledge.py,sha256=hVAyQwCmewjTAdvfNHz6517obwxr3-KRb8yxmBkL1j4,17836
48
49
  gooddata_eval/core/agentic/metric_skill.py,sha256=PX-nSGsszJYZHC4tUu732rwSrXjfA23YpHtJOVccdqw,64702
49
50
  gooddata_eval/core/agentic/report_skill.py,sha256=ZpuKuQpor56ywDKauzQKAx18vFHcW6uq3nFgV2GjVvM,1583
@@ -96,8 +97,8 @@ gooddata_eval/core/summary/http_client.py,sha256=Umae42fiiJQ0e4hv63NRROHYvcFAGgX
96
97
  gooddata_eval/core/takeaway/__init__.py,sha256=U54lANKm34yjqm7dZL9KkGouPbwAaQWC9wiAmb5B5g4,32
97
98
  gooddata_eval/core/takeaway/evaluate.py,sha256=AjS_rCHWUSJKv0jfEfL0-dVPoDaf3RkGdmeZiIwjd6A,11312
98
99
  gooddata_eval/core/takeaway/http_client.py,sha256=YMfafOcHJ184i49Qoh0ZNPKKTMKBSgeDUM4zk_H3yM8,3955
99
- gooddata_eval-1.80.1.dev12.dist-info/METADATA,sha256=XfGT6N0u_4_sv7bl5gScWklEwv8hqmmIZXjQEy8PPJ0,76726
100
- gooddata_eval-1.80.1.dev12.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
101
- gooddata_eval-1.80.1.dev12.dist-info/entry_points.txt,sha256=28nFp5Viknx4haPYgzK9QHlwPFfC6rPF6RmjC2ht8EI,56
102
- gooddata_eval-1.80.1.dev12.dist-info/licenses/LICENSE.txt,sha256=LVfVlC9maU3K9lgMwdZnClQQsOIbOekdcdVKr9qzJtk,256836
103
- gooddata_eval-1.80.1.dev12.dist-info/RECORD,,
100
+ gooddata_eval-1.81.1.dev1.dist-info/METADATA,sha256=NRtLA1BPT64QzeM-EAcR41BS4LGk9YMgwa2ZZvojvYQ,79825
101
+ gooddata_eval-1.81.1.dev1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
102
+ gooddata_eval-1.81.1.dev1.dist-info/entry_points.txt,sha256=28nFp5Viknx4haPYgzK9QHlwPFfC6rPF6RmjC2ht8EI,56
103
+ gooddata_eval-1.81.1.dev1.dist-info/licenses/LICENSE.txt,sha256=LVfVlC9maU3K9lgMwdZnClQQsOIbOekdcdVKr9qzJtk,256836
104
+ gooddata_eval-1.81.1.dev1.dist-info/RECORD,,