gooddata-eval 1.80.1.dev9__py3-none-any.whl → 1.80.1.dev11__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gooddata_eval/core/agentic/_catalog.py +19 -21
- gooddata_eval/core/agentic/alert_skill.py +762 -85
- gooddata_eval/core/evaluators/alert_skill.py +1 -1
- gooddata_eval/core/models.py +2 -1
- {gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/METADATA +2 -2
- {gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/RECORD +9 -9
- {gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/WHEEL +0 -0
- {gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/entry_points.txt +0 -0
- {gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/licenses/LICENSE.txt +0 -0
|
@@ -73,27 +73,25 @@ class CatalogMetricAlert:
|
|
|
73
73
|
"""Alert name the user asked for; ``None`` means unasserted."""
|
|
74
74
|
dashboard_id: str | None = None
|
|
75
75
|
"""Dashboard the alert must be bound to; ``None`` means unasserted."""
|
|
76
|
+
expect_alert: bool = True
|
|
77
|
+
"""``False``: the request names nothing the alert can monitor, so no alert may be proposed or created."""
|
|
78
|
+
sensitivity: str | None = None
|
|
79
|
+
"""ANOMALY sensitivity (LOW/MEDIUM/HIGH); ``None`` means unasserted."""
|
|
80
|
+
trigger_interval: str | None = None
|
|
81
|
+
"""Interval of a ONCE_PER_INTERVAL trigger (DAY/WEEK/MONTH/QUARTER/YEAR); ``None`` means unasserted."""
|
|
82
|
+
date_dataset_id: str | None = None
|
|
83
|
+
"""Date dataset an ANOMALY alert detects on; ``None`` means unasserted."""
|
|
84
|
+
setup_turns: tuple[str, ...] = ()
|
|
85
|
+
"""Messages sent in the same conversation before the question, not scored."""
|
|
86
|
+
alternatives: tuple[CatalogMetricAlert, ...] = ()
|
|
87
|
+
"""Complete expectations any one of which passes (``any_of``); empty means this one alone."""
|
|
88
|
+
check_first_proposal: tuple[str, ...] = ()
|
|
89
|
+
"""Fields (``filters``, ``recipients``) also scored on the first proposal, before the simulated user replies."""
|
|
76
90
|
|
|
77
91
|
@classmethod
|
|
78
92
|
def from_dict(cls, d: dict) -> CatalogMetricAlert:
|
|
79
|
-
"""Build a CatalogMetricAlert
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
recipients = list(recipients_raw)
|
|
85
|
-
return cls(
|
|
86
|
-
operator=d.get("operator", "GREATER_THAN"),
|
|
87
|
-
threshold=d.get("threshold"),
|
|
88
|
-
threshold_from=d.get("threshold_from"),
|
|
89
|
-
threshold_to=d.get("threshold_to"),
|
|
90
|
-
trigger=d.get("trigger", "not specified"),
|
|
91
|
-
metric_id=d.get("metric_id"),
|
|
92
|
-
recipients=recipients,
|
|
93
|
-
filters=d.get("filters"),
|
|
94
|
-
attributes=d.get("attributes"),
|
|
95
|
-
granularity=AnomalyDetectionGranularity.parse(d.get("granularity")),
|
|
96
|
-
comparison=d.get("comparison"),
|
|
97
|
-
title=d.get("title"),
|
|
98
|
-
dashboard_id=d.get("dashboard_id"),
|
|
99
|
-
)
|
|
93
|
+
"""Build a CatalogMetricAlert with the parsing and validation a dataset item's expected_output gets."""
|
|
94
|
+
# Imported here: alert_skill imports this module.
|
|
95
|
+
from gooddata_eval.core.agentic.alert_skill import _normalize_expected_output # noqa: PLC0415
|
|
96
|
+
|
|
97
|
+
return _normalize_expected_output(d)
|
|
@@ -3,9 +3,11 @@
|
|
|
3
3
|
|
|
4
4
|
from __future__ import annotations
|
|
5
5
|
|
|
6
|
+
import dataclasses
|
|
6
7
|
import json
|
|
7
8
|
import os
|
|
8
9
|
import re
|
|
10
|
+
import string
|
|
9
11
|
import time
|
|
10
12
|
from dataclasses import dataclass, field
|
|
11
13
|
from typing import Any
|
|
@@ -41,6 +43,7 @@ from gooddata_eval.core.agentic._trace_linker import (
|
|
|
41
43
|
submit_trace_scoring,
|
|
42
44
|
utc_now,
|
|
43
45
|
)
|
|
46
|
+
from gooddata_eval.core.agentic.metric_skill import _delete_metric, _extract_created_metric_ids
|
|
44
47
|
from gooddata_eval.core.chat.render import render_answer_text
|
|
45
48
|
from gooddata_eval.core.chat.sse_client import ChatClient, ChatError
|
|
46
49
|
from gooddata_eval.core.config import ReasoningEffort
|
|
@@ -75,9 +78,10 @@ _COMPARISON_ARGS = {
|
|
|
75
78
|
"date_dataset_id": "comparison_date_dataset_id",
|
|
76
79
|
"date_attribute_id": "comparison_date_attribute_id",
|
|
77
80
|
"arithmetic_operator": "arithmetic_operator",
|
|
81
|
+
"compare_metric_id": "compare_metric_id",
|
|
78
82
|
}
|
|
79
83
|
# Compared verbatim: object ids are case-sensitive, unlike the enum-valued properties.
|
|
80
|
-
_COMPARISON_ID_ARGS = ("comparison_date_dataset_id", "comparison_date_attribute_id")
|
|
84
|
+
_COMPARISON_ID_ARGS = ("comparison_date_dataset_id", "comparison_date_attribute_id", "compare_metric_id")
|
|
81
85
|
# What create_metric_alert applies when the argument is left out, per its own contract. A
|
|
82
86
|
# metric-to-metric comparison has no periods, so periods_ago defaults only for a period kind.
|
|
83
87
|
_COMPARISON_ARG_DEFAULTS: dict[str, object] = {"comparison_periods_ago": 1, "arithmetic_operator": "DIFFERENCE"}
|
|
@@ -97,7 +101,66 @@ _ALERT_CHECKS = (
|
|
|
97
101
|
"attributes_correct",
|
|
98
102
|
"granularity_correct",
|
|
99
103
|
)
|
|
100
|
-
_CONDITIONAL_ALERT_CHECKS = (
|
|
104
|
+
_CONDITIONAL_ALERT_CHECKS = (
|
|
105
|
+
"comparison_correct",
|
|
106
|
+
"title_correct",
|
|
107
|
+
"dashboard_correct",
|
|
108
|
+
"alert_sensitivity_correct",
|
|
109
|
+
"alert_trigger_interval_correct",
|
|
110
|
+
"alert_date_dataset_correct",
|
|
111
|
+
"alert_initial_filters_correct",
|
|
112
|
+
"alert_initial_recipients_correct",
|
|
113
|
+
)
|
|
114
|
+
# Fields `check_first_proposal` may name; each one is scored on the first proposal as well.
|
|
115
|
+
_FIRST_PROPOSAL_FIELDS = ("filters", "recipients")
|
|
116
|
+
# Labels of the `any_of` combinations in the simulated user's rule 9; an item lists at most this many.
|
|
117
|
+
_COMBINATION_LABELS = string.ascii_uppercase
|
|
118
|
+
# The only CatalogMetricAlert fields `any_of` options may differ in. Rule 9 states them per
|
|
119
|
+
# combination and rules 1 and 5 defer to it; rules 1-8 state every other field once.
|
|
120
|
+
_ANY_OF_FIELDS = ("threshold", "threshold_from", "threshold_to", "filters")
|
|
121
|
+
# The only check of an item that expects no alert; it replaces every other check.
|
|
122
|
+
_NO_ALERT_CHECK = "alert_not_proposed"
|
|
123
|
+
# Score names published only by an item that states the matching expectation (gdc-nas combo_report).
|
|
124
|
+
ALERT_CONDITIONAL_SCORES = (*_CONDITIONAL_ALERT_CHECKS, _NO_ALERT_CHECK)
|
|
125
|
+
|
|
126
|
+
_SENSITIVITIES = ("LOW", "MEDIUM", "HIGH")
|
|
127
|
+
# What create_metric_alert applies to an ANOMALY alert when `sensitivity` is left out, per its own contract.
|
|
128
|
+
_DEFAULT_SENSITIVITY = "MEDIUM"
|
|
129
|
+
_TRIGGER_INTERVALS = ("DAY", "WEEK", "MONTH", "QUARTER", "YEAR")
|
|
130
|
+
# The tool whose call is the agent proposing an alert, whether or not the call succeeded.
|
|
131
|
+
_PROPOSAL_TOOL = "prepare_metric_alert_proposal"
|
|
132
|
+
# The metric skill's write tool. The alert prompt lets the agent offer a metric the workspace lacks.
|
|
133
|
+
_CREATE_METRIC_TOOL = "create_metric"
|
|
134
|
+
# A no-alert item asserts nothing about an alert, so stating any of these is a fixture mistake.
|
|
135
|
+
_ALERT_ONLY_KEYS = (
|
|
136
|
+
"operator",
|
|
137
|
+
"threshold",
|
|
138
|
+
"threshold_from",
|
|
139
|
+
"threshold_to",
|
|
140
|
+
"filters",
|
|
141
|
+
"time window/filters",
|
|
142
|
+
"time_window",
|
|
143
|
+
"attributes",
|
|
144
|
+
"granularity",
|
|
145
|
+
"detection granularity",
|
|
146
|
+
"comparison",
|
|
147
|
+
"title",
|
|
148
|
+
"dashboard",
|
|
149
|
+
"dashboard_id",
|
|
150
|
+
"sensitivity",
|
|
151
|
+
"trigger_interval",
|
|
152
|
+
"trigger interval",
|
|
153
|
+
"date_dataset_id",
|
|
154
|
+
"date dataset",
|
|
155
|
+
"check_first_proposal",
|
|
156
|
+
"check first proposal",
|
|
157
|
+
)
|
|
158
|
+
# A no-alert run stops after this many agent turns: the simulated user only declines. Measured on
|
|
159
|
+
# 2026-11-25 with the cap at the default budget of 6 (6 runs, a churn-rate and a website-traffic
|
|
160
|
+
# request, gpt-5.6-luna): every agent answered in turn 1, confirmed it would not create the alert
|
|
161
|
+
# in turn 2, and spent turns 3-6 on pleasantries without a tool call. Three turns cover that with
|
|
162
|
+
# one to spare.
|
|
163
|
+
_NO_ALERT_MAX_ITERATIONS = 3
|
|
101
164
|
|
|
102
165
|
# Expected-recipient spellings that mean the owner of the API token.
|
|
103
166
|
_CURRENT_USER_RECIPIENT = "me"
|
|
@@ -178,9 +241,7 @@ def _check_threshold(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
|
178
241
|
act_from = _to_number(actual_args.get("from_value", actual_args.get("fromValue")))
|
|
179
242
|
act_to = _to_number(actual_args.get("to_value", actual_args.get("toValue")))
|
|
180
243
|
return exp_from == act_from and exp_to == act_to
|
|
181
|
-
|
|
182
|
-
act_thr = _to_number(actual_args.get("threshold"))
|
|
183
|
-
return exp_thr == act_thr
|
|
244
|
+
return _to_number(expected.threshold) == _to_number(actual_args.get("threshold"))
|
|
184
245
|
|
|
185
246
|
|
|
186
247
|
def _check_trigger(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
@@ -198,9 +259,8 @@ def _check_trigger(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
|
198
259
|
return exp_trigger == act_api
|
|
199
260
|
|
|
200
261
|
|
|
201
|
-
def
|
|
202
|
-
|
|
203
|
-
act_filters = actual_args.get("filters", actual_args.get("attribute_filters")) or []
|
|
262
|
+
def _filters_match(exp_filters: list | str | None, act_filters: list) -> bool:
|
|
263
|
+
"""``None`` asserts nothing, ``[]`` asserts no filter, a list must match entry by entry."""
|
|
204
264
|
if exp_filters is None:
|
|
205
265
|
return True
|
|
206
266
|
if not exp_filters:
|
|
@@ -210,6 +270,11 @@ def _check_filters(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
|
210
270
|
return _deep_subset(exp_filters, act_filters)
|
|
211
271
|
|
|
212
272
|
|
|
273
|
+
def _check_filters(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
274
|
+
act_filters = actual_args.get("filters", actual_args.get("attribute_filters")) or []
|
|
275
|
+
return _filters_match(expected.filters, act_filters)
|
|
276
|
+
|
|
277
|
+
|
|
213
278
|
def _attribute_label_ids(items: list, *, side: str) -> list[str]:
|
|
214
279
|
"""Canonicalise group-by entries to bare label ids, whatever spelling they arrive in.
|
|
215
280
|
|
|
@@ -358,6 +423,42 @@ def _check_dashboard(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
|
358
423
|
return isinstance(actual, str) and actual == expected.dashboard_id
|
|
359
424
|
|
|
360
425
|
|
|
426
|
+
def _check_enum_arg(expected_value: str | None, actual_args: dict, arg: str, default: str | None = None) -> bool | None:
|
|
427
|
+
"""Case-folded compare of an enum-valued argument; ``None`` when the fixture states no value.
|
|
428
|
+
|
|
429
|
+
``default`` is the value ``create_metric_alert`` applies when the argument is left out, so an
|
|
430
|
+
omitted argument is compared as that value.
|
|
431
|
+
"""
|
|
432
|
+
if expected_value is None:
|
|
433
|
+
return None
|
|
434
|
+
actual = actual_args.get(arg)
|
|
435
|
+
if actual is None:
|
|
436
|
+
actual = default
|
|
437
|
+
return isinstance(actual, str) and actual.strip().upper() == expected_value
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _check_trigger_interval(expected: CatalogMetricAlert, actual_args: dict) -> bool | None:
|
|
441
|
+
"""The stated interval, on an alert that fires once per interval; ``None`` when unasserted.
|
|
442
|
+
|
|
443
|
+
The tool applies ``trigger_interval`` only to ONCE_PER_INTERVAL and defaults the trigger to
|
|
444
|
+
ALWAYS. ``_check_trigger`` skips ANOMALY alerts, so an anomaly alert sent without that trigger
|
|
445
|
+
would otherwise score an interval it never uses.
|
|
446
|
+
"""
|
|
447
|
+
if expected.trigger_interval is None:
|
|
448
|
+
return None
|
|
449
|
+
actual_trigger = actual_args.get("trigger") or actual_args.get("triggerMode") or "ALWAYS"
|
|
450
|
+
if _TRIGGER_DISPLAY_TO_API.get(actual_trigger, actual_trigger) != "ONCE_PER_INTERVAL":
|
|
451
|
+
return False
|
|
452
|
+
return _check_enum_arg(expected.trigger_interval, actual_args, "trigger_interval")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _check_date_dataset(expected: CatalogMetricAlert, actual_args: dict) -> bool | None:
|
|
456
|
+
"""The ANOMALY detection dataset, compared verbatim; ``None`` when unasserted."""
|
|
457
|
+
if expected.date_dataset_id is None:
|
|
458
|
+
return None
|
|
459
|
+
return actual_args.get("date_dataset_id") == expected.date_dataset_id
|
|
460
|
+
|
|
461
|
+
|
|
361
462
|
def _check_metric(expected: CatalogMetricAlert, actual_args: dict) -> bool:
|
|
362
463
|
if not expected.metric_id:
|
|
363
464
|
return True
|
|
@@ -396,6 +497,65 @@ def _resolve_internal_recipient_ids(sdk: GoodDataSdk, emails: list[str]) -> set[
|
|
|
396
497
|
return ids
|
|
397
498
|
|
|
398
499
|
|
|
500
|
+
_AUTOMATION_PAGE_SIZE = 500
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _automation_ids(host: str, token: str, workspace_id: str) -> set[str] | None:
|
|
504
|
+
"""Ids of every automation of the workspace, page by page, or None when they cannot all be listed.
|
|
505
|
+
|
|
506
|
+
A partial list would make an automation that existed before the run look new to the cleanup,
|
|
507
|
+
so any failure, including a page that adds nothing, returns None.
|
|
508
|
+
"""
|
|
509
|
+
ids: set[str] = set()
|
|
510
|
+
page = 0
|
|
511
|
+
try:
|
|
512
|
+
while True:
|
|
513
|
+
resp = httpx.get(
|
|
514
|
+
f"{host.rstrip('/')}/api/v1/entities/workspaces/{workspace_id}/automations",
|
|
515
|
+
params={"size": _AUTOMATION_PAGE_SIZE, "page": page},
|
|
516
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
517
|
+
timeout=30.0,
|
|
518
|
+
)
|
|
519
|
+
resp.raise_for_status()
|
|
520
|
+
body = resp.json()
|
|
521
|
+
# A body without a `data` list is not an empty workspace: read as one, it would make
|
|
522
|
+
# an alert that existed before the run look new to the cleanup.
|
|
523
|
+
data = body.get("data") if isinstance(body, dict) else None
|
|
524
|
+
if not isinstance(data, list):
|
|
525
|
+
raise ValueError(f"page {page} has no data list")
|
|
526
|
+
page_ids = {item.get("id") for item in data if isinstance(item, dict)}
|
|
527
|
+
if len(page_ids) != len(data) or not all(isinstance(i, str) and i for i in page_ids):
|
|
528
|
+
raise ValueError(f"page {page} lists an automation without an id")
|
|
529
|
+
if len(data) < _AUTOMATION_PAGE_SIZE:
|
|
530
|
+
return ids | page_ids
|
|
531
|
+
if page_ids <= ids:
|
|
532
|
+
raise ValueError(f"page {page} repeats automations already listed")
|
|
533
|
+
ids |= page_ids
|
|
534
|
+
page += 1
|
|
535
|
+
except Exception as exc:
|
|
536
|
+
print(f"[CLEANUP] Listing automations failed: {exc}")
|
|
537
|
+
return None
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _parsed_arguments(tc: ToolCallEvent) -> dict:
|
|
541
|
+
"""A tool call's arguments, or ``{}`` when they are not a JSON object."""
|
|
542
|
+
args = tc.parsed_arguments()
|
|
543
|
+
return args if isinstance(args, dict) else {}
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _named_automation_ids(tool_call_events: list[ToolCallEvent]) -> set[str]:
|
|
547
|
+
"""``automation_id`` values the agent passed to the proposal and create tools.
|
|
548
|
+
|
|
549
|
+
A create call can succeed on the server while its event is missing from the turn the
|
|
550
|
+
harness reads, so the id the agent named is the only handle left for cleanup.
|
|
551
|
+
"""
|
|
552
|
+
names = (_PROPOSAL_TOOL, "create_metric_alert")
|
|
553
|
+
# Filtered before the set: a rejected call may carry an unhashable value such as a list, and
|
|
554
|
+
# this runs in the cleanup, where an error would drop the run and the other named ids.
|
|
555
|
+
ids = (_parsed_arguments(tc).get("automation_id") for tc in tool_call_events if tc.function_name in names)
|
|
556
|
+
return {i for i in ids if isinstance(i, str) and i}
|
|
557
|
+
|
|
558
|
+
|
|
399
559
|
def _resolve_current_user_id(host: str, token: str) -> str | None:
|
|
400
560
|
"""Id of the user that owns ``token``, or None if the profile cannot be read.
|
|
401
561
|
|
|
@@ -483,15 +643,24 @@ def generate_simulated_alert_response(
|
|
|
483
643
|
raise OSError("OPENAI_API_KEY environment variable is not set")
|
|
484
644
|
|
|
485
645
|
openai_client = _OpenAI(api_key=api_key)
|
|
646
|
+
if not expected.expect_alert:
|
|
647
|
+
return _ask_simulated_user(
|
|
648
|
+
openai_client, _no_alert_sim_user_prompt(question), conversation_history, agent_message
|
|
649
|
+
)
|
|
486
650
|
|
|
487
651
|
metric = expected.metric_id or "not specified"
|
|
652
|
+
# Rule 9 lists the values of the `any_of` combinations; rule 1 points there instead of
|
|
653
|
+
# stating the item's own value, which no combination may share.
|
|
654
|
+
in_rule_9 = "one of the combinations in rule 9"
|
|
488
655
|
operator = expected.operator
|
|
489
656
|
# BETWEEN / NOT_BETWEEN carry their value in threshold_from/threshold_to, so `threshold` is
|
|
490
657
|
# None for them. Rule 3 asks the sim-user to verify the threshold, and reporting "not
|
|
491
658
|
# specified" made it demand the agent delete both bounds of a BETWEEN condition — an
|
|
492
659
|
# impossible request that burned every iteration without the alert ever being created.
|
|
493
660
|
threshold: str | float | int
|
|
494
|
-
if
|
|
661
|
+
if any(_states_threshold(a) for a in expected.alternatives):
|
|
662
|
+
threshold = in_rule_9
|
|
663
|
+
elif expected.operator in ("BETWEEN", "NOT_BETWEEN") and (
|
|
495
664
|
expected.threshold_from is not None or expected.threshold_to is not None
|
|
496
665
|
):
|
|
497
666
|
threshold = f"between {expected.threshold_from} and {expected.threshold_to}"
|
|
@@ -524,7 +693,9 @@ def generate_simulated_alert_response(
|
|
|
524
693
|
" Do not wait for the agent to ask — state it alongside the metric and condition answers.\n"
|
|
525
694
|
)
|
|
526
695
|
trigger = expected.trigger
|
|
527
|
-
|
|
696
|
+
alternative_filters = any(a.filters is not None for a in expected.alternatives)
|
|
697
|
+
# The combinations' filters replace the item's own, so rule 1 must not state those as well.
|
|
698
|
+
filters = None if alternative_filters else expected.filters
|
|
528
699
|
|
|
529
700
|
# "not specified" is the normalizer's stand-in for an absent trigger, which the product
|
|
530
701
|
# persists as its ALWAYS default and `_check_trigger` asserts as ALWAYS. Both the cadence to
|
|
@@ -533,12 +704,20 @@ def generate_simulated_alert_response(
|
|
|
533
704
|
# ONCE/ONCE_PER_INTERVAL proposal that the assertion then failed.
|
|
534
705
|
trigger_key = "ALWAYS" if trigger in _ALWAYS_TRIGGER_VALUES else trigger
|
|
535
706
|
trigger_request = _TRIGGER_INSTRUCTIONS.get(trigger_key, f"set the trigger to {trigger}")
|
|
707
|
+
if expected.trigger_interval:
|
|
708
|
+
trigger_request += f", with a trigger interval of {expected.trigger_interval}"
|
|
536
709
|
|
|
537
710
|
# Three branches, matching the three states of `expected.filters`. `[]` and `None` must not
|
|
538
711
|
# share one: telling the sim-user "you want NO filters" on an unstated expectation makes it
|
|
539
712
|
# refuse filters the request genuinely implies (e.g. "orders from the United States"), which
|
|
540
713
|
# quietly turns that fixture into a weaker test rather than a failing one.
|
|
541
|
-
if
|
|
714
|
+
if alternative_filters:
|
|
715
|
+
filters_rule = (
|
|
716
|
+
"5. The filters you want depend on the combination in rule 9 you accept. Refuse any filter "
|
|
717
|
+
"that is not part of that combination. A combination that names no filters wants only the "
|
|
718
|
+
"filters your original request implies: do not invent a date window it never asked for.\n"
|
|
719
|
+
)
|
|
720
|
+
elif filters:
|
|
542
721
|
filters_rule = (
|
|
543
722
|
f"5. Your alert needs exactly these filters and NOTHING else: {filters}. "
|
|
544
723
|
"If the agent offers, proposes or asks about any further date/time window, "
|
|
@@ -571,7 +750,10 @@ def generate_simulated_alert_response(
|
|
|
571
750
|
"7. This is an ANOMALY alert. Anomaly detection REQUIRES a time granularity, and that "
|
|
572
751
|
f"granularity is NOT a date filter. State it in your first reply and repeat it whenever "
|
|
573
752
|
f"asked: use {granularity} granularity. Rule 5 constrains filters on the metric only — it "
|
|
574
|
-
"never applies to this detection interval, so never refuse to give one
|
|
753
|
+
"never applies to this detection interval, so never refuse to give one."
|
|
754
|
+
+ (f" Use {expected.sensitivity} sensitivity." if expected.sensitivity else "")
|
|
755
|
+
+ (f" Detect on the date dataset {expected.date_dataset_id}." if expected.date_dataset_id else "")
|
|
756
|
+
+ "\n"
|
|
575
757
|
)
|
|
576
758
|
elif operator in _RELATIVE_OPERATORS:
|
|
577
759
|
# The item names no comparison date or period; delegating is an answer the agent accepts,
|
|
@@ -582,7 +764,9 @@ def generate_simulated_alert_response(
|
|
|
582
764
|
"year), and those are NOT a date filter. Rule 5 constrains filters on the metric only — "
|
|
583
765
|
"it never applies to the comparison. If the agent asks which date or which period the "
|
|
584
766
|
"comparison should use, do not refuse and do not name one yourself: hand the choice back, "
|
|
585
|
-
"for example 'Pick whichever date and period fit best.'
|
|
767
|
+
"for example 'Pick whichever date and period fit best.' A proposal's filters may list one "
|
|
768
|
+
"relative date filter for that comparison date: it is the comparison period, not a time "
|
|
769
|
+
"window, so never refuse it.\n"
|
|
586
770
|
)
|
|
587
771
|
else:
|
|
588
772
|
period_rule = (
|
|
@@ -591,6 +775,9 @@ def generate_simulated_alert_response(
|
|
|
591
775
|
)
|
|
592
776
|
|
|
593
777
|
original_request = f'Your original request to the agent was: "{question}"\n' if question else ""
|
|
778
|
+
if expected.setup_turns:
|
|
779
|
+
earlier = " / ".join(f'"{turn}"' for turn in expected.setup_turns)
|
|
780
|
+
original_request = f"Earlier in this conversation you asked: {earlier}.\n" + original_request
|
|
594
781
|
|
|
595
782
|
# The agent may offer several metrics and describe one as ignoring filters or counting all
|
|
596
783
|
# time. That reads like rule 5's "no filters ... all time", which made the simulated user
|
|
@@ -624,6 +811,9 @@ def generate_simulated_alert_response(
|
|
|
624
811
|
f"1. Your goal: metric={metric}, operator={operator}, threshold={threshold}, "
|
|
625
812
|
f"recipients={recipients}, trigger={trigger_key}"
|
|
626
813
|
+ (f", filters={filters}" if filters else "")
|
|
814
|
+
+ (f", sensitivity={expected.sensitivity}" if expected.sensitivity else "")
|
|
815
|
+
+ (f", trigger interval={expected.trigger_interval}" if expected.trigger_interval else "")
|
|
816
|
+
+ (f", date dataset={expected.date_dataset_id}" if expected.date_dataset_id else "")
|
|
627
817
|
+ ".\n"
|
|
628
818
|
+ metric_choice_rule
|
|
629
819
|
+ "2. Never revert or change a decision that was already confirmed in a previous turn.\n"
|
|
@@ -642,9 +832,46 @@ def generate_simulated_alert_response(
|
|
|
642
832
|
" Repeat it if the agent proposes a different cadence.\n"
|
|
643
833
|
+ period_rule
|
|
644
834
|
+ title_rule
|
|
835
|
+
+ _alternatives_rule(expected)
|
|
645
836
|
+ "Reply concisely and directly."
|
|
646
837
|
)
|
|
647
838
|
|
|
839
|
+
return _ask_simulated_user(openai_client, system_prompt, conversation_history, agent_message)
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _states_threshold(option: CatalogMetricAlert) -> bool:
|
|
843
|
+
return option.threshold is not None or option.threshold_from is not None or option.threshold_to is not None
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def _alternatives_rule(expected: CatalogMetricAlert) -> str:
|
|
847
|
+
"""Rule 9: the combinations an `any_of` item accepts, by their threshold and filters.
|
|
848
|
+
|
|
849
|
+
Options differ in nothing else (``_ANY_OF_FIELDS``), so rules 1-8 state every other field.
|
|
850
|
+
"""
|
|
851
|
+
if not expected.alternatives:
|
|
852
|
+
return ""
|
|
853
|
+
combinations: list[str] = []
|
|
854
|
+
for letter, option in zip(_COMBINATION_LABELS, expected.alternatives, strict=False):
|
|
855
|
+
parts: list[str] = []
|
|
856
|
+
if option.threshold is not None:
|
|
857
|
+
parts.append(f"threshold={option.threshold}")
|
|
858
|
+
if option.threshold_from is not None or option.threshold_to is not None:
|
|
859
|
+
parts.append(f"threshold=between {option.threshold_from} and {option.threshold_to}")
|
|
860
|
+
if option.filters is not None:
|
|
861
|
+
parts.append(f"filters={json.dumps(option.filters)}" if option.filters else "filters=no filter at all")
|
|
862
|
+
# Never empty: options differ only in threshold and filters, and never repeat one another.
|
|
863
|
+
combinations.append(f"{letter}) " + ", ".join(parts))
|
|
864
|
+
return (
|
|
865
|
+
"9. Your goal can be met by any ONE of these combinations: "
|
|
866
|
+
+ " | ".join(combinations)
|
|
867
|
+
+ ". A value a combination names replaces the value rules 1-8 give for that field. "
|
|
868
|
+
"Accept a proposal only when it matches one combination in full. If it mixes fields of "
|
|
869
|
+
"different combinations or matches none, do NOT confirm: ask for the combination closest to "
|
|
870
|
+
"what the agent proposed. Never name a value yourself unless the agent asks for one.\n"
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def _ask_simulated_user(openai_client: Any, system_prompt: str, conversation_history: list, agent_message: str) -> str:
|
|
648
875
|
messages: list = [{"role": "system", "content": system_prompt}]
|
|
649
876
|
messages.extend(conversation_history)
|
|
650
877
|
messages.append(
|
|
@@ -658,6 +885,24 @@ def generate_simulated_alert_response(
|
|
|
658
885
|
return response.choices[0].message.content or ""
|
|
659
886
|
|
|
660
887
|
|
|
888
|
+
def _no_alert_sim_user_prompt(question: str) -> str:
|
|
889
|
+
"""The simulated user of an item whose request names nothing the workspace can monitor.
|
|
890
|
+
|
|
891
|
+
It never accepts a substitute: the check is whether the agent proposes one anyway.
|
|
892
|
+
"""
|
|
893
|
+
return (
|
|
894
|
+
"You are a user who asked an AI agent to create an alert.\n"
|
|
895
|
+
f'Your original request to the agent was: "{question}"\n'
|
|
896
|
+
"The workspace may not have what you asked for. Rules you MUST follow:\n"
|
|
897
|
+
"1. You want an alert only on exactly what you asked for. Never accept a different or similar metric, "
|
|
898
|
+
"never ask the agent to create a new metric, and never confirm an alert proposal.\n"
|
|
899
|
+
"2. If the agent offers alternatives or asks which one to use, decline them all and say you only wanted "
|
|
900
|
+
"what you asked for.\n"
|
|
901
|
+
"3. If the agent says it cannot create the alert, accept that and end politely.\n"
|
|
902
|
+
"Reply concisely and directly."
|
|
903
|
+
)
|
|
904
|
+
|
|
905
|
+
|
|
661
906
|
def _delete_alert(sdk: GoodDataSdk, workspace_id: str, alert_id: str) -> None:
|
|
662
907
|
"""Best-effort delete of an alert (automation) created during evaluation.
|
|
663
908
|
|
|
@@ -687,6 +932,14 @@ class AlertEvaluation:
|
|
|
687
932
|
comparison_correct: bool | None = None
|
|
688
933
|
title_correct: bool | None = None
|
|
689
934
|
dashboard_correct: bool | None = None
|
|
935
|
+
alert_sensitivity_correct: bool | None = None
|
|
936
|
+
alert_trigger_interval_correct: bool | None = None
|
|
937
|
+
alert_date_dataset_correct: bool | None = None
|
|
938
|
+
# Scored on the first proposal, before the simulated user could correct it.
|
|
939
|
+
alert_initial_filters_correct: bool | None = None
|
|
940
|
+
alert_initial_recipients_correct: bool | None = None
|
|
941
|
+
# Set only for an item that expects no alert; then it is the run's one check.
|
|
942
|
+
alert_not_proposed: bool | None = None
|
|
690
943
|
|
|
691
944
|
def checks(self) -> dict[str, bool]:
|
|
692
945
|
"""Every check that ran, by name; strict_pass requires all of them.
|
|
@@ -695,6 +948,8 @@ class AlertEvaluation:
|
|
|
695
948
|
not report a ``title_correct`` it was never scored on, and a refusal on it is not counted
|
|
696
949
|
as a title failure.
|
|
697
950
|
"""
|
|
951
|
+
if self.alert_not_proposed is not None:
|
|
952
|
+
return {_NO_ALERT_CHECK: self.alert_not_proposed}
|
|
698
953
|
ran: dict[str, bool] = {name: getattr(self, name) for name in _ALERT_CHECKS}
|
|
699
954
|
for name in _CONDITIONAL_ALERT_CHECKS:
|
|
700
955
|
value = getattr(self, name)
|
|
@@ -829,6 +1084,9 @@ def _normalize_expected_comparison(expected: dict) -> dict[str, str | int | floa
|
|
|
829
1084
|
if arg is None:
|
|
830
1085
|
# Validated here so a misspelled property fails before the run spends an API call.
|
|
831
1086
|
raise ValueError(f"Unrecognised comparison property {key!r}; expected one of {sorted(_COMPARISON_ARGS)}")
|
|
1087
|
+
if arg in _COMPARISON_ID_ARGS and value is not None and not isinstance(value, str):
|
|
1088
|
+
# str() would turn ["net_sales_goal"] into an id no tool argument can ever equal.
|
|
1089
|
+
raise ValueError(f"Comparison {key} must be an object id string, got {value!r}")
|
|
832
1090
|
canonical = _canonical_comparison_value(arg, value)
|
|
833
1091
|
if canonical is None and arg == "comparison_periods_ago" and str(value or "").strip():
|
|
834
1092
|
raise ValueError(f"Comparison periods_ago must be a number, got {value!r}")
|
|
@@ -868,8 +1126,153 @@ def _normalize_expected_dashboard(expected: dict) -> str | None:
|
|
|
868
1126
|
return parsed
|
|
869
1127
|
|
|
870
1128
|
|
|
1129
|
+
def _normalize_expected_enum(expected: dict, allowed: tuple[str, ...], *keys: str) -> str | None:
|
|
1130
|
+
"""A stated enum value, upper-cased; raises on a value outside ``allowed`` so a typo never reads green."""
|
|
1131
|
+
value = _normalize_expected_text(expected, *keys)
|
|
1132
|
+
if value is None:
|
|
1133
|
+
return None
|
|
1134
|
+
canonical = value.upper()
|
|
1135
|
+
if canonical not in allowed:
|
|
1136
|
+
raise ValueError(f"{keys[0]} expectation must be one of {list(allowed)}, got {value!r}")
|
|
1137
|
+
return canonical
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def _normalize_expect_alert(expected: dict) -> bool:
|
|
1141
|
+
"""``Expect alert: false`` marks an item whose request must end without any alert."""
|
|
1142
|
+
value = _case_insensitive_get(expected, "expect_alert", "expect alert")
|
|
1143
|
+
if value is None:
|
|
1144
|
+
return True
|
|
1145
|
+
if not isinstance(value, bool):
|
|
1146
|
+
raise ValueError(f"expect_alert must be true or false, got {value!r}")
|
|
1147
|
+
if not value:
|
|
1148
|
+
stated = sorted(k for k in expected if str(k).strip().lower() in _ALERT_ONLY_KEYS)
|
|
1149
|
+
if stated:
|
|
1150
|
+
raise ValueError(f"expect_alert: false states no alert, but the item also states {stated}")
|
|
1151
|
+
return value
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
def _normalize_setup_turns(expected: dict) -> tuple[str, ...]:
|
|
1155
|
+
"""Messages sent before the question; each one a non-empty string."""
|
|
1156
|
+
turns = _case_insensitive_get(expected, "setup_turns", "setup turns")
|
|
1157
|
+
if turns is None:
|
|
1158
|
+
return ()
|
|
1159
|
+
if not isinstance(turns, list) or not all(isinstance(t, str) and t.strip() for t in turns):
|
|
1160
|
+
raise ValueError(f"setup_turns must be a list of non-empty strings, got {turns!r}")
|
|
1161
|
+
return tuple(turns)
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
def _normalize_check_first_proposal(
|
|
1165
|
+
expected: dict, *, filters_stated: bool, recipients_stated: bool
|
|
1166
|
+
) -> tuple[str, ...]:
|
|
1167
|
+
"""Fields also scored on the first proposal; each must be one the item states."""
|
|
1168
|
+
value = _case_insensitive_get(expected, *_CHECK_FIRST_PROPOSAL_KEYS)
|
|
1169
|
+
if value is None:
|
|
1170
|
+
return ()
|
|
1171
|
+
if not isinstance(value, list) or not value or any(field not in _FIRST_PROPOSAL_FIELDS for field in value):
|
|
1172
|
+
raise ValueError(
|
|
1173
|
+
f"check_first_proposal must be a non-empty list of {list(_FIRST_PROPOSAL_FIELDS)}, got {value!r}"
|
|
1174
|
+
)
|
|
1175
|
+
if "filters" in value and not filters_stated:
|
|
1176
|
+
raise ValueError("check_first_proposal names filters, but the item states no filter expectation")
|
|
1177
|
+
if "recipients" in value and not recipients_stated:
|
|
1178
|
+
raise ValueError("check_first_proposal names recipients, but the item states no recipients")
|
|
1179
|
+
return tuple(dict.fromkeys(value))
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
_ANY_OF_KEYS = ("any_of", "any of")
|
|
1183
|
+
_CHECK_FIRST_PROPOSAL_KEYS = ("check_first_proposal", "check first proposal")
|
|
1184
|
+
# Keys that describe the item, not one possible alert, so an `any_of` option may not state them.
|
|
1185
|
+
_ITEM_LEVEL_KEYS = (
|
|
1186
|
+
*_ANY_OF_KEYS,
|
|
1187
|
+
*_CHECK_FIRST_PROPOSAL_KEYS,
|
|
1188
|
+
"setup_turns",
|
|
1189
|
+
"setup turns",
|
|
1190
|
+
"expect_alert",
|
|
1191
|
+
"expect alert",
|
|
1192
|
+
)
|
|
1193
|
+
# Spellings of the filter expectation; an option stating one replaces all of them.
|
|
1194
|
+
_FILTER_KEYS = ("filters", "time window/filters", "time_window")
|
|
1195
|
+
# Every group of spellings the normalizer reads as one field; an option stating one spelling
|
|
1196
|
+
# replaces the whole group, or the item's other spelling would be read instead of the option's.
|
|
1197
|
+
_KEY_SPELLINGS = (
|
|
1198
|
+
_FILTER_KEYS,
|
|
1199
|
+
("recipients", "recipient(s)"),
|
|
1200
|
+
("metric_id", "metric"),
|
|
1201
|
+
("dashboard_id", "dashboard"),
|
|
1202
|
+
("granularity", "detection granularity"),
|
|
1203
|
+
("trigger_interval", "trigger interval"),
|
|
1204
|
+
("date_dataset_id", "date dataset"),
|
|
1205
|
+
)
|
|
1206
|
+
|
|
1207
|
+
|
|
1208
|
+
def _merge_option(base: dict, option: dict) -> dict:
|
|
1209
|
+
"""``base`` with ``option``'s keys replacing the same keys, compared case-insensitively."""
|
|
1210
|
+
replaced = {str(k).strip().lower() for k in option}
|
|
1211
|
+
for spellings in _KEY_SPELLINGS:
|
|
1212
|
+
if replaced & set(spellings):
|
|
1213
|
+
replaced |= set(spellings)
|
|
1214
|
+
return {**{k: v for k, v in base.items() if str(k).strip().lower() not in replaced}, **option}
|
|
1215
|
+
|
|
1216
|
+
|
|
871
1217
|
def _normalize_expected_output(expected: dict) -> CatalogMetricAlert:
|
|
872
|
-
"""Parse expected_output
|
|
1218
|
+
"""Parse expected_output into CatalogMetricAlert; ``any_of`` lists complete alternatives.
|
|
1219
|
+
|
|
1220
|
+
Each ``any_of`` option replaces some fields of the item (``Threshold``, ``Filters``, ...) and
|
|
1221
|
+
keeps the rest, so fields that must agree (a threshold and the period it is measured over)
|
|
1222
|
+
are matched together, never one from each option.
|
|
1223
|
+
"""
|
|
1224
|
+
options = _case_insensitive_get(expected, *_ANY_OF_KEYS)
|
|
1225
|
+
if options is None:
|
|
1226
|
+
return _normalize_single_expectation(expected)
|
|
1227
|
+
if not isinstance(options, list) or len(options) < 2 or not all(isinstance(o, dict) and o for o in options):
|
|
1228
|
+
raise ValueError(f"any_of must list at least two non-empty objects, got {options!r}")
|
|
1229
|
+
if len(options) > len(_COMBINATION_LABELS):
|
|
1230
|
+
raise ValueError(f"any_of lists {len(options)} options; the simulated user is told at most 26")
|
|
1231
|
+
for option in options:
|
|
1232
|
+
item_level = sorted(k for k in option if str(k).strip().lower() in _ITEM_LEVEL_KEYS)
|
|
1233
|
+
if item_level:
|
|
1234
|
+
raise ValueError(f"an any_of option may not state {item_level}; state them once for the item")
|
|
1235
|
+
base = {k: v for k, v in expected.items() if str(k).strip().lower() not in _ANY_OF_KEYS}
|
|
1236
|
+
if _normalize_expect_alert(base) is False:
|
|
1237
|
+
raise ValueError("expect_alert: false states no alert, so it cannot list alternatives")
|
|
1238
|
+
alternatives = tuple(_normalize_single_expectation(_merge_option(base, option)) for option in options)
|
|
1239
|
+
_validate_alternatives(alternatives)
|
|
1240
|
+
# The item is what the options share, not the base parsed on its own: the base alone may be
|
|
1241
|
+
# incomplete (a trigger interval whose trigger only the options give), and a value every
|
|
1242
|
+
# option replaces is no longer the goal. A field the options disagree on keeps its default;
|
|
1243
|
+
# rule 9 states it per combination.
|
|
1244
|
+
shared = {
|
|
1245
|
+
f.name: getattr(alternatives[0], f.name)
|
|
1246
|
+
for f in dataclasses.fields(CatalogMetricAlert)
|
|
1247
|
+
if all(getattr(a, f.name) == getattr(alternatives[0], f.name) for a in alternatives[1:])
|
|
1248
|
+
}
|
|
1249
|
+
return dataclasses.replace(CatalogMetricAlert(**shared), alternatives=alternatives)
|
|
1250
|
+
|
|
1251
|
+
|
|
1252
|
+
def _validate_alternatives(alternatives: tuple[CatalogMetricAlert, ...]) -> None:
|
|
1253
|
+
"""Reject `any_of` options the simulated user could not tell apart or that would accept anything."""
|
|
1254
|
+
exempt = (*_ANY_OF_FIELDS, "alternatives")
|
|
1255
|
+
differing = sorted(
|
|
1256
|
+
f.name
|
|
1257
|
+
for f in dataclasses.fields(CatalogMetricAlert)
|
|
1258
|
+
if f.name not in exempt and any(getattr(a, f.name) != getattr(alternatives[0], f.name) for a in alternatives)
|
|
1259
|
+
)
|
|
1260
|
+
if differing:
|
|
1261
|
+
# Rules 1-8 state each other field once; the simulated user never sees a proposal's
|
|
1262
|
+
# group-by at all. A field that differs would be asked for one way and scored another.
|
|
1263
|
+
raise ValueError(f"any_of options may differ only in threshold and filters, not in {differing}")
|
|
1264
|
+
for name, states in (("Threshold", _states_threshold), ("Filters", lambda a: a.filters is not None)):
|
|
1265
|
+
if len({states(a) for a in alternatives}) > 1:
|
|
1266
|
+
# An option without it inherits an unstated base and accepts any value: the mix any_of blocks.
|
|
1267
|
+
raise ValueError(f"every any_of option must state {name}, or none may (Filters: [] means no filter)")
|
|
1268
|
+
for i, option in enumerate(alternatives):
|
|
1269
|
+
# A misspelled key ("Thresold") is ignored, which often leaves two options the same.
|
|
1270
|
+
if option in alternatives[:i]:
|
|
1271
|
+
raise ValueError(f"any_of option {i + 1} repeats an earlier one; is one of its keys misspelled?")
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _normalize_single_expectation(expected: dict) -> CatalogMetricAlert:
|
|
1275
|
+
"""Parse one expectation, accepting display-format or internal-format keys."""
|
|
873
1276
|
operator = _case_insensitive_get(expected, "operator") or "GREATER_THAN"
|
|
874
1277
|
threshold = _case_insensitive_get(expected, "threshold")
|
|
875
1278
|
threshold_from = _case_insensitive_get(expected, "threshold_from")
|
|
@@ -901,6 +1304,20 @@ def _normalize_expected_output(expected: dict) -> CatalogMetricAlert:
|
|
|
901
1304
|
comparison = _normalize_expected_comparison(expected)
|
|
902
1305
|
title = _normalize_expected_text(expected, "title")
|
|
903
1306
|
dashboard_id = _normalize_expected_dashboard(expected)
|
|
1307
|
+
expect_alert = _normalize_expect_alert(expected)
|
|
1308
|
+
sensitivity = _normalize_expected_enum(expected, _SENSITIVITIES, "sensitivity")
|
|
1309
|
+
trigger_interval = _normalize_expected_enum(expected, _TRIGGER_INTERVALS, "trigger_interval", "trigger interval")
|
|
1310
|
+
date_dataset_id = _normalize_expected_text(expected, "date_dataset_id", "date dataset")
|
|
1311
|
+
setup_turns = _normalize_setup_turns(expected)
|
|
1312
|
+
check_first_proposal = _normalize_check_first_proposal(
|
|
1313
|
+
expected, filters_stated=filters is not None, recipients_stated=bool(recipients)
|
|
1314
|
+
)
|
|
1315
|
+
if trigger_interval is not None and trigger != "ONCE_PER_INTERVAL":
|
|
1316
|
+
raise ValueError(f"trigger_interval applies only to the ONCE_PER_INTERVAL trigger, got trigger {trigger!r}")
|
|
1317
|
+
# Both are ANOMALY arguments. On any other operator the agent sends neither, so a stated
|
|
1318
|
+
# MEDIUM would always match the default and only raise the quality score.
|
|
1319
|
+
if (sensitivity is not None or date_dataset_id is not None) and operator != "ANOMALY":
|
|
1320
|
+
raise ValueError(f"sensitivity and date_dataset_id apply only to the ANOMALY operator, got {operator!r}")
|
|
904
1321
|
|
|
905
1322
|
return CatalogMetricAlert(
|
|
906
1323
|
operator=operator,
|
|
@@ -916,23 +1333,78 @@ def _normalize_expected_output(expected: dict) -> CatalogMetricAlert:
|
|
|
916
1333
|
comparison=comparison,
|
|
917
1334
|
title=title,
|
|
918
1335
|
dashboard_id=dashboard_id,
|
|
1336
|
+
expect_alert=expect_alert,
|
|
1337
|
+
sensitivity=sensitivity,
|
|
1338
|
+
trigger_interval=trigger_interval,
|
|
1339
|
+
date_dataset_id=date_dataset_id,
|
|
1340
|
+
setup_turns=setup_turns,
|
|
1341
|
+
check_first_proposal=check_first_proposal,
|
|
919
1342
|
)
|
|
920
1343
|
|
|
921
1344
|
|
|
922
|
-
def
|
|
923
|
-
"""
|
|
1345
|
+
def _alert_call_failed(result: dict | None) -> bool:
|
|
1346
|
+
"""Whether a ``create_metric_alert`` result reports an error, so the call created nothing.
|
|
1347
|
+
|
|
1348
|
+
An MCP error carries ``isError``. gen-ai's tool registry reports rejected arguments and a
|
|
1349
|
+
failed execution as ``{"success": false, "error": ...}`` instead, with no ``isError``.
|
|
1350
|
+
"""
|
|
1351
|
+
if not isinstance(result, dict):
|
|
1352
|
+
return False
|
|
1353
|
+
data = result.get("data")
|
|
1354
|
+
payloads = [result, data] if isinstance(data, dict) else [result]
|
|
1355
|
+
return any(p.get("isError") or p.get("success") is False for p in payloads)
|
|
1356
|
+
|
|
1357
|
+
|
|
1358
|
+
def _created_alert_id(result: dict | None) -> str | None:
|
|
1359
|
+
"""Server-assigned id of the automation a call created: it lives in the result, not the arguments."""
|
|
1360
|
+
if not isinstance(result, dict):
|
|
1361
|
+
return None
|
|
1362
|
+
data = result.get("data")
|
|
1363
|
+
alert_id = result.get("id") or (data.get("id") if isinstance(data, dict) else None)
|
|
1364
|
+
return alert_id if isinstance(alert_id, str) and alert_id else None
|
|
1365
|
+
|
|
1366
|
+
|
|
1367
|
+
@dataclass
|
|
1368
|
+
class _AlertCalls:
|
|
1369
|
+
"""Every ``create_metric_alert`` call of a turn, read for scoring and for cleanup."""
|
|
1370
|
+
|
|
1371
|
+
called: bool = False
|
|
1372
|
+
"""The agent called the tool at least once."""
|
|
1373
|
+
created: bool = False
|
|
1374
|
+
"""At least one call did not report an error."""
|
|
1375
|
+
created_ids: list[str] = field(default_factory=list)
|
|
1376
|
+
"""Ids of every alert the calls created; each one is deleted after the run."""
|
|
1377
|
+
args: dict = field(default_factory=dict)
|
|
1378
|
+
"""Arguments of the first call that did not fail, else of the last call."""
|
|
1379
|
+
alert_id: str | None = None
|
|
1380
|
+
"""Id of the alert the call in ``args`` created, None when that call failed or its result has no id."""
|
|
1381
|
+
|
|
1382
|
+
|
|
1383
|
+
def _extract_alert_calls(tool_call_events: list[ToolCallEvent]) -> _AlertCalls:
|
|
1384
|
+
"""Read every ``create_metric_alert`` call of a turn.
|
|
1385
|
+
|
|
1386
|
+
The agent may retry after an error. A call that failed created nothing, so the run is scored
|
|
1387
|
+
on the first call that did not fail, and the id of every alert a call created is collected so
|
|
1388
|
+
that alert is deleted after the run.
|
|
1389
|
+
"""
|
|
1390
|
+
calls = _AlertCalls()
|
|
924
1391
|
for tc in tool_call_events:
|
|
925
|
-
if tc.function_name
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
1392
|
+
if tc.function_name != "create_metric_alert":
|
|
1393
|
+
continue
|
|
1394
|
+
calls.called = True
|
|
1395
|
+
args = tc.parsed_arguments() or {}
|
|
1396
|
+
result = tc.parsed_result()
|
|
1397
|
+
if _alert_call_failed(result):
|
|
1398
|
+
if not calls.created:
|
|
1399
|
+
calls.args = args
|
|
1400
|
+
continue
|
|
1401
|
+
alert_id = _created_alert_id(result)
|
|
1402
|
+
if alert_id is not None:
|
|
1403
|
+
calls.created_ids.append(alert_id)
|
|
1404
|
+
if not calls.created:
|
|
1405
|
+
calls.created = True
|
|
1406
|
+
calls.args, calls.alert_id = args, alert_id
|
|
1407
|
+
return calls
|
|
936
1408
|
|
|
937
1409
|
|
|
938
1410
|
def render_alert_proposal(proposal: dict) -> str:
|
|
@@ -940,16 +1412,20 @@ def render_alert_proposal(proposal: dict) -> str:
|
|
|
940
1412
|
|
|
941
1413
|
The alert skill's confirmation step deliberately emits no text part (GDAI-2032) — the
|
|
942
1414
|
prompt and the CTA live only in the proposal payload, which the frontend renders as a
|
|
943
|
-
widget. Dumping the payload (rather than prose) keeps recipients, condition, trigger
|
|
944
|
-
dashboard visible so the simulated user can still verify them against its
|
|
945
|
-
not need updating whenever ``AlertProposal`` grows a field.
|
|
1415
|
+
widget. Dumping the payload (rather than prose) keeps recipients, condition, trigger,
|
|
1416
|
+
filters and dashboard visible so the simulated user can still verify them against its
|
|
1417
|
+
goal, and does not need updating whenever ``AlertProposal`` grows a field.
|
|
946
1418
|
"""
|
|
947
1419
|
cta = proposal.get("cta") or "Should I create this alert?"
|
|
948
1420
|
summary = {k: v for k, v in proposal.items() if k != "cta"}
|
|
949
1421
|
alert = dict(summary.get("alert") or {})
|
|
950
|
-
#
|
|
951
|
-
#
|
|
952
|
-
|
|
1422
|
+
# `execution` is the only place a proposal carries its filters, which rule 3 of the simulated
|
|
1423
|
+
# user checks. Hoisting them keeps them visible. The rest stays out: the measures
|
|
1424
|
+
# repeat `condition`, and the simulated user is told nothing about group-bys, so a date
|
|
1425
|
+
# group-by would only read as a time window rule 5 tells it to refuse.
|
|
1426
|
+
execution = alert.pop("execution", None)
|
|
1427
|
+
if isinstance(execution, dict):
|
|
1428
|
+
alert["filters"] = execution.get("filters") or []
|
|
953
1429
|
if "alert" in summary:
|
|
954
1430
|
# Key off presence, not truthiness: an alert whose only key was `execution` must
|
|
955
1431
|
# still be replaced, otherwise the original (execution-bearing) dict survives.
|
|
@@ -969,6 +1445,127 @@ def render_turn_for_simulated_user(chat_result: ChatResult) -> str:
|
|
|
969
1445
|
return "\n\n".join(chunk for chunk in chunks if chunk)
|
|
970
1446
|
|
|
971
1447
|
|
|
1448
|
+
def _first_proposal(turns: list[list[ToolCallEvent]]) -> tuple[dict, dict] | None:
|
|
1449
|
+
"""Arguments and result of the first proposal the user was shown, or None when none succeeded.
|
|
1450
|
+
|
|
1451
|
+
``turns`` holds the tool calls of each scored turn, in order. The user sees only the last
|
|
1452
|
+
proposal of a turn, so a proposal the agent replaced within the same turn is not the answer.
|
|
1453
|
+
|
|
1454
|
+
The result carries the proposal's filters in the AFM form ``create_metric_alert`` receives
|
|
1455
|
+
(``afm_filters``, empty when left out), the same form the expectation is written in.
|
|
1456
|
+
"""
|
|
1457
|
+
for events in turns:
|
|
1458
|
+
shown: tuple[dict, dict] | None = None
|
|
1459
|
+
for tc in events:
|
|
1460
|
+
if tc.function_name != _PROPOSAL_TOOL:
|
|
1461
|
+
continue
|
|
1462
|
+
result = tc.parsed_result()
|
|
1463
|
+
# gen-ai's result always names the stored proposal; its filters default to none.
|
|
1464
|
+
if isinstance(result, dict) and result.get("success") is not False and result.get("alert_proposal_ref"):
|
|
1465
|
+
shown = _parsed_arguments(tc), result
|
|
1466
|
+
if shown is not None:
|
|
1467
|
+
return shown
|
|
1468
|
+
return None
|
|
1469
|
+
|
|
1470
|
+
|
|
1471
|
+
def _proposal_recipient_args(proposal_args: dict) -> dict:
|
|
1472
|
+
"""A proposal's recipient list as the ``create_metric_alert`` arguments `_check_recipients` reads.
|
|
1473
|
+
|
|
1474
|
+
The list may arrive JSON-encoded as a string, as the create tool's recipient lists do.
|
|
1475
|
+
"""
|
|
1476
|
+
raw = proposal_args.get("recipients")
|
|
1477
|
+
if isinstance(raw, str):
|
|
1478
|
+
try:
|
|
1479
|
+
raw = json.loads(raw)
|
|
1480
|
+
except ValueError:
|
|
1481
|
+
raw = None
|
|
1482
|
+
recipients = [r for r in raw if isinstance(r, dict)] if isinstance(raw, list) else []
|
|
1483
|
+
return {
|
|
1484
|
+
"internal_recipients": [r["id"] for r in recipients if r.get("id")],
|
|
1485
|
+
"external_recipients": [r["email"] for r in recipients if not r.get("id") and r.get("email")],
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def _evaluate_first_proposal(
|
|
1490
|
+
expected: CatalogMetricAlert,
|
|
1491
|
+
turns: list[list[ToolCallEvent]],
|
|
1492
|
+
sdk: GoodDataSdk,
|
|
1493
|
+
current_user_id: str | None,
|
|
1494
|
+
) -> tuple[bool | None, bool | None]:
|
|
1495
|
+
"""(filters, recipients) of the first proposal; ``None`` for a field the item does not name.
|
|
1496
|
+
|
|
1497
|
+
The final alert can be right only because the simulated user corrected the first proposal.
|
|
1498
|
+
These checks keep that first answer visible.
|
|
1499
|
+
"""
|
|
1500
|
+
if not expected.check_first_proposal:
|
|
1501
|
+
return None, None
|
|
1502
|
+
proposal = _first_proposal(turns)
|
|
1503
|
+
filters_ok: bool | None = None
|
|
1504
|
+
recipients_ok: bool | None = None
|
|
1505
|
+
if "filters" in expected.check_first_proposal:
|
|
1506
|
+
filters_ok = proposal is not None and _check_filters(
|
|
1507
|
+
expected, {"filters": proposal[1].get("afm_filters") or []}
|
|
1508
|
+
)
|
|
1509
|
+
if "recipients" in expected.check_first_proposal:
|
|
1510
|
+
recipients_ok = proposal is not None and _check_recipients(
|
|
1511
|
+
expected, _proposal_recipient_args(proposal[0]), sdk=sdk, current_user_id=current_user_id
|
|
1512
|
+
)
|
|
1513
|
+
return filters_ok, recipients_ok
|
|
1514
|
+
|
|
1515
|
+
|
|
1516
|
+
def _evaluate_alert(
|
|
1517
|
+
expected: CatalogMetricAlert,
|
|
1518
|
+
actual_args: dict,
|
|
1519
|
+
alert_created: bool,
|
|
1520
|
+
sdk: GoodDataSdk,
|
|
1521
|
+
current_user_id: str | None,
|
|
1522
|
+
proposal_turns: list[list[ToolCallEvent]] | None = None,
|
|
1523
|
+
) -> AlertEvaluation:
|
|
1524
|
+
"""Score the created alert's arguments; a conditional check is ``None`` when the item states no value.
|
|
1525
|
+
|
|
1526
|
+
``proposal_turns`` holds the tool calls of each scored turn, read for the first-proposal checks.
|
|
1527
|
+
"""
|
|
1528
|
+
|
|
1529
|
+
if expected.alternatives:
|
|
1530
|
+
# The option the run comes closest to; a full match on any option passes.
|
|
1531
|
+
evaluations = [
|
|
1532
|
+
_evaluate_alert(option, actual_args, alert_created, sdk, current_user_id, proposal_turns)
|
|
1533
|
+
for option in expected.alternatives
|
|
1534
|
+
]
|
|
1535
|
+
return max(evaluations, key=lambda ev: (ev.strict_pass, sum(ev.checks().values())))
|
|
1536
|
+
|
|
1537
|
+
def conditional(check: bool | None) -> bool | None:
|
|
1538
|
+
return None if check is None else alert_created and check
|
|
1539
|
+
|
|
1540
|
+
initial_filters, initial_recipients = _evaluate_first_proposal(expected, proposal_turns or [], sdk, current_user_id)
|
|
1541
|
+
return AlertEvaluation(
|
|
1542
|
+
alert_created=alert_created,
|
|
1543
|
+
operator_correct=alert_created and expected.operator == actual_args.get("operator"),
|
|
1544
|
+
threshold_correct=alert_created and _check_threshold(expected, actual_args),
|
|
1545
|
+
trigger_correct=alert_created and _check_trigger(expected, actual_args),
|
|
1546
|
+
filters_correct=alert_created and _check_filters(expected, actual_args),
|
|
1547
|
+
metric_correct=alert_created and _check_metric(expected, actual_args),
|
|
1548
|
+
recipients_correct=alert_created
|
|
1549
|
+
and _check_recipients(expected, actual_args, sdk=sdk, current_user_id=current_user_id),
|
|
1550
|
+
attributes_correct=alert_created and _check_attributes(expected, actual_args),
|
|
1551
|
+
granularity_correct=alert_created and _check_granularity(expected, actual_args),
|
|
1552
|
+
comparison_correct=None
|
|
1553
|
+
if expected.comparison is None
|
|
1554
|
+
else alert_created and _check_comparison(expected, actual_args),
|
|
1555
|
+
title_correct=None if expected.title is None else alert_created and _check_title(expected, actual_args),
|
|
1556
|
+
dashboard_correct=None
|
|
1557
|
+
if expected.dashboard_id is None
|
|
1558
|
+
else alert_created and _check_dashboard(expected, actual_args),
|
|
1559
|
+
alert_sensitivity_correct=conditional(
|
|
1560
|
+
_check_enum_arg(expected.sensitivity, actual_args, "sensitivity", default=_DEFAULT_SENSITIVITY)
|
|
1561
|
+
),
|
|
1562
|
+
alert_trigger_interval_correct=conditional(_check_trigger_interval(expected, actual_args)),
|
|
1563
|
+
alert_date_dataset_correct=conditional(_check_date_dataset(expected, actual_args)),
|
|
1564
|
+
alert_initial_filters_correct=initial_filters,
|
|
1565
|
+
alert_initial_recipients_correct=initial_recipients,
|
|
1566
|
+
)
|
|
1567
|
+
|
|
1568
|
+
|
|
972
1569
|
def run_agentic_alert_skill(
|
|
973
1570
|
host: str,
|
|
974
1571
|
token: str,
|
|
@@ -983,9 +1580,13 @@ def run_agentic_alert_skill(
|
|
|
983
1580
|
user_context: dict | None = None,
|
|
984
1581
|
) -> AgenticAlertSummary:
|
|
985
1582
|
"""Run the alert-skill agentic evaluation K times and return a summary."""
|
|
1583
|
+
if max_iterations < 1:
|
|
1584
|
+
# With no turn the agent never gets the question, and a no-alert item would pass unasked.
|
|
1585
|
+
raise ValueError(f"max_iterations must be at least 1, got {max_iterations}")
|
|
986
1586
|
expected = _normalize_expected_output(expected_output)
|
|
987
1587
|
current_user_id: str | None = None
|
|
988
|
-
|
|
1588
|
+
# A no-alert item scores no recipients, so it needs no current user. `any_of` options share theirs.
|
|
1589
|
+
if expected.expect_alert and _CURRENT_USER_RECIPIENT in expected.recipients:
|
|
989
1590
|
current_user_id = _resolve_current_user_id(host, token)
|
|
990
1591
|
if current_user_id is None:
|
|
991
1592
|
# A harness fault: report it as an item error, not as the agent's recipient mistake.
|
|
@@ -1002,15 +1603,31 @@ def run_agentic_alert_skill(
|
|
|
1002
1603
|
sdk = GoodDataSdk.create(host, token)
|
|
1003
1604
|
|
|
1004
1605
|
def _run_once(conv_id: str) -> AlertRunResult:
|
|
1005
|
-
|
|
1606
|
+
alert_ids_to_delete: list[str] = []
|
|
1607
|
+
# A metric the agent created stays in the shared workspace, and the item's next run would find it.
|
|
1608
|
+
metric_ids_to_delete: list[str] = []
|
|
1609
|
+
|
|
1610
|
+
def _track_writes(events: list[ToolCallEvent]) -> _AlertCalls:
|
|
1611
|
+
"""The turn's alert calls; records every alert and metric it created for cleanup."""
|
|
1612
|
+
calls = _extract_alert_calls(events)
|
|
1613
|
+
alert_ids_to_delete.extend(calls.created_ids)
|
|
1614
|
+
metric_ids_to_delete.extend(_extract_created_metric_ids(events))
|
|
1615
|
+
return calls
|
|
1616
|
+
|
|
1617
|
+
# Taken before the run, so cleanup by a named id never touches an alert the run did not create.
|
|
1618
|
+
existing_ids = _automation_ids(host, token, workspace_id)
|
|
1619
|
+
all_tool_call_events: list[ToolCallEvent] = []
|
|
1620
|
+
# Tool calls of each question and follow-up turn; setup turns are not scored.
|
|
1621
|
+
scored_turns: list[list[ToolCallEvent]] = []
|
|
1622
|
+
# Events of turns that broke mid-stream: not part of the run's record, but they can name an alert.
|
|
1623
|
+
partial_events: list[ToolCallEvent] = []
|
|
1006
1624
|
run_started = time.monotonic()
|
|
1007
1625
|
try:
|
|
1008
1626
|
alert_id: str | None = None
|
|
1009
1627
|
actual_args: dict = {}
|
|
1010
|
-
|
|
1628
|
+
alert_created = False
|
|
1011
1629
|
reasoning_steps: list[str] = []
|
|
1012
1630
|
response_id: str | None = None
|
|
1013
|
-
all_tool_call_events: list[ToolCallEvent] = []
|
|
1014
1631
|
all_reasoning_step_events: list[ReasoningStepEvent] = []
|
|
1015
1632
|
turn_offset = 0.0 # each turn's call_ts/ts restarts near 0 -- shift by prior turns' wall time
|
|
1016
1633
|
tool_index_offset = 0
|
|
@@ -1026,8 +1643,44 @@ def run_agentic_alert_skill(
|
|
|
1026
1643
|
# that simply runs out of range() is correctly labelled without a trailing else.
|
|
1027
1644
|
exit_reason = LoopExit.BUDGET_EXHAUSTED
|
|
1028
1645
|
turns_used = 0
|
|
1646
|
+
no_alert = not expected.expect_alert
|
|
1647
|
+
# A no-alert run ends when the agent proposes anything; the simulated user only declines.
|
|
1648
|
+
iterations = min(max_iterations, _NO_ALERT_MAX_ITERATIONS) if no_alert else max_iterations
|
|
1649
|
+
proposed = False
|
|
1650
|
+
# Whether the agent wrote anything in a scored turn; a no-alert run may end quiet after declining.
|
|
1651
|
+
answered = False
|
|
1029
1652
|
run_started = time.monotonic()
|
|
1030
|
-
|
|
1653
|
+
# Setup turns set the scene (a chart to alert on) and are not scored. A failed one
|
|
1654
|
+
# ends the run as the agent's failure, like a failed question turn.
|
|
1655
|
+
for number, turn in enumerate(expected.setup_turns, start=1):
|
|
1656
|
+
try:
|
|
1657
|
+
setup = client.send_message(conv_id, turn)
|
|
1658
|
+
except ChatError as exc:
|
|
1659
|
+
print(f"[CHAT] setup turn {number} failed for conversation {conv_id}: {exc}")
|
|
1660
|
+
# A broken stream can still have created an alert server-side.
|
|
1661
|
+
partial = exc.partial_result
|
|
1662
|
+
if partial is not None:
|
|
1663
|
+
reasoning_steps.extend(partial.reasoning_steps or [])
|
|
1664
|
+
response_id = partial.response_id or response_id
|
|
1665
|
+
_track_writes(partial.tool_call_events or [])
|
|
1666
|
+
partial_events.extend(partial.tool_call_events or [])
|
|
1667
|
+
exit_reason = chat_failure_exit(exc)
|
|
1668
|
+
iterations = 0
|
|
1669
|
+
break
|
|
1670
|
+
steps += setup.reasoning_step_count
|
|
1671
|
+
reasoning_steps.extend(setup.reasoning_steps or [])
|
|
1672
|
+
turn_offset, tool_index_offset, reasoning_index_offset = shift_and_index_events(
|
|
1673
|
+
setup,
|
|
1674
|
+
turn_offset=turn_offset,
|
|
1675
|
+
tool_index_offset=tool_index_offset,
|
|
1676
|
+
reasoning_index_offset=reasoning_index_offset,
|
|
1677
|
+
)
|
|
1678
|
+
all_tool_call_events.extend(setup.tool_call_events or [])
|
|
1679
|
+
all_reasoning_step_events.extend(setup.reasoning_step_events or [])
|
|
1680
|
+
_track_writes(setup.tool_call_events or [])
|
|
1681
|
+
conversation_history.append({"role": "user", "content": turn})
|
|
1682
|
+
conversation_history.append({"role": "assistant", "content": render_answer_text(setup)})
|
|
1683
|
+
for _iteration in range(iterations):
|
|
1031
1684
|
turns_used = _iteration + 1
|
|
1032
1685
|
try:
|
|
1033
1686
|
chat_result = client.send_message(conv_id, current_question)
|
|
@@ -1036,7 +1689,7 @@ def run_agentic_alert_skill(
|
|
|
1036
1689
|
# discarding every K-run already completed along with any exit_reason.
|
|
1037
1690
|
print(f"[CHAT] send_message failed for conversation {conv_id}: {exc}")
|
|
1038
1691
|
# The stream can break AFTER create_metric_alert already succeeded
|
|
1039
|
-
# server-side. That id only ever reached
|
|
1692
|
+
# server-side. That id only ever reached alert_ids_to_delete from the
|
|
1040
1693
|
# normal path below, so breaking here left the alert in the workspace for
|
|
1041
1694
|
# the `finally` cleanup to miss -- a real object leaking out of a failed
|
|
1042
1695
|
# run, not a reporting gap.
|
|
@@ -1044,9 +1697,8 @@ def run_agentic_alert_skill(
|
|
|
1044
1697
|
if partial is not None:
|
|
1045
1698
|
reasoning_steps.extend(partial.reasoning_steps or [])
|
|
1046
1699
|
response_id = partial.response_id or response_id
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
alert_id_to_delete = partial_alert_id
|
|
1700
|
+
_track_writes(partial.tool_call_events or [])
|
|
1701
|
+
partial_events.extend(partial.tool_call_events or [])
|
|
1050
1702
|
exit_reason = chat_failure_exit(exc)
|
|
1051
1703
|
break
|
|
1052
1704
|
# `turns_used` counts attempts (set above, so a failed send still shows the
|
|
@@ -1063,19 +1715,41 @@ def run_agentic_alert_skill(
|
|
|
1063
1715
|
reasoning_index_offset=reasoning_index_offset,
|
|
1064
1716
|
)
|
|
1065
1717
|
all_tool_call_events.extend(chat_result.tool_call_events or [])
|
|
1718
|
+
scored_turns.append(list(chat_result.tool_call_events or []))
|
|
1066
1719
|
all_reasoning_step_events.extend(chat_result.reasoning_step_events or [])
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1720
|
+
calls = _track_writes(chat_result.tool_call_events or [])
|
|
1721
|
+
tools_called = {tc.function_name for tc in chat_result.tool_call_events or []}
|
|
1722
|
+
substitute = _PROPOSAL_TOOL in tools_called or _CREATE_METRIC_TOOL in tools_called
|
|
1723
|
+
if no_alert and (calls.called or substitute or chat_result.alert_proposals):
|
|
1724
|
+
# Nothing in the request can be monitored, so any proposal is a substitute the
|
|
1725
|
+
# user never agreed to. A proposal call the tool rejected leaves no proposal
|
|
1726
|
+
# part, but the agent still tried to propose one. A metric the agent creates
|
|
1727
|
+
# is a substitute too: the simulated user never asks for one.
|
|
1728
|
+
proposed = True
|
|
1729
|
+
actual_args = calls.args
|
|
1730
|
+
exit_reason = LoopExit.SUCCESS
|
|
1731
|
+
break
|
|
1732
|
+
if calls.created:
|
|
1733
|
+
alert_id, actual_args = calls.alert_id, calls.args
|
|
1734
|
+
alert_created = True
|
|
1070
1735
|
exit_reason = LoopExit.SUCCESS
|
|
1071
1736
|
break
|
|
1737
|
+
if calls.called:
|
|
1738
|
+
# Every call reported an error, so nothing was created. Scoring their arguments
|
|
1739
|
+
# would pass a run whose creation failed, and ending here would label it a
|
|
1740
|
+
# success. The agent gets the next turn to recover, as with a user, and the
|
|
1741
|
+
# failed arguments are kept for triage.
|
|
1742
|
+
actual_args = calls.args
|
|
1072
1743
|
response_text = render_turn_for_simulated_user(chat_result)
|
|
1073
|
-
# Stop if agent gave a completely empty response (stuck)
|
|
1074
|
-
|
|
1744
|
+
# Stop if the agent gave a completely empty response (stuck), or wrote nothing after
|
|
1745
|
+
# every create call failed: the rendered turn holds no tool results, so the simulated
|
|
1746
|
+
# user would be asked to answer an empty message.
|
|
1747
|
+
if not response_text and (calls.called or not chat_result.tool_call_events):
|
|
1075
1748
|
exit_reason = LoopExit.AGENT_SILENT
|
|
1076
1749
|
break
|
|
1750
|
+
answered = answered or bool(response_text)
|
|
1077
1751
|
# Stop before generating a follow-up for the last iteration
|
|
1078
|
-
if _iteration >=
|
|
1752
|
+
if _iteration >= iterations - 1:
|
|
1079
1753
|
break
|
|
1080
1754
|
# Recorded rather than raised, matching metric_skill and kda_skill. Letting it
|
|
1081
1755
|
# propagate did keep a harness fault from being scored as a content failure,
|
|
@@ -1099,25 +1773,27 @@ def run_agentic_alert_skill(
|
|
|
1099
1773
|
conversation_history.append({"role": "user", "content": follow_up})
|
|
1100
1774
|
current_question = follow_up
|
|
1101
1775
|
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1776
|
+
if no_alert:
|
|
1777
|
+
# Only a run that spent its whole budget without a proposal shows the agent
|
|
1778
|
+
# declining. A run cut short by a chat failure or a failed simulated user never
|
|
1779
|
+
# gave the agent the turns to propose one. An agent that declined and then had
|
|
1780
|
+
# nothing to add to the user's "OK, thanks" ends silent, and that is a decline
|
|
1781
|
+
# too; one silent from its first turn never answered the request.
|
|
1782
|
+
declined = not proposed and (
|
|
1783
|
+
exit_reason == LoopExit.BUDGET_EXHAUSTED or (exit_reason == LoopExit.AGENT_SILENT and answered)
|
|
1784
|
+
)
|
|
1785
|
+
ev = AlertEvaluation(
|
|
1786
|
+
alert_created=False,
|
|
1787
|
+
operator_correct=False,
|
|
1788
|
+
threshold_correct=False,
|
|
1789
|
+
trigger_correct=False,
|
|
1790
|
+
filters_correct=False,
|
|
1791
|
+
metric_correct=False,
|
|
1792
|
+
recipients_correct=False,
|
|
1793
|
+
alert_not_proposed=declined,
|
|
1794
|
+
)
|
|
1795
|
+
else:
|
|
1796
|
+
ev = _evaluate_alert(expected, actual_args, alert_created, sdk, current_user_id, scored_turns)
|
|
1121
1797
|
return AlertRunResult(
|
|
1122
1798
|
conversation_id=conv_id,
|
|
1123
1799
|
alert_id=alert_id,
|
|
@@ -1134,8 +1810,17 @@ def run_agentic_alert_skill(
|
|
|
1134
1810
|
run_latency_s=time.monotonic() - run_started,
|
|
1135
1811
|
)
|
|
1136
1812
|
finally:
|
|
1137
|
-
|
|
1138
|
-
_delete_alert(sdk, workspace_id,
|
|
1813
|
+
for created_id in dict.fromkeys(alert_ids_to_delete):
|
|
1814
|
+
_delete_alert(sdk, workspace_id, created_id)
|
|
1815
|
+
unseen = _named_automation_ids(all_tool_call_events + partial_events) - set(alert_ids_to_delete)
|
|
1816
|
+
if unseen and existing_ids is not None:
|
|
1817
|
+
now = _automation_ids(host, token, workspace_id) or set()
|
|
1818
|
+
for leaked_id in sorted((unseen & now) - existing_ids):
|
|
1819
|
+
print(f"[CLEANUP] Deleting alert {leaked_id}: created, but its create call was not in the turn")
|
|
1820
|
+
_delete_alert(sdk, workspace_id, leaked_id)
|
|
1821
|
+
# After the alerts: an alert on a created metric would keep that metric in use.
|
|
1822
|
+
for metric_id in dict.fromkeys(metric_ids_to_delete):
|
|
1823
|
+
_delete_metric(sdk, workspace_id, metric_id)
|
|
1139
1824
|
|
|
1140
1825
|
try:
|
|
1141
1826
|
conv_id_0 = initial_conversation_id if initial_conversation_id is not None else client.create_conversation()
|
|
@@ -1156,9 +1841,11 @@ def run_agentic_alert_skill(
|
|
|
1156
1841
|
|
|
1157
1842
|
pass_at_k = any(r.eval.strict_pass for r in run_results)
|
|
1158
1843
|
pass_power_k = all(r.eval.strict_pass for r in run_results)
|
|
1844
|
+
# A passing run first: with `any_of`, a failing run scored against a larger option can have
|
|
1845
|
+
# more true checks than a passing one.
|
|
1159
1846
|
best = max(
|
|
1160
1847
|
run_results,
|
|
1161
|
-
key=lambda r: sum(r.eval.checks().values()),
|
|
1848
|
+
key=lambda r: (r.eval.strict_pass, sum(r.eval.checks().values())),
|
|
1162
1849
|
)
|
|
1163
1850
|
return AgenticAlertSummary(
|
|
1164
1851
|
run_results=run_results,
|
|
@@ -1302,18 +1989,13 @@ def evaluate_agentic_alert_skill(
|
|
|
1302
1989
|
|
|
1303
1990
|
best = summary.best
|
|
1304
1991
|
ev = best.eval
|
|
1992
|
+
# The checks that ran, not a fixed field list: quality_score is the share of true booleans
|
|
1993
|
+
# here, so a no-alert item must not carry the alert checks it was never scored on, and a
|
|
1994
|
+
# stated conditional check must count.
|
|
1305
1995
|
detail = agentic_detail(
|
|
1306
1996
|
best.tool_call_events,
|
|
1307
1997
|
best.reasoning_step_events,
|
|
1308
|
-
|
|
1309
|
-
operator_correct=ev.operator_correct,
|
|
1310
|
-
threshold_correct=ev.threshold_correct,
|
|
1311
|
-
trigger_correct=ev.trigger_correct,
|
|
1312
|
-
filters_correct=ev.filters_correct,
|
|
1313
|
-
metric_correct=ev.metric_correct,
|
|
1314
|
-
recipients_correct=ev.recipients_correct,
|
|
1315
|
-
attributes_correct=ev.attributes_correct,
|
|
1316
|
-
granularity_correct=ev.granularity_correct,
|
|
1998
|
+
**ev.checks(),
|
|
1317
1999
|
actual_alert_arguments=best.actual_alert_arguments,
|
|
1318
2000
|
# Why the loop stopped. alert_created=False alone cannot tell a refusal from a run
|
|
1319
2001
|
# that hit max_iterations while still on track -- see LoopExit.
|
|
@@ -1335,12 +2017,7 @@ def evaluate_agentic_alert_skill(
|
|
|
1335
2017
|
raise_agentic_failure(
|
|
1336
2018
|
AlertSkillAssertionError,
|
|
1337
2019
|
f"Alert skill assertion failed. {gate_note} strict_pass={ev.strict_pass}. "
|
|
1338
|
-
f"
|
|
1339
|
-
f"threshold_correct={ev.threshold_correct}, trigger_correct={ev.trigger_correct}, "
|
|
1340
|
-
f"filters_correct={ev.filters_correct}, metric_correct={ev.metric_correct}, "
|
|
1341
|
-
f"recipients_correct={ev.recipients_correct}, "
|
|
1342
|
-
f"attributes_correct={ev.attributes_correct}, "
|
|
1343
|
-
f"granularity_correct={ev.granularity_correct}. "
|
|
2020
|
+
f"Checks: {ev.checks()}. "
|
|
1344
2021
|
f"Actual args: {best.actual_alert_arguments}",
|
|
1345
2022
|
harness_error=run_labels.harness_error_record,
|
|
1346
2023
|
shadow=run_labels.shadow(gate),
|
|
@@ -28,7 +28,7 @@ def _extract_metric_id(metric_str: str) -> str | None:
|
|
|
28
28
|
def _extract_automation_id(tool_event) -> str | None:
|
|
29
29
|
"""Real server-assigned id of the automation this call created.
|
|
30
30
|
|
|
31
|
-
Mirrors ``core/agentic/alert_skill.py``'s ``
|
|
31
|
+
Mirrors ``core/agentic/alert_skill.py``'s ``_created_alert_id`` — the id
|
|
32
32
|
lives in the tool *result* (what the server assigned), not the tool call
|
|
33
33
|
*arguments* (what the agent asked for).
|
|
34
34
|
"""
|
gooddata_eval/core/models.py
CHANGED
|
@@ -39,7 +39,8 @@ class LoopExit(str, Enum):
|
|
|
39
39
|
"""The agent produced the expected output; the loop broke early."""
|
|
40
40
|
|
|
41
41
|
AGENT_SILENT = "agent_silent"
|
|
42
|
-
"""The agent returned neither text nor a tool call -- genuinely stuck.
|
|
42
|
+
"""The agent returned neither text nor a tool call -- genuinely stuck. The alert skill also
|
|
43
|
+
ends here when the agent writes nothing after every ``create_metric_alert`` call failed."""
|
|
43
44
|
|
|
44
45
|
BUDGET_EXHAUSTED = "budget_exhausted"
|
|
45
46
|
"""The loop hit ``max_iterations`` without the agent producing its output. Says nothing
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: gooddata-eval
|
|
3
|
-
Version: 1.80.1.
|
|
3
|
+
Version: 1.80.1.dev11
|
|
4
4
|
Summary: Evaluate the GoodData AI agent against your own questions and models.
|
|
5
5
|
Project-URL: Source, https://github.com/gooddata/gooddata-python-sdk
|
|
6
6
|
Author-email: GoodData <support@gooddata.com>
|
|
@@ -18,7 +18,7 @@ Classifier: Topic :: Scientific/Engineering
|
|
|
18
18
|
Classifier: Topic :: Software Development
|
|
19
19
|
Classifier: Typing :: Typed
|
|
20
20
|
Requires-Python: >=3.11
|
|
21
|
-
Requires-Dist: gooddata-sdk~=1.80.1.
|
|
21
|
+
Requires-Dist: gooddata-sdk~=1.80.1.dev11
|
|
22
22
|
Requires-Dist: httpx<1.0,>=0.27
|
|
23
23
|
Requires-Dist: jsonpatch<2.0,>=1.33
|
|
24
24
|
Requires-Dist: orjson<4.0.0,>=3.9.15
|
|
@@ -10,7 +10,7 @@ gooddata_eval/core/config.py,sha256=hla5t294uHC5Q9bzrhPjsdkwEcetLsEH-GqGAhs94b4,
|
|
|
10
10
|
gooddata_eval/core/connection.py,sha256=mh-Do5-Ti0-DXXikfCIH10eTTUbKuZUAS_sLoPNDJ5I,1229
|
|
11
11
|
gooddata_eval/core/granularity.py,sha256=CbniwgxtVj0oyf41UjeeZbBzOpeisSBlAfdkL79e6O0,3932
|
|
12
12
|
gooddata_eval/core/interaction.py,sha256=hJxrTNpEN7s0fctdJGW511bf_thfXJJ1Dn3E2cGgtP0,2224
|
|
13
|
-
gooddata_eval/core/models.py,sha256=
|
|
13
|
+
gooddata_eval/core/models.py,sha256=Fkm50EJlxbm9rA_FRxm6B_9RAiRuvbqj0xGEL1Xg26M,30810
|
|
14
14
|
gooddata_eval/core/number_format.py,sha256=bQv3YqlMtBHNSMZx2_qGMWXFDdeXNkAGVg3WFIKUd-k,9264
|
|
15
15
|
gooddata_eval/core/outcome.py,sha256=Ax9uAgxUlKSATWd_xFp959jijVhsNoH0oSmRyOnXsWA,6509
|
|
16
16
|
gooddata_eval/core/runner.py,sha256=IrMOVFUd-WkcYLhYiQYeEzZjacYKnjao3GBm6JGtisQ,21605
|
|
@@ -18,7 +18,7 @@ gooddata_eval/core/scoring.py,sha256=buY7ZoO08Dt59m2PPhFeNOyix5yYlf4mVxFyOn-aibk
|
|
|
18
18
|
gooddata_eval/core/timing.py,sha256=0LEUYPHqF1RfhVRT8Ju9hSwJB64GpI9udnIP5GZvV9s,8303
|
|
19
19
|
gooddata_eval/core/workspace.py,sha256=S8exiy5gpDtcRtT8-i2fIRALF34Pbo0J46xm8X_ldus,11846
|
|
20
20
|
gooddata_eval/core/agentic/__init__.py,sha256=GYzw5NOraZagjhbGaiqRskAnjqx0zjSZFs67cgRa3Hk,4826
|
|
21
|
-
gooddata_eval/core/agentic/_catalog.py,sha256=
|
|
21
|
+
gooddata_eval/core/agentic/_catalog.py,sha256=7Ke9OOocxuorHgP4SqEwuSl8VXRU3hZkoQKFLpGbQp4,4479
|
|
22
22
|
gooddata_eval/core/agentic/_clarification.py,sha256=oCghvd7aO0yIn4kkQcjdFm5-j2zfIGmw1Et0MkT_dAM,22770
|
|
23
23
|
gooddata_eval/core/agentic/_conversation_context.py,sha256=vh5mUgRs4h-tn2039dn47xkQfa3s-RXwDWZW_UeXAas,17175
|
|
24
24
|
gooddata_eval/core/agentic/_editor_takeaways.py,sha256=WCd_lTBEC5plPIyiPx7Q7j4XN42qQZAxTrXDMHfLLas,11757
|
|
@@ -33,7 +33,7 @@ gooddata_eval/core/agentic/_outcome.py,sha256=AL1ULyD9zpC8A-MhyLp2CW68Rnezl39heR
|
|
|
33
33
|
gooddata_eval/core/agentic/_search_expectation.py,sha256=I_NSxfuT0r5uOwvGe6hCcgpeGvdtLAcCki_RgELJaes,13964
|
|
34
34
|
gooddata_eval/core/agentic/_trace_linker.py,sha256=Bc-UOPB3bcJqb6kmHnkMnbNVbZPPB7Dn5awM7bNm-qY,15851
|
|
35
35
|
gooddata_eval/core/agentic/agent_switcher.py,sha256=DWkv2iB0RGzM4-wLkhoru4b8fPYHDwYaBPcSVcjZ74g,37636
|
|
36
|
-
gooddata_eval/core/agentic/alert_skill.py,sha256=
|
|
36
|
+
gooddata_eval/core/agentic/alert_skill.py,sha256=GExU9e6KPce4RfBRrKQ35RI7I9VCbE6ITCr-0qI36VE,99164
|
|
37
37
|
gooddata_eval/core/agentic/anomaly_detection.py,sha256=XMd0zsS3hgASJND6UwhNXdoBXUzDm_pMuGS2Dv-1FNg,30053
|
|
38
38
|
gooddata_eval/core/agentic/conversation.py,sha256=AC-k4ju2Ic_X8UkERLWHstNKKBGTtrj7p-Ld-82K8T8,75946
|
|
39
39
|
gooddata_eval/core/agentic/dashboard_skill.py,sha256=eHQWVcoYIBc0QCJnu4VmpZVMffNHckSCYuBo67a-asE,132462
|
|
@@ -66,7 +66,7 @@ gooddata_eval/core/evaluators/_llm_judge.py,sha256=A5lukKt8IG26BoN_oU2DvkOHAQwV0
|
|
|
66
66
|
gooddata_eval/core/evaluators/_maql.py,sha256=XpamaPXixBTpiMGrZYnV0t_4DEmuPSa32PqQOk0RG_k,4348
|
|
67
67
|
gooddata_eval/core/evaluators/_rubric.py,sha256=hHBsE52M2E2JaRuN07Vs1ST0nVaq44kft5QqgoaO3-g,4248
|
|
68
68
|
gooddata_eval/core/evaluators/_text_utils.py,sha256=GWGJB6uJFhwZTiy4QcthXd2z_GtUdh5p6gZqHVnfBo4,1816
|
|
69
|
-
gooddata_eval/core/evaluators/alert_skill.py,sha256=
|
|
69
|
+
gooddata_eval/core/evaluators/alert_skill.py,sha256=iLDV8ZSAMjgiGxi6i7RpdVzcMXVihEn5yiz4JqV2wVE,6201
|
|
70
70
|
gooddata_eval/core/evaluators/base.py,sha256=H9EMG57jX0W4vmasgJNUhwRjtGRuVBik2MhN9ZDV1Jk,777
|
|
71
71
|
gooddata_eval/core/evaluators/catalog_metadata.py,sha256=knj_7N_nEznHHnJMnBVYsNGMqA4GYQLmfGnQHUkIg9Y,8868
|
|
72
72
|
gooddata_eval/core/evaluators/general_question.py,sha256=3YIuCH7t_Ih6Of8hozRUHd6Vaum2X3KxhKFCjzthLHg,2170
|
|
@@ -95,8 +95,8 @@ gooddata_eval/core/summary/http_client.py,sha256=Umae42fiiJQ0e4hv63NRROHYvcFAGgX
|
|
|
95
95
|
gooddata_eval/core/takeaway/__init__.py,sha256=U54lANKm34yjqm7dZL9KkGouPbwAaQWC9wiAmb5B5g4,32
|
|
96
96
|
gooddata_eval/core/takeaway/evaluate.py,sha256=AjS_rCHWUSJKv0jfEfL0-dVPoDaf3RkGdmeZiIwjd6A,11312
|
|
97
97
|
gooddata_eval/core/takeaway/http_client.py,sha256=YMfafOcHJ184i49Qoh0ZNPKKTMKBSgeDUM4zk_H3yM8,3955
|
|
98
|
-
gooddata_eval-1.80.1.
|
|
99
|
-
gooddata_eval-1.80.1.
|
|
100
|
-
gooddata_eval-1.80.1.
|
|
101
|
-
gooddata_eval-1.80.1.
|
|
102
|
-
gooddata_eval-1.80.1.
|
|
98
|
+
gooddata_eval-1.80.1.dev11.dist-info/METADATA,sha256=mMH-PZinClOY4DfryyqjpnFr-uooGJh1GRL_-pfqEVU,73708
|
|
99
|
+
gooddata_eval-1.80.1.dev11.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
100
|
+
gooddata_eval-1.80.1.dev11.dist-info/entry_points.txt,sha256=28nFp5Viknx4haPYgzK9QHlwPFfC6rPF6RmjC2ht8EI,56
|
|
101
|
+
gooddata_eval-1.80.1.dev11.dist-info/licenses/LICENSE.txt,sha256=LVfVlC9maU3K9lgMwdZnClQQsOIbOekdcdVKr9qzJtk,256836
|
|
102
|
+
gooddata_eval-1.80.1.dev11.dist-info/RECORD,,
|
|
File without changes
|
{gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{gooddata_eval-1.80.1.dev9.dist-info → gooddata_eval-1.80.1.dev11.dist-info}/licenses/LICENSE.txt
RENAMED
|
File without changes
|