gooddata-eval 1.80.1.dev5__py3-none-any.whl → 1.80.1.dev6__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.
- gooddata_eval/core/agentic/_metric_expectation.py +450 -0
- gooddata_eval/core/agentic/_metric_workspace.py +233 -0
- gooddata_eval/core/agentic/metric_skill.py +601 -56
- {gooddata_eval-1.80.1.dev5.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/METADATA +2 -2
- {gooddata_eval-1.80.1.dev5.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/RECORD +8 -6
- {gooddata_eval-1.80.1.dev5.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/WHEEL +0 -0
- {gooddata_eval-1.80.1.dev5.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/entry_points.txt +0 -0
- {gooddata_eval-1.80.1.dev5.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/licenses/LICENSE.txt +0 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
# (C) 2026 GoodData Corporation. All rights reserved.
|
|
2
|
+
"""What a metric-skill item expects, parsed from its ``expected_output``, and the matchers that judge it.
|
|
3
|
+
|
|
4
|
+
An item states its expectation in one of two shapes. A list of ``{"maql": ...}`` candidates, or a
|
|
5
|
+
dict carrying one candidate, is the original shape: the agent must create one metric whose MAQL
|
|
6
|
+
matches a candidate. A dict that carries any key of ``OPTION_KEYS`` is the options shape: every key
|
|
7
|
+
is a check the item opts into, and an item without a key is not held to it. A malformed options dict
|
|
8
|
+
raises ``ValueError`` before any request, so a typo never reads green.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import difflib
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from gooddata_eval.core.evaluators._maql import normalize_maql
|
|
19
|
+
|
|
20
|
+
FORMAT_KINDS = ("percent", "currency", "integer", "decimal")
|
|
21
|
+
|
|
22
|
+
_FIELD_KEYS = (
|
|
23
|
+
"title",
|
|
24
|
+
"metric_id",
|
|
25
|
+
"format",
|
|
26
|
+
"format_kind",
|
|
27
|
+
"format_contains",
|
|
28
|
+
"description",
|
|
29
|
+
"description_contains",
|
|
30
|
+
"tags",
|
|
31
|
+
"tags_include",
|
|
32
|
+
)
|
|
33
|
+
_UPDATE_KEYS = (*_FIELD_KEYS, "maql")
|
|
34
|
+
OPTION_KEYS = frozenset(
|
|
35
|
+
{
|
|
36
|
+
"candidates",
|
|
37
|
+
"user_replies",
|
|
38
|
+
"run_all_replies",
|
|
39
|
+
"expect_no_create",
|
|
40
|
+
"expected_mentions",
|
|
41
|
+
"expect_no_overwrite",
|
|
42
|
+
"expect_clarification",
|
|
43
|
+
"confirmation_turn",
|
|
44
|
+
"expect_confirmation_stop",
|
|
45
|
+
"rubric",
|
|
46
|
+
"expected_fields",
|
|
47
|
+
"expected_update",
|
|
48
|
+
"expected_metrics",
|
|
49
|
+
"expect_no_deletion",
|
|
50
|
+
"expect_executes",
|
|
51
|
+
"score_first_proposal",
|
|
52
|
+
"expect_suggestions",
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
_CURRENCY_MARKS = ("$", "€", "£", "¥", "Kč")
|
|
57
|
+
_DECIMAL_RE = re.compile(r"\.[0#]")
|
|
58
|
+
_PLACEHOLDER_RE = re.compile(r"\{metric/@(\d+)\}")
|
|
59
|
+
# A formula in an inline code span or in a fenced block, with or without a language tag.
|
|
60
|
+
_PROPOSED_MAQL_RE = re.compile(r"```[a-zA-Z]*\s*(SELECT\b[^`]*?)\s*```|`(SELECT\b[^`]*)`", re.IGNORECASE)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class FieldSpec:
|
|
65
|
+
"""Values the stored metric must carry. A field left as None or empty is not checked."""
|
|
66
|
+
|
|
67
|
+
title: str | None = None
|
|
68
|
+
metric_id: str | None = None
|
|
69
|
+
format: str | None = None
|
|
70
|
+
format_kind: str | None = None
|
|
71
|
+
format_contains: tuple[str, ...] = ()
|
|
72
|
+
description: str | None = None
|
|
73
|
+
description_contains: tuple[str, ...] = ()
|
|
74
|
+
tags: frozenset[str] | None = None
|
|
75
|
+
tags_include: frozenset[str] = frozenset()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class UpdateSpec:
|
|
80
|
+
"""An existing metric the agent must update: the listed fields change, every other field stays."""
|
|
81
|
+
|
|
82
|
+
metric_id: str
|
|
83
|
+
fields: FieldSpec
|
|
84
|
+
maql: tuple[str, ...] = ()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class MetricExpectation:
|
|
89
|
+
"""The parsed expectation of one metric-skill item."""
|
|
90
|
+
|
|
91
|
+
candidates: list[dict] = field(default_factory=list)
|
|
92
|
+
legacy: bool = True
|
|
93
|
+
user_replies: tuple[str, ...] = ()
|
|
94
|
+
run_all_replies: bool = False
|
|
95
|
+
expect_no_create: bool = False
|
|
96
|
+
expected_mentions: tuple[str, ...] = ()
|
|
97
|
+
expect_no_overwrite: bool = False
|
|
98
|
+
expect_clarification: bool = False
|
|
99
|
+
confirmation_turn: int | None = None
|
|
100
|
+
rubric: str | None = None
|
|
101
|
+
expected_fields: FieldSpec | None = None
|
|
102
|
+
expected_update: UpdateSpec | None = None
|
|
103
|
+
expected_metrics: tuple[tuple[str, ...], ...] = ()
|
|
104
|
+
# Ids of metrics that must still exist after the run. A list, not a flag: other items create and delete
|
|
105
|
+
# their own metrics in the same workspace at the same time.
|
|
106
|
+
expect_no_deletion: tuple[str, ...] = ()
|
|
107
|
+
expect_executes: bool = False
|
|
108
|
+
score_first_proposal: bool = False
|
|
109
|
+
expect_suggestions: bool = False
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def needs_workspace(self) -> bool:
|
|
113
|
+
"""Whether a run reads the workspace's metrics through REST: every options-shape item does."""
|
|
114
|
+
return not self.legacy
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _is_options_shape(raw: Any) -> bool:
|
|
118
|
+
return isinstance(raw, dict) and any(key in OPTION_KEYS for key in raw)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _misspelt_option_key(candidate: dict) -> tuple[str, str] | None:
|
|
122
|
+
"""A key of an original-shape candidate that reads as a misspelt option key, with the key it resembles.
|
|
123
|
+
|
|
124
|
+
Such a key keeps the dict in the original shape, so the check it asks for would be dropped without a word. The
|
|
125
|
+
fields a candidate carries beside its MAQL (title, format, tags, ...) resemble no option key.
|
|
126
|
+
"""
|
|
127
|
+
for key in candidate:
|
|
128
|
+
match = difflib.get_close_matches(str(key), OPTION_KEYS, n=1, cutoff=0.8)
|
|
129
|
+
if match:
|
|
130
|
+
return str(key), match[0]
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _strings(value: Any, name: str) -> tuple[str, ...]:
|
|
135
|
+
"""A non-empty string, or a list of them, as a tuple."""
|
|
136
|
+
items = [value] if isinstance(value, str) else value
|
|
137
|
+
if not isinstance(items, list) or not items or not all(isinstance(s, str) and s.strip() for s in items):
|
|
138
|
+
raise ValueError(f"{name} must be a non-empty string or a list of them, got {value!r}")
|
|
139
|
+
return tuple(items)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _flag(raw: dict, name: str) -> bool:
|
|
143
|
+
value = raw.get(name, False)
|
|
144
|
+
if not isinstance(value, bool):
|
|
145
|
+
raise ValueError(f"{name} must be true or false, got {value!r}")
|
|
146
|
+
return value
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _candidates(value: Any, name: str) -> list[dict]:
|
|
150
|
+
"""``[{"maql": ...}]`` or a plain list of MAQL strings, as candidate dicts."""
|
|
151
|
+
if isinstance(value, str):
|
|
152
|
+
value = [value]
|
|
153
|
+
if not isinstance(value, list) or not value:
|
|
154
|
+
raise ValueError(f"{name} must be a non-empty list of MAQL candidates, got {value!r}")
|
|
155
|
+
out: list[dict] = []
|
|
156
|
+
for candidate in value:
|
|
157
|
+
maql = candidate.get("maql") if isinstance(candidate, dict) else candidate
|
|
158
|
+
if not isinstance(maql, str) or not maql.strip():
|
|
159
|
+
raise ValueError(f"{name}: every candidate needs a non-empty MAQL, got {candidate!r}")
|
|
160
|
+
out.append(candidate if isinstance(candidate, dict) else {"maql": maql})
|
|
161
|
+
return out
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _field_spec(raw: Any, name: str, allowed: tuple[str, ...]) -> FieldSpec:
|
|
165
|
+
if not isinstance(raw, dict) or not raw:
|
|
166
|
+
raise ValueError(f"{name} must be a non-empty object, got {raw!r}")
|
|
167
|
+
unknown = sorted(set(raw) - set(allowed))
|
|
168
|
+
if unknown:
|
|
169
|
+
raise ValueError(f"{name}: unknown key(s) {unknown}; allowed: {list(allowed)}")
|
|
170
|
+
kind = raw.get("format_kind")
|
|
171
|
+
if "format_kind" in raw and kind not in FORMAT_KINDS:
|
|
172
|
+
raise ValueError(f"{name}.format_kind must be one of {FORMAT_KINDS}, got {kind!r}")
|
|
173
|
+
for key in ("title", "metric_id", "format", "description"):
|
|
174
|
+
if key in raw and (not isinstance(raw[key], str) or not raw[key].strip()):
|
|
175
|
+
raise ValueError(f"{name}.{key} must be a non-empty string, got {raw[key]!r}")
|
|
176
|
+
return FieldSpec(
|
|
177
|
+
title=raw.get("title"),
|
|
178
|
+
metric_id=raw.get("metric_id"),
|
|
179
|
+
format=raw.get("format"),
|
|
180
|
+
format_kind=kind,
|
|
181
|
+
format_contains=_strings(raw["format_contains"], f"{name}.format_contains") if "format_contains" in raw else (),
|
|
182
|
+
description=raw.get("description"),
|
|
183
|
+
description_contains=(
|
|
184
|
+
_strings(raw["description_contains"], f"{name}.description_contains")
|
|
185
|
+
if "description_contains" in raw
|
|
186
|
+
else ()
|
|
187
|
+
),
|
|
188
|
+
tags=frozenset(_strings(raw["tags"], f"{name}.tags")) if "tags" in raw else None,
|
|
189
|
+
tags_include=frozenset(_strings(raw["tags_include"], f"{name}.tags_include"))
|
|
190
|
+
if "tags_include" in raw
|
|
191
|
+
else frozenset(),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def parse_expectation(raw: Any) -> MetricExpectation:
|
|
196
|
+
"""Parse and validate an item's ``expected_output``.
|
|
197
|
+
|
|
198
|
+
Raises:
|
|
199
|
+
ValueError: The options shape names an unknown key, a key holds the wrong type, two keys
|
|
200
|
+
contradict each other, or the item checks nothing at all.
|
|
201
|
+
"""
|
|
202
|
+
if not _is_options_shape(raw):
|
|
203
|
+
legacy = raw if isinstance(raw, list) else [raw]
|
|
204
|
+
if not all(isinstance(c, dict) for c in legacy):
|
|
205
|
+
raise ValueError(
|
|
206
|
+
f"expected_output: a candidate list holds dicts with a 'maql' key, got {raw!r}; "
|
|
207
|
+
"plain MAQL strings go under 'candidates'"
|
|
208
|
+
)
|
|
209
|
+
for candidate in legacy:
|
|
210
|
+
misspelt = _misspelt_option_key(candidate)
|
|
211
|
+
if misspelt is not None:
|
|
212
|
+
raise ValueError(f"expected_output: unknown key {misspelt[0]!r}; did you mean {misspelt[1]!r}?")
|
|
213
|
+
return MetricExpectation(candidates=list(legacy))
|
|
214
|
+
|
|
215
|
+
unknown = sorted(set(raw) - OPTION_KEYS)
|
|
216
|
+
if unknown:
|
|
217
|
+
raise ValueError(f"expected_output: unknown key(s) {unknown}; allowed: {sorted(OPTION_KEYS)}")
|
|
218
|
+
|
|
219
|
+
candidates = _candidates(raw["candidates"], "candidates") if "candidates" in raw else []
|
|
220
|
+
replies = _strings(raw["user_replies"], "user_replies") if "user_replies" in raw else ()
|
|
221
|
+
run_all = _flag(raw, "run_all_replies")
|
|
222
|
+
no_create = _flag(raw, "expect_no_create")
|
|
223
|
+
mentions = _strings(raw["expected_mentions"], "expected_mentions") if "expected_mentions" in raw else ()
|
|
224
|
+
|
|
225
|
+
if "confirmation_turn" in raw and "expect_confirmation_stop" in raw:
|
|
226
|
+
raise ValueError("give confirmation_turn or expect_confirmation_stop, not both")
|
|
227
|
+
confirmation_turn: int | None = None
|
|
228
|
+
if "confirmation_turn" in raw:
|
|
229
|
+
confirmation_turn = raw["confirmation_turn"]
|
|
230
|
+
if isinstance(confirmation_turn, bool) or not isinstance(confirmation_turn, int) or confirmation_turn < 2:
|
|
231
|
+
raise ValueError(f"confirmation_turn must be an integer of at least 2, got {confirmation_turn!r}")
|
|
232
|
+
elif _flag(raw, "expect_confirmation_stop"):
|
|
233
|
+
confirmation_turn = 2
|
|
234
|
+
|
|
235
|
+
rubric = raw.get("rubric")
|
|
236
|
+
if "rubric" in raw and (not isinstance(rubric, str) or not rubric.strip()):
|
|
237
|
+
raise ValueError(f"rubric must be a non-empty string, got {rubric!r}")
|
|
238
|
+
|
|
239
|
+
fields = _field_spec(raw["expected_fields"], "expected_fields", _FIELD_KEYS) if "expected_fields" in raw else None
|
|
240
|
+
|
|
241
|
+
update: UpdateSpec | None = None
|
|
242
|
+
if "expected_update" in raw:
|
|
243
|
+
upd = raw["expected_update"]
|
|
244
|
+
if not isinstance(upd, dict) or not isinstance(upd.get("metric_id"), str) or not upd["metric_id"].strip():
|
|
245
|
+
raise ValueError(f"expected_update needs a metric_id, got {upd!r}")
|
|
246
|
+
maql = _strings(upd["maql"], "expected_update.maql") if "maql" in upd else ()
|
|
247
|
+
rest = {k: v for k, v in upd.items() if k not in ("metric_id", "maql")}
|
|
248
|
+
unknown_upd = sorted(set(rest) - set(_UPDATE_KEYS))
|
|
249
|
+
if unknown_upd:
|
|
250
|
+
raise ValueError(f"expected_update: unknown key(s) {unknown_upd}; allowed: {['metric_id', *_UPDATE_KEYS]}")
|
|
251
|
+
if not rest and not maql:
|
|
252
|
+
raise ValueError("expected_update must list at least one field that changes")
|
|
253
|
+
update = UpdateSpec(
|
|
254
|
+
metric_id=upd["metric_id"],
|
|
255
|
+
fields=_field_spec(rest, "expected_update", _FIELD_KEYS) if rest else FieldSpec(),
|
|
256
|
+
maql=maql,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
metrics: tuple[tuple[str, ...], ...] = ()
|
|
260
|
+
if "expected_metrics" in raw:
|
|
261
|
+
entries = raw["expected_metrics"]
|
|
262
|
+
if not isinstance(entries, list) or len(entries) < 2:
|
|
263
|
+
raise ValueError(f"expected_metrics must list at least two metrics, got {entries!r}")
|
|
264
|
+
parsed: list[tuple[str, ...]] = []
|
|
265
|
+
for i, entry in enumerate(entries):
|
|
266
|
+
source = entry.get("candidates", entry.get("maql")) if isinstance(entry, dict) else entry
|
|
267
|
+
parsed.append(tuple(c["maql"] for c in _candidates(source, f"expected_metrics[{i}]")))
|
|
268
|
+
for ref in _PLACEHOLDER_RE.findall(" ".join(parsed[-1])):
|
|
269
|
+
if int(ref) >= i:
|
|
270
|
+
raise ValueError(
|
|
271
|
+
f"expected_metrics[{i}] refers to {{metric/@{ref}}}, which is not an earlier entry"
|
|
272
|
+
)
|
|
273
|
+
metrics = tuple(parsed)
|
|
274
|
+
|
|
275
|
+
no_deletion = _strings(raw["expect_no_deletion"], "expect_no_deletion") if "expect_no_deletion" in raw else ()
|
|
276
|
+
executes = _flag(raw, "expect_executes")
|
|
277
|
+
suggestions = _flag(raw, "expect_suggestions")
|
|
278
|
+
no_overwrite = _flag(raw, "expect_no_overwrite")
|
|
279
|
+
if no_create and (candidates or metrics or fields or update or executes or suggestions):
|
|
280
|
+
raise ValueError(
|
|
281
|
+
"expect_no_create cannot be combined with candidates, expected_metrics, expected_fields, "
|
|
282
|
+
"expected_update, expect_executes or expect_suggestions: each needs a written metric"
|
|
283
|
+
)
|
|
284
|
+
if (executes or suggestions) and not (candidates or fields):
|
|
285
|
+
raise ValueError("expect_executes and expect_suggestions need candidates or expected_fields: a metric to judge")
|
|
286
|
+
if update and no_overwrite:
|
|
287
|
+
raise ValueError("expected_update writes over an existing metric, which expect_no_overwrite forbids")
|
|
288
|
+
if mentions and not no_create:
|
|
289
|
+
raise ValueError("expected_mentions needs expect_no_create")
|
|
290
|
+
if run_all and not replies:
|
|
291
|
+
raise ValueError("run_all_replies needs user_replies")
|
|
292
|
+
if metrics and (candidates or not replies):
|
|
293
|
+
raise ValueError("expected_metrics needs user_replies and replaces candidates")
|
|
294
|
+
if update and candidates:
|
|
295
|
+
raise ValueError("expected_update carries its own maql; drop candidates")
|
|
296
|
+
|
|
297
|
+
spec = MetricExpectation(
|
|
298
|
+
candidates=candidates,
|
|
299
|
+
legacy=False,
|
|
300
|
+
user_replies=replies,
|
|
301
|
+
run_all_replies=run_all,
|
|
302
|
+
expect_no_create=no_create,
|
|
303
|
+
expected_mentions=mentions,
|
|
304
|
+
expect_no_overwrite=no_overwrite,
|
|
305
|
+
expect_clarification=_flag(raw, "expect_clarification"),
|
|
306
|
+
confirmation_turn=confirmation_turn,
|
|
307
|
+
rubric=rubric,
|
|
308
|
+
expected_fields=fields,
|
|
309
|
+
expected_update=update,
|
|
310
|
+
expected_metrics=metrics,
|
|
311
|
+
expect_no_deletion=no_deletion,
|
|
312
|
+
expect_executes=executes,
|
|
313
|
+
score_first_proposal=_flag(raw, "score_first_proposal"),
|
|
314
|
+
expect_suggestions=suggestions,
|
|
315
|
+
)
|
|
316
|
+
if spec.score_first_proposal and not candidates:
|
|
317
|
+
raise ValueError("score_first_proposal needs candidates")
|
|
318
|
+
# Checks of what the agent must do. expect_no_create counts: a completed answer without a write is its point.
|
|
319
|
+
# expect_no_overwrite, confirmation_turn and expect_no_deletion only forbid, so alone they pass an agent that
|
|
320
|
+
# does nothing at all.
|
|
321
|
+
if not (candidates or no_create or metrics or update or fields or spec.expect_clarification or rubric):
|
|
322
|
+
if no_overwrite or confirmation_turn is not None or no_deletion:
|
|
323
|
+
raise ValueError(
|
|
324
|
+
"expect_no_overwrite, confirmation_turn and expect_no_deletion pass an agent that does nothing; "
|
|
325
|
+
"add candidates, expected_fields, expected_update, expected_metrics, expect_no_create, "
|
|
326
|
+
"expect_clarification or a rubric"
|
|
327
|
+
)
|
|
328
|
+
raise ValueError("expected_output checks nothing: give candidates or at least one expect_* key")
|
|
329
|
+
return spec
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def format_matches_kind(fmt: str, kind: str) -> bool:
|
|
333
|
+
"""Whether a number format string shows the given kind of number. A missing format shows no kind."""
|
|
334
|
+
if not fmt.strip():
|
|
335
|
+
return False
|
|
336
|
+
if kind == "percent":
|
|
337
|
+
return "%" in fmt
|
|
338
|
+
if kind == "currency":
|
|
339
|
+
return any(mark in fmt for mark in _CURRENCY_MARKS)
|
|
340
|
+
if kind == "integer":
|
|
341
|
+
return _DECIMAL_RE.search(fmt) is None
|
|
342
|
+
return _DECIMAL_RE.search(fmt) is not None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _norm_text(value: Any) -> str:
|
|
346
|
+
return " ".join(str(value or "").split()).casefold()
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _tags(value: Any) -> frozenset[str]:
|
|
350
|
+
return frozenset(_norm_text(t) for t in (value or []))
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def stored_fields(attributes: dict) -> dict:
|
|
354
|
+
"""The comparable fields of a metric's entity attributes: every writable one, none the server manages."""
|
|
355
|
+
content = attributes.get("content") or {}
|
|
356
|
+
return {
|
|
357
|
+
"title": attributes.get("title") or "",
|
|
358
|
+
"description": attributes.get("description") or "",
|
|
359
|
+
"tags": sorted(attributes.get("tags") or []),
|
|
360
|
+
"format": content.get("format") or "",
|
|
361
|
+
"maql": content.get("maql") or "",
|
|
362
|
+
"isHidden": bool(attributes.get("isHidden")),
|
|
363
|
+
"isHiddenFromKda": bool(attributes.get("isHiddenFromKda")),
|
|
364
|
+
"conditionalFormatting": attributes.get("conditionalFormatting"),
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def field_mismatches(spec: FieldSpec, metric_id: str, attributes: dict | None) -> list[str]:
|
|
369
|
+
"""How the stored metric differs from the spec; empty when every listed field matches."""
|
|
370
|
+
if attributes is None:
|
|
371
|
+
return [f"metric {metric_id!r} is not stored in the workspace"]
|
|
372
|
+
stored = stored_fields(attributes)
|
|
373
|
+
out: list[str] = []
|
|
374
|
+
if spec.metric_id is not None and spec.metric_id != metric_id:
|
|
375
|
+
out.append(f"metric_id: expected {spec.metric_id!r}, got {metric_id!r}")
|
|
376
|
+
if spec.title is not None and _norm_text(spec.title) != _norm_text(stored["title"]):
|
|
377
|
+
out.append(f"title: expected {spec.title!r}, got {stored['title']!r}")
|
|
378
|
+
if spec.format is not None and spec.format.strip() != stored["format"].strip():
|
|
379
|
+
out.append(f"format: expected {spec.format!r}, got {stored['format']!r}")
|
|
380
|
+
if spec.format_kind is not None and not format_matches_kind(stored["format"], spec.format_kind):
|
|
381
|
+
out.append(f"format: expected a {spec.format_kind} format, got {stored['format']!r}")
|
|
382
|
+
out += [f"format: {s!r} not in {stored['format']!r}" for s in spec.format_contains if s not in stored["format"]]
|
|
383
|
+
if spec.description is not None and spec.description.strip() != stored["description"].strip():
|
|
384
|
+
out.append(f"description: expected {spec.description!r}, got {stored['description']!r}")
|
|
385
|
+
out += [
|
|
386
|
+
f"description: {s!r} not in {stored['description']!r}"
|
|
387
|
+
for s in spec.description_contains
|
|
388
|
+
if _norm_text(s) not in _norm_text(stored["description"])
|
|
389
|
+
]
|
|
390
|
+
if spec.tags is not None and _tags(spec.tags) != _tags(stored["tags"]):
|
|
391
|
+
out.append(f"tags: expected {sorted(spec.tags)}, got {stored['tags']}")
|
|
392
|
+
missing = _tags(spec.tags_include) - _tags(stored["tags"])
|
|
393
|
+
if missing:
|
|
394
|
+
out.append(f"tags: {sorted(missing)} missing from {stored['tags']}")
|
|
395
|
+
return out
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def update_mismatches(spec: UpdateSpec, before: dict | None, after: dict | None) -> list[str]:
|
|
399
|
+
"""How an update differs from the spec: a listed field did not change as asked, or another field moved."""
|
|
400
|
+
if before is None:
|
|
401
|
+
return [f"metric {spec.metric_id!r} did not exist before the run"]
|
|
402
|
+
out = field_mismatches(spec.fields, spec.metric_id, after)
|
|
403
|
+
if after is None:
|
|
404
|
+
return out
|
|
405
|
+
old, new = stored_fields(before), stored_fields(after)
|
|
406
|
+
if spec.maql and not any(normalize_maql(m) == normalize_maql(new["maql"]) for m in spec.maql):
|
|
407
|
+
out.append(f"maql: expected one of {list(spec.maql)}, got {new['maql']!r}")
|
|
408
|
+
listed = {
|
|
409
|
+
"title": spec.fields.title is not None,
|
|
410
|
+
"description": spec.fields.description is not None or bool(spec.fields.description_contains),
|
|
411
|
+
"tags": spec.fields.tags is not None or bool(spec.fields.tags_include),
|
|
412
|
+
"format": spec.fields.format is not None
|
|
413
|
+
or spec.fields.format_kind is not None
|
|
414
|
+
or bool(spec.fields.format_contains),
|
|
415
|
+
"maql": bool(spec.maql),
|
|
416
|
+
}
|
|
417
|
+
for key in old:
|
|
418
|
+
same = normalize_maql(old[key]) == normalize_maql(new[key]) if key == "maql" else old[key] == new[key]
|
|
419
|
+
if listed.get(key) and same:
|
|
420
|
+
# The final value matching is not enough: a request already met before the run proves no update.
|
|
421
|
+
out.append(f"{key} did not change although the request asked for it: still {new[key]!r}")
|
|
422
|
+
elif not listed.get(key) and not same:
|
|
423
|
+
out.append(f"{key} changed although the request did not ask for it: {old[key]!r} -> {new[key]!r}")
|
|
424
|
+
return out
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def substitute_placeholders(maql: str, created_ids: list[str | None]) -> str:
|
|
428
|
+
"""Replace ``{metric/@n}`` with the id of the metric matched for entry n."""
|
|
429
|
+
|
|
430
|
+
def _sub(match: re.Match) -> str:
|
|
431
|
+
index = int(match.group(1))
|
|
432
|
+
metric_id = created_ids[index] if index < len(created_ids) else None
|
|
433
|
+
return f"{{metric/{metric_id}}}" if metric_id else match.group(0)
|
|
434
|
+
|
|
435
|
+
return _PLACEHOLDER_RE.sub(_sub, maql)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def first_proposed_maql(texts: list[str]) -> str | None:
|
|
439
|
+
"""The MAQL of the first formula the agent showed in a code span or a fenced block, if any."""
|
|
440
|
+
for text in texts:
|
|
441
|
+
found = _PROPOSED_MAQL_RE.search(text or "")
|
|
442
|
+
if found:
|
|
443
|
+
return (found.group(1) or found.group(2)).strip()
|
|
444
|
+
return None
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def missing_mentions(mentions: tuple[str, ...], texts: list[str]) -> list[str]:
|
|
448
|
+
"""The expected mentions no agent reply names, compared case-insensitively."""
|
|
449
|
+
joined = _norm_text(" ".join(texts))
|
|
450
|
+
return [m for m in mentions if _norm_text(m) not in joined]
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# (C) 2026 GoodData Corporation. All rights reserved.
|
|
2
|
+
"""Workspace access the metric-skill evaluator needs beyond the chat: the metrics, a test execution, the conversation
|
|
3
|
+
history.
|
|
4
|
+
|
|
5
|
+
Metrics are read through the SDK's entity API. Restores go through the metric entity endpoint, never through the
|
|
6
|
+
agent's ``create_metric`` tool: that tool writes its defaults over any field it is not given, so a restore through it
|
|
7
|
+
would change the metric it tries to restore.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import functools
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
from gooddata_api_client.exceptions import ApiException, NotFoundException
|
|
18
|
+
from gooddata_sdk import GoodDataSdk
|
|
19
|
+
from gooddata_sdk.utils import load_all_entities
|
|
20
|
+
|
|
21
|
+
from gooddata_eval.core._retry import RETRYABLE_STATUS_CODES, is_retryable_request_error, retry_transient
|
|
22
|
+
from gooddata_eval.core.agentic._clarification import _page_with_retry
|
|
23
|
+
|
|
24
|
+
_METRICS = "/api/v1/entities/workspaces/{ws}/metrics"
|
|
25
|
+
_EXECUTE = "/api/v1/actions/workspaces/{ws}/execution/afm/execute"
|
|
26
|
+
_ITEMS = "/api/v1/ai/workspaces/{ws}/chat/conversations/{conversation_id}/items"
|
|
27
|
+
_JSON_API = "application/vnd.gooddata.api+json"
|
|
28
|
+
# Every attribute a metric write accepts except areRelationsValid, which the server computes.
|
|
29
|
+
_WRITABLE = ("title", "description", "tags", "content", "isHidden", "isHiddenFromKda", "conditionalFormatting")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class WorkspaceReadError(RuntimeError):
|
|
33
|
+
"""The harness could not read the workspace or the conversation, so the run cannot be scored."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _TransientStatus(Exception):
|
|
37
|
+
"""A request answered with a retryable status; carries the response for the final report."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, response: httpx.Response):
|
|
40
|
+
super().__init__(f"HTTP {response.status_code}")
|
|
41
|
+
self.response = response
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_transient_request(exc: Exception) -> bool:
|
|
45
|
+
return isinstance(exc, _TransientStatus) or is_retryable_request_error(exc)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class MetricWorkspace:
|
|
49
|
+
"""Reads and restores one workspace's metrics, executes a metric, and reads a conversation's items."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, host: str, token: str, workspace_id: str, sdk: GoodDataSdk, *, timeout: float = 60.0):
|
|
52
|
+
self._base = host.rstrip("/")
|
|
53
|
+
self._ws = workspace_id
|
|
54
|
+
self._entities = sdk._client.entities_api
|
|
55
|
+
self._auth = {"Authorization": f"Bearer {token}"}
|
|
56
|
+
self._client = httpx.Client(timeout=timeout)
|
|
57
|
+
# Metrics a run could not put back; while any is listed, later runs are not driven.
|
|
58
|
+
self.unrestored: list[str] = []
|
|
59
|
+
|
|
60
|
+
def close(self) -> None:
|
|
61
|
+
self._client.close()
|
|
62
|
+
|
|
63
|
+
def list_metrics(self) -> dict[str, dict]:
|
|
64
|
+
"""Every metric of the workspace, as metric id -> entity attributes.
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
WorkspaceReadError: A page could not be read after the transient retries.
|
|
68
|
+
"""
|
|
69
|
+
list_page = functools.partial(self._entities.get_all_entities_metrics, self._ws, _check_return_type=False)
|
|
70
|
+
try:
|
|
71
|
+
data = load_all_entities(functools.partial(_page_with_retry, list_page)).data
|
|
72
|
+
except (ApiException, httpx.HTTPError, OSError) as exc:
|
|
73
|
+
raise WorkspaceReadError(f"could not list metrics: {exc}") from exc
|
|
74
|
+
out: dict[str, dict] = {}
|
|
75
|
+
for obj in data:
|
|
76
|
+
# A row the run could not restore from makes the snapshot useless, so it fails the snapshot.
|
|
77
|
+
attributes = obj.get("attributes") if isinstance(obj, dict) else None
|
|
78
|
+
if not isinstance(obj, dict) or not obj.get("id") or not isinstance(attributes, dict):
|
|
79
|
+
raise WorkspaceReadError(f"could not list metrics: unreadable row {obj!r}")
|
|
80
|
+
if not isinstance(attributes.get("content"), dict) or not attributes["content"].get("maql"):
|
|
81
|
+
raise WorkspaceReadError(f"could not list metrics: metric {obj['id']!r} has no MAQL")
|
|
82
|
+
out[obj["id"]] = attributes
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
def get_metric(self, metric_id: str) -> dict | None:
|
|
86
|
+
"""One metric's entity attributes, or None when it does not exist.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
WorkspaceReadError: The lookup failed for a reason other than a 404.
|
|
90
|
+
"""
|
|
91
|
+
try:
|
|
92
|
+
doc = self._entities.get_entity_metrics(self._ws, metric_id, _check_return_type=False)
|
|
93
|
+
except NotFoundException:
|
|
94
|
+
return None
|
|
95
|
+
except (ApiException, httpx.HTTPError, OSError) as exc:
|
|
96
|
+
raise WorkspaceReadError(f"could not read metric {metric_id}: {exc}") from exc
|
|
97
|
+
# The document is a model even with _check_return_type=False; only its data is a plain dict.
|
|
98
|
+
data = doc.get("data") if isinstance(doc, dict) else getattr(doc, "data", None)
|
|
99
|
+
attributes = data.get("attributes") if isinstance(data, dict) else None
|
|
100
|
+
if not isinstance(attributes, dict):
|
|
101
|
+
raise WorkspaceReadError(f"could not read metric {metric_id}: no attributes in {data!r}")
|
|
102
|
+
return attributes
|
|
103
|
+
|
|
104
|
+
def restore_metric(self, metric_id: str, attributes: dict, *, exists: bool) -> bool:
|
|
105
|
+
"""Write a metric back to the given attributes, retrying transient failures; True on success.
|
|
106
|
+
|
|
107
|
+
A failure is printed, not raised: the caller reports it as a harness error.
|
|
108
|
+
"""
|
|
109
|
+
body = {
|
|
110
|
+
"data": {
|
|
111
|
+
"id": metric_id,
|
|
112
|
+
"type": "metric",
|
|
113
|
+
"attributes": {k: attributes[k] for k in _WRITABLE if attributes.get(k) is not None},
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
base = f"{self._base}{_METRICS.format(ws=self._ws)}"
|
|
117
|
+
headers = {**self._auth, "Content-Type": _JSON_API}
|
|
118
|
+
|
|
119
|
+
def _send() -> httpx.Response:
|
|
120
|
+
if exists:
|
|
121
|
+
resp = self._client.put(f"{base}/{metric_id}", json=body, headers=headers)
|
|
122
|
+
else:
|
|
123
|
+
resp = self._client.post(base, json=body, headers=headers)
|
|
124
|
+
if resp.status_code in RETRYABLE_STATUS_CODES:
|
|
125
|
+
raise _TransientStatus(resp)
|
|
126
|
+
return resp
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
resp = retry_transient(_send, is_retryable=_is_transient_request)
|
|
130
|
+
except _TransientStatus as exc:
|
|
131
|
+
resp = exc.response
|
|
132
|
+
except httpx.HTTPError as exc:
|
|
133
|
+
print(f"[CLEANUP] Could not restore metric {metric_id}: {exc}")
|
|
134
|
+
return False
|
|
135
|
+
if not resp.is_success:
|
|
136
|
+
print(f"[CLEANUP] Could not restore metric {metric_id}: HTTP {resp.status_code} {resp.text[:200]}")
|
|
137
|
+
return resp.is_success
|
|
138
|
+
|
|
139
|
+
def execute_metric(self, metric_id: str) -> str | None:
|
|
140
|
+
"""Compute the metric alone; None when it computes, else the reason the platform gave.
|
|
141
|
+
|
|
142
|
+
Only a 4xx rejection is a reason. A rate limit (429) or a service fault (5xx) is retried, and one that
|
|
143
|
+
outlasts the retries is raised: it says nothing about the metric.
|
|
144
|
+
|
|
145
|
+
Raises:
|
|
146
|
+
WorkspaceReadError: The request did not reach the platform, the platform did not serve it, or its
|
|
147
|
+
answer was unreadable.
|
|
148
|
+
"""
|
|
149
|
+
afm = {
|
|
150
|
+
"execution": {
|
|
151
|
+
"measures": [
|
|
152
|
+
{
|
|
153
|
+
"localIdentifier": "m",
|
|
154
|
+
"definition": {"measure": {"item": {"identifier": {"id": metric_id, "type": "metric"}}}},
|
|
155
|
+
}
|
|
156
|
+
],
|
|
157
|
+
"attributes": [],
|
|
158
|
+
"filters": [],
|
|
159
|
+
},
|
|
160
|
+
"resultSpec": {"dimensions": [{"localIdentifier": "d", "itemIdentifiers": ["measureGroup"]}]},
|
|
161
|
+
}
|
|
162
|
+
url = f"{self._base}{_EXECUTE.format(ws=self._ws)}"
|
|
163
|
+
|
|
164
|
+
def _served(step: str, send: Callable[[], httpx.Response]) -> httpx.Response:
|
|
165
|
+
"""The response once it is no rate limit or service fault, retrying those; raises when they persist."""
|
|
166
|
+
|
|
167
|
+
def _attempt() -> httpx.Response:
|
|
168
|
+
resp = send()
|
|
169
|
+
if resp.status_code in RETRYABLE_STATUS_CODES:
|
|
170
|
+
raise _TransientStatus(resp)
|
|
171
|
+
return resp
|
|
172
|
+
|
|
173
|
+
try:
|
|
174
|
+
resp = retry_transient(_attempt, is_retryable=_is_transient_request)
|
|
175
|
+
except _TransientStatus as exc:
|
|
176
|
+
resp = exc.response
|
|
177
|
+
if resp.status_code in RETRYABLE_STATUS_CODES or resp.status_code >= 500:
|
|
178
|
+
raise WorkspaceReadError(f"could not execute metric {metric_id}: {step} HTTP {resp.status_code}")
|
|
179
|
+
return resp
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
resp = _served(
|
|
183
|
+
"execute",
|
|
184
|
+
lambda: self._client.post(url, json=afm, headers={**self._auth, "Content-Type": "application/json"}),
|
|
185
|
+
)
|
|
186
|
+
if not resp.is_success:
|
|
187
|
+
return f"execute: HTTP {resp.status_code} {resp.text[:300]}"
|
|
188
|
+
body = resp.json()
|
|
189
|
+
response = body.get("executionResponse") if isinstance(body, dict) else None
|
|
190
|
+
links = response.get("links") if isinstance(response, dict) else None
|
|
191
|
+
result_id = links.get("executionResult") if isinstance(links, dict) else None
|
|
192
|
+
if not isinstance(result_id, str) or not result_id:
|
|
193
|
+
raise WorkspaceReadError(f"could not execute metric {metric_id}: no executionResult in {body!r}"[:400])
|
|
194
|
+
result = _served("result", lambda: self._client.get(f"{url}/result/{result_id}", headers=self._auth))
|
|
195
|
+
if not result.is_success:
|
|
196
|
+
return f"result: HTTP {result.status_code} {result.text[:300]}"
|
|
197
|
+
computed = result.json()
|
|
198
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
199
|
+
raise WorkspaceReadError(f"could not execute metric {metric_id}: {type(exc).__name__}: {exc}") from exc
|
|
200
|
+
if not isinstance(computed, dict) or not isinstance(computed.get("data"), list):
|
|
201
|
+
# A computed result carries its data list, empty or not; a 200 without one proves no computation.
|
|
202
|
+
raise WorkspaceReadError(f"could not execute metric {metric_id}: no data list in {str(computed)[:200]}")
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
def conversation_items(self, conversation_id: str) -> list[dict[str, Any]]:
|
|
206
|
+
"""The conversation's stored items, oldest first.
|
|
207
|
+
|
|
208
|
+
Raises:
|
|
209
|
+
WorkspaceReadError: The items could not be read.
|
|
210
|
+
"""
|
|
211
|
+
try:
|
|
212
|
+
resp = self._client.get(
|
|
213
|
+
f"{self._base}{_ITEMS.format(ws=self._ws, conversation_id=conversation_id)}", headers=self._auth
|
|
214
|
+
)
|
|
215
|
+
resp.raise_for_status()
|
|
216
|
+
body = resp.json()
|
|
217
|
+
except (httpx.HTTPError, ValueError) as exc:
|
|
218
|
+
raise WorkspaceReadError(f"could not read conversation {conversation_id}: {exc}") from exc
|
|
219
|
+
key = next((k for k in ("items", "data") if isinstance(body, dict) and k in body), None)
|
|
220
|
+
items = body[key] if key is not None else None
|
|
221
|
+
if not isinstance(items, list):
|
|
222
|
+
# A shape without its items list would read as a conversation with no suggestions, and pass.
|
|
223
|
+
raise WorkspaceReadError(f"conversation {conversation_id}: no items list in {str(body)[:200]}")
|
|
224
|
+
return items
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def last_suggestions(items: list[dict[str, Any]]) -> dict | None:
|
|
228
|
+
"""The suggestions of the latest assistant item that carries them."""
|
|
229
|
+
for item in reversed(items):
|
|
230
|
+
content = item.get("content") if isinstance(item, dict) else None
|
|
231
|
+
if isinstance(content, dict) and isinstance(content.get("suggestions"), dict):
|
|
232
|
+
return content["suggestions"]
|
|
233
|
+
return None
|