gooddata-eval 1.81.1.dev4__py3-none-any.whl → 1.81.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.
@@ -338,7 +338,9 @@ def _dispatch_agentic(
338
338
  token=token,
339
339
  workspace_id=workspace_id,
340
340
  question=item.question,
341
- expected_output=eo if isinstance(eo, dict) else {},
341
+ # Passed as stored: the evaluator rejects a non-object expectation, None included, instead
342
+ # of running it with nothing pinned.
343
+ expected_output=eo,
342
344
  k=k,
343
345
  gate=gate,
344
346
  agent_id=agent_id,
@@ -26,6 +26,7 @@ import re
26
26
  from dataclasses import dataclass
27
27
  from typing import Literal
28
28
 
29
+ from gooddata_eval.core.chat.sse_client import ADHOC_VIZ_ID
29
30
  from gooddata_eval.core.config import judge_model
30
31
  from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError, LLMJudge, _message_content
31
32
  from gooddata_eval.core.models import ChatResult
@@ -77,6 +78,136 @@ _REQUEST_RE = re.compile(
77
78
  re.IGNORECASE,
78
79
  )
79
80
 
81
+ # The dashboard editor shows an existing chart and then stops until the user asks for it to be
82
+ # placed, so that turn ends by asking to go ahead with a placement, in words the approval phrases
83
+ # above do not cover. Read on a dashboard edit only (classify_edit_reply): elsewhere "Should I
84
+ # replace the filter?" is not a step any skill's flow defines.
85
+ _PLACEMENT_VERBS = r"replace|place|put|swap|add|insert|move"
86
+ _PLACEMENT_VERB_RE = re.compile(rf"\b(?:{_PLACEMENT_VERBS})\b", re.IGNORECASE)
87
+ # The verbs name filters and other widgets too ("Do you want me to add anything else?", "Should I replace
88
+ # the date filter?"), so one counts only when a chart is what it places: a pronoun or a chart noun close
89
+ # after it ("put it there", "replace Order breakdown with this chart", "replace Order breakdown with it"),
90
+ # or, once the conversation has shown a chart, any object but a lowercase "filter" (a title such as
91
+ # "Filter Usage" is a chart) or an open "anything else" ("I'll replace Order Breakdown in the same
92
+ # position"). "With it" names the chart, so "replace the date filter with it" still places one.
93
+ _CHART_NOUNS = r"charts?|visualizations?|insights?"
94
+ _PLACED_CHART_RE = re.compile(
95
+ rf"\b(?:{_PLACEMENT_VERBS})\s+(?:\S+\s+)?(?:it|them)\b"
96
+ rf"|\b(?:{_PLACEMENT_VERBS})\s+(?:\S+\s+){{0,5}}?(?:{_CHART_NOUNS})\b"
97
+ rf"|\b(?:{_PLACEMENT_VERBS})\b[^,;]*?\bwith\s+(?:it|them|(?:this|that|the)\s+(?:new\s+)?(?:{_CHART_NOUNS}))\b",
98
+ re.IGNORECASE,
99
+ )
100
+ _PLACED_ANYTHING_RE = re.compile(
101
+ rf"\b(?:{_PLACEMENT_VERBS})\b(?!\s+(?:anything|something|more|else|another)\b)"
102
+ r"(?!\s+(?:\S+\s+){0,3}?(?-i:filters?)\b)",
103
+ re.IGNORECASE,
104
+ )
105
+ _IF_YOU_WANT_ME_TO = r"\b(?:if|when|once|whether)\s+you(?:['’]d|\s+would)?\s+(?:want|like)\s+me\s+to\s+"
106
+ _PLACEMENT_ASK_RE = re.compile(
107
+ rf"(?:{_SHOULD_I}|{_WANT_ME_TO}|{_IF_YOU_WANT_ME_TO})(?:{_PLACEMENT_VERBS})\b",
108
+ re.IGNORECASE,
109
+ )
110
+ # These name no placement of their own ("Once you confirm the new title, I'll rename it"), so they
111
+ # count only in a sentence that places a chart (_PLACED_CHART_RE).
112
+ _GO_AHEAD_RE = re.compile(
113
+ r"\b(?:once|when|after|if)\s+you\s+confirm\b"
114
+ r"|\bconfirm,?\s+and\s+i(?:['’]ll|\s+will)\b"
115
+ rf"|\b(?:tell|ask)\s+me\s+to\s+(?:{_PLACEMENT_VERBS}|{_APPROVAL_VERBS})\b",
116
+ re.IGNORECASE,
117
+ )
118
+ # Beside a chart the same reply shows, an offer to place it ("I can replace Order breakdown with it",
119
+ # "Top 10 Buyers is ready to replace Order breakdown") is that same stop, put as a statement. Without a
120
+ # chart shown it is no step of the flow, so it stays a reply that did nothing.
121
+ _PLACEMENT_OFFER_RE = re.compile(
122
+ rf"\b(?:i\s+can|i\s+could|(?:is|are|am|i['’]m)\s+ready\s+to)\s+(?:{_PLACEMENT_VERBS})\b",
123
+ re.IGNORECASE,
124
+ )
125
+ # "Where should I place them?" and "Which chart should I replace?" ask for something a yes does not
126
+ # supply, so the placement verb in them is no request to go ahead.
127
+ _WH_ASK_RE = re.compile(
128
+ r"\b(?:where|which|what|how|when|who|whom|whose)\b(?:\s+\w+){0,3}?\s+(?:should|shall|may|can|do|would)\s+(?:i|you)\b",
129
+ re.IGNORECASE,
130
+ )
131
+ # What a yes does not supply either: something to confirm other than going ahead ("once you confirm
132
+ # which section"; "confirm the placement" is going ahead), a value to provide ("please specify the
133
+ # size", "let me know the section") or a numbered list of placement options. A chart's description
134
+ # ("it lets you select a buyer", "it ranks 1. Alice 2. Bob", "1. Net orders on the left axis") asks
135
+ # nothing ("please select a buyer in the filter bar" included), so a request for a place counts anywhere,
136
+ # any other request only from the first placement sentence on, and a numbered list only when two of its
137
+ # items are placements.
138
+ _CONFIRM_WHAT_RE = re.compile(
139
+ r"\bconfirm\s+(?:which|where|what|how|the\s+(?:\w+\s+)?(?:size|section|tab|width|height)s?)\b",
140
+ re.IGNORECASE,
141
+ )
142
+ _PLACE_VALUES = r"size|section|tab|width|height|position|row|column|spot"
143
+ _REQUEST_VERBS = r"select|choose|pick|specify|provide|clarify|share"
144
+ _PLACE_REQUEST_RE = re.compile(
145
+ rf"\bplease\s+(?:{_REQUEST_VERBS})\s+(?:\S+\s+){{0,2}}?(?:which|where|(?:{_PLACE_VALUES})s?)\b"
146
+ rf"|\b(?:let\s+me\s+know|tell\s+me)\s+(?:which|where|(?:what|the)\s+(?:\w+\s+)?(?:{_PLACE_VALUES})s?\b"
147
+ r"|how\s+(?:wide|tall|big|large|many)\b)",
148
+ re.IGNORECASE,
149
+ )
150
+ _EDIT_REQUEST_RE = re.compile(
151
+ rf"\bplease\s+(?:{_REQUEST_VERBS})\b|\breply\s+with\b|^\s*(?:select|choose|pick)\s+(?:one|a|an|the)\b",
152
+ re.IGNORECASE,
153
+ )
154
+ _PLACE_WORDS = (
155
+ rf"{_PLACEMENT_VERBS}|above|below|before|after|left|right|top|bottom|next\s+to|section|row|tab|instead"
156
+ r"|at\s+the\s+(?:end|start|beginning)"
157
+ )
158
+ # An item of a numbered list is a placement when it opens with a placement verb ("Replace Order breakdown"),
159
+ # places "it" ("Keep Order breakdown and add it below") or opens with where to put it ("above Orders over
160
+ # time"). The noun ("Net orders per place") is no placement. A chart's
161
+ # description can name a place in every item ("1. Net orders on the left axis"), seldom a placement.
162
+ _LIST_MARKER_RE = re.compile(r"(?:^|(?<=\s))\(?([1-9])[.)](?=\s)")
163
+ _LIST_ITEM_END_RE = re.compile(r"[\n?]|\.(?:\s|$)")
164
+ _ITEM_PLACEMENT_RE = re.compile(
165
+ rf"^\s*(?:{_PLACEMENT_VERBS})\b|\b(?:{_PLACEMENT_VERBS})\s+(?:\S+\s+)?(?:it|them)\b", re.IGNORECASE
166
+ )
167
+ _ITEM_OPENS_WITH_PLACE_RE = re.compile(
168
+ r"^\s*(?:above|below|before|after|beside|under|next\s+to|instead\s+of|in\s+place\s+of"
169
+ r"|at\s+the\s+(?:top|bottom|end|start|beginning))\b",
170
+ re.IGNORECASE,
171
+ )
172
+ # A second option offered in a sentence after the placement ask: "I can also add it next to it instead".
173
+ # The sentence must offer a placement: "The chart uses net orders instead of gross orders" describes it.
174
+ _LATER_OPTION_RE = re.compile(r"\b(?:instead|otherwise)\b|\bif\s+you(?:['’]d|\s+would)?\s+prefer\b", re.IGNORECASE)
175
+ # "Should I place it before or after Orders over time?" asks where, which a yes does not answer, and
176
+ # so does "Should I place it now, or would you like to review it first?". An "or" that hands the turn
177
+ # back without a second option ("or not?", "or let me know") is no choice. Any case counts: a
178
+ # placement sentence holds no MAQL, the formula spans are masked before this is read.
179
+ # A widget's name can hold an "or" too ("Should I replace Won or Lost Deals with it?", "the same width or
180
+ # height"), so "or" offers a choice only when a place, a placement verb or a question of its own follows it
181
+ # within two words; "alternatively" always does.
182
+ _PLACEMENT_NOT_AN_OPTION = r"not\b|(?:is|are)\s+there\b|anything\b|something\b|if\s+you\b|let\s+me\s+know\b"
183
+ _OR_CHOICE_FOLLOWS = rf"{_PLACE_WORDS}|(?:would|do)\s+you\s+(?:like|want|prefer)|(?:should|shall|can)\s+i"
184
+ _PLACEMENT_CHOICE_RE = re.compile(
185
+ rf"\bor\b(?![\s,]+(?:{_PLACEMENT_NOT_AN_OPTION}))[\s,]+(?:[\w'’-]+[\s,]+){{0,2}}?(?:{_OR_CHOICE_FOLLOWS})\b"
186
+ rf"|\balternatively\b(?![\s,]+(?:{_PLACEMENT_NOT_AN_OPTION}))",
187
+ re.IGNORECASE,
188
+ )
189
+ # "Should I place it in Sales or Finance?" names two destinations: an "or" that follows the placement's
190
+ # "in", "to" or "on" within two words ("in Sales or", "to the Sales tab or") and opens another name
191
+ # ("Finance", "the Finance tab") is a choice. A lowercase word after it is no place ("or leave it", "or
192
+ # keep it as a draft", "now or later"), and the window keeps out a widget's name further on ("in place of
193
+ # Won or Lost Deals").
194
+ _DESTINATION_CHOICE_RE = re.compile(
195
+ rf"\b(?:{_PLACEMENT_VERBS})\b[^,;]*?\b(?:in|into|to|on|onto)\s+(?:the\s+)?"
196
+ rf"[“\"'‘]?[\w'’-]+[”\"'’]?(?:\s+[“\"'‘]?[\w'’-]+[”\"'’]?)?\s+or[\s,]+(?:(?:the|a|an)\s+)?(?-i:[“\"'‘]?[A-Z])",
197
+ re.IGNORECASE,
198
+ )
199
+ # "Should I place it, and how wide should it be?" asks a second thing inside the placement sentence. A
200
+ # relative clause (", which keeps the same width") asks nothing, so the clause must open with "and" or
201
+ # "but" and hold a question verb of its own.
202
+ _SECOND_ASK_RE = re.compile(
203
+ r"\b(?:and|but)\s+(?:how|which|where|what|when)\b[^?]*\b(?:should|shall|would|do|does|can|could)\b[^?]*\?",
204
+ re.IGNORECASE,
205
+ )
206
+ _OR_WORD_RE = re.compile(r"\bor\b", re.IGNORECASE)
207
+ _LEADING_CHOICE_RE = re.compile(r"\s*(?:or|alternatively)\b", re.IGNORECASE)
208
+ # "Which **section** should I place it in?": Markdown emphasis would split the words the checks read.
209
+ _EMPHASIS_RE = re.compile(r"\*+|(?<!\w)_+|_+(?!\w)")
210
+
80
211
  _MESSAGE_CHARS = 800
81
212
  _TRANSCRIPT_MESSAGES = 40
82
213
 
@@ -122,6 +253,101 @@ def asks_in_text(chat_result: ChatResult, rendered_text: str) -> bool:
122
253
  return any(s.rstrip().endswith("?") and not _CONFIRMATION_RE.search(s) for s in sentences)
123
254
 
124
255
 
256
+ def _numbered_placements(text: str) -> int:
257
+ """How many items of the reply's first numbered list (1., 2., ...) are placements."""
258
+ markers = list(_LIST_MARKER_RE.finditer(text))
259
+ start = next((i for i, m in enumerate(markers) if m.group(1) == "1"), None)
260
+ if start is None:
261
+ return 0
262
+ items: list[str] = []
263
+ for expected, (marker, following) in enumerate(
264
+ zip(markers[start:], [*markers[start + 1 :], None], strict=False), start=1
265
+ ):
266
+ if marker.group(1) != str(expected):
267
+ break
268
+ item = text[marker.end() : following.start() if following else len(text)]
269
+ if following is None or following.group(1) != str(expected + 1):
270
+ end = _LIST_ITEM_END_RE.search(item)
271
+ item = item[: end.start()] if end else item
272
+ items.append(item)
273
+ break
274
+ items.append(item)
275
+ return sum(bool(_ITEM_PLACEMENT_RE.search(i) or _ITEM_OPENS_WITH_PLACE_RE.match(i)) for i in items)
276
+
277
+
278
+ def classify_edit_reply(chat_result: ChatResult, rendered_text: str, *, shown_earlier: bool = False) -> ReplyKind:
279
+ """Kind of a dashboard-edit reply that did not produce the patch.
280
+
281
+ ``classify_reply``, plus the editor's own confirmation step: a reply that only asks to go
282
+ ahead with placing a chart ("Should I replace Order breakdown with it?", "Once you confirm,
283
+ I'll place it", "ask me to place it when you're ready") is a confirmation, so it is told yes. So is
284
+ an offer to place it ("I can replace Order breakdown with it") once a chart has been shown: in this
285
+ reply, or anywhere in the conversation so far (``shown_earlier``), as when the editor asks again in a
286
+ turn after its preview.
287
+ Either kind of confirmation turns into a question when the reply also asks for something a yes
288
+ does not supply: another question ("Which size should it have? Once you confirm, I'll place it."),
289
+ a choice in the placement itself ("Should I put it before or after Orders over time?", "in Sales or
290
+ Finance"), a numbered list with two placement items, something to confirm other than going ahead
291
+ ("once you confirm which section"), a request for a place ("Please specify the size") or, from the
292
+ ask on, any other request.
293
+ """
294
+ if has_structured_question(chat_result):
295
+ return "question"
296
+ text = (rendered_text or "").strip()
297
+ kind = classify_reply(chat_result, text)
298
+ if chat_result.alert_proposals:
299
+ return kind
300
+ plain = _EMPHASIS_RE.sub("", _FORMULA_SPAN_RE.sub(" ", text))
301
+ sentences = [s for s in _SENTENCE_END_RE.split(plain) if s.strip()]
302
+ # ADHOC_VIZ_ID stands for a chart the reply did not show, so it makes no offer.
303
+ created = chat_result.created_visualizations
304
+ shown = [viz for viz in (created.objects if created else []) if viz.id != ADHOC_VIZ_ID]
305
+ offers = bool(shown) or shown_earlier
306
+ placing = [
307
+ bool(_PLACEMENT_ASK_RE.search(s) or _GO_AHEAD_RE.search(s) or (offers and _PLACEMENT_OFFER_RE.search(s)))
308
+ and bool(_PLACED_CHART_RE.search(s) or (offers and _PLACED_ANYTHING_RE.search(s)))
309
+ and not _WH_ASK_RE.search(s)
310
+ for s in sentences
311
+ ]
312
+ if not any(placing):
313
+ return "question" if kind == "confirmation" and asks_in_text(chat_result, text) else kind
314
+ # A shown chart's title is a name, so an "or" inside one ("Orders or Returns") is no choice. Only a
315
+ # title of three words or more with an "or" in it is masked, and only as whole words: a title like
316
+ # "a" or "or" would otherwise eat into the sentence around it.
317
+ shown_titles = [
318
+ re.escape(title)
319
+ for viz in shown
320
+ if (title := (viz.title or "").strip()) and len(title.split()) >= 3 and _OR_WORD_RE.search(title)
321
+ ]
322
+ title_re = re.compile(rf"(?<!\w)(?:{'|'.join(shown_titles)})(?!\w)", re.IGNORECASE) if shown_titles else None
323
+ first = placing.index(True)
324
+ # The second option can come as a sentence of its own after the ask: "Should I replace it? Alternatively, ...".
325
+ masked = [title_re.sub(" ", s) if title_re else s for s in sentences]
326
+ if any(
327
+ _PLACEMENT_CHOICE_RE.search(s) or (is_placing and _DESTINATION_CHOICE_RE.search(s))
328
+ for i, (s, is_placing) in enumerate(zip(masked, placing, strict=True))
329
+ if is_placing or (i > first and _LEADING_CHOICE_RE.match(s))
330
+ ):
331
+ return "question"
332
+ # A request for a place counts wherever it stands ("Please specify the section. Should I place it?").
333
+ if any(_CONFIRM_WHAT_RE.search(s) or _PLACE_REQUEST_RE.search(s) for s in sentences):
334
+ return "question"
335
+ if any(_EDIT_REQUEST_RE.search(s) for s in sentences[first:]):
336
+ return "question"
337
+ # Any sentence after the ask counts, an offer too: "Should I replace it? Otherwise, I can add it as a new row."
338
+ if any(_LATER_OPTION_RE.search(s) and _PLACEMENT_VERB_RE.search(s) for s in sentences[first + 1 :]):
339
+ return "question"
340
+ if _numbered_placements(plain) >= 2:
341
+ return "question"
342
+ asks_more = any(
343
+ s.rstrip().endswith("?")
344
+ and not _CONFIRMATION_RE.search(s)
345
+ and (not is_placing or bool(_SECOND_ASK_RE.search(s)))
346
+ for s, is_placing in zip(sentences, placing, strict=True)
347
+ )
348
+ return "question" if asks_more else "confirmation"
349
+
350
+
125
351
  @dataclass
126
352
  class TranscriptEntry:
127
353
  role: Literal["user", "assistant"]
@@ -0,0 +1,155 @@
1
+ # (C) 2026 GoodData Corporation. All rights reserved.
2
+ """Whether a KDA answer, and the suggestions after it, name the drivers the analysis returned.
3
+
4
+ The execute tool returns ``data.significant_drivers``: one row per attribute value, with its own
5
+ ``delta`` between the periods. The answer is read as text, so a driver counts as named when its
6
+ value appears as a whole word, plural allowed. Two kinds of value are skipped: a date, which the
7
+ answer writes as "July 19" where the driver says "2025-07-19", and a value shorter than three
8
+ characters, which matches ordinary words ("A", "No", "1").
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any
15
+
16
+ # How many of the largest drivers a failed check reports.
17
+ _TOP_DRIVERS = 5
18
+ _MIN_VALUE_CHARS = 3
19
+ _DATE_VALUE = re.compile(
20
+ r"^\d{4}-\d{1,2}(-\d{1,2})?([ T]\d{1,2}(:\d{2}){0,2}(\.\d+)?(Z|[+-]\d{2}(:?\d{2})?)?)?$", re.IGNORECASE
21
+ )
22
+ # "10,769" is the same number as "10769". A plain space is not a separator: "2024 100 stores" is two numbers.
23
+ _THOUSANDS = re.compile(r"(?<=\d)[,  ](?=\d{3}(?!\d))")
24
+ _NUMBER = re.compile(r"\d+(\.\d+)?")
25
+
26
+
27
+ def _normalized(text: str) -> str:
28
+ return " ".join(_THOUSANDS.sub("", text).casefold().split())
29
+
30
+
31
+ def _value_text(value: Any) -> str | None:
32
+ if isinstance(value, bool) or value is None:
33
+ return None
34
+ if isinstance(value, float) and value.is_integer():
35
+ value = int(value)
36
+ raw = str(value).strip()
37
+ if _DATE_VALUE.match(raw):
38
+ return None
39
+ text = _normalized(raw)
40
+ return text if len(text) >= _MIN_VALUE_CHARS else None
41
+
42
+
43
+ def _drivers(execute_result: Any) -> list[dict[str, Any]]:
44
+ data = execute_result.get("data") if isinstance(execute_result, dict) else None
45
+ drivers = data.get("significant_drivers") if isinstance(data, dict) else None
46
+ return [d for d in drivers if isinstance(d, dict)] if isinstance(drivers, list) else []
47
+
48
+
49
+ def _delta(driver: dict[str, Any]) -> float:
50
+ delta = driver.get("delta")
51
+ if isinstance(delta, bool) or not isinstance(delta, int | float):
52
+ return 0.0
53
+ return abs(float(delta))
54
+
55
+
56
+ def _ran(execute_result: Any) -> bool:
57
+ return isinstance(execute_result, dict) and execute_result.get("success") is True
58
+
59
+
60
+ def driver_values(execute_result: Any, limit: int | None = None) -> list[str]:
61
+ """The driver values an answer can name, largest change first, without repeats."""
62
+ ranked = sorted(_drivers(execute_result), key=_delta, reverse=True)
63
+ values = list(dict.fromkeys(v for v in (_value_text(d.get("value")) for d in ranked) if v))
64
+ return values if limit is None else values[:limit]
65
+
66
+
67
+ def _value_pattern(value: str) -> str:
68
+ """A whole number never matches inside a decimal; a word matches its plural, "y" also as "ies"."""
69
+ if _NUMBER.fullmatch(value):
70
+ return rf"(?<![\w.]){re.escape(value)}(?!\w|[.,]\d)"
71
+ if len(value) > 1 and value.endswith("y") and value[-2] not in "aeiou":
72
+ return rf"(?<!\w){re.escape(value[:-1])}(?:y|ies)(?!\w)"
73
+ return rf"(?<!\w){re.escape(value)}(?:e?s)?(?!\w)"
74
+
75
+
76
+ def named_values(text: str, values: list[str]) -> list[str]:
77
+ """The values that appear in ``text`` as whole words, singular or plural."""
78
+ haystack = _normalized(text)
79
+ return [v for v in values if re.search(_value_pattern(v), haystack)]
80
+
81
+
82
+ def check_answer_grounded(execute_result: Any, answer: str) -> tuple[bool, dict[str, Any]]:
83
+ """Whether the answer names a driver the analysis returned.
84
+
85
+ Any driver counts, not only the largest: a question about regions is answered with the region
86
+ drivers, which need not be the largest ones. An analysis that ran and returned no driver to
87
+ name passes; a run with no analysis does not.
88
+ """
89
+ if not _ran(execute_result):
90
+ return False, {"reason": "no analysis ran"}
91
+ values = driver_values(execute_result)
92
+ if not values:
93
+ return True, {"top_drivers": []}
94
+ named = named_values(answer, values)
95
+ return bool(named), {"top_drivers": values[:_TOP_DRIVERS], "named": named}
96
+
97
+
98
+ def suggested_actions(suggestions: Any) -> list[dict[str, Any]]:
99
+ """The suggested actions, [] when there are none.
100
+
101
+ Raises:
102
+ ValueError: The suggestions have a shape this check cannot read.
103
+ """
104
+ if suggestions is None:
105
+ return []
106
+ actions = suggestions.get("actions") if isinstance(suggestions, dict) else suggestions
107
+ if actions is None:
108
+ return []
109
+ if not isinstance(actions, list) or not all(isinstance(a, dict) for a in actions):
110
+ raise ValueError(f"unreadable suggestion actions {actions!r}")
111
+ return actions
112
+
113
+
114
+ def check_suggestions_name_driver(execute_result: Any, answer: str, suggestions: Any) -> tuple[bool, dict[str, Any]]:
115
+ """Whether the first suggested action names a driver the answer named.
116
+
117
+ True when there are no actions, or the answer names no driver: the rule binds only an answer
118
+ that highlights drivers by name. False when no analysis ran.
119
+
120
+ Raises:
121
+ ValueError: The suggestions have a shape this check cannot read.
122
+ """
123
+ actions = suggested_actions(suggestions)
124
+ if not _ran(execute_result):
125
+ return False, {"reason": "no analysis ran"}
126
+ if not actions:
127
+ return True, {"first_action": None}
128
+ first = actions[0]
129
+ in_answer = named_values(answer, driver_values(execute_result))
130
+ if not in_answer:
131
+ return True, {"first_action": first, "drivers_in_answer": []}
132
+ action_text = f"{first.get('query') or ''} {first.get('label') or ''}"
133
+ named = named_values(action_text, in_answer)
134
+ return bool(named), {"first_action": first, "drivers_in_answer": in_answer, "named": named}
135
+
136
+
137
+ def suggestions_from_turn(items: list[dict[str, Any]], turn: int) -> Any:
138
+ """The suggestions of the last turn from user turn ``turn`` (0-based) on, None when that turn has none.
139
+
140
+ A later user message starts a new turn: the suggestions of an earlier turn are not the last turn's.
141
+ """
142
+ users = 0
143
+ latest: Any = None
144
+ for item in items:
145
+ role = item.get("role") if isinstance(item, dict) else None
146
+ if role == "user":
147
+ users += 1
148
+ latest = None
149
+ continue
150
+ if role != "assistant" or users <= turn:
151
+ continue
152
+ content = item.get("content")
153
+ if isinstance(content, dict) and content.get("suggestions") is not None:
154
+ latest = content["suggestions"]
155
+ return latest
@@ -8,6 +8,18 @@ the key, nothing here runs and the item is scored on completion only.
8
8
  ``any_of`` lists complete alternatives. Each option replaces some fields of the item, and a run
9
9
  passes when one option matches every field. The summary goes with the date attribute, so an
10
10
  option that changes one usually states both.
11
+
12
+ The behaviour keys are opt-in as well, and each adds one score:
13
+
14
+ - ``expect_no_create: true``: no analysis may be created or run (``kda_not_created``).
15
+ - ``expect_clarification: false``: the turn that asks for the analysis runs it (``kda_first_turn``).
16
+ ``true``: the first turn asks a question and runs nothing (``kda_clarified``).
17
+ - ``user_replies``: scripted messages sent after the question, in the same conversation. The
18
+ analysis of the last scripted turn, or of a later one, is the one scored.
19
+ - ``rubric``: an LLM judge grades the conversation against it (``kda_rubric``).
20
+ - ``check_answer: true``: the answer names a driver the analysis returned (``kda_answer_grounded``).
21
+ - ``check_suggestions: true``: when the answer names a driver, the first suggested action names one
22
+ too (``kda_suggestions``).
11
23
  """
12
24
 
13
25
  from __future__ import annotations
@@ -33,7 +45,19 @@ _FIELD_KEYS = {
33
45
  "summary": "Summary",
34
46
  }
35
47
  _OPTION_KEYS = frozenset(_FIELD_KEYS.values())
36
- _ITEM_KEYS = _OPTION_KEYS | {"check_fields", "any_of"}
48
+ _BEHAVIOUR_KEYS = frozenset(
49
+ {"expect_no_create", "expect_clarification", "user_replies", "rubric", "check_answer", "check_suggestions"}
50
+ )
51
+ _ITEM_KEYS = _OPTION_KEYS | {"check_fields", "any_of"} | _BEHAVIOUR_KEYS
52
+ # The scores the behaviour keys add, each published only by an item that sets its key.
53
+ KDA_BEHAVIOUR_SCORES = (
54
+ "kda_not_created",
55
+ "kda_first_turn",
56
+ "kda_clarified",
57
+ "kda_rubric",
58
+ "kda_answer_grounded",
59
+ "kda_suggestions",
60
+ )
37
61
  _SUMMARY_VALUES = ("analyzed_value", "reference_value", "change")
38
62
  _SUMMARY_KEYS = frozenset({*_SUMMARY_VALUES, "absolute_tolerance"})
39
63
  _DEFAULT_TOLERANCE = 0.01
@@ -43,8 +67,12 @@ _MEASURE_TYPES = ("metric", "fact", "attribute")
43
67
  _AGGREGATIONS = ("SUM", "AVG", "MIN", "MAX", "MEDIAN", "COUNT")
44
68
  _FILTER_STATES = ("include", "exclude")
45
69
  # Spelled like the item's other keys, these would leave the checks off without a word.
46
- _OPT_IN_KEYS = ("check_fields", "any_of")
70
+ _OPT_IN_KEYS = ("check_fields", "any_of", *sorted(_BEHAVIOUR_KEYS))
47
71
  _DATE_FILTER = "date_filter"
72
+ _RANKING_FILTER = "ranking_filter"
73
+ _RANKING_SIDES = ("top", "bottom")
74
+ # The keys of the tool's ranking filter. The tool echoes the optional ones as null.
75
+ _RANKING_KEYS = frozenset({"type", "using", "attribute", *_RANKING_SIDES, "strict_limit_of_rows"})
48
76
  # The agent's tools take an attribute by its label or its attribute id. Both ids are equal in the
49
77
  # eval workspaces, so a filter is matched on the id alone.
50
78
  _TYPE_PREFIXES = ("label/", "attribute/")
@@ -66,9 +94,18 @@ class KdaFieldOption:
66
94
 
67
95
  @dataclass(frozen=True)
68
96
  class KdaExpectation:
69
- """The item's field checks. ``options`` is empty when the item does not opt in."""
97
+ """The item's checks. ``options`` is empty when the item does not opt into the field checks.
98
+
99
+ ``expect_clarification`` is None when the item does not set it.
100
+ """
70
101
 
71
102
  options: tuple[KdaFieldOption, ...] = ()
103
+ expect_no_create: bool = False
104
+ expect_clarification: bool | None = None
105
+ user_replies: tuple[str, ...] = ()
106
+ rubric: str | None = None
107
+ check_answer: bool = False
108
+ check_suggestions: bool = False
72
109
 
73
110
  @property
74
111
  def check_fields(self) -> bool:
@@ -141,6 +178,25 @@ def _check_attribute_filter(entry: dict[str, Any]) -> None:
141
178
  raise ValueError(f"attribute_filter {next(iter(state))} must be a non-empty list of strings, got {entry!r}")
142
179
 
143
180
 
181
+ def _check_ranking_filter(entry: dict[str, Any]) -> None:
182
+ if unknown := set(entry) - _RANKING_KEYS:
183
+ raise ValueError(f"ranking_filter has unknown keys {sorted(unknown)}, got {entry!r}")
184
+ using, attribute = entry.get("using"), entry.get("attribute")
185
+ if not isinstance(using, str) or not using.strip():
186
+ raise ValueError(f"ranking_filter needs a non-empty using, got {entry!r}")
187
+ if not isinstance(attribute, str) or not attribute.strip():
188
+ raise ValueError(f"ranking_filter needs a non-empty attribute, got {entry!r}")
189
+ counts = [entry.get(side) for side in _RANKING_SIDES if entry.get(side) is not None]
190
+ if len(counts) != 1 or not _is_count(counts[0]):
191
+ raise ValueError(f"ranking_filter needs exactly one of top, bottom as a positive integer, got {entry!r}")
192
+ if not isinstance(entry.get("strict_limit_of_rows"), bool | None):
193
+ raise ValueError(f"ranking_filter strict_limit_of_rows must be true, false or null, got {entry!r}")
194
+
195
+
196
+ def _is_count(value: Any) -> bool:
197
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
198
+
199
+
144
200
  def _filters(value: Any) -> tuple[Any, ...]:
145
201
  if not isinstance(value, list):
146
202
  raise ValueError(f"Filters must be a list, [] for none, got {value!r}")
@@ -151,6 +207,8 @@ def _filters(value: Any) -> tuple[Any, ...]:
151
207
  raise ValueError("Filters must not hold a date_filter: date filters are not checked, the periods are")
152
208
  if entry.get("type") == "attribute_filter":
153
209
  _check_attribute_filter(entry)
210
+ if entry.get("type") == _RANKING_FILTER:
211
+ _check_ranking_filter(entry)
154
212
  return tuple(_filter_key(entry) for entry in value)
155
213
 
156
214
 
@@ -197,26 +255,22 @@ def _reject_respelt_keys(expected: dict[str, Any]) -> None:
197
255
  raise ValueError(f"write {canonical!r}, not {key!r}")
198
256
 
199
257
 
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:
258
+ def _field_options(expected: dict[str, Any]) -> tuple[KdaFieldOption, ...]:
259
+ """The field checks of an item, empty when it does not set ``check_fields: true``."""
260
+ if "check_fields" not in expected:
261
+ if "any_of" in expected:
206
262
  raise ValueError("any_of is read only with check_fields: true")
207
- return KdaExpectation()
263
+ return ()
208
264
  flag = expected["check_fields"]
209
265
  if not isinstance(flag, bool):
210
266
  raise ValueError(f"check_fields must be true or false, got {flag!r}")
211
267
  if not flag:
212
268
  if "any_of" in expected:
213
269
  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)}")
270
+ return ()
217
271
  base = {key: value for key, value in expected.items() if key in _OPTION_KEYS}
218
272
  if "any_of" not in expected:
219
- return KdaExpectation(options=(_option(base, "expected_output"),))
273
+ return (_option(base, "expected_output"),)
220
274
  options = expected["any_of"]
221
275
  if not isinstance(options, list) or len(options) < 2 or not all(isinstance(o, dict) and o for o in options):
222
276
  raise ValueError(f"any_of must list at least two non-empty objects, got {options!r}")
@@ -227,7 +281,64 @@ def parse_kda_expectation(expected: Any) -> KdaExpectation:
227
281
  f"any_of[{index}] has keys {sorted(unknown)}; an option may state only {sorted(_OPTION_KEYS)}"
228
282
  )
229
283
  parsed.append(_option({**base, **option}, f"any_of[{index}]"))
230
- return KdaExpectation(options=tuple(parsed))
284
+ return tuple(parsed)
285
+
286
+
287
+ def _flag(expected: dict[str, Any], key: str) -> bool | None:
288
+ if key not in expected:
289
+ return None
290
+ value = expected[key]
291
+ if not isinstance(value, bool):
292
+ raise ValueError(f"{key} must be true or false, got {value!r}")
293
+ return value
294
+
295
+
296
+ def _user_replies(value: Any) -> tuple[str, ...]:
297
+ if not isinstance(value, list) or not value or not all(isinstance(v, str) and v.strip() for v in value):
298
+ raise ValueError(f"user_replies must be a non-empty list of non-empty strings, got {value!r}")
299
+ return tuple(v.strip() for v in value)
300
+
301
+
302
+ def parse_kda_expectation(expected: Any) -> KdaExpectation:
303
+ """Read the item's checks, raising ValueError on a malformed one before any request is sent."""
304
+ if not isinstance(expected, dict):
305
+ return KdaExpectation()
306
+ _reject_respelt_keys(expected)
307
+ options = _field_options(expected)
308
+ # An item that opts into no check may carry other keys; one that opts in is read whole.
309
+ if (options or _BEHAVIOUR_KEYS & set(expected)) and (unknown := set(expected) - _ITEM_KEYS):
310
+ raise ValueError(f"expected_output has unknown keys {sorted(unknown)}")
311
+ no_create = _flag(expected, "expect_no_create") or False
312
+ clarification = _flag(expected, "expect_clarification")
313
+ check_answer = _flag(expected, "check_answer") or False
314
+ check_suggestions = _flag(expected, "check_suggestions") or False
315
+ rubric = expected.get("rubric")
316
+ if "rubric" in expected and (not isinstance(rubric, str) or not rubric.strip()):
317
+ raise ValueError(f"rubric must be a non-empty string, got {rubric!r}")
318
+ replies = _user_replies(expected["user_replies"]) if "user_replies" in expected else ()
319
+ if no_create:
320
+ # Each of these needs an analysis that ran, which the item says must not happen.
321
+ clashes = [
322
+ key
323
+ for key, on in (
324
+ ("check_fields", bool(options)),
325
+ ("check_answer", check_answer),
326
+ ("check_suggestions", check_suggestions),
327
+ ("expect_clarification", clarification is not None),
328
+ )
329
+ if on
330
+ ]
331
+ if clashes:
332
+ raise ValueError(f"expect_no_create cannot be combined with {', '.join(clashes)}")
333
+ return KdaExpectation(
334
+ options=options,
335
+ expect_no_create=no_create,
336
+ expect_clarification=clarification,
337
+ user_replies=replies,
338
+ rubric=rubric.strip() if isinstance(rubric, str) else None,
339
+ check_answer=check_answer,
340
+ check_suggestions=check_suggestions,
341
+ )
231
342
 
232
343
 
233
344
  def _bare_id(using: Any) -> Any:
@@ -253,6 +364,16 @@ def _filter_key(entry: dict[str, Any]) -> Any:
253
364
  tuple(sorted(state.get("include") or [])),
254
365
  tuple(sorted(state.get("exclude") or [])),
255
366
  )
367
+ if entry.get("type") == _RANKING_FILTER and isinstance(entry.get("using"), str):
368
+ # The tool echoes optional keys as null (strict_limit_of_rows), and names the attribute either way.
369
+ return (
370
+ _RANKING_FILTER,
371
+ entry["using"].strip(),
372
+ _bare_id(entry.get("attribute")),
373
+ *(json.dumps(entry.get(side), default=str) for side in _RANKING_SIDES),
374
+ # Unset reads as false: the tool echoes null when the agent did not ask for a strict limit.
375
+ bool(entry.get("strict_limit_of_rows")),
376
+ )
256
377
  return json.dumps(entry, sort_keys=True, default=str)
257
378
 
258
379