-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate.py
More file actions
275 lines (225 loc) · 8.49 KB
/
Copy pathevaluate.py
File metadata and controls
275 lines (225 loc) · 8.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
"""Agent evaluation framework for systematic benchmarking.
Defines tasks with metrics, runs agents N times, aggregates results
with statistics. Inspired by agentscope's evaluation module.
Usage:
from hawk.evaluate import Benchmark, EvalTask, run_benchmark
tasks = [
EvalTask(
name="weather-lookup",
prompt="What's the weather in NYC?",
expected_tools=["get_weather"],
validate=lambda r: "temperature" in r.response,
),
]
results = run_benchmark(agent, tasks, runs=3)
print(results.summary())
"""
from __future__ import annotations
import statistics
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable, Protocol
if TYPE_CHECKING:
from collections.abc import Awaitable
class SyncBenchAgent(Protocol):
"""Structural type for the agent accepted by run_benchmark."""
def reset(self) -> None: ...
def chat(self, prompt: str) -> Any: ...
class AsyncBenchAgent(Protocol):
"""Structural type for the agent accepted by run_benchmark_async."""
def reset(self) -> None: ...
def chat(self, prompt: str) -> Awaitable[Any]: ...
@dataclass
class EvalTask:
"""A single evaluation task."""
name: str
prompt: str
category: str = "general"
expected_tools: list[str] = field(default_factory=list)
validate: Callable[[Any], bool] | None = None
max_turns: int = 10
@dataclass
class EvalResult:
"""Result of a single evaluation run."""
task_name: str
success: bool
duration_ms: float
tokens_in: int = 0
tokens_out: int = 0
turns_taken: int = 0
error: str | None = None
@dataclass
class BenchmarkResults:
"""Aggregated benchmark results."""
results: list[EvalResult] = field(default_factory=list)
@property
def total_tasks(self) -> int:
return len(self.results)
@property
def passed(self) -> int:
return sum(1 for r in self.results if r.success)
@property
def failed(self) -> int:
return self.total_tasks - self.passed
@property
def pass_rate(self) -> float:
return self.passed / max(self.total_tasks, 1)
@property
def avg_duration_ms(self) -> float:
durations = [r.duration_ms for r in self.results]
return statistics.mean(durations) if durations else 0.0
@property
def total_tokens(self) -> int:
return sum(r.tokens_in + r.tokens_out for r in self.results)
def by_category(self) -> dict[str, list[EvalResult]]:
cats: dict[str, list[EvalResult]] = {}
for r in self.results:
cat = r.task_name.split("/")[0] if "/" in r.task_name else "general"
cats.setdefault(cat, []).append(r)
return cats
def summary(self) -> str:
lines = [
f"Benchmark Results: {self.passed}/{self.total_tasks} passed ({self.pass_rate:.0%})",
f"Avg duration: {self.avg_duration_ms:.0f}ms",
f"Total tokens: {self.total_tokens}",
]
if self.failed > 0:
failures = [r for r in self.results if not r.success]
lines.append("Failures:")
for f in failures[:10]:
lines.append(f" - {f.task_name}: {f.error or 'validation failed'}")
return "\n".join(lines)
def _extract_tool_names(response: Any) -> set[str]:
"""Extract tool names from a chat response's tool_calls.
Handles both OpenAI-style ({"function": {"name": ...}}) and
flat ({"name": ...}) tool call dicts.
"""
tool_calls = getattr(response, "tool_calls", None)
if not tool_calls:
return set()
names: set[str] = set()
for tc in tool_calls:
if not isinstance(tc, dict):
continue
fn = tc.get("function")
if isinstance(fn, dict) and "name" in fn:
names.add(fn["name"])
elif "name" in tc:
names.add(tc["name"])
return names
def run_benchmark(
agent: SyncBenchAgent,
tasks: list[EvalTask],
*,
runs: int = 1,
reset_between_tasks: bool = True,
) -> BenchmarkResults:
"""Run a benchmark suite against an agent.
Args:
agent: A hawk Agent instance with a .chat() method.
tasks: List of evaluation tasks.
runs: Number of times to run each task.
reset_between_tasks: Whether to reset agent state between tasks.
Returns:
Aggregated benchmark results.
"""
results = BenchmarkResults()
for task in tasks:
for _run_idx in range(runs):
if reset_between_tasks:
agent.reset()
start = time.perf_counter()
try:
response = agent.chat(task.prompt)
duration = (time.perf_counter() - start) * 1000
success = True
error_msg: str | None = None
if task.validate:
success = task.validate(response)
# Verify expected tools were invoked
if success and task.expected_tools:
used = _extract_tool_names(response)
missing = set(task.expected_tools) - used
if missing:
success = False
error_msg = f"expected tools not used: {sorted(missing)}"
results.results.append(
EvalResult(
task_name=f"{task.category}/{task.name}"
if task.category != "general"
else task.name,
success=success,
duration_ms=duration,
tokens_in=getattr(response, "tokens_in", 0),
tokens_out=getattr(response, "tokens_out", 0),
turns_taken=getattr(response, "turns_taken", 0),
error=error_msg,
)
)
except Exception as e:
duration = (time.perf_counter() - start) * 1000
results.results.append(
EvalResult(
task_name=f"{task.category}/{task.name}"
if task.category != "general"
else task.name,
success=False,
duration_ms=duration,
error=str(e),
)
)
return results
async def run_benchmark_async(
agent: AsyncBenchAgent,
tasks: list[EvalTask],
*,
runs: int = 1,
reset_between_tasks: bool = True,
) -> BenchmarkResults:
"""Async version of run_benchmark."""
results = BenchmarkResults()
for task in tasks:
for _run_idx in range(runs):
if reset_between_tasks:
agent.reset()
start = time.perf_counter()
try:
response = await agent.chat(task.prompt)
duration = (time.perf_counter() - start) * 1000
success = True
error_msg: str | None = None
if task.validate:
success = task.validate(response)
# Verify expected tools were invoked
if success and task.expected_tools:
used = _extract_tool_names(response)
missing = set(task.expected_tools) - used
if missing:
success = False
error_msg = f"expected tools not used: {sorted(missing)}"
results.results.append(
EvalResult(
task_name=f"{task.category}/{task.name}"
if task.category != "general"
else task.name,
success=success,
duration_ms=duration,
tokens_in=getattr(response, "tokens_in", 0),
tokens_out=getattr(response, "tokens_out", 0),
turns_taken=getattr(response, "turns_taken", 0),
error=error_msg,
)
)
except Exception as e:
duration = (time.perf_counter() - start) * 1000
results.results.append(
EvalResult(
task_name=f"{task.category}/{task.name}"
if task.category != "general"
else task.name,
success=False,
duration_ms=duration,
error=str(e),
)
)
return results