gooddata-eval 1.80.1.dev8__py3-none-any.whl → 1.80.1.dev10__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.
@@ -24,6 +24,7 @@ from gooddata_eval.core.agentic.forecasting import evaluate_agentic_forecasting
24
24
  from gooddata_eval.core.agentic.general_question import evaluate_agentic_general_question
25
25
  from gooddata_eval.core.agentic.guardrail import evaluate_agentic_guardrail
26
26
  from gooddata_eval.core.agentic.kda_skill import evaluate_agentic_kda_skill
27
+ from gooddata_eval.core.agentic.knowledge import evaluate_agentic_knowledge
27
28
  from gooddata_eval.core.agentic.metric_skill import evaluate_agentic_metric_skill
28
29
  from gooddata_eval.core.agentic.search_tool import evaluate_agentic_search_tool
29
30
  from gooddata_eval.core.agentic.visualization import evaluate_agentic_visualization
@@ -65,6 +66,7 @@ AGENTIC_TEST_KINDS = frozenset(
65
66
  "agentic_anomaly_detection",
66
67
  "agentic_what_if",
67
68
  "agentic_agent_switcher",
69
+ "agentic_knowledge",
68
70
  }
69
71
  )
70
72
 
@@ -398,6 +400,19 @@ def _dispatch_agentic(
398
400
  gate=gate,
399
401
  **lf_kw,
400
402
  )
403
+ elif kind == "agentic_knowledge":
404
+ return evaluate_agentic_knowledge(
405
+ host=host,
406
+ token=token,
407
+ workspace_id=workspace_id,
408
+ question=item.question,
409
+ expected_output=eo,
410
+ k=k,
411
+ gate=gate,
412
+ agent_id=agent_id,
413
+ user_context=item.user_context,
414
+ **lf_kw,
415
+ )
401
416
  elif kind == "agentic_conversation":
402
417
  fixture_data = eo.get("fixture") or eo if isinstance(eo, dict) else {}
403
418
  return evaluate_agentic_conversation(
@@ -919,20 +919,70 @@ def _normalize_expected_output(expected: dict) -> CatalogMetricAlert:
919
919
  )
920
920
 
921
921
 
922
- def _extract_alert_call(tool_call_events: list[ToolCallEvent]) -> tuple[str | None, dict, bool]:
923
- """Return (alert_id, args, tool_called). tool_called=True whenever create_metric_alert appears."""
922
+ def _alert_call_failed(result: dict | None) -> bool:
923
+ """Whether a ``create_metric_alert`` result reports an error, so the call created nothing.
924
+
925
+ An MCP error carries ``isError``. gen-ai's tool registry reports rejected arguments and a
926
+ failed execution as ``{"success": false, "error": ...}`` instead, with no ``isError``.
927
+ """
928
+ if not isinstance(result, dict):
929
+ return False
930
+ data = result.get("data")
931
+ payloads = [result, data] if isinstance(data, dict) else [result]
932
+ return any(p.get("isError") or p.get("success") is False for p in payloads)
933
+
934
+
935
+ def _created_alert_id(result: dict | None) -> str | None:
936
+ """Server-assigned id of the automation a call created: it lives in the result, not the arguments."""
937
+ if not isinstance(result, dict):
938
+ return None
939
+ data = result.get("data")
940
+ alert_id = result.get("id") or (data.get("id") if isinstance(data, dict) else None)
941
+ return alert_id if isinstance(alert_id, str) and alert_id else None
942
+
943
+
944
+ @dataclass
945
+ class _AlertCalls:
946
+ """Every ``create_metric_alert`` call of a turn, read for scoring and for cleanup."""
947
+
948
+ called: bool = False
949
+ """The agent called the tool at least once."""
950
+ created: bool = False
951
+ """At least one call did not report an error."""
952
+ created_ids: list[str] = field(default_factory=list)
953
+ """Ids of every alert the calls created; each one is deleted after the run."""
954
+ args: dict = field(default_factory=dict)
955
+ """Arguments of the first call that did not fail, else of the last call."""
956
+ alert_id: str | None = None
957
+ """Id of the alert the call in ``args`` created, None when that call failed or its result has no id."""
958
+
959
+
960
+ def _extract_alert_calls(tool_call_events: list[ToolCallEvent]) -> _AlertCalls:
961
+ """Read every ``create_metric_alert`` call, not only the first.
962
+
963
+ The agent may retry after an error. Reading only the first call scored the arguments of a
964
+ call that failed and missed the id of the retry that succeeded, so that alert leaked into
965
+ the workspace (QA-29886). The run is scored on the first call that did not fail, which is
966
+ the first call whenever none failed, as before.
967
+ """
968
+ calls = _AlertCalls()
924
969
  for tc in tool_call_events:
925
- if tc.function_name == "create_metric_alert":
926
- args = tc.parsed_arguments() or {}
927
- alert_id: str | None = None
928
- if tc.result:
929
- try:
930
- result_data = json.loads(tc.result)
931
- alert_id = result_data.get("id") or (result_data.get("data") or {}).get("id")
932
- except Exception:
933
- pass
934
- return alert_id, args, True
935
- return None, {}, False
970
+ if tc.function_name != "create_metric_alert":
971
+ continue
972
+ calls.called = True
973
+ args = tc.parsed_arguments() or {}
974
+ result = tc.parsed_result()
975
+ if _alert_call_failed(result):
976
+ if not calls.created:
977
+ calls.args = args
978
+ continue
979
+ alert_id = _created_alert_id(result)
980
+ if alert_id is not None:
981
+ calls.created_ids.append(alert_id)
982
+ if not calls.created:
983
+ calls.created = True
984
+ calls.args, calls.alert_id = args, alert_id
985
+ return calls
936
986
 
937
987
 
938
988
  def render_alert_proposal(proposal: dict) -> str:
@@ -940,16 +990,20 @@ def render_alert_proposal(proposal: dict) -> str:
940
990
 
941
991
  The alert skill's confirmation step deliberately emits no text part (GDAI-2032) — the
942
992
  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 and
944
- dashboard visible so the simulated user can still verify them against its goal, and does
945
- not need updating whenever ``AlertProposal`` grows a field.
993
+ widget. Dumping the payload (rather than prose) keeps recipients, condition, trigger,
994
+ filters and dashboard visible so the simulated user can still verify them against its
995
+ goal, and does not need updating whenever ``AlertProposal`` grows a field.
946
996
  """
947
997
  cta = proposal.get("cta") or "Should I create this alert?"
948
998
  summary = {k: v for k, v in proposal.items() if k != "cta"}
949
999
  alert = dict(summary.get("alert") or {})
950
- # The AFM execution block is opaque wire dicts — noise that would crowd out the fields
951
- # the simulated user actually has to check.
952
- alert.pop("execution", None)
1000
+ # `execution` is the only place a proposal carries its filters, which rule 3 of the simulated
1001
+ # user checks. Hoisting them keeps them visible (QA-29886). The rest stays out: the measures
1002
+ # repeat `condition`, and the simulated user is told nothing about group-bys, so a date
1003
+ # group-by would only read as a time window rule 5 tells it to refuse.
1004
+ execution = alert.pop("execution", None)
1005
+ if isinstance(execution, dict):
1006
+ alert["filters"] = execution.get("filters") or []
953
1007
  if "alert" in summary:
954
1008
  # Key off presence, not truthiness: an alert whose only key was `execution` must
955
1009
  # still be replaced, otherwise the original (execution-bearing) dict survives.
@@ -1002,12 +1056,12 @@ def run_agentic_alert_skill(
1002
1056
  sdk = GoodDataSdk.create(host, token)
1003
1057
 
1004
1058
  def _run_once(conv_id: str) -> AlertRunResult:
1005
- alert_id_to_delete: str | None = None
1059
+ alert_ids_to_delete: list[str] = []
1006
1060
  run_started = time.monotonic()
1007
1061
  try:
1008
1062
  alert_id: str | None = None
1009
1063
  actual_args: dict = {}
1010
- tool_called = False
1064
+ alert_created = False
1011
1065
  reasoning_steps: list[str] = []
1012
1066
  response_id: str | None = None
1013
1067
  all_tool_call_events: list[ToolCallEvent] = []
@@ -1036,7 +1090,7 @@ def run_agentic_alert_skill(
1036
1090
  # discarding every K-run already completed along with any exit_reason.
1037
1091
  print(f"[CHAT] send_message failed for conversation {conv_id}: {exc}")
1038
1092
  # The stream can break AFTER create_metric_alert already succeeded
1039
- # server-side. That id only ever reached alert_id_to_delete from the
1093
+ # server-side. That id only ever reached alert_ids_to_delete from the
1040
1094
  # normal path below, so breaking here left the alert in the workspace for
1041
1095
  # the `finally` cleanup to miss -- a real object leaking out of a failed
1042
1096
  # run, not a reporting gap.
@@ -1044,9 +1098,7 @@ def run_agentic_alert_skill(
1044
1098
  if partial is not None:
1045
1099
  reasoning_steps.extend(partial.reasoning_steps or [])
1046
1100
  response_id = partial.response_id or response_id
1047
- partial_alert_id, _, partial_tool_called = _extract_alert_call(partial.tool_call_events or [])
1048
- if partial_tool_called:
1049
- alert_id_to_delete = partial_alert_id
1101
+ alert_ids_to_delete.extend(_extract_alert_calls(partial.tool_call_events or []).created_ids)
1050
1102
  exit_reason = chat_failure_exit(exc)
1051
1103
  break
1052
1104
  # `turns_used` counts attempts (set above, so a failed send still shows the
@@ -1064,14 +1116,24 @@ def run_agentic_alert_skill(
1064
1116
  )
1065
1117
  all_tool_call_events.extend(chat_result.tool_call_events or [])
1066
1118
  all_reasoning_step_events.extend(chat_result.reasoning_step_events or [])
1067
- alert_id, actual_args, tool_called = _extract_alert_call(chat_result.tool_call_events or [])
1068
- if tool_called:
1069
- alert_id_to_delete = alert_id
1119
+ calls = _extract_alert_calls(chat_result.tool_call_events or [])
1120
+ alert_ids_to_delete.extend(calls.created_ids)
1121
+ if calls.created:
1122
+ alert_id, actual_args = calls.alert_id, calls.args
1123
+ alert_created = True
1070
1124
  exit_reason = LoopExit.SUCCESS
1071
1125
  break
1126
+ if calls.called:
1127
+ # Every call reported an error, so nothing was created. Scoring their arguments
1128
+ # would pass a run whose creation failed, and ending here would label it a
1129
+ # success. The agent gets the next turn to recover, as with a user, and the
1130
+ # failed arguments are kept for triage.
1131
+ actual_args = calls.args
1072
1132
  response_text = render_turn_for_simulated_user(chat_result)
1073
- # Stop if agent gave a completely empty response (stuck)
1074
- if not response_text and not chat_result.tool_call_events:
1133
+ # Stop if the agent gave a completely empty response (stuck), or wrote nothing after
1134
+ # every create call failed: the rendered turn holds no tool results, so the simulated
1135
+ # user would be asked to answer an empty message.
1136
+ if not response_text and (calls.called or not chat_result.tool_call_events):
1075
1137
  exit_reason = LoopExit.AGENT_SILENT
1076
1138
  break
1077
1139
  # Stop before generating a follow-up for the last iteration
@@ -1100,23 +1162,23 @@ def run_agentic_alert_skill(
1100
1162
  current_question = follow_up
1101
1163
 
1102
1164
  ev = AlertEvaluation(
1103
- alert_created=tool_called,
1104
- operator_correct=tool_called and expected.operator == actual_args.get("operator"),
1105
- threshold_correct=tool_called and _check_threshold(expected, actual_args),
1106
- trigger_correct=tool_called and _check_trigger(expected, actual_args),
1107
- filters_correct=tool_called and _check_filters(expected, actual_args),
1108
- metric_correct=tool_called and _check_metric(expected, actual_args),
1109
- recipients_correct=tool_called
1165
+ alert_created=alert_created,
1166
+ operator_correct=alert_created and expected.operator == actual_args.get("operator"),
1167
+ threshold_correct=alert_created and _check_threshold(expected, actual_args),
1168
+ trigger_correct=alert_created and _check_trigger(expected, actual_args),
1169
+ filters_correct=alert_created and _check_filters(expected, actual_args),
1170
+ metric_correct=alert_created and _check_metric(expected, actual_args),
1171
+ recipients_correct=alert_created
1110
1172
  and _check_recipients(expected, actual_args, sdk=sdk, current_user_id=current_user_id),
1111
- attributes_correct=tool_called and _check_attributes(expected, actual_args),
1112
- granularity_correct=tool_called and _check_granularity(expected, actual_args),
1173
+ attributes_correct=alert_created and _check_attributes(expected, actual_args),
1174
+ granularity_correct=alert_created and _check_granularity(expected, actual_args),
1113
1175
  comparison_correct=None
1114
1176
  if expected.comparison is None
1115
- else tool_called and _check_comparison(expected, actual_args),
1116
- title_correct=None if expected.title is None else tool_called and _check_title(expected, actual_args),
1177
+ else alert_created and _check_comparison(expected, actual_args),
1178
+ title_correct=None if expected.title is None else alert_created and _check_title(expected, actual_args),
1117
1179
  dashboard_correct=None
1118
1180
  if expected.dashboard_id is None
1119
- else tool_called and _check_dashboard(expected, actual_args),
1181
+ else alert_created and _check_dashboard(expected, actual_args),
1120
1182
  )
1121
1183
  return AlertRunResult(
1122
1184
  conversation_id=conv_id,
@@ -1134,8 +1196,8 @@ def run_agentic_alert_skill(
1134
1196
  run_latency_s=time.monotonic() - run_started,
1135
1197
  )
1136
1198
  finally:
1137
- if alert_id_to_delete:
1138
- _delete_alert(sdk, workspace_id, alert_id_to_delete)
1199
+ for created_id in dict.fromkeys(alert_ids_to_delete):
1200
+ _delete_alert(sdk, workspace_id, created_id)
1139
1201
 
1140
1202
  try:
1141
1203
  conv_id_0 = initial_conversation_id if initial_conversation_id is not None else client.create_conversation()
@@ -0,0 +1,449 @@
1
+ # (C) 2026 GoodData Corporation
2
+ """Agentic knowledge evaluation runner.
3
+
4
+ Each run is a fresh conversation that sends `expected_output.setup_turns` in order, then the
5
+ question (no simulated user), and grades the answer to the question with `AgenticKnowledgeEvaluator`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from gooddata_eval.core.agentic._failed_runs import build_failed_runs
15
+ from gooddata_eval.core.agentic._gate import (
16
+ DEFAULT_GATE,
17
+ EvalGate,
18
+ gate_passed,
19
+ log_gate_scores,
20
+ stamp_gate_metadata,
21
+ )
22
+ from gooddata_eval.core.agentic._outcome import (
23
+ agentic_success,
24
+ attach_labels,
25
+ chat_failure_exit,
26
+ failure_message_head,
27
+ label_runs,
28
+ mark_unscored_run,
29
+ raise_agentic_failure,
30
+ )
31
+ from gooddata_eval.core.agentic._trace_linker import (
32
+ RunIdentity,
33
+ RunTraceContext,
34
+ SubmitTraceLink,
35
+ conversations_to_link,
36
+ open_item_trace,
37
+ run_trace_link_inline,
38
+ submit_trace_scoring,
39
+ utc_now,
40
+ )
41
+ from gooddata_eval.core.chat.sse_client import ChatClient, ChatError
42
+ from gooddata_eval.core.config import ReasoningEffort
43
+ from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError
44
+ from gooddata_eval.core.evaluators.base import ItemEvaluation
45
+ from gooddata_eval.core.evaluators.knowledge import AgenticKnowledgeEvaluator, item_turns
46
+ from gooddata_eval.core.langfuse.item_scope import item_scope
47
+ from gooddata_eval.core.models import (
48
+ AgenticAssertionError,
49
+ AgenticEvalOutcome,
50
+ ChatResult,
51
+ DatasetItem,
52
+ LoopExit,
53
+ ReasoningStepEvent,
54
+ ToolCallEvent,
55
+ build_latency_breakdown,
56
+ shift_and_index_events,
57
+ )
58
+ from gooddata_eval.core.timing import PhaseTimings, log_timer, run_latency_s, sum_timings
59
+
60
+ _DEFAULT_K = 1
61
+ # Code checks that gate the verdict; each is its own Langfuse score, to split retrieval from reasoning.
62
+ CODE_CHECKS = (
63
+ "knowledge_searched",
64
+ "expected_documents_found",
65
+ "forbidden_documents_absent",
66
+ "expected_source_found",
67
+ "answered",
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class KnowledgeRunResult:
73
+ """Outcome of one K-run conversation."""
74
+
75
+ conversation_id: str
76
+ evaluation: ItemEvaluation
77
+ turn_results: list[ChatResult] = field(default_factory=list)
78
+ reasoning_steps: list[str] = field(default_factory=list)
79
+ response_id: str | None = None
80
+ timings: PhaseTimings = field(default_factory=PhaseTimings)
81
+ run_latency_s: float = 0.0
82
+ # All turns, rebased onto one timeline.
83
+ tool_call_events: list[ToolCallEvent] = field(default_factory=list)
84
+ reasoning_step_events: list[ReasoningStepEvent] = field(default_factory=list)
85
+ # Set when a turn or the conversation creation failed; such a run is not graded.
86
+ chat_error: str | None = None
87
+ exit_reason: LoopExit | None = None
88
+
89
+ @property
90
+ def judge_error(self) -> str | None:
91
+ """Why the judge left a run without a verdict; None when it graded or was not asked.
92
+
93
+ `grade_rubric` sets `evaluation.error` only when every code check held and no gating
94
+ criterion got a readable verdict, so the judge's verdict was the one still open.
95
+ """
96
+ return self.evaluation.error if self.chat_error is None else None
97
+
98
+ @property
99
+ def passed(self) -> bool:
100
+ return self.chat_error is None and self.evaluation.passed
101
+
102
+
103
+ @dataclass
104
+ class AgenticKnowledgeSummary:
105
+ """Aggregated outcome of K runs for one knowledge item."""
106
+
107
+ run_results: list[KnowledgeRunResult]
108
+ pass_at_k: bool
109
+ pass_power_k: bool
110
+ best: KnowledgeRunResult
111
+
112
+
113
+ def _turn_events(turn_results: list[ChatResult]) -> tuple[list[ToolCallEvent], list[ReasoningStepEvent], list[str]]:
114
+ """Tool events, reasoning events and reasoning steps of the given turns, on one timeline."""
115
+ tool_events: list[ToolCallEvent] = []
116
+ reasoning_events: list[ReasoningStepEvent] = []
117
+ reasoning_steps: list[str] = []
118
+ offsets = (0.0, 0, 0)
119
+ for result in turn_results:
120
+ offsets = shift_and_index_events(
121
+ result, turn_offset=offsets[0], tool_index_offset=offsets[1], reasoning_index_offset=offsets[2]
122
+ )
123
+ tool_events += result.tool_call_events or []
124
+ reasoning_events += result.reasoning_step_events or []
125
+ reasoning_steps += result.reasoning_steps or []
126
+ return tool_events, reasoning_events, reasoning_steps
127
+
128
+
129
+ def _failed_run(
130
+ conversation_id: str, message: str, turn_results: list[ChatResult], agent_s: float, exit_reason: LoopExit
131
+ ) -> KnowledgeRunResult:
132
+ """A run that never reached its last answer, kept so completed runs survive.
133
+
134
+ The completed turns keep their events, so the latency breakdown still covers them.
135
+ """
136
+ tool_events, reasoning_events, reasoning_steps = _turn_events(turn_results)
137
+ return KnowledgeRunResult(
138
+ exit_reason=exit_reason,
139
+ conversation_id=conversation_id,
140
+ evaluation=ItemEvaluation(passed=False, rank_key=(-1, 0.0), detail={}, error=message),
141
+ turn_results=turn_results,
142
+ reasoning_steps=reasoning_steps,
143
+ timings=PhaseTimings(agent_s=agent_s),
144
+ run_latency_s=agent_s,
145
+ tool_call_events=tool_events,
146
+ reasoning_step_events=reasoning_events,
147
+ chat_error=message,
148
+ )
149
+
150
+
151
+ def _run_single_knowledge(
152
+ client: ChatClient,
153
+ evaluator: AgenticKnowledgeEvaluator,
154
+ conversation_id: str,
155
+ item: DatasetItem,
156
+ turns: list[str],
157
+ ) -> KnowledgeRunResult:
158
+ agent_started = time.monotonic()
159
+ turn_results: list[ChatResult] = []
160
+ for turn in turns:
161
+ try:
162
+ turn_results.append(client.send_message(conversation_id, turn))
163
+ except ChatError as exc: # noqa: PERF203 -- one failed turn ends this run only
164
+ message = f"chat failed on turn {len(turn_results) + 1}/{len(turns)}: {exc}"
165
+ elapsed = time.monotonic() - agent_started
166
+ return _failed_run(conversation_id, message, turn_results, elapsed, chat_failure_exit(exc))
167
+ agent_elapsed = time.monotonic() - agent_started
168
+
169
+ judge_started = time.monotonic()
170
+ evaluation = evaluator.evaluate(item, turn_results)
171
+ judge_elapsed = time.monotonic() - judge_started
172
+ log_timer(f"[timer] knowledge {conversation_id} agent {agent_elapsed:.2f}s, judge {judge_elapsed:.2f}s")
173
+
174
+ tool_events, reasoning_events, reasoning_steps = _turn_events(turn_results)
175
+ return KnowledgeRunResult(
176
+ conversation_id=conversation_id,
177
+ evaluation=evaluation,
178
+ turn_results=turn_results,
179
+ reasoning_steps=reasoning_steps,
180
+ response_id=turn_results[-1].response_id,
181
+ timings=PhaseTimings(agent_s=agent_elapsed, judge_s=judge_elapsed),
182
+ run_latency_s=agent_elapsed + judge_elapsed,
183
+ tool_call_events=tool_events,
184
+ reasoning_step_events=reasoning_events,
185
+ )
186
+
187
+
188
+ def run_agentic_knowledge(
189
+ host: str,
190
+ token: str,
191
+ workspace_id: str,
192
+ question: str,
193
+ expected_output: Any,
194
+ k: int = _DEFAULT_K,
195
+ initial_conversation_id: str | None = None,
196
+ reasoning_effort: ReasoningEffort | None = None,
197
+ agent_id: str | None = None,
198
+ user_context: dict[str, Any] | None = None,
199
+ dataset_item_id: str = "",
200
+ dataset_name: str = "agent_knowledge",
201
+ ) -> AgenticKnowledgeSummary:
202
+ """Run the knowledge item K times, each on a fresh conversation, and return a summary.
203
+
204
+ Raises:
205
+ ValueError: The item is invalid; raised before any request.
206
+ """
207
+ item = DatasetItem(
208
+ id=dataset_item_id or "agentic_knowledge",
209
+ dataset_name=dataset_name,
210
+ test_kind="agentic_knowledge",
211
+ question=question,
212
+ expected_output=expected_output,
213
+ )
214
+ AgenticKnowledgeEvaluator.validate(item)
215
+ all_turns = item_turns(item)
216
+ client = ChatClient(
217
+ host=host,
218
+ token=token,
219
+ workspace_id=workspace_id,
220
+ reasoning_effort=reasoning_effort,
221
+ agent_id=agent_id,
222
+ user_context=user_context,
223
+ )
224
+ run_results: list[KnowledgeRunResult] = []
225
+ try:
226
+ evaluator = AgenticKnowledgeEvaluator()
227
+ for run_idx in range(k):
228
+ owned = not (run_idx == 0 and initial_conversation_id is not None)
229
+ if owned:
230
+ try:
231
+ conv_id = client.create_conversation()
232
+ except Exception as exc: # noqa: BLE001 -- a lost conversation must not discard completed runs
233
+ message = f"conversation creation failed: {exc}"
234
+ run_results.append(_failed_run("", message, [], 0.0, LoopExit.CHAT_ERROR))
235
+ continue
236
+ else:
237
+ conv_id = str(initial_conversation_id)
238
+ try:
239
+ run_results.append(_run_single_knowledge(client, evaluator, conv_id, item, all_turns))
240
+ finally:
241
+ if owned:
242
+ client.delete_conversation(conv_id)
243
+ finally:
244
+ client.close()
245
+
246
+ # Chat failures and judge failures both leave a run without a verdict.
247
+ scored = [r for r in run_results if r.chat_error is None and r.judge_error is None]
248
+ pass_at_k = any(r.passed for r in scored)
249
+ pass_power_k = len(scored) == len(run_results) and bool(scored) and all(r.passed for r in scored)
250
+ best = max(scored or run_results, key=lambda r: r.evaluation.rank_key)
251
+ return AgenticKnowledgeSummary(run_results=run_results, pass_at_k=pass_at_k, pass_power_k=pass_power_k, best=best)
252
+
253
+
254
+ def _run_detail(run: KnowledgeRunResult) -> dict:
255
+ """Diagnostics for one run: evaluation detail, latency breakdown, chat error."""
256
+ detail = dict(run.evaluation.detail)
257
+ if run.chat_error is not None:
258
+ detail["chat_error"] = run.chat_error
259
+ detail["latency_breakdown"] = build_latency_breakdown(run.tool_call_events, run.reasoning_step_events)
260
+ return detail
261
+
262
+
263
+ def _check_scores(run: KnowledgeRunResult) -> dict[str, bool]:
264
+ """Per-run Langfuse scores: `knowledge_pass` plus each code check the run recorded."""
265
+ detail = run.evaluation.detail
266
+ checks = {name: detail[name] for name in CODE_CHECKS if isinstance(detail.get(name), bool)}
267
+ return {"knowledge_pass": run.evaluation.passed, **checks}
268
+
269
+
270
+ def _quality_checks(run: KnowledgeRunResult) -> dict[str, bool]:
271
+ """Every bool verdict in the detail: code checks and judge criteria, no `knowledge_pass`.
272
+
273
+ Same set as `rank_key` quality and the report's `quality_score`, so nothing counts twice.
274
+ """
275
+ return {name: value for name, value in run.evaluation.detail.items() if isinstance(value, bool)}
276
+
277
+
278
+ def _failure_reason(run: KnowledgeRunResult) -> str:
279
+ """Failed gating checks as `name=False`, plus the judge or chat error."""
280
+ detail = run.evaluation.detail
281
+ failed = [
282
+ f"{name}=False"
283
+ for name, value in detail.items()
284
+ if value is False and (name in CODE_CHECKS or name.startswith(("include_", "exclude_")))
285
+ ]
286
+ parts = [", ".join(failed)] if failed else []
287
+ if run.evaluation.error:
288
+ parts.append(run.evaluation.error)
289
+ return "; ".join(parts) or "criteria not satisfied"
290
+
291
+
292
+ class KnowledgeAssertionError(AgenticAssertionError):
293
+ """Raised when an agentic knowledge evaluation fails."""
294
+
295
+
296
+ def evaluate_agentic_knowledge(
297
+ host: str,
298
+ token: str,
299
+ workspace_id: str,
300
+ question: str,
301
+ expected_output: Any,
302
+ k: int = _DEFAULT_K,
303
+ initial_conversation_id: str | None = None,
304
+ gate: EvalGate = DEFAULT_GATE,
305
+ agent_id: str | None = None,
306
+ user_context: dict[str, Any] | None = None,
307
+ langfuse: object | None = None,
308
+ dataset_item_id: str = "",
309
+ dataset_name: str = "agent_knowledge",
310
+ run_timestamp: str | None = None,
311
+ model_version_override: str | None = None,
312
+ run_metadata_extra: dict | None = None,
313
+ reasoning_effort: ReasoningEffort | None = None,
314
+ submit_trace_link: SubmitTraceLink = run_trace_link_inline,
315
+ ) -> AgenticEvalOutcome:
316
+ """Run the evaluation, log to Langfuse, and raise KnowledgeAssertionError on failure."""
317
+ identity = RunIdentity(
318
+ host,
319
+ token,
320
+ workspace_id,
321
+ dataset_name,
322
+ run_timestamp,
323
+ model_version_override,
324
+ run_metadata_extra,
325
+ reasoning_effort,
326
+ )
327
+ langfuse, window_start, scope = open_item_trace(langfuse, identity, dataset_item_id, suffix_runs=k > 1)
328
+ with item_scope(scope):
329
+ summary = run_agentic_knowledge(
330
+ host=host,
331
+ token=token,
332
+ workspace_id=workspace_id,
333
+ question=question,
334
+ expected_output=expected_output,
335
+ k=k,
336
+ initial_conversation_id=initial_conversation_id,
337
+ reasoning_effort=reasoning_effort,
338
+ agent_id=agent_id,
339
+ user_context=user_context,
340
+ dataset_item_id=dataset_item_id,
341
+ dataset_name=dataset_name,
342
+ )
343
+
344
+ # Before the Langfuse scores, so a run the judge could not grade gets its ERROR marker there.
345
+ run_labels = label_runs(summary.run_results, passed=lambda r: r.passed, judge_error=lambda r: r.judge_error)
346
+
347
+ if langfuse is not None and dataset_item_id:
348
+ window_end = utc_now()
349
+
350
+ def _write_scores(ctx: RunTraceContext) -> None:
351
+ stamp_gate_metadata(ctx.run_metadata, k=len(summary.run_results), gate=gate)
352
+ for run_idx, run in enumerate(summary.run_results):
353
+ if run.chat_error is not None:
354
+ continue
355
+ if run.judge_error is not None:
356
+ # No verdict: a knowledge_pass=0 would publish a failure nobody assessed.
357
+ mark_unscored_run(ctx, run_idx, run.conversation_id, run_labels.error_label(run_idx))
358
+ continue
359
+ pt = ctx.trace(run.conversation_id)
360
+ scores = _check_scores(run)
361
+ with ctx.observe(pt, run_idx, conversation_id=run.conversation_id, output=scores) as tid:
362
+ for name, value in scores.items():
363
+ ctx.score(tid, name=name, value=float(value), data_type="BOOLEAN")
364
+ ctx.quality(
365
+ tid,
366
+ strict_checks=_quality_checks(run),
367
+ latency_sec=pt.latency if pt else None,
368
+ cost_usd=pt.total_cost if pt else None,
369
+ )
370
+ log_gate_scores(ctx, tid, gate=gate, pass_at_k=summary.pass_at_k, pass_power_k=summary.pass_power_k)
371
+
372
+ submit_trace_scoring(
373
+ submit_trace_link,
374
+ identity,
375
+ langfuse=langfuse,
376
+ dataset_item_id=dataset_item_id,
377
+ conversation_ids=conversations_to_link(
378
+ [r.conversation_id for r in summary.run_results if r.chat_error is None and r.judge_error is None],
379
+ [r.conversation_id for r in summary.run_results if r.judge_error is not None],
380
+ ),
381
+ window_start=window_start,
382
+ window_end=window_end,
383
+ suffix_runs=k > 1,
384
+ write_scores=_write_scores,
385
+ scope=scope,
386
+ item_input=question,
387
+ )
388
+
389
+ best = summary.best
390
+ unscored = [r.judge_error for r in summary.run_results if r.judge_error is not None]
391
+ detail = _run_detail(best)
392
+ if unscored:
393
+ detail["unscored_runs"] = len(unscored)
394
+ detail["judge_errors"] = unscored
395
+ timings = sum_timings([r.timings for r in summary.run_results])
396
+ runs_passed = sum(1 for r in summary.run_results if r.passed)
397
+ runs_effective = len(summary.run_results)
398
+ run_latencies_s = [r.run_latency_s for r in summary.run_results]
399
+ failed_runs = build_failed_runs(summary.run_results, labels=run_labels, detail=_run_detail)
400
+
401
+ if unscored and not any(r.chat_error is None and r.judge_error is None for r in summary.run_results):
402
+ # No run got a verdict: the item is a harness error, not K failures.
403
+ error = JudgeResponseError(
404
+ f"judge returned no readable verdict for any of the {len(unscored)} graded run(s): " + " | ".join(unscored)
405
+ )
406
+ error.reasoning_steps = best.reasoning_steps
407
+ error.conversation_id = best.conversation_id
408
+ error.response_id = best.response_id
409
+ error.detail = detail
410
+ error.runs_passed = runs_passed
411
+ error.runs_effective = runs_effective
412
+ error.failed_runs = failed_runs
413
+ error.run_latencies_s = run_latencies_s
414
+ error.best_run_latency_s = run_latency_s(best.timings)
415
+ error.timings = timings
416
+ attach_labels(error, run_labels, gate)
417
+ raise error
418
+
419
+ if not gate_passed(gate, pass_at_k=summary.pass_at_k, pass_power_k=summary.pass_power_k):
420
+ head = failure_message_head(gate, run_labels, runs_passed, failed_runs, len(unscored))
421
+ raise_agentic_failure(
422
+ KnowledgeAssertionError,
423
+ f"Knowledge answer failed for '{dataset_item_id or question}'. {head} {_failure_reason(best)}",
424
+ harness_error=run_labels.harness_error_record,
425
+ shadow=run_labels.shadow(gate),
426
+ reasoning_steps=best.reasoning_steps,
427
+ conversation_id=best.conversation_id,
428
+ response_id=best.response_id,
429
+ detail=detail,
430
+ runs_passed=runs_passed,
431
+ runs_effective=runs_effective,
432
+ failed_runs=failed_runs,
433
+ run_latencies_s=run_latencies_s,
434
+ best_run_latency_s=run_latency_s(best.timings),
435
+ timings=timings,
436
+ )
437
+ return agentic_success(
438
+ shadow=run_labels.shadow(gate),
439
+ reasoning_steps=best.reasoning_steps,
440
+ conversation_id=best.conversation_id,
441
+ response_id=best.response_id,
442
+ detail=detail,
443
+ runs_passed=runs_passed,
444
+ runs_effective=runs_effective,
445
+ failed_runs=failed_runs,
446
+ run_latencies_s=run_latencies_s,
447
+ best_run_latency_s=run_latency_s(best.timings),
448
+ timings=timings,
449
+ )
@@ -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 ``_extract_alert_call`` — the id
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
  """
@@ -0,0 +1,246 @@
1
+ # (C) 2026 GoodData Corporation
2
+ """Evaluator for agentic_knowledge: retrieval checks plus an LLM-judge rubric on the last answer.
3
+
4
+ The AI chat answers from knowledge documents through the `search_knowledge` and
5
+ `get_knowledge_chunks` tools. An item sends `setup_turns`, then its question, in one
6
+ conversation and grades the answer to the question. `expected_output` is:
7
+
8
+ {
9
+ "setup_turns": ["...earlier user turns, sent in order before the question..."],
10
+ "expect_search": true,
11
+ "expected_documents": ["...document titles some knowledge tool must return..."],
12
+ "forbidden_documents": ["...document titles no knowledge tool may return..."],
13
+ "expected_source": "the parent workspace",
14
+ "must_include": ["...criteria the last answer must satisfy..."],
15
+ "must_not_include": ["...characteristics the last answer must not show..."],
16
+ "rubric": ["...soft quality dimensions..."]
17
+ }
18
+
19
+ Every key is optional. Retrieval checks gate the verdict before the judge, so a failed item
20
+ shows whether the document was never found (retrieval) or found and misused (reasoning).
21
+ """
22
+
23
+ import re
24
+ from collections.abc import Sequence
25
+ from typing import Any
26
+
27
+ from gooddata_eval.core.chat.render import render_answer_text
28
+ from gooddata_eval.core.evaluators._llm_judge import LLMJudge
29
+ from gooddata_eval.core.evaluators._rubric import Criterion, grade_rubric
30
+ from gooddata_eval.core.evaluators.base import ItemEvaluation
31
+ from gooddata_eval.core.models import ChatResult, DatasetItem, ToolCallEvent
32
+
33
+ SEARCH_TOOL = "search_knowledge"
34
+ CHUNKS_TOOL = "get_knowledge_chunks"
35
+
36
+ _POSITIVE_STEPS = [
37
+ "Read the INPUT (the conversation so far, ending with the user's last question) and the "
38
+ "EXPECTED OUTPUT (one criterion the assistant's last answer must satisfy).",
39
+ "Read the ACTUAL OUTPUT (the assistant's last answer).",
40
+ "Score 1 if the actual output clearly satisfies the criterion.",
41
+ "Score 0 if the criterion is missing, contradicted, or only partially addressed.",
42
+ ]
43
+
44
+ # Presence question, inverted in code.
45
+ _VIOLATION_STEPS = [
46
+ "Read the CHARACTERISTIC described in EXPECTED OUTPUT, including any exceptions it states.",
47
+ "Read the ACTUAL OUTPUT (the assistant's last answer).",
48
+ "Decide only whether the actual output exhibits the characteristic, not whether it is correct or wanted.",
49
+ "Score 1 if the actual output clearly exhibits the described characteristic.",
50
+ "Score 0 if it does not exhibit it.",
51
+ ]
52
+
53
+ _BOOL_KEYS = ("expect_search",)
54
+ _LIST_KEYS = ("setup_turns", "expected_documents", "forbidden_documents", "must_include", "must_not_include", "rubric")
55
+ _STR_KEYS = ("expected_source",)
56
+ _KNOWN_KEYS = frozenset(_BOOL_KEYS + _LIST_KEYS + _STR_KEYS)
57
+ # The `source` labels gen-ai puts on knowledge tool results.
58
+ SOURCE_LABELS = ("this workspace", "the parent workspace", "an ancestor workspace", "AI Hub")
59
+
60
+ # Earlier user turns and answers shown to the judge are cut to this many characters each.
61
+ _EARLIER_TURN_CHARS = 1500
62
+
63
+ # "**Sources**", "### Sources" or "Sources:" on a line of its own.
64
+ _SOURCES_HEADING = re.compile(r"^\s*(?:\*\*Sources:?\*\*|#{1,6}\s*Sources:?|Sources:)\s*$", re.IGNORECASE)
65
+ _BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s+(.+?)\s*$")
66
+ _EMPHASIS = re.compile(r"^(\*\*|\*|_)(.+?)\1")
67
+
68
+
69
+ def _norm(text: Any) -> str:
70
+ return str(text or "").strip().casefold()
71
+
72
+
73
+ def item_turns(item: DatasetItem) -> list[str]:
74
+ """All user turns of a validated item: `setup_turns`, then the question (the graded turn)."""
75
+ expected = item.expected_output if isinstance(item.expected_output, dict) else {}
76
+ return [*expected.get("setup_turns", []), item.question]
77
+
78
+
79
+ def knowledge_results(events: Sequence[ToolCallEvent]) -> list[dict[str, Any]]:
80
+ """One row per document any knowledge tool returned, in call order.
81
+
82
+ - `search_knowledge`: `{"results": [{"title", "filename", "source", ...}]}`, one row each
83
+ - `get_knowledge_chunks`: `{"title", "filename", "source", "chunks": [...]}`, one row;
84
+ a document it did not find (no title, no filename) adds none
85
+ """
86
+ rows: list[dict[str, Any]] = []
87
+ for event in events:
88
+ parsed = event.parsed_result() if event.result else None
89
+ if not isinstance(parsed, dict):
90
+ continue
91
+ if event.function_name == SEARCH_TOOL and isinstance(parsed.get("results"), list):
92
+ rows.extend(row for row in parsed["results"] if isinstance(row, dict))
93
+ elif event.function_name == CHUNKS_TOOL and _row_names(parsed):
94
+ rows.append({key: parsed.get(key) for key in ("title", "filename", "source")})
95
+ return rows
96
+
97
+
98
+ def _row_names(row: dict[str, Any]) -> set[str]:
99
+ """Normalized title and filename of a result row; either can match a document."""
100
+ return {name for name in (_norm(row.get("title")), _norm(row.get("filename"))) if name}
101
+
102
+
103
+ def _row_label(row: dict[str, Any]) -> str:
104
+ return str(row.get("title") or "").strip() or str(row.get("filename") or "").strip()
105
+
106
+
107
+ def parse_sources_cited(answer: str) -> list[str]:
108
+ """Titles in the last "Sources" section of an answer; [] when there is none.
109
+
110
+ - heading line: `**Sources**`, `### Sources` or `Sources:`
111
+ - each following bullet: `- *Title* (filename), pp. 1-2 — from *source*`, or `- Title (...)`
112
+ - stops at the first non-blank line that is not a bullet
113
+ """
114
+ lines = answer.splitlines()
115
+ start = next((i for i in range(len(lines) - 1, -1, -1) if _SOURCES_HEADING.match(lines[i])), None)
116
+ if start is None:
117
+ return []
118
+ titles: list[str] = []
119
+ for line in lines[start + 1 :]:
120
+ if not line.strip():
121
+ continue
122
+ bullet = _BULLET.match(line)
123
+ if bullet is None:
124
+ break
125
+ text = bullet.group(1)
126
+ emphasis = _EMPHASIS.match(text)
127
+ title = emphasis.group(2) if emphasis else text.split(" (", 1)[0]
128
+ if title.strip():
129
+ titles.append(title.strip())
130
+ return titles
131
+
132
+
133
+ def _clip(text: str) -> str:
134
+ return text if len(text) <= _EARLIER_TURN_CHARS else text[:_EARLIER_TURN_CHARS] + "… (truncated)"
135
+
136
+
137
+ def judge_input(turns: Sequence[str], answers: Sequence[str]) -> str:
138
+ """What the judge reads as INPUT: the question, or the conversation up to the last question."""
139
+ if len(turns) == 1:
140
+ return turns[0]
141
+ parts: list[str] = []
142
+ for turn, answer in zip(turns[:-1], answers, strict=False):
143
+ parts.append(f"User: {_clip(turn)}\nAssistant: {_clip(answer)}")
144
+ parts.append(f"User (last question): {turns[-1]}")
145
+ return "\n\n".join(parts)
146
+
147
+
148
+ class AgenticKnowledgeEvaluator:
149
+ test_kind = "agentic_knowledge"
150
+
151
+ def __init__(self):
152
+ self._positive_judge = LLMJudge(evaluation_steps=_POSITIVE_STEPS)
153
+ self._violation_judge = LLMJudge(evaluation_steps=_VIOLATION_STEPS)
154
+
155
+ @staticmethod
156
+ def validate(item: DatasetItem) -> None:
157
+ """Reject an item this evaluator cannot read, before any request.
158
+
159
+ Raises:
160
+ ValueError: Blank question, `expected_output` not an object, an unknown key,
161
+ or a value of the wrong type.
162
+ """
163
+ prefix = f"agentic_knowledge item '{item.id}'"
164
+ if not item.question.strip():
165
+ raise ValueError(f"{prefix}: question must be a non-empty string")
166
+ expected = item.expected_output if item.expected_output is not None else {}
167
+ if not isinstance(expected, dict):
168
+ raise ValueError(f"{prefix}: expected_output must be a JSON object")
169
+ # `test_kind` routes the item (langfuse_source) and is not an expectation.
170
+ unknown = sorted(set(expected) - _KNOWN_KEYS - {"test_kind"})
171
+ if unknown:
172
+ raise ValueError(f"{prefix}: unknown expected_output key(s) {unknown}; known: {sorted(_KNOWN_KEYS)}")
173
+ for key in _BOOL_KEYS:
174
+ if key in expected and not isinstance(expected[key], bool):
175
+ raise ValueError(f"{prefix}: {key} must be true or false")
176
+ for key in _LIST_KEYS:
177
+ value = expected.get(key, [])
178
+ if not isinstance(value, list) or not all(isinstance(v, str) and v.strip() for v in value):
179
+ raise ValueError(f"{prefix}: {key} must be a JSON array of non-empty strings")
180
+ for key in _STR_KEYS:
181
+ if key in expected and not (isinstance(expected[key], str) and expected[key].strip()):
182
+ raise ValueError(f"{prefix}: {key} must be a non-empty string")
183
+ source = expected.get("expected_source")
184
+ if isinstance(source, str) and _norm(source) not in {_norm(label) for label in SOURCE_LABELS}:
185
+ raise ValueError(f"{prefix}: expected_source must be one of {list(SOURCE_LABELS)}")
186
+ if "expected_source" in expected and not expected.get("expected_documents"):
187
+ raise ValueError(f"{prefix}: expected_source needs expected_documents to say which document")
188
+
189
+ def evaluate(self, item: DatasetItem, turn_results: Sequence[ChatResult]) -> ItemEvaluation:
190
+ """Grade one run: every turn's result, in order; the last one is the graded answer."""
191
+ self.validate(item)
192
+ expected: dict[str, Any] = item.expected_output if isinstance(item.expected_output, dict) else {}
193
+ turns = item_turns(item)
194
+ answers = [render_answer_text(result) for result in turn_results]
195
+ last = answers[-1] if answers else ""
196
+ detail: dict[str, Any] = {"actual_output": last, **self.retrieval_checks(expected, turn_results)}
197
+ detail["answered"] = bool(last)
198
+ detail["sources_cited"] = parse_sources_cited(last)
199
+ detail["turn_count"] = len(turn_results)
200
+
201
+ passed = all(v for v in detail.values() if isinstance(v, bool))
202
+ if not last:
203
+ return ItemEvaluation(passed=False, rank_key=(0, 0.0), detail=detail)
204
+
205
+ def _criteria(key: str, prefix: str) -> list[Criterion]:
206
+ return [(f"{prefix}_{i}", str(c)) for i, c in enumerate(expected.get(key, []))]
207
+
208
+ return grade_rubric(
209
+ self._positive_judge,
210
+ self._violation_judge,
211
+ question=judge_input(turns, answers),
212
+ actual=last,
213
+ must_include=_criteria("must_include", "include"),
214
+ must_not_include=_criteria("must_not_include", "exclude"),
215
+ rubric=_criteria("rubric", "rubric"),
216
+ detail=detail,
217
+ passed=passed,
218
+ )
219
+
220
+ @staticmethod
221
+ def retrieval_checks(expected: dict[str, Any], turn_results: Sequence[ChatResult]) -> dict[str, Any]:
222
+ """Code checks over every turn's knowledge tool calls.
223
+
224
+ - bools gate the verdict; each is present only when its key is set
225
+ - `documents_retrieved` is a list, so it never gates or counts towards quality
226
+ """
227
+ events = [event for result in turn_results for event in result.tool_call_events or []]
228
+ rows = knowledge_results(events)
229
+ found = set().union(*(_row_names(row) for row in rows)) if rows else set()
230
+ checks: dict[str, Any] = {}
231
+ if expected.get("expect_search", True):
232
+ checks["knowledge_searched"] = any(e.function_name == SEARCH_TOOL for e in events)
233
+ wanted = expected.get("expected_documents") or []
234
+ if wanted:
235
+ checks["expected_documents_found"] = all(_norm(title) in found for title in wanted)
236
+ forbidden = expected.get("forbidden_documents") or []
237
+ if forbidden:
238
+ checks["forbidden_documents_absent"] = not any(_norm(title) in found for title in forbidden)
239
+ source = expected.get("expected_source")
240
+ if source:
241
+ wanted_names = {_norm(title) for title in wanted}
242
+ checks["expected_source_found"] = any(
243
+ _row_names(row) & wanted_names and _norm(row.get("source")) == _norm(source) for row in rows
244
+ )
245
+ checks["documents_retrieved"] = sorted({label for row in rows if (label := _row_label(row))})
246
+ return checks
@@ -47,6 +47,7 @@ MULTI_TURN_KINDS = frozenset(
47
47
  "agentic_what_if",
48
48
  "agentic_forecasting",
49
49
  "agentic_agent_switcher",
50
+ "agentic_knowledge",
50
51
  }
51
52
  )
52
53
 
@@ -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.dev8
3
+ Version: 1.80.1.dev10
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.dev8
21
+ Requires-Dist: gooddata-sdk~=1.80.1.dev10
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
@@ -162,7 +162,7 @@ gd-eval run \
162
162
  | `--runs K` | `2` | Independent runs per item. |
163
163
  | `--gate` | `any` | Which verdict decides an item: `any` = pass@K (a run passing is enough), `power` = pass^K (every run must pass, so the verdict measures stability). Identical at `--runs 1`. Kinds that repeat K runs only — `power` is refused when the dataset also has non-agentic items or `agentic_conversation`, which are always decided on pass@K. |
164
164
  | `--concurrency K` | `1` | Number of items evaluated concurrently. `1` = sequential (default). Increase to load-test the agent under simultaneous requests — see *Concurrency and workspace safety* below. |
165
- | `--judge-model MODEL` | `gpt-4o` | Model used for LLM-as-judge scoring — `agentic_general_question`, `agentic_guardrail`, `general_question`, `guardrail`, `dashboard_summary`, `document_takeaway` and `catalog_metadata`. Also settable via `GD_EVAL_JUDGE_MODEL`. Two things to weigh before changing it: the gpt-5 family rejects `temperature=0`, so verdicts stop being reproducible (the run warns when this happens); and choosing the same model the agent runs means the judge grades its own family's output. |
165
+ | `--judge-model MODEL` | `gpt-4o` | Model used for LLM-as-judge scoring — `agentic_general_question`, `agentic_guardrail`, `general_question`, `guardrail`, `dashboard_summary`, `document_takeaway`, `catalog_metadata` and `agentic_knowledge`. Also settable via `GD_EVAL_JUDGE_MODEL`. Two things to weigh before changing it: the gpt-5 family rejects `temperature=0`, so verdicts stop being reproducible (the run warns when this happens); and choosing the same model the agent runs means the judge grades its own family's output. |
166
166
  | `--reasoning-effort LEVEL` | server default | `LOW`, `MEDIUM` or `HIGH`, sent as `options.reasoningEffort` on every chat message. Requires the `enableGenAiReasoningEffort` feature flag on the target organization — without it the server ignores the value. Applies to chat items only; `dashboard_summary`, `document_takeaway` and `catalog_metadata` items go through their own endpoints, which have no such option. |
167
167
 
168
168
  **Concurrency and workspace safety.** Agentic kinds that create workspace objects
@@ -354,7 +354,7 @@ their eval kind, and states latency for each:
354
354
  - **Multi-turn** — kinds that drive a simulated user or fixture turns: `agentic_visualization` (and
355
355
  `vis_agentic`), `agentic_metric_skill`, `agentic_alert_skill`, `agentic_dashboard_skill`,
356
356
  `agentic_document_skill`, `agentic_kda_skill`, `agentic_anomaly_detection`, `agentic_what_if`,
357
- `agentic_agent_switcher` and `agentic_conversation`.
357
+ `agentic_agent_switcher`, `agentic_knowledge` and `agentic_conversation`.
358
358
 
359
359
  ```json
360
360
  "summary": {
@@ -1013,6 +1013,56 @@ first message when the new conversation is bound to another agent (`agent_bound`
1013
1013
  are reported as `turn<N>_<check>`, e.g. `turn2_skills_used`, `turn2_include_0`. The CI entry point
1014
1014
  is `evaluate_agentic_agent_switcher`, which takes the whole item; `--agent-id` does not apply.
1015
1015
 
1016
+ ### `agentic_knowledge` items
1017
+
1018
+ Knowledge items ask the AI chat questions it answers from knowledge documents (tools
1019
+ `search_knowledge` and `get_knowledge_chunks`). Each run is a fresh conversation that sends
1020
+ `expected_output.setup_turns` in order (no simulated user), then `question`, and grades the
1021
+ answer to `question`. `question` is the graded turn; `setup_turns` (a JSON array of non-empty
1022
+ strings, optional) holds the earlier user turns of a multi-turn item, as in `agentic_search`.
1023
+ In a Langfuse dataset, set `test_kind` (in
1024
+ `metadata` or `expectedOutput`) to route an item to this kind.
1025
+
1026
+ ```json
1027
+ {
1028
+ "id": "kn-001",
1029
+ "dataset_name": "agent_knowledge",
1030
+ "test_kind": "agentic_knowledge",
1031
+ "question": "And for 45 %?",
1032
+ "expected_output": {
1033
+ "setup_turns": ["Who must approve a 30 % discount?"],
1034
+ "expected_documents": ["Discount Policy"],
1035
+ "forbidden_documents": ["Discount Policy 2023"],
1036
+ "expected_source": "the parent workspace",
1037
+ "must_include": ["Says that discounts above 40 % are not allowed."],
1038
+ "must_not_include": ["Says that the CFO must approve the discount."]
1039
+ }
1040
+ }
1041
+ ```
1042
+
1043
+ Every `expected_output` key is optional; unknown keys and wrong types are rejected before
1044
+ any request. Code checks over the knowledge tool results of all turns gate the verdict, so a
1045
+ failed item shows whether retrieval (document never found) or reasoning (found, answered
1046
+ wrong) failed:
1047
+
1048
+ - `expect_search` (default `true`) — at least one `search_knowledge` call (`knowledge_searched`).
1049
+ - `expected_documents` — each title is in some knowledge tool result (`expected_documents_found`).
1050
+ - `forbidden_documents` — no title is in any knowledge tool result (`forbidden_documents_absent`).
1051
+ - `expected_source` — an expected document's result carries this `source` label
1052
+ (`expected_source_found`); needs `expected_documents`. One of gen-ai's labels: `this
1053
+ workspace`, `the parent workspace`, `an ancestor workspace`, `AI Hub`.
1054
+ - `must_include`, `must_not_include`, `rubric` — judge criteria on the answer to `question`,
1055
+ graded like `dashboard_summary`; the judge reads the setup turns and their answers as INPUT.
1056
+
1057
+ Titles match case-insensitively on a result's `title` or `filename`. An answer to `question`
1058
+ without text fails (`answered`). Diagnostics that never gate: `documents_retrieved`,
1059
+ `sources_cited` (titles in the answer's trailing "Sources" list) and `turn_count`. Langfuse
1060
+ gets `knowledge_pass` plus each code check as its own score per run; `quality_score` counts the
1061
+ code checks and judge verdicts. A run the judge could not grade is an ERROR (`eval_error`), not
1062
+ a fail. The judge steps are calibrated with
1063
+ `make calibrate-knowledge` (needs `OPENAI_API_KEY`); the CI entry point is
1064
+ `evaluate_agentic_knowledge`.
1065
+
1016
1066
  ### Items asked in a dashboard context (`user_context`)
1017
1067
 
1018
1068
  An item can be asked the way a user asks from an open dashboard or an attached widget.
@@ -1115,6 +1165,7 @@ from that turn on until another turn changes it, as the attached context does in
1115
1165
  | `document_takeaway` | One short takeaway for a page (via `/takeaway` endpoint): deterministic format checks plus a rubric scored by LLM | `[llm-judge]` |
1116
1166
  | `catalog_metadata` | Analytics Catalog title or description for one object (via the `analyticsCatalog/generate*` endpoints): format checks plus a rubric scored by LLM | `[llm-judge]` |
1117
1167
  | `agentic_agent_switcher` | One conversation switched between agents: each answer stamped with the active agent, one switch marker per switch, and per-turn judge, skill, alert and chart checks | `agent_switcher_input`; `[llm-judge]` for judge criteria |
1168
+ | `agentic_knowledge` | Answer from knowledge documents, after optional setup turns: retrieval checks on the knowledge tool results plus a rubric on the last answer scored by LLM | `[llm-judge]` |
1118
1169
 
1119
1170
  ## Optional extras
1120
1171
 
@@ -1,7 +1,7 @@
1
1
  gooddata_eval/__init__.py,sha256=9Nz0iJXzkJWiL40PijM6AMpAqQOH-dbYNfDtDysBPYc,186
2
2
  gooddata_eval/_version.py,sha256=L4nT6RJQ2vc_F9stvO59xZv92xsRUqbpUh1sGlb-UNU,195
3
3
  gooddata_eval/cli/__init__.py,sha256=U54lANKm34yjqm7dZL9KkGouPbwAaQWC9wiAmb5B5g4,32
4
- gooddata_eval/cli/agentic_runner.py,sha256=MvD2P02C4Uksi5drMMHxVzB7k1kWWnFfken3CVZ2hso,33628
4
+ gooddata_eval/cli/agentic_runner.py,sha256=WZmNrOqVuOL-pV7vRXzMvhJzMRaai3TJJfJ5S8AAtt8,34115
5
5
  gooddata_eval/cli/main.py,sha256=_SEw16H2Hc772K-TB9tZyZKUlL_k695KM--aYitaIa8,34790
6
6
  gooddata_eval/core/__init__.py,sha256=U54lANKm34yjqm7dZL9KkGouPbwAaQWC9wiAmb5B5g4,32
7
7
  gooddata_eval/core/_output.py,sha256=sFbNtKg1lx431jpb15jISLlOXGTZ-r_KodfaTVyka6I,580
@@ -9,8 +9,8 @@ gooddata_eval/core/_retry.py,sha256=H2jZLGYbD72hUXI4S0KDQzcg93h3iz76D2A7mjXGKvI,
9
9
  gooddata_eval/core/config.py,sha256=hla5t294uHC5Q9bzrhPjsdkwEcetLsEH-GqGAhs94b4,4823
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
- gooddata_eval/core/interaction.py,sha256=xM29pITCOnYvuI28Xx9y7Nl831JR6BNmW0fOGTN2RNs,2195
13
- gooddata_eval/core/models.py,sha256=4-b_TzHAYKP19VSwmLhQYMAUnNuYyaDFxN1csK2koag,30696
12
+ gooddata_eval/core/interaction.py,sha256=hJxrTNpEN7s0fctdJGW511bf_thfXJJ1Dn3E2cGgtP0,2224
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
@@ -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=N0gWOPiETnA83wLOoDZ4QNjcxXm2oDMv7x9CNEuemAg,63623
36
+ gooddata_eval/core/agentic/alert_skill.py,sha256=GLmvEVxsiBhqL-RkZ_kKp6MFYQmIRyP-0iXCqSJA2BE,66730
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
@@ -43,6 +43,7 @@ gooddata_eval/core/agentic/forecasting.py,sha256=vpq0BOuXNaMqlbPOt_MQi6avw6eqkbq
43
43
  gooddata_eval/core/agentic/general_question.py,sha256=YPaz7tbeV0lTHlfmUPNvJ5FD6y-nh5ZqpwLSQqpJI4Y,20480
44
44
  gooddata_eval/core/agentic/guardrail.py,sha256=_7-nlBNVnGaYJx9Oq8V08npe1IunxgwH1bqKs0yplhY,17904
45
45
  gooddata_eval/core/agentic/kda_skill.py,sha256=L89qH8-cUzJxr105GsGC7WK4Cpg6i_M8wbUca8Wf-2Y,27881
46
+ gooddata_eval/core/agentic/knowledge.py,sha256=hVAyQwCmewjTAdvfNHz6517obwxr3-KRb8yxmBkL1j4,17836
46
47
  gooddata_eval/core/agentic/metric_skill.py,sha256=1XCaeAVN8UTu5CVxFcEANyK0ATktCKsyO-ciFHSMdGM,57243
47
48
  gooddata_eval/core/agentic/report_skill.py,sha256=ZpuKuQpor56ywDKauzQKAx18vFHcW6uq3nFgV2GjVvM,1583
48
49
  gooddata_eval/core/agentic/search_tool.py,sha256=oo5hPlEp4gabz_gsMzcn_dYn0T8tbjmq6PDA5K1Oak8,30553
@@ -65,11 +66,12 @@ gooddata_eval/core/evaluators/_llm_judge.py,sha256=A5lukKt8IG26BoN_oU2DvkOHAQwV0
65
66
  gooddata_eval/core/evaluators/_maql.py,sha256=XpamaPXixBTpiMGrZYnV0t_4DEmuPSa32PqQOk0RG_k,4348
66
67
  gooddata_eval/core/evaluators/_rubric.py,sha256=hHBsE52M2E2JaRuN07Vs1ST0nVaq44kft5QqgoaO3-g,4248
67
68
  gooddata_eval/core/evaluators/_text_utils.py,sha256=GWGJB6uJFhwZTiy4QcthXd2z_GtUdh5p6gZqHVnfBo4,1816
68
- gooddata_eval/core/evaluators/alert_skill.py,sha256=I5Zgo972JR6WhqYeDZ8ttncBr8tehlklFQhukqPdy8M,6203
69
+ gooddata_eval/core/evaluators/alert_skill.py,sha256=iLDV8ZSAMjgiGxi6i7RpdVzcMXVihEn5yiz4JqV2wVE,6201
69
70
  gooddata_eval/core/evaluators/base.py,sha256=H9EMG57jX0W4vmasgJNUhwRjtGRuVBik2MhN9ZDV1Jk,777
70
71
  gooddata_eval/core/evaluators/catalog_metadata.py,sha256=knj_7N_nEznHHnJMnBVYsNGMqA4GYQLmfGnQHUkIg9Y,8868
71
72
  gooddata_eval/core/evaluators/general_question.py,sha256=3YIuCH7t_Ih6Of8hozRUHd6Vaum2X3KxhKFCjzthLHg,2170
72
73
  gooddata_eval/core/evaluators/guardrail.py,sha256=J3sX0v_ImbV-GC3c_vMtQrn9Sn0sy-zH5B-Bdc_8TXI,3157
74
+ gooddata_eval/core/evaluators/knowledge.py,sha256=3iz324JSquptJMS8b1qXVwiqp-_zPMsZUDpp-8VhSgw,11923
73
75
  gooddata_eval/core/evaluators/metric_skill.py,sha256=ckQvo-TX_bwGWcTkxaHMztMcg7lYBegH5uFOK4wfNSo,3005
74
76
  gooddata_eval/core/evaluators/search_tool.py,sha256=c6iK_tHMaDaUjYuo5EnAYDGe53gTDTQtUl226hZq0JY,3070
75
77
  gooddata_eval/core/evaluators/summary.py,sha256=h3Z3Zu5cwc9TVLMa7Q6yUwLjPpFtOEGSHyRgyuYukNc,4258
@@ -93,8 +95,8 @@ gooddata_eval/core/summary/http_client.py,sha256=Umae42fiiJQ0e4hv63NRROHYvcFAGgX
93
95
  gooddata_eval/core/takeaway/__init__.py,sha256=U54lANKm34yjqm7dZL9KkGouPbwAaQWC9wiAmb5B5g4,32
94
96
  gooddata_eval/core/takeaway/evaluate.py,sha256=AjS_rCHWUSJKv0jfEfL0-dVPoDaf3RkGdmeZiIwjd6A,11312
95
97
  gooddata_eval/core/takeaway/http_client.py,sha256=YMfafOcHJ184i49Qoh0ZNPKKTMKBSgeDUM4zk_H3yM8,3955
96
- gooddata_eval-1.80.1.dev8.dist-info/METADATA,sha256=zxKFkhkMpSbgeF4OYcY1FqB3e5-fh00FF4C_Kx9IhdY,70720
97
- gooddata_eval-1.80.1.dev8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
98
- gooddata_eval-1.80.1.dev8.dist-info/entry_points.txt,sha256=28nFp5Viknx4haPYgzK9QHlwPFfC6rPF6RmjC2ht8EI,56
99
- gooddata_eval-1.80.1.dev8.dist-info/licenses/LICENSE.txt,sha256=LVfVlC9maU3K9lgMwdZnClQQsOIbOekdcdVKr9qzJtk,256836
100
- gooddata_eval-1.80.1.dev8.dist-info/RECORD,,
98
+ gooddata_eval-1.80.1.dev10.dist-info/METADATA,sha256=uvCc2vZ0ty6wVDcTF4jsodLFoaNUrTkv9p0jav4BSpU,73708
99
+ gooddata_eval-1.80.1.dev10.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
100
+ gooddata_eval-1.80.1.dev10.dist-info/entry_points.txt,sha256=28nFp5Viknx4haPYgzK9QHlwPFfC6rPF6RmjC2ht8EI,56
101
+ gooddata_eval-1.80.1.dev10.dist-info/licenses/LICENSE.txt,sha256=LVfVlC9maU3K9lgMwdZnClQQsOIbOekdcdVKr9qzJtk,256836
102
+ gooddata_eval-1.80.1.dev10.dist-info/RECORD,,