evalsuite-python 0.6.0__cp39-abi3-win_arm64.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.
Files changed (72) hide show
  1. evalsuite/__init__.py +268 -0
  2. evalsuite/__main__.py +5 -0
  3. evalsuite/_bench_metrics.py +2080 -0
  4. evalsuite/_core.pyd +0 -0
  5. evalsuite/_lazy.py +32 -0
  6. evalsuite/_native.py +60 -0
  7. evalsuite/api.py +275 -0
  8. evalsuite/benchmarks.py +946 -0
  9. evalsuite/calibration.py +392 -0
  10. evalsuite/classification/__init__.py +51 -0
  11. evalsuite/classification/_common.py +111 -0
  12. evalsuite/classification/metrics.py +945 -0
  13. evalsuite/cli/__init__.py +5 -0
  14. evalsuite/cli/main.py +606 -0
  15. evalsuite/clinical/__init__.py +18 -0
  16. evalsuite/clinical/metrics.py +342 -0
  17. evalsuite/clinical/report.py +366 -0
  18. evalsuite/core/__init__.py +1 -0
  19. evalsuite/core/context.py +199 -0
  20. evalsuite/core/exceptions.py +52 -0
  21. evalsuite/core/export.py +100 -0
  22. evalsuite/core/registry.py +90 -0
  23. evalsuite/core/result.py +379 -0
  24. evalsuite/core/types.py +23 -0
  25. evalsuite/core/validation.py +256 -0
  26. evalsuite/llmsys/__init__.py +189 -0
  27. evalsuite/llmsys/_common.py +215 -0
  28. evalsuite/llmsys/agents.py +384 -0
  29. evalsuite/llmsys/code.py +923 -0
  30. evalsuite/llmsys/efficiency.py +346 -0
  31. evalsuite/llmsys/longcontext.py +361 -0
  32. evalsuite/llmsys/multilingual.py +339 -0
  33. evalsuite/llmsys/robustness.py +504 -0
  34. evalsuite/llmsys/safety.py +509 -0
  35. evalsuite/llmsys/uncertainty.py +229 -0
  36. evalsuite/plot.py +651 -0
  37. evalsuite/py.typed +0 -0
  38. evalsuite/regression/__init__.py +41 -0
  39. evalsuite/regression/metrics.py +629 -0
  40. evalsuite/reporting.py +241 -0
  41. evalsuite/stats/__init__.py +46 -0
  42. evalsuite/stats/_resolve.py +229 -0
  43. evalsuite/stats/compare.py +420 -0
  44. evalsuite/stats/effect.py +159 -0
  45. evalsuite/stats/hypothesis.py +593 -0
  46. evalsuite/stats/intervals.py +338 -0
  47. evalsuite/stats/paired.py +214 -0
  48. evalsuite/stats/results.py +129 -0
  49. evalsuite/text/__init__.py +154 -0
  50. evalsuite/text/_common.py +97 -0
  51. evalsuite/text/factuality.py +469 -0
  52. evalsuite/text/generation.py +1346 -0
  53. evalsuite/text/judge.py +556 -0
  54. evalsuite/text/qa.py +108 -0
  55. evalsuite/text/rag.py +235 -0
  56. evalsuite/text/reasoning.py +215 -0
  57. evalsuite/text/report.py +158 -0
  58. evalsuite/text/retrieval.py +238 -0
  59. evalsuite/text/semantic.py +499 -0
  60. evalsuite/text/spice.py +162 -0
  61. evalsuite/text/structured.py +793 -0
  62. evalsuite/version.py +3 -0
  63. evalsuite/vision/__init__.py +47 -0
  64. evalsuite/vision/detection.py +696 -0
  65. evalsuite/vision/segmentation.py +1028 -0
  66. evalsuite_python-0.6.0.dist-info/METADATA +509 -0
  67. evalsuite_python-0.6.0.dist-info/RECORD +72 -0
  68. evalsuite_python-0.6.0.dist-info/WHEEL +4 -0
  69. evalsuite_python-0.6.0.dist-info/entry_points.txt +2 -0
  70. evalsuite_python-0.6.0.dist-info/licenses/LICENSE +21 -0
  71. evalsuite_python-0.6.0.dist-info/licenses/LICENSE-APACHE +191 -0
  72. evalsuite_python-0.6.0.dist-info/sboms/evalsuite-py.cyclonedx.json +576 -0
@@ -0,0 +1,384 @@
1
+ """Agent and tool-use evaluation (v0.5.0).
2
+
3
+ A trajectory is the list of tool calls an agent made for one task, each a dict with ``"name"``, optional
4
+ ``"arguments"`` (dict or JSON string) and optional ``"ok"`` (whether the call executed successfully). Tool-call
5
+ precision / recall / F1 and tool-selection and argument accuracy against a reference are the existing
6
+ ``es.tool_call_f1``, ``es.tool_selection_accuracy`` and ``es.tool_argument_accuracy``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Mapping, Sequence
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+
17
+ from ..core.exceptions import InputValidationError
18
+ from ..core.registry import register
19
+ from ..core.result import MetricResult
20
+ from ..text.structured import validate_json_schema
21
+ from ._common import bools, floats, lists_of, rate, same_length, seq, summary
22
+
23
+ __all__ = [
24
+ "agent_cost_per_task",
25
+ "human_intervention_rate",
26
+ "invalid_tool_call_rate",
27
+ "plan_adherence",
28
+ "state_tracking_accuracy",
29
+ "steps_per_task",
30
+ "task_completion_rate",
31
+ "tool_failure_recovery_rate",
32
+ "tool_use_efficiency",
33
+ "unnecessary_tool_call_rate",
34
+ ]
35
+
36
+ _C = "agents"
37
+ _REF_AGENTBENCH = "Liu X, Yu H, Zhang H, et al. AgentBench: evaluating LLMs as agents. ICLR. 2024."
38
+ _REF_AGENTBOARD = (
39
+ "Ma C, Zhang J, Zhu Z, et al. AgentBoard: an analytical evaluation board of multi-turn LLM agents. NeurIPS "
40
+ "Datasets and Benchmarks. 2024."
41
+ )
42
+ _REF_TAU = (
43
+ "Yao S, Shinn N, Razavi P, Narasimhan K. τ-bench: a benchmark for tool-agent-user interaction in real-world "
44
+ "domains. arXiv:2406.12045. 2024."
45
+ )
46
+ _REF_BFCL = (
47
+ "Patil SG, Mao H, Cheng-Jie Ji C, et al. The Berkeley Function Calling Leaderboard (BFCL): from tool use to "
48
+ "agentic evaluation of large language models. ICML. 2025."
49
+ )
50
+ _REF_DST = (
51
+ "Mrkšić N, Ó Séaghdha D, Wen TH, Thomson B, Young S. Neural belief tracker: data-driven dialogue state "
52
+ "tracking. ACL. 2017:1777-1788."
53
+ )
54
+ _REF_TOOLEMU = (
55
+ "Ruan Y, Dong H, Wang A, et al. Identifying the risks of LM agents with an LM-emulated sandbox. ICLR. 2024."
56
+ )
57
+
58
+
59
+ def _trajectories(x: Any, name: str = "trajectories") -> list[list[dict[str, Any]]]:
60
+ out = []
61
+ for i, traj in enumerate(lists_of(x, name)):
62
+ calls = []
63
+ for j, c in enumerate(traj):
64
+ if not isinstance(c, Mapping) or "name" not in c:
65
+ raise InputValidationError(f"{name}[{i}][{j}] must be a dict with a 'name'.")
66
+ args = c.get("arguments", {})
67
+ if isinstance(args, str):
68
+ try:
69
+ args = json.loads(args) if args.strip() else {}
70
+ except ValueError:
71
+ args = {"__unparseable__": args}
72
+ calls.append({"name": c["name"], "arguments": args, "ok": c.get("ok")})
73
+ out.append(calls)
74
+ return out
75
+
76
+
77
+ def _key(call: Mapping[str, Any]) -> str:
78
+ return json.dumps([call["name"], call["arguments"]], sort_keys=True, default=str)
79
+
80
+
81
+ @register(
82
+ category=_C,
83
+ task="agents",
84
+ name="Task / goal completion rate",
85
+ definition="Share of tasks the agent completes (its goal state reached or judged successful), with the mean "
86
+ "progress rate when partial progress is scored (AgentBoard).",
87
+ formula="completed tasks / tasks",
88
+ range="[0, 1]",
89
+ input_requirements=("completed",),
90
+ references=(_REF_AGENTBENCH, _REF_AGENTBOARD),
91
+ )
92
+ def task_completion_rate(completed: Any, *, progress: Any = None) -> MetricResult:
93
+ c = bools(completed, "completed")
94
+ extra: dict[str, Any] = {}
95
+ if progress is not None:
96
+ p = floats(progress, "progress", lo=0, hi=1)
97
+ same_length(("completed", c), ("progress", p))
98
+ extra["progress_rate"] = float(p.mean())
99
+ return rate("task_completion_rate", "Task completion rate", c, extra)
100
+
101
+
102
+ @register(
103
+ category=_C,
104
+ task="tool-use",
105
+ name="Invalid tool-call / execution failure rate",
106
+ definition="Share of tool calls that are invalid (unknown tool, unparseable or schema-violating arguments, "
107
+ "checked against each tool's JSON Schema) and, where execution results are recorded, the share that failed "
108
+ "to execute.",
109
+ formula="invalid calls / calls",
110
+ range="[0, 1]",
111
+ input_requirements=("trajectories", "tools"),
112
+ references=(_REF_BFCL,),
113
+ higher_is_better=False,
114
+ )
115
+ def invalid_tool_call_rate(trajectories: Any, tools: Mapping[str, Any]) -> MetricResult:
116
+ """``tools``: tool name -> JSON Schema of its arguments (``{}`` accepts anything)."""
117
+ if not isinstance(tools, Mapping) or not tools:
118
+ raise InputValidationError("tools must be a non-empty mapping tool name -> argument JSON Schema.")
119
+ trajs = _trajectories(trajectories)
120
+ invalid, failed, executed = [], 0, 0
121
+ reasons = {"unknown_tool": 0, "unparseable_arguments": 0, "schema": 0}
122
+ for traj in trajs:
123
+ for call in traj:
124
+ bad = False
125
+ if call["name"] not in tools:
126
+ reasons["unknown_tool"] += 1
127
+ bad = True
128
+ elif isinstance(call["arguments"], Mapping) and "__unparseable__" in call["arguments"]:
129
+ reasons["unparseable_arguments"] += 1
130
+ bad = True
131
+ elif validate_json_schema(call["arguments"], tools[call["name"]] or {}):
132
+ reasons["schema"] += 1
133
+ bad = True
134
+ invalid.append(bad)
135
+ if call["ok"] is not None:
136
+ executed += 1
137
+ failed += not bool(call["ok"])
138
+ if not invalid:
139
+ raise InputValidationError("The trajectories contain no tool calls.")
140
+ n = len(invalid)
141
+ extra = {
142
+ "by_reason": {k: v / n for k, v in reasons.items()},
143
+ "execution_failure_rate": failed / executed if executed else float("nan"),
144
+ }
145
+ return rate("invalid_tool_call_rate", "Invalid tool-call rate", np.array(invalid), extra)
146
+
147
+
148
+ @register(
149
+ category=_C,
150
+ task="tool-use",
151
+ name="Tool-use efficiency",
152
+ definition="How close the number of tool calls is to the minimum needed: the mean of optimal / actual calls "
153
+ "per task (1 = no wasted calls), with the mean excess calls.",
154
+ formula="mean_t min(1, optimal_t / actual_t)",
155
+ range="[0, 1]",
156
+ input_requirements=("n_calls", "optimal_calls"),
157
+ references=(_REF_AGENTBOARD,),
158
+ )
159
+ def tool_use_efficiency(n_calls: Any, optimal_calls: Any) -> MetricResult:
160
+ a = floats(n_calls, "n_calls", lo=0)
161
+ o = floats(optimal_calls, "optimal_calls", lo=0)
162
+ same_length(("n_calls", a), ("optimal_calls", o))
163
+ eff = np.where(a == 0, np.where(o == 0, 1.0, 0.0), np.minimum(1.0, o / np.where(a == 0, 1, a)))
164
+ return MetricResult(
165
+ "tool_use_efficiency",
166
+ "Tool-use efficiency",
167
+ float(eff.mean()),
168
+ {"mean_excess_calls": float(np.maximum(0, a - o).mean()), "n_tasks": int(a.size)},
169
+ )
170
+
171
+
172
+ @register(
173
+ category=_C,
174
+ task="agents",
175
+ name="Steps / tool calls per task",
176
+ definition="Distribution of the number of steps (and tool calls) per task: mean, median and high "
177
+ "percentiles, overall and for completed tasks only.",
178
+ formula="mean_t steps_t",
179
+ range="[0, ∞)",
180
+ input_requirements=("steps",),
181
+ references=(_REF_AGENTBOARD, _REF_TAU),
182
+ higher_is_better=False,
183
+ )
184
+ def steps_per_task(steps: Any, *, tool_calls: Any = None, completed: Any = None) -> MetricResult:
185
+ s = floats(steps, "steps", lo=0)
186
+ extra: dict[str, Any] = {"steps": summary(s)}
187
+ if tool_calls is not None:
188
+ t = floats(tool_calls, "tool_calls", lo=0)
189
+ same_length(("steps", s), ("tool_calls", t))
190
+ extra["tool_calls"] = summary(t)
191
+ if completed is not None:
192
+ c = bools(completed, "completed")
193
+ same_length(("steps", s), ("completed", c))
194
+ extra["mean_steps_completed"] = float(s[c].mean()) if c.any() else float("nan")
195
+ return MetricResult("steps_per_task", "Steps per task", float(s.mean()), extra)
196
+
197
+
198
+ def _lcs(a: Sequence[Any], b: Sequence[Any]) -> int:
199
+ if not a or not b:
200
+ return 0
201
+ prev = [0] * (len(b) + 1)
202
+ for x in a:
203
+ cur = [0]
204
+ for j, y in enumerate(b):
205
+ cur.append(prev[j] + 1 if x == y else max(prev[j + 1], cur[j]))
206
+ prev = cur
207
+ return prev[-1]
208
+
209
+
210
+ @register(
211
+ category=_C,
212
+ task="planning",
213
+ name="Planning accuracy / plan adherence",
214
+ definition="Agreement between the steps executed and a reference plan, in order: precision and recall of the "
215
+ "longest common subsequence, their F1 (the value), and the exact-plan match rate.",
216
+ formula="P = LCS / |executed|, R = LCS / |plan|, F1 = 2PR / (P + R)",
217
+ range="[0, 1]",
218
+ input_requirements=("plans", "executed"),
219
+ references=(_REF_AGENTBOARD,),
220
+ )
221
+ def plan_adherence(plans: Any, executed: Any) -> MetricResult:
222
+ """``plans`` and ``executed``: per task, a list of step identifiers (tool names, action labels, ...)."""
223
+ ps, es_ = lists_of(plans, "plans"), lists_of(executed, "executed")
224
+ same_length(("plans", ps), ("executed", es_))
225
+ f1s, prec, rec = [], [], []
226
+ for p, e in zip(ps, es_):
227
+ lcs = _lcs(p, e)
228
+ pr = lcs / len(e) if e else float(not p)
229
+ rc = lcs / len(p) if p else 1.0
230
+ prec.append(pr)
231
+ rec.append(rc)
232
+ f1s.append(0.0 if pr + rc == 0 else 2 * pr * rc / (pr + rc))
233
+ return MetricResult(
234
+ "plan_adherence",
235
+ "Plan adherence (F1)",
236
+ float(np.mean(f1s)),
237
+ {
238
+ "precision": float(np.mean(prec)),
239
+ "recall": float(np.mean(rec)),
240
+ "exact_match": float(np.mean([list(p) == list(e) for p, e in zip(ps, es_)])),
241
+ },
242
+ )
243
+
244
+
245
+ @register(
246
+ category=_C,
247
+ task="state-tracking",
248
+ name="State-tracking accuracy",
249
+ definition="Dialogue / environment state tracking: joint goal accuracy (every slot of the state correct at a "
250
+ "turn) and slot accuracy (share of slots correct over the union of expected and predicted slots).",
251
+ formula="JGA = mean_turns 1[state = expected]",
252
+ range="[0, 1]",
253
+ input_requirements=("expected_states", "predicted_states"),
254
+ references=(_REF_DST,),
255
+ )
256
+ def state_tracking_accuracy(expected_states: Any, predicted_states: Any) -> MetricResult:
257
+ e, p = seq(expected_states, "expected_states"), seq(predicted_states, "predicted_states")
258
+ same_length(("expected_states", e), ("predicted_states", p))
259
+ joint, slots_ok, slots_n = [], 0, 0
260
+ for i, (a, b) in enumerate(zip(e, p)):
261
+ if not isinstance(a, Mapping) or not isinstance(b, Mapping):
262
+ raise InputValidationError(f"States at turn {i} must be dicts slot -> value.")
263
+ joint.append(dict(a) == dict(b))
264
+ keys = set(a) | set(b)
265
+ slots_n += len(keys)
266
+ slots_ok += sum(k in a and k in b and a[k] == b[k] for k in keys)
267
+ return MetricResult(
268
+ "state_tracking_accuracy",
269
+ "Joint goal accuracy",
270
+ float(np.mean(joint)),
271
+ {"slot_accuracy": slots_ok / slots_n if slots_n else 1.0, "n_turns": len(e)},
272
+ )
273
+
274
+
275
+ @register(
276
+ category=_C,
277
+ task="tool-use",
278
+ name="Recovery from tool failures",
279
+ definition="Among failed tool calls, the share after which the agent later succeeded with the same tool in "
280
+ "the same task (retried correctly or fixed the arguments).",
281
+ formula="#failed calls followed by a successful call of that tool / #failed calls",
282
+ range="[0, 1]",
283
+ input_requirements=("trajectories",),
284
+ references=(_REF_TAU, _REF_TOOLEMU),
285
+ )
286
+ def tool_failure_recovery_rate(trajectories: Any) -> MetricResult:
287
+ flags = []
288
+ for traj in _trajectories(trajectories):
289
+ for i, call in enumerate(traj):
290
+ if call["ok"] is False:
291
+ flags.append(any(c["name"] == call["name"] and c["ok"] is True for c in traj[i + 1 :]))
292
+ if not flags:
293
+ raise InputValidationError("No tool call failed (no 'ok': False): the recovery rate is undefined.")
294
+ return rate("tool_failure_recovery_rate", "Tool-failure recovery rate", np.array(flags))
295
+
296
+
297
+ @register(
298
+ category=_C,
299
+ task="tool-use",
300
+ name="Unnecessary tool-call / loop rate",
301
+ definition="Share of tool calls that exactly repeat an earlier call (same tool and arguments) in the same "
302
+ "task, "
303
+ "and the share of tasks stuck in a loop (the same call repeated consecutively at least ``loop_length`` "
304
+ "times).",
305
+ formula="repeated calls / calls",
306
+ range="[0, 1]",
307
+ input_requirements=("trajectories",),
308
+ references=(_REF_AGENTBOARD,),
309
+ higher_is_better=False,
310
+ )
311
+ def unnecessary_tool_call_rate(trajectories: Any, *, loop_length: int = 3) -> MetricResult:
312
+ if isinstance(loop_length, bool) or not isinstance(loop_length, int) or loop_length < 2:
313
+ raise InputValidationError("loop_length must be an integer >= 2.")
314
+ repeats, total, loops = [], 0, []
315
+ trajs = _trajectories(trajectories)
316
+ for traj in trajs:
317
+ seen: set[str] = set()
318
+ run, longest, prev = 0, 0, None
319
+ for call in traj:
320
+ k = _key(call)
321
+ repeats.append(k in seen)
322
+ seen.add(k)
323
+ run = run + 1 if k == prev else 1
324
+ longest = max(longest, run)
325
+ prev = k
326
+ total += 1
327
+ loops.append(longest >= loop_length)
328
+ if not total:
329
+ raise InputValidationError("The trajectories contain no tool calls.")
330
+ return rate(
331
+ "unnecessary_tool_call_rate",
332
+ "Unnecessary tool-call rate",
333
+ np.array(repeats),
334
+ {"loop_rate": float(np.mean(loops)), "loop_length": loop_length},
335
+ )
336
+
337
+
338
+ @register(
339
+ category=_C,
340
+ task="agents",
341
+ name="Human intervention rate",
342
+ definition="Share of tasks that needed at least one human intervention (correction, approval override, "
343
+ "takeover), with the mean number of interventions per task.",
344
+ formula="tasks with ≥1 intervention / tasks",
345
+ range="[0, 1]",
346
+ input_requirements=("interventions",),
347
+ references=(_REF_TAU,),
348
+ higher_is_better=False,
349
+ )
350
+ def human_intervention_rate(interventions: Any) -> MetricResult:
351
+ n = floats(interventions, "interventions", lo=0)
352
+ return rate(
353
+ "human_intervention_rate",
354
+ "Human intervention rate",
355
+ n > 0,
356
+ {"mean_per_task": float(n.mean())},
357
+ )
358
+
359
+
360
+ @register(
361
+ category=_C,
362
+ task="agents",
363
+ name="End-to-end execution time / cost per task",
364
+ definition="Mean wall-clock time and monetary cost per task, and the cost per successful task (total cost "
365
+ "divided by completed tasks), the figure that matters when failures are retried.",
366
+ formula="cost per success = Σ cost / #completed",
367
+ range="[0, ∞)",
368
+ input_requirements=("costs",),
369
+ references=(_REF_AGENTBENCH,),
370
+ higher_is_better=False,
371
+ )
372
+ def agent_cost_per_task(costs: Any, *, durations: Any = None, completed: Any = None) -> MetricResult:
373
+ c = floats(costs, "costs", lo=0)
374
+ extra: dict[str, Any] = {"total_cost": float(c.sum())}
375
+ if durations is not None:
376
+ d = floats(durations, "durations", lo=0)
377
+ same_length(("costs", c), ("durations", d))
378
+ extra["time"] = summary(d)
379
+ if completed is not None:
380
+ ok = bools(completed, "completed")
381
+ same_length(("costs", c), ("completed", ok))
382
+ extra["cost_per_success"] = float(c.sum()) / int(ok.sum()) if ok.any() else float("inf")
383
+ extra["success_rate"] = float(ok.mean())
384
+ return MetricResult("agent_cost_per_task", "Cost per task", float(c.mean()), extra)