gooddata-eval 1.81.1.dev5__py3-none-any.whl → 1.81.1.dev7__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,280 @@
1
+ # (C) 2026 GoodData Corporation. All rights reserved.
2
+ """Whether a forecast answer names a value the forecast predicted.
3
+
4
+ ``execute_forecast`` returns parallel lists in ``data``: ``attribute`` names the period, ``origin``
5
+ holds the actual values and ``prediction`` the forecast. The forecast line starts from the last
6
+ actual value: a row that repeats the last actual period, with that value as its prediction and
7
+ both bounds. The periods after it carry a prediction only, and those are the values a grounded
8
+ answer names. ``data.points`` holds the same rows but keeps only the oldest ``max_points`` of them,
9
+ so a long history can leave every prediction out of it.
10
+
11
+ The answer is read as text. A number counts as a value when the value rounds to it at the last
12
+ digit the answer wrote: ``5.54M`` names 5,541,967.50, ``5.5 million`` too, ``5.55M`` does not,
13
+ and ``6M`` names nothing because one digit agrees with too many values. Both the English and the Czech way of writing a
14
+ number are read (``1,234.5`` and ``1 234,5``), and a percentage also matches a ratio
15
+ (``48.1%`` names 0.481).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import re
22
+ from dataclasses import dataclass
23
+ from typing import Any
24
+
25
+ # A number of one digit agrees with too many values to name one.
26
+ _MIN_DIGITS = 2
27
+ # How many predicted values a detail lists.
28
+ _LISTED = 5
29
+ _SCALES = {
30
+ "k": 1e3,
31
+ "thousand": 1e3,
32
+ "thousands": 1e3,
33
+ "tis": 1e3,
34
+ "tisíc": 1e3,
35
+ "tisíce": 1e3,
36
+ "m": 1e6,
37
+ "mn": 1e6,
38
+ "mil": 1e6,
39
+ "mln": 1e6,
40
+ "million": 1e6,
41
+ "millions": 1e6,
42
+ "milion": 1e6,
43
+ "milionu": 1e6,
44
+ "miliony": 1e6,
45
+ "milionů": 1e6,
46
+ "b": 1e9,
47
+ "bn": 1e9,
48
+ "billion": 1e9,
49
+ "billions": 1e9,
50
+ "bln": 1e9,
51
+ "mld": 1e9,
52
+ "miliard": 1e9,
53
+ "miliarda": 1e9,
54
+ "miliardu": 1e9,
55
+ "miliardy": 1e9,
56
+ }
57
+ _GROUP_SPACES = "   "
58
+ # A grouped number (5,541,967.50 or 5 541 967,50), else a plain one (193, 5.54, 1,5).
59
+ _NUMBER = re.compile(
60
+ rf"(?<![\w.,])(?P<num>\d{{1,3}}(?:[,.{_GROUP_SPACES}]\d{{3}})+(?:[.,]\d+)?(?!\d)|\d+(?:[.,]\d+)?(?!\d))"
61
+ r"(?:\s?(?P<pct>%)|\s?(?P<word>[^\W\d_]+))?"
62
+ )
63
+ # A date or a timestamp: 2025-10, 2025-10-17, 2025-10-17T14:30:00Z, 2025-10-17 14:30+02:00.
64
+ _ISO_DATE = re.compile(
65
+ r"\b\d{4}-\d{2}(?:-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)?(?![\d:])"
66
+ )
67
+ _MONTHS = (
68
+ r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec|january|february|march|april|june|july|august"
69
+ r"|september|october|november|december|ledna|února|března|dubna|května|června|července|srpna|září|října"
70
+ r"|listopadu|prosince|leden|únor|březen|duben|květen|červen|červenec|srpen|říjen|listopad|prosinec)"
71
+ )
72
+ # A date written with a month name: "October 17, 2025", "17. října 2025", "October 2025". Its day and
73
+ # year are not values, whatever follows them.
74
+ _WRITTEN_DATE = re.compile(
75
+ # A day is one or two digits that no group or decimal follows: "October 5,541,967.50" is a value.
76
+ rf"\b{_MONTHS}\.?\s+\d{{1,2}}(?:st|nd|rd|th)?\b(?![.,]\d)(?:,?\s+\d{{4}}\b)?"
77
+ rf"|(?<![\d.,])\d{{1,2}}\.?\s+{_MONTHS}\b(?:\s+\d{{4}}\b)?"
78
+ rf"|\b{_MONTHS}\.?\s+\d{{4}}\b",
79
+ re.IGNORECASE,
80
+ )
81
+ _YEAR = re.compile(r"(?:19|20)\d\d")
82
+ # A bare year is a date only after one of these words: "2045 orders" is a value, "October 2025" is not.
83
+ # Words that may follow a year in a date ("in 2025 Q4", "2025 rok"), which leave it a date.
84
+ _DATE_WORD = re.compile(r"q[1-4]|h[12]|fy|year|years|rok|roku|roce|and|a|to|do", re.IGNORECASE)
85
+ # A year followed by one of these is a period, whatever precedes it. The word reader stops at a digit,
86
+ # so "2025 Q4" gives "q".
87
+ _PERIOD_AFTER_YEAR = re.compile(r"q|h|q[1-4]|h[12]|fy", re.IGNORECASE)
88
+ _BEFORE_YEAR = re.compile(
89
+ r"\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec|january|february|march|april|june|july|august"
90
+ r"|september|october|november|december|q[1-4]|h[12]|fy|in|of|year|since|until|through|to|from|by|and"
91
+ r"|ledna|února|března|dubna|května|června|července|srpna|září|října|listopadu|prosince|leden|únor|březen"
92
+ r"|duben|květen|červen|červenec|srpen|říjen|listopad|prosinec|v|roce|rok|roku|od|do|a)\.?,?\s*$",
93
+ re.IGNORECASE,
94
+ )
95
+ # A date written in numbers: 17. 10. 2025, 17. 10., 17.10.2025, 10/17/2025. Without the space or the
96
+ # year, "48.1." would be a value at the end of a sentence.
97
+ _NUMERIC_DATE = re.compile(
98
+ r"(?<![\d.,])(?:\d{1,2}\.\s\d{1,2}\.(?:\s?\d{4}\b)?|\d{1,2}\.\d{1,2}\.\d{4}\b)|\b\d{1,2}/\d{1,2}/\d{2,4}\b"
99
+ )
100
+ # A number followed by one of these counts periods, as in "the next 14 days": the horizon, not a value.
101
+ _SPAN_WORD = re.compile(
102
+ r"days?|weeks?|months?|quarters?|years?|periods?|den|dny|dní|dnů|týden|týdny|týdnů|měsíc|měsíce|měsíců"
103
+ r"|čtvrtletí|roky|let|období",
104
+ re.IGNORECASE,
105
+ )
106
+ # What follows a confidence level: "95% confidence", "95 % CI", "interval spolehlivosti 95 %" is not.
107
+ _CONFIDENCE_AFTER = re.compile(r"\s?%?\s*(?:confidence|ci\b|prediction interval|spolehlivost)", re.IGNORECASE)
108
+ # English: comma or space groups, dot decimals. Czech: dot or space groups, comma decimals.
109
+ _READINGS = (
110
+ (re.compile(rf"\d{{1,3}}(?:[,{_GROUP_SPACES}]\d{{3}})*(?:\.\d+)?|\d+(?:\.\d+)?"), f",{_GROUP_SPACES}", "."),
111
+ (re.compile(rf"\d{{1,3}}(?:[.{_GROUP_SPACES}]\d{{3}})*(?:,\d+)?|\d+(?:,\d+)?"), f".{_GROUP_SPACES}", ","),
112
+ )
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class _Number:
117
+ text: str
118
+ value: float
119
+ # The place of the last digit written, scaled: 0.01 for "5.54", 10,000 for "5.54M".
120
+ unit: float
121
+ percent: bool
122
+
123
+
124
+ def _readings(token: str) -> list[tuple[float, float, int]]:
125
+ """(value, unit of the last significant digit, significant digits) for each way the token can be read.
126
+
127
+ The zeros that end a whole number are rounding: "5,540,000" is written to the ten thousand, so
128
+ its unit is 10,000 and it has three significant digits.
129
+ """
130
+ out: list[tuple[float, float, int]] = []
131
+ for pattern, groups, decimal in _READINGS:
132
+ if not pattern.fullmatch(token):
133
+ continue
134
+ plain = token.translate({ord(c): None for c in groups}).replace(decimal, ".")
135
+ whole, _, fraction = plain.partition(".")
136
+ if fraction:
137
+ unit = 10.0 ** -len(fraction)
138
+ significant = len((whole + fraction).lstrip("0"))
139
+ else:
140
+ trailing = len(whole) - len(whole.rstrip("0"))
141
+ unit = 10.0**trailing
142
+ significant = len(whole.strip("0"))
143
+ reading = (float(plain), unit, significant)
144
+ if reading not in out:
145
+ out.append(reading)
146
+ return out
147
+
148
+
149
+ def answer_numbers(text: str) -> list[_Number]:
150
+ """The numbers an answer writes, each in every reading it allows.
151
+
152
+ Left out: dates (2025-10, October 17, 17. 10. 2025, October 2025, a year after a preposition such
153
+ as "in 2025"), a span of time ("the next 14 days"), a confidence level ("95% confidence") and
154
+ numbers of one significant digit.
155
+ """
156
+ numbers: list[_Number] = []
157
+ text = _NUMERIC_DATE.sub(" ", _WRITTEN_DATE.sub(" ", _ISO_DATE.sub(" ", text)))
158
+ for match in _NUMBER.finditer(text):
159
+ token = match.group("num")
160
+ word = (match.group("word") or "").casefold()
161
+ scale = _SCALES.get(word, 1.0)
162
+ percent = match.group("pct") is not None
163
+ before = text[max(0, match.start() - 16) : match.start()]
164
+ # "rise to 2045 orders" names a count: a year-like number followed by a noun is a value.
165
+ counted = bool(word) and not _DATE_WORD.fullmatch(word)
166
+ dated = bool(_PERIOD_AFTER_YEAR.fullmatch(word)) or (bool(_BEFORE_YEAR.search(before)) and not counted)
167
+ if scale == 1.0 and not percent and _YEAR.fullmatch(token) and dated:
168
+ continue
169
+ if scale == 1.0 and not percent and _SPAN_WORD.fullmatch(word):
170
+ continue
171
+ if _CONFIDENCE_AFTER.match(text, match.end("pct") if percent else match.end("num")):
172
+ continue
173
+ written = match.group(0).strip() if scale != 1.0 or percent else token
174
+ numbers.extend(
175
+ _Number(written, value * scale, unit * scale, percent)
176
+ for value, unit, significant in _readings(token)
177
+ if significant >= _MIN_DIGITS
178
+ )
179
+ return numbers
180
+
181
+
182
+ def _agrees(number: _Number, value: float) -> bool:
183
+ """Whether the number is the value rounded to the number's last digit (signs aside)."""
184
+ targets = (abs(value), abs(value) * 100) if number.percent else (abs(value),)
185
+ return any(abs(number.value - t) <= number.unit / 2 * (1 + 1e-9) for t in targets)
186
+
187
+
188
+ def _numbers_of(data: dict[str, Any], key: str) -> list[Any]:
189
+ values = data.get(key)
190
+ return values if isinstance(values, list) else []
191
+
192
+
193
+ def _finite(value: Any) -> float | None:
194
+ if isinstance(value, bool) or not isinstance(value, int | float):
195
+ return None
196
+ try:
197
+ number = float(value)
198
+ except OverflowError: # an int too large for a float
199
+ return None
200
+ return number if math.isfinite(number) else None
201
+
202
+
203
+ def forecast_values(execute_result: Any) -> dict[str, list[float]]:
204
+ """The predicted values after the last actual period, their bounds, and the starting point.
205
+
206
+ ``predicted`` and ``bounds`` are the periods the forecast adds; ``anchor`` is the prediction
207
+ the last actual period carries, which the line starts from and which is not a forecast.
208
+ """
209
+ data = execute_result.get("data") if isinstance(execute_result, dict) else None
210
+ if not isinstance(data, dict):
211
+ return {"predicted": [], "bounds": [], "anchor": []}
212
+ attribute = _numbers_of(data, "attribute")
213
+ origin = _numbers_of(data, "origin")
214
+ prediction = _numbers_of(data, "prediction")
215
+ lower = _numbers_of(data, "lower_bound")
216
+ upper = _numbers_of(data, "upper_bound")
217
+
218
+ def at(values: list[Any], index: int) -> Any:
219
+ return values[index] if index < len(values) else None
220
+
221
+ actual_periods = {
222
+ period
223
+ for index, period in enumerate(attribute)
224
+ if isinstance(period, str) and _finite(at(origin, index)) is not None
225
+ }
226
+ predicted: list[float] = []
227
+ bounds: list[float] = []
228
+ anchor: list[float] = []
229
+ for index, raw in enumerate(prediction):
230
+ value = _finite(raw)
231
+ if value is None:
232
+ continue
233
+ # The starting point repeats the last actual period, as a row of its own or on the actual
234
+ # row. Without periods to compare, it is the first predicted row when its interval has no
235
+ # width: a flat series has rows of no width after it too, and those are forecasts.
236
+ period = at(attribute, index)
237
+ starts_line = (
238
+ _finite(at(origin, index)) is not None
239
+ or (isinstance(period, str) and period in actual_periods)
240
+ or (
241
+ not actual_periods
242
+ and not predicted
243
+ and not anchor
244
+ and _finite(at(lower, index)) == value == _finite(at(upper, index))
245
+ )
246
+ )
247
+ if starts_line:
248
+ anchor.append(value)
249
+ continue
250
+ predicted.append(value)
251
+ for side in (lower, upper):
252
+ bound = _finite(at(side, index))
253
+ if bound is not None:
254
+ bounds.append(bound)
255
+ return {"predicted": predicted, "bounds": bounds, "anchor": anchor}
256
+
257
+
258
+ def _named(numbers: list[_Number], values: list[float]) -> list[str]:
259
+ return list(dict.fromkeys(n.text for n in numbers if any(_agrees(n, v) for v in values)))
260
+
261
+
262
+ def check_answer_grounded(execute_result: Any, answer: str) -> tuple[bool, dict[str, Any]]:
263
+ """Whether the answer names a value the forecast predicted for a period after the actuals.
264
+
265
+ The bounds and the starting point are reported but not required: an answer may leave the
266
+ interval out, and may mention the last actual value as context.
267
+ """
268
+ if not (isinstance(execute_result, dict) and execute_result.get("success") is True):
269
+ return False, {"reason": "no forecast ran"}
270
+ values = forecast_values(execute_result)
271
+ if not values["predicted"]:
272
+ return False, {"reason": "the forecast returned no predicted value"}
273
+ numbers = answer_numbers(answer)
274
+ named = _named(numbers, values["predicted"])
275
+ return bool(named), {
276
+ "predicted": values["predicted"][:_LISTED],
277
+ "named": named,
278
+ "bounds_named": _named(numbers, values["bounds"]),
279
+ "anchor_named": _named(numbers, values["anchor"]),
280
+ }
@@ -9,7 +9,7 @@ import logging
9
9
  import os
10
10
  import threading
11
11
  import time
12
- from collections.abc import Iterator
12
+ from collections.abc import Generator
13
13
  from contextlib import contextmanager
14
14
  from datetime import UTC, datetime, timedelta
15
15
  from typing import TYPE_CHECKING, Any
@@ -395,7 +395,7 @@ def observe(
395
395
  conversation_id: str | None = None,
396
396
  item_input: Any = None,
397
397
  output: Any = None,
398
- ) -> Iterator[ScoreTarget | None]:
398
+ ) -> Generator[ScoreTarget | None, None, None]:
399
399
  """Export gd-eval's experiment root span for one run and yield where to score it.
400
400
 
401
401
  A run belongs to a Langfuse experiment through the attributes on that span, so the span
@@ -557,7 +557,7 @@ _PENDING_SCORES: contextvars.ContextVar[list[dict[str, Any]] | None] = contextva
557
557
 
558
558
 
559
559
  @contextmanager
560
- def collect_scores(langfuse: HttpxLangfuseClient) -> Iterator[None]:
560
+ def collect_scores(langfuse: HttpxLangfuseClient) -> Generator[None, None, None]:
561
561
  """Hold every ``score_safe`` write made in the block and send them as one batch at its end.
562
562
 
563
563
  The batch is sent even when the drain was cancelled meanwhile, without retrying, so the