gooddata-eval 1.80.1.dev4__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/cli/agentic_runner.py +28 -10
- gooddata_eval/core/agentic/_metric_expectation.py +450 -0
- gooddata_eval/core/agentic/_metric_workspace.py +233 -0
- gooddata_eval/core/agentic/_search_expectation.py +310 -0
- gooddata_eval/core/agentic/alert_skill.py +20 -2
- gooddata_eval/core/agentic/metric_skill.py +601 -56
- gooddata_eval/core/agentic/search_tool.py +421 -89
- gooddata_eval/core/agentic/visualization.py +14 -5
- {gooddata_eval-1.80.1.dev4.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/METADATA +2 -2
- {gooddata_eval-1.80.1.dev4.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/RECORD +13 -10
- {gooddata_eval-1.80.1.dev4.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/WHEEL +0 -0
- {gooddata_eval-1.80.1.dev4.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/entry_points.txt +0 -0
- {gooddata_eval-1.80.1.dev4.dist-info → gooddata_eval-1.80.1.dev6.dist-info}/licenses/LICENSE.txt +0 -0
|
@@ -11,6 +11,7 @@ from typing import Any, TypedDict
|
|
|
11
11
|
|
|
12
12
|
from gooddata_eval.core.agentic._gate import DEFAULT_GATE, EvalGate, normalize_gate
|
|
13
13
|
from gooddata_eval.core.agentic._langfuse import make_langfuse_client
|
|
14
|
+
from gooddata_eval.core.agentic._search_expectation import SEARCH_ARGUMENT_KEYS
|
|
14
15
|
from gooddata_eval.core.agentic._trace_linker import BackgroundTraceLinker, SubmitTraceLink, run_trace_link_inline
|
|
15
16
|
from gooddata_eval.core.agentic.alert_skill import evaluate_agentic_alert_skill
|
|
16
17
|
from gooddata_eval.core.agentic.anomaly_detection import evaluate_agentic_anomaly_detection
|
|
@@ -81,7 +82,8 @@ UNGATED_AGENTIC_TEST_KINDS = frozenset({"agentic_conversation"})
|
|
|
81
82
|
# reads like a model regression.
|
|
82
83
|
#
|
|
83
84
|
# agentic_general_question, agentic_guardrail answer questions only, no tool writes
|
|
84
|
-
# agentic_search search_objects, read-only by definition
|
|
85
|
+
# agentic_search search_objects, read-only by definition; an item
|
|
86
|
+
# with setup_turns runs serially (item_runs_in_parallel)
|
|
85
87
|
# vis_agentic, agentic_visualization visualizations come back as AAC proposals
|
|
86
88
|
# in the chat response; nothing is persisted
|
|
87
89
|
# and neither module has cleanup code
|
|
@@ -115,6 +117,18 @@ def runs_in_parallel(test_kind: str) -> bool:
|
|
|
115
117
|
return test_kind in PARALLEL_SAFE_TEST_KINDS
|
|
116
118
|
|
|
117
119
|
|
|
120
|
+
def item_runs_in_parallel(item: DatasetItem) -> bool:
|
|
121
|
+
"""True for an item of a cleared kind that sends nothing the clearance does not cover.
|
|
122
|
+
|
|
123
|
+
``agentic_search`` is cleared for its search. An item's ``setup_turns`` are free text sent before the question,
|
|
124
|
+
and nothing stops one from asking the agent to save something, so such an item runs serially.
|
|
125
|
+
"""
|
|
126
|
+
if not runs_in_parallel(item.test_kind):
|
|
127
|
+
return False
|
|
128
|
+
eo = item.expected_output
|
|
129
|
+
return not (item.test_kind == "agentic_search" and isinstance(eo, dict) and "setup_turns" in eo)
|
|
130
|
+
|
|
131
|
+
|
|
118
132
|
def _parse_visualization_expected(expected_output: Any) -> list[CreatedVisualization]:
|
|
119
133
|
"""Parse expected_output into a list of CreatedVisualization candidates.
|
|
120
134
|
|
|
@@ -253,15 +267,18 @@ def _dispatch_agentic(
|
|
|
253
267
|
**lf_kw,
|
|
254
268
|
)
|
|
255
269
|
elif kind == "agentic_search":
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
270
|
+
if not isinstance(eo, dict):
|
|
271
|
+
raise ValueError(f"agentic_search expected_output must be an object, got {eo!r}")
|
|
272
|
+
eo_dict = eo
|
|
273
|
+
# Anything but bare search_objects arguments is parsed as an item, so an unknown key fails it.
|
|
274
|
+
is_item_shape = "tool_call" in eo_dict or not eo_dict.keys() <= SEARCH_ARGUMENT_KEYS
|
|
259
275
|
return evaluate_agentic_search_tool(
|
|
260
276
|
host=host,
|
|
261
277
|
token=token,
|
|
262
278
|
workspace_id=workspace_id,
|
|
263
279
|
question=item.question,
|
|
264
|
-
expected_tool_call=
|
|
280
|
+
expected_tool_call=None if is_item_shape else eo_dict,
|
|
281
|
+
expected_output=eo_dict if is_item_shape else None,
|
|
265
282
|
k=k,
|
|
266
283
|
gate=gate,
|
|
267
284
|
agent_id=agent_id,
|
|
@@ -485,7 +502,8 @@ def run_agentic_items(
|
|
|
485
502
|
) -> EvalReport:
|
|
486
503
|
"""Run agentic items through evaluate_agentic_* and return an EvalReport.
|
|
487
504
|
|
|
488
|
-
``concurrency`` > 1 runs PARALLEL_SAFE_TEST_KINDS items simultaneously
|
|
505
|
+
``concurrency`` > 1 runs PARALLEL_SAFE_TEST_KINDS items simultaneously, except those
|
|
506
|
+
``item_runs_in_parallel`` holds back.
|
|
489
507
|
WORKSPACE_MUTATING_TEST_KINDS items always run one at a time, and in a separate phase
|
|
490
508
|
from the parallel ones -- a metric being created and dropped mid-run would otherwise be
|
|
491
509
|
visible to a catalog-reading item running alongside it.
|
|
@@ -637,13 +655,13 @@ def run_agentic_items(
|
|
|
637
655
|
concurrency = max(1, concurrency)
|
|
638
656
|
indexed = list(enumerate(items, start=1))
|
|
639
657
|
if concurrency > 1:
|
|
640
|
-
parallel = [(i, it) for i, it in indexed if
|
|
641
|
-
serial = [(i, it) for i, it in indexed if not
|
|
658
|
+
parallel = [(i, it) for i, it in indexed if item_runs_in_parallel(it)]
|
|
659
|
+
serial = [(i, it) for i, it in indexed if not item_runs_in_parallel(it)]
|
|
642
660
|
if not parallel and serial:
|
|
643
661
|
blocked = ", ".join(sorted({it.test_kind for _, it in serial}))
|
|
644
662
|
print(
|
|
645
|
-
f"warning: --concurrency {concurrency} has no effect here; every item is a "
|
|
646
|
-
|
|
663
|
+
f"warning: --concurrency {concurrency} has no effect here; every item ({blocked}) is a "
|
|
664
|
+
"workspace-mutating kind or a search item with setup turns, and those always run one at a time.",
|
|
647
665
|
file=sys.stderr,
|
|
648
666
|
)
|
|
649
667
|
else:
|
|
@@ -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]
|