agent-eval-dashboard 0.1.0__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.
- agent_eval_dashboard/__init__.py +6 -0
- agent_eval_dashboard/cli.py +48 -0
- agent_eval_dashboard/recorder.py +193 -0
- agent_eval_dashboard/report.py +283 -0
- agent_eval_dashboard/runner.py +233 -0
- agent_eval_dashboard/server.py +108 -0
- agent_eval_dashboard/template.html +344 -0
- agent_eval_dashboard-0.1.0.dist-info/METADATA +321 -0
- agent_eval_dashboard-0.1.0.dist-info/RECORD +11 -0
- agent_eval_dashboard-0.1.0.dist-info/WHEEL +4 -0
- agent_eval_dashboard-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Part 3: the command. Serves an evals SQLite file as a page, or writes it to one HTML file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from agent_eval_dashboard import report, server
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def parse_args(argv: list[str] | None) -> argparse.Namespace:
|
|
14
|
+
"""Read the command-line words."""
|
|
15
|
+
parser = argparse.ArgumentParser(
|
|
16
|
+
prog="agent-eval-dashboard",
|
|
17
|
+
description="Show an evals SQLite file as a page: a local server, or one HTML file with -o.",
|
|
18
|
+
)
|
|
19
|
+
parser.add_argument("db", type=Path, help="the SQLite file, for example evals.db")
|
|
20
|
+
parser.add_argument("--experiment", help="show only this experiment's batches")
|
|
21
|
+
parser.add_argument("-o", "--output", type=Path, default=None,
|
|
22
|
+
help="write one offline HTML file instead of starting the server")
|
|
23
|
+
parser.add_argument("--no-browser", action="store_true",
|
|
24
|
+
help="start the server but do not open a browser (ignored with -o)")
|
|
25
|
+
return parser.parse_args(argv)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: list[str] | None = None) -> int:
|
|
29
|
+
"""The command starts here.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
0 when the page was written or the server was stopped with Ctrl+C,
|
|
33
|
+
1 when there are no runs to show or the file is too old.
|
|
34
|
+
"""
|
|
35
|
+
args = parse_args(argv)
|
|
36
|
+
title = args.experiment or "All experiments"
|
|
37
|
+
try:
|
|
38
|
+
if args.output is None:
|
|
39
|
+
server.serve(args.db, args.experiment, open_browser=not args.no_browser)
|
|
40
|
+
return 0
|
|
41
|
+
runs = report.load_runs(args.db, args.experiment)
|
|
42
|
+
except (report.NoRunsFound, report.OldDatabase) as e:
|
|
43
|
+
print(f"agent-eval-dashboard: {e}", file=sys.stderr)
|
|
44
|
+
return 1
|
|
45
|
+
page = report.render_html(report.build_page(runs, title=title, now=datetime.now(UTC)))
|
|
46
|
+
args.output.write_text(page, encoding="utf-8")
|
|
47
|
+
print(f"Wrote {args.output} ({len(runs)} runs)")
|
|
48
|
+
return 0
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Part 1: the recorder. Saves each run and each case into one SQLite file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
import uuid
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
SCHEMA = """
|
|
13
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
14
|
+
run_id TEXT PRIMARY KEY,
|
|
15
|
+
created_at TEXT NOT NULL,
|
|
16
|
+
experiment TEXT NOT NULL,
|
|
17
|
+
model TEXT NOT NULL,
|
|
18
|
+
harness TEXT NOT NULL,
|
|
19
|
+
label TEXT NOT NULL,
|
|
20
|
+
system_prompt TEXT,
|
|
21
|
+
tools TEXT NOT NULL,
|
|
22
|
+
batch_id TEXT
|
|
23
|
+
);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS cases (
|
|
25
|
+
run_id TEXT NOT NULL REFERENCES runs(run_id),
|
|
26
|
+
case_id TEXT NOT NULL,
|
|
27
|
+
input TEXT NOT NULL,
|
|
28
|
+
expected_tools TEXT NOT NULL,
|
|
29
|
+
called TEXT NOT NULL,
|
|
30
|
+
verdict TEXT NOT NULL CHECK (verdict IN ('PASS', 'FAIL', 'ERROR')),
|
|
31
|
+
reason TEXT NOT NULL,
|
|
32
|
+
answer TEXT,
|
|
33
|
+
cost_usd REAL,
|
|
34
|
+
tokens INTEGER,
|
|
35
|
+
turns INTEGER,
|
|
36
|
+
seconds REAL,
|
|
37
|
+
saved_at TEXT
|
|
38
|
+
);
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
CASE_COLUMNS = ("run_id, case_id, input, expected_tools, called, verdict, reason, "
|
|
42
|
+
"answer, cost_usd, tokens, turns, seconds, saved_at")
|
|
43
|
+
|
|
44
|
+
STAMP = "%Y-%m-%dT%H:%M:%SZ" # every time in the file: UTC, to the second
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def new_id() -> str:
|
|
48
|
+
"""A new run or batch id, for example 20261202-171230-91e186."""
|
|
49
|
+
return datetime.now(UTC).strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:6]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class OldDatabase(Exception):
|
|
53
|
+
"""The file was made before tokens, turns and seconds. There is no migration."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def is_old_db(conn: sqlite3.Connection) -> bool:
|
|
57
|
+
"""True when the cases table exists but has no tokens, turns or seconds columns."""
|
|
58
|
+
columns = {row[1] for row in conn.execute("PRAGMA table_info(cases)")}
|
|
59
|
+
return bool(columns) and not {"tokens", "turns", "seconds"} <= columns
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class EvalLog:
|
|
63
|
+
"""One run: create it, call case() or error() once per case, then close()."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, db: str | Path, experiment: str, model: str, harness: str,
|
|
66
|
+
label: str, tools: list[dict], system_prompt: str | None = None,
|
|
67
|
+
batch: str | None = None) -> None:
|
|
68
|
+
"""batch: runs with the same text show as one entry in the run list. Without it,
|
|
69
|
+
this run is a batch of its own."""
|
|
70
|
+
for name, value in (("experiment", experiment), ("model", model),
|
|
71
|
+
("harness", harness), ("label", label)):
|
|
72
|
+
_need_text(name, value)
|
|
73
|
+
if system_prompt is not None:
|
|
74
|
+
_need_text("system_prompt", system_prompt)
|
|
75
|
+
if batch is not None:
|
|
76
|
+
_need_text("batch", batch)
|
|
77
|
+
clean_tools = _clean_tools(tools)
|
|
78
|
+
|
|
79
|
+
now = datetime.now(UTC)
|
|
80
|
+
self.run_id = new_id()
|
|
81
|
+
self.batch_id = batch if batch is not None else new_id()
|
|
82
|
+
self._conn = sqlite3.connect(db)
|
|
83
|
+
try:
|
|
84
|
+
self._conn.executescript(SCHEMA)
|
|
85
|
+
if is_old_db(self._conn):
|
|
86
|
+
raise OldDatabase(f"old evals.db, delete it ({db})")
|
|
87
|
+
_add_missing_columns(self._conn)
|
|
88
|
+
self._conn.execute(
|
|
89
|
+
"INSERT INTO runs (run_id, created_at, experiment, model, harness, label, system_prompt,"
|
|
90
|
+
" tools, batch_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
91
|
+
(self.run_id, now.strftime(STAMP), experiment, model,
|
|
92
|
+
harness, label, system_prompt, json.dumps(clean_tools), self.batch_id),
|
|
93
|
+
)
|
|
94
|
+
self._conn.commit()
|
|
95
|
+
except BaseException:
|
|
96
|
+
self._conn.close() # no open connection is left behind when the run can't start
|
|
97
|
+
raise
|
|
98
|
+
|
|
99
|
+
def case(self, case_id: str, input_text: str, expected_tools: list[str], called: list[dict],
|
|
100
|
+
*, passed: bool, reason: str, answer: str | None = None,
|
|
101
|
+
cost_usd: float | None = None, tokens: int | None = None, turns: int | None = None,
|
|
102
|
+
seconds: float | None = None) -> None:
|
|
103
|
+
"""Save one judged case. You decide passed; the recorder only stores it."""
|
|
104
|
+
if not isinstance(passed, bool):
|
|
105
|
+
raise ValueError(f"'passed' must be True or False, got {passed!r}")
|
|
106
|
+
if not isinstance(called, list) or not all(
|
|
107
|
+
isinstance(c, dict) and isinstance(c.get("tool"), str) and c["tool"] for c in called
|
|
108
|
+
):
|
|
109
|
+
raise ValueError(f"'called' must be a list of {{'tool': ..., 'args': ...}}, got {called!r}")
|
|
110
|
+
try:
|
|
111
|
+
json.dumps(called, ensure_ascii=False)
|
|
112
|
+
except (TypeError, ValueError) as e:
|
|
113
|
+
raise ValueError(f"'called' args must be saveable as JSON, got {called!r} ({e})") from e
|
|
114
|
+
if answer is not None and not isinstance(answer, str):
|
|
115
|
+
raise ValueError(f"'answer' must be text or None, got {answer!r}")
|
|
116
|
+
if cost_usd is not None and (isinstance(cost_usd, bool) or not isinstance(cost_usd, int | float)):
|
|
117
|
+
raise ValueError(f"'cost_usd' must be a number or None, got {cost_usd!r}")
|
|
118
|
+
_need_count("tokens", tokens)
|
|
119
|
+
_need_count("turns", turns)
|
|
120
|
+
self._save(case_id, input_text, expected_tools, called,
|
|
121
|
+
"PASS" if passed else "FAIL", reason, answer, cost_usd, tokens, turns, seconds)
|
|
122
|
+
|
|
123
|
+
def error(self, case_id: str, input_text: str, expected_tools: list[str], *, reason: str,
|
|
124
|
+
seconds: float | None = None) -> None:
|
|
125
|
+
"""Save a case that crashed. It is left out of the pass rate."""
|
|
126
|
+
self._save(case_id, input_text, expected_tools, [], "ERROR", reason, None, None, None, None, seconds)
|
|
127
|
+
|
|
128
|
+
def discard(self) -> None:
|
|
129
|
+
"""Delete this run and its cases. run_eval uses it when a bug in the developer's code stops a run."""
|
|
130
|
+
self._conn.execute("DELETE FROM cases WHERE run_id = ?", (self.run_id,))
|
|
131
|
+
self._conn.execute("DELETE FROM runs WHERE run_id = ?", (self.run_id,))
|
|
132
|
+
self._conn.commit()
|
|
133
|
+
|
|
134
|
+
def close(self) -> None:
|
|
135
|
+
self._conn.close()
|
|
136
|
+
|
|
137
|
+
def _save(self, case_id: str, input_text: str, expected_tools: list[str], called: list[dict],
|
|
138
|
+
verdict: str, reason: str, answer: str | None, cost_usd: float | None,
|
|
139
|
+
tokens: int | None, turns: int | None, seconds: float | None) -> None:
|
|
140
|
+
if seconds is not None and (isinstance(seconds, bool) or not isinstance(seconds, int | float)
|
|
141
|
+
or seconds < 0):
|
|
142
|
+
raise ValueError(f"'seconds' must be a number of 0 or more, or None, got {seconds!r}")
|
|
143
|
+
_need_text("case_id", case_id)
|
|
144
|
+
_need_text("input_text", input_text)
|
|
145
|
+
_need_text("reason", reason)
|
|
146
|
+
if not isinstance(expected_tools, list) or not all(isinstance(t, str) and t for t in expected_tools):
|
|
147
|
+
raise ValueError(f"'expected_tools' must be a list of tool names, got {expected_tools!r}")
|
|
148
|
+
self._conn.execute(
|
|
149
|
+
f"INSERT INTO cases ({CASE_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
150
|
+
(self.run_id, case_id, input_text, json.dumps(expected_tools),
|
|
151
|
+
json.dumps(called, ensure_ascii=False), verdict, reason, answer, cost_usd,
|
|
152
|
+
tokens, turns, seconds, datetime.now(UTC).strftime(STAMP)),
|
|
153
|
+
)
|
|
154
|
+
self._conn.commit()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _add_missing_columns(conn: sqlite3.Connection) -> None:
|
|
158
|
+
"""A file made before batch_id and saved_at is still supported: add the columns.
|
|
159
|
+
Old rows keep NULL there. Only the recorder does this; the page maker never writes."""
|
|
160
|
+
for table, column in (("runs", "batch_id"), ("cases", "saved_at")):
|
|
161
|
+
if column not in {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}:
|
|
162
|
+
try:
|
|
163
|
+
conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} TEXT")
|
|
164
|
+
except sqlite3.OperationalError as e:
|
|
165
|
+
# Another recorder added it between our check and here: that is fine.
|
|
166
|
+
if "duplicate column name" not in str(e):
|
|
167
|
+
raise
|
|
168
|
+
conn.commit()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _need_text(name: str, value: Any) -> None:
|
|
172
|
+
if not isinstance(value, str) or not value.strip():
|
|
173
|
+
raise ValueError(f"'{name}' is required and must be non-empty text, got {value!r}")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _need_count(name: str, value: Any) -> None:
|
|
177
|
+
"""tokens and turns: a whole number of 0 or more, or None. A bool is not a number here."""
|
|
178
|
+
if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 0):
|
|
179
|
+
raise ValueError(f"'{name}' must be a whole number of 0 or more, or None, got {value!r}")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _clean_tools(tools: Any) -> list[dict]:
|
|
183
|
+
"""Check the tools list and fill shown_name with name when it is missing."""
|
|
184
|
+
if not isinstance(tools, list):
|
|
185
|
+
raise ValueError(f"'tools' must be a list of {{'name', 'description'}}, got {tools!r}")
|
|
186
|
+
clean = []
|
|
187
|
+
for t in tools:
|
|
188
|
+
if not (isinstance(t, dict) and isinstance(t.get("name"), str) and t["name"]
|
|
189
|
+
and isinstance(t.get("description"), str)):
|
|
190
|
+
raise ValueError(f"'tools' item needs 'name' and 'description', got {t!r}")
|
|
191
|
+
clean.append({"name": t["name"], "shown_name": t.get("shown_name") or t["name"],
|
|
192
|
+
"description": t["description"]})
|
|
193
|
+
return clean
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Part 3: read the runs from the SQLite file, group them into batches and setups, make the page."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from importlib import resources
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from agent_eval_dashboard.recorder import STAMP, OldDatabase, is_old_db
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class NoRunsFound(Exception):
|
|
15
|
+
"""The file or the experiment has no runs."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class UnfinishedSave(NoRunsFound):
|
|
19
|
+
"""A writer stopped mid-save and left a hot journal; a read-only open can't roll it back."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_runs(db_path: str | Path, experiment: str | None = None) -> list[dict]:
|
|
23
|
+
"""Read every run (with its cases) from the file, oldest first.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
NoRunsFound: the file is missing, is not an eval database, has no tables,
|
|
27
|
+
or has no matching runs.
|
|
28
|
+
UnfinishedSave: (a NoRunsFound) a save was interrupted and left a hot journal.
|
|
29
|
+
OldDatabase: the file was made before tokens, turns and seconds.
|
|
30
|
+
"""
|
|
31
|
+
path = Path(db_path)
|
|
32
|
+
where = f"for {experiment}" if experiment else f"in {path.name}"
|
|
33
|
+
if not path.is_file():
|
|
34
|
+
raise NoRunsFound(f"no runs found {where} (file not found: {path})")
|
|
35
|
+
conn = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)
|
|
36
|
+
conn.row_factory = sqlite3.Row
|
|
37
|
+
try:
|
|
38
|
+
if is_old_db(conn):
|
|
39
|
+
raise OldDatabase(f"old evals.db, delete it ({path})")
|
|
40
|
+
# Every run first: old rows are grouped into batches BEFORE the experiment filter (6.1).
|
|
41
|
+
runs = _with_batches([dict(r) for r in conn.execute("SELECT * FROM runs ORDER BY rowid")])
|
|
42
|
+
if experiment:
|
|
43
|
+
runs = [run for run in runs if run["experiment"] == experiment]
|
|
44
|
+
cases_by_run: dict[str, list[dict]] = {run["run_id"]: [] for run in runs}
|
|
45
|
+
for c in conn.execute("SELECT * FROM cases ORDER BY rowid"): # one query, grouped here
|
|
46
|
+
if c["run_id"] in cases_by_run:
|
|
47
|
+
cases_by_run[c["run_id"]].append(
|
|
48
|
+
{"saved_at": None, **dict(c), "expected_tools": json.loads(c["expected_tools"]),
|
|
49
|
+
"called": json.loads(c["called"])})
|
|
50
|
+
for run in runs:
|
|
51
|
+
run["tools"] = json.loads(run["tools"])
|
|
52
|
+
run["cases"] = cases_by_run[run["run_id"]]
|
|
53
|
+
except sqlite3.OperationalError as e: # for example: no such table
|
|
54
|
+
journal = path.with_name(path.name + "-journal")
|
|
55
|
+
if "readonly" in str(e) or (journal.is_file() and journal.stat().st_size > 0):
|
|
56
|
+
raise UnfinishedSave(
|
|
57
|
+
f"can't read {path.name}: it looks like a save was interrupted (a -journal file is"
|
|
58
|
+
" next to it). Open it once with sqlite3 or run the eval again to recover."
|
|
59
|
+
) from e
|
|
60
|
+
raise NoRunsFound(f"no runs found {where} ({e})") from e
|
|
61
|
+
except sqlite3.DatabaseError as e: # for example: the file is not SQLite at all
|
|
62
|
+
raise NoRunsFound(f"no runs found {where}: {path.name} is not an eval database ({e})") from e
|
|
63
|
+
finally:
|
|
64
|
+
conn.close()
|
|
65
|
+
if not runs:
|
|
66
|
+
raise NoRunsFound(f"no runs found {where}")
|
|
67
|
+
return runs
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _with_batches(runs: list[dict]) -> list[dict]:
|
|
71
|
+
"""Give every run its batch id in "batch". Runs must be in rowid order and unfiltered.
|
|
72
|
+
|
|
73
|
+
A run with a batch_id uses it. Old runs (NULL batch_id, or a file without the column) that sit
|
|
74
|
+
next to each other with the same experiment + label + harness form one batch, with the id
|
|
75
|
+
"legacy-<run_id of its first run>". Anything else in between ends that batch.
|
|
76
|
+
"""
|
|
77
|
+
previous: dict | None = None
|
|
78
|
+
for run in runs:
|
|
79
|
+
run.setdefault("batch_id", None)
|
|
80
|
+
same = ("experiment", "label", "harness")
|
|
81
|
+
if run["batch_id"] is not None:
|
|
82
|
+
run["batch"] = run["batch_id"]
|
|
83
|
+
elif (previous is not None and previous["batch_id"] is None
|
|
84
|
+
and all(previous[k] == run[k] for k in same)):
|
|
85
|
+
run["batch"] = previous["batch"]
|
|
86
|
+
else:
|
|
87
|
+
run["batch"] = f"legacy-{run['run_id']}"
|
|
88
|
+
previous = run
|
|
89
|
+
return runs
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _parse_stamp(text: str) -> datetime:
|
|
93
|
+
"""A time saved by the recorder ("2026-12-02T17:12:30Z"), as an aware UTC datetime."""
|
|
94
|
+
return datetime.strptime(text, STAMP).replace(tzinfo=UTC)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def when_text(created_at: str) -> str:
|
|
98
|
+
"""The batch time in the local time of this computer, for example "Dec 2, 17:12"."""
|
|
99
|
+
local = _parse_stamp(created_at).astimezone()
|
|
100
|
+
return f"{local:%b} {local.day}, {local:%H:%M}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def ago_text(saved: datetime, now: datetime) -> str:
|
|
104
|
+
"""For example "last case saved 4 min ago". Whole numbers, rounded down."""
|
|
105
|
+
seconds = max(0, int((now - saved).total_seconds()))
|
|
106
|
+
if seconds < 60:
|
|
107
|
+
amount = f"{seconds} s"
|
|
108
|
+
elif seconds < 3600:
|
|
109
|
+
amount = f"{seconds // 60} min"
|
|
110
|
+
elif seconds < 86400:
|
|
111
|
+
amount = f"{seconds // 3600} h"
|
|
112
|
+
else:
|
|
113
|
+
amount = f"{seconds // 86400} d"
|
|
114
|
+
return f"last case saved {amount} ago"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def build_page(runs: list[dict], title: str, now: datetime) -> dict:
|
|
118
|
+
"""The page data: one build_report() per batch, newest batch first.
|
|
119
|
+
|
|
120
|
+
runs come from load_runs (each run has its batch id in "batch"). now is an aware datetime,
|
|
121
|
+
used for the "last case saved ... ago" text.
|
|
122
|
+
"""
|
|
123
|
+
groups: dict[str, list[dict]] = {}
|
|
124
|
+
for run in runs: # rowid order, so a batch's place is the rowid of its first run
|
|
125
|
+
groups.setdefault(run["batch"], []).append(run)
|
|
126
|
+
batches = [_batch(batch_id, batch_runs, title, now) for batch_id, batch_runs in groups.items()]
|
|
127
|
+
batches.reverse() # newest first
|
|
128
|
+
return {"title": title, "show_experiment": len({run["experiment"] for run in runs}) > 1,
|
|
129
|
+
"batches": batches}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _batch(batch_id: str, runs: list[dict], title: str, now: datetime) -> dict:
|
|
133
|
+
"""One entry in the run list, with the dashboard data of its own runs only."""
|
|
134
|
+
report = build_report(runs, title=title)
|
|
135
|
+
labels = list(dict.fromkeys(run["label"] for run in runs))
|
|
136
|
+
experiments = list(dict.fromkeys(run["experiment"] for run in runs))
|
|
137
|
+
# In the list a setup is named by its model, unless the batch mixes labels or experiments.
|
|
138
|
+
short = len(labels) == 1 and len(experiments) == 1
|
|
139
|
+
saved = [_parse_stamp(c["saved_at"] or run["created_at"]) for run in runs for c in run["cases"]]
|
|
140
|
+
newest = max(saved) if saved else max(_parse_stamp(run["created_at"]) for run in runs)
|
|
141
|
+
return {
|
|
142
|
+
"id": batch_id,
|
|
143
|
+
"experiment": " / ".join(experiments),
|
|
144
|
+
"when": when_text(runs[0]["created_at"]),
|
|
145
|
+
"label": " / ".join(labels),
|
|
146
|
+
"models": [{"name": s["model"] if short else s["name"], "passed": s["passed"], "judged": s["judged"]}
|
|
147
|
+
for s in report["setups"]],
|
|
148
|
+
"repeats": max(s["runs"] for s in report["setups"]),
|
|
149
|
+
"cases": len({c["case_id"] for run in runs for c in run["cases"]}),
|
|
150
|
+
"last_saved": ago_text(newest, now),
|
|
151
|
+
"report": report,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def cell_word(verdicts: list[str]) -> str:
|
|
156
|
+
"""The word in one grid cell. ERROR runs are not counted as runs."""
|
|
157
|
+
judged = [v for v in verdicts if v != "ERROR"]
|
|
158
|
+
if not verdicts:
|
|
159
|
+
return ""
|
|
160
|
+
if not judged:
|
|
161
|
+
return "ERROR"
|
|
162
|
+
if len(judged) == 1:
|
|
163
|
+
return judged[0]
|
|
164
|
+
passes = judged.count("PASS")
|
|
165
|
+
if passes == len(judged):
|
|
166
|
+
return "STABLE"
|
|
167
|
+
if passes == 0:
|
|
168
|
+
return "ALWAYS FAILS"
|
|
169
|
+
return "FLAKY"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _average(rows: list[dict], key: str) -> float | None:
|
|
173
|
+
"""The average of one value over the rows that recorded it, or None."""
|
|
174
|
+
values = [r[key] for r in rows if r[key] is not None]
|
|
175
|
+
return sum(values) / len(values) if values else None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cell_stats(judged: list[dict]) -> str:
|
|
179
|
+
"""The averages line under a cell word, for example "2.0k tok · 1.5 turns · 3.5 s".
|
|
180
|
+
|
|
181
|
+
Only the parts that were recorded show. ERROR rows must already be left out.
|
|
182
|
+
"""
|
|
183
|
+
parts = []
|
|
184
|
+
tokens = _average(judged, "tokens")
|
|
185
|
+
if tokens is not None:
|
|
186
|
+
n = round(tokens)
|
|
187
|
+
parts.append(f"{n} tok" if n < 1000 else f"{n / 1000:.1f}k tok")
|
|
188
|
+
turns = _average(judged, "turns")
|
|
189
|
+
if turns is not None:
|
|
190
|
+
parts.append(f"{turns:.1f} turns")
|
|
191
|
+
seconds = _average(judged, "seconds")
|
|
192
|
+
if seconds is not None:
|
|
193
|
+
parts.append(f"{seconds:.1f} s")
|
|
194
|
+
return " · ".join(parts)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def build_report(runs: list[dict], title: str) -> dict:
|
|
198
|
+
"""Group runs by setup (experiment + model + label) and work out everything the page shows.
|
|
199
|
+
|
|
200
|
+
A row is experiment + case id, so 2 experiments that both have "c01" never mix.
|
|
201
|
+
"""
|
|
202
|
+
groups: dict[tuple[str, str, str], list[dict]] = {}
|
|
203
|
+
for run in runs:
|
|
204
|
+
groups.setdefault((run["experiment"], run["model"], run["label"]), []).append(run)
|
|
205
|
+
|
|
206
|
+
show_experiment = len({run["experiment"] for run in runs}) > 1
|
|
207
|
+
setups = [_setup(experiment, model, label, setup_runs, show_experiment)
|
|
208
|
+
for (experiment, model, label), setup_runs in groups.items()]
|
|
209
|
+
|
|
210
|
+
# Every (experiment, case id), in first-seen order, with every input it was given.
|
|
211
|
+
seen: dict[tuple[str, str], dict] = {}
|
|
212
|
+
for run in runs:
|
|
213
|
+
for c in run["cases"]:
|
|
214
|
+
entry = seen.setdefault((run["experiment"], c["case_id"]), {"inputs": set()})
|
|
215
|
+
entry["inputs"].add(c["input"])
|
|
216
|
+
entry["latest"] = c
|
|
217
|
+
|
|
218
|
+
cases = []
|
|
219
|
+
for (experiment, case_id), entry in seen.items():
|
|
220
|
+
cells = []
|
|
221
|
+
for (setup_experiment, _, _), setup_runs in groups.items():
|
|
222
|
+
results = [
|
|
223
|
+
{"run_no": n, "verdict": c["verdict"], "reason": c["reason"], "called": c["called"],
|
|
224
|
+
"answer": c["answer"], "cost_usd": c["cost_usd"],
|
|
225
|
+
"tokens": c["tokens"], "turns": c["turns"], "seconds": c["seconds"]}
|
|
226
|
+
for n, run in enumerate(setup_runs, start=1)
|
|
227
|
+
for c in run["cases"] if c["case_id"] == case_id
|
|
228
|
+
] if setup_experiment == experiment else []
|
|
229
|
+
verdicts = [r["verdict"] for r in results]
|
|
230
|
+
cells.append({"word": cell_word(verdicts), "passed": verdicts.count("PASS"),
|
|
231
|
+
"judged": len([v for v in verdicts if v != "ERROR"]),
|
|
232
|
+
"errors": verdicts.count("ERROR"), "results": results,
|
|
233
|
+
"stats": cell_stats([r for r in results if r["verdict"] != "ERROR"])})
|
|
234
|
+
cases.append({"experiment": experiment, "case_id": case_id, "input": entry["latest"]["input"],
|
|
235
|
+
"expected_tools": entry["latest"]["expected_tools"],
|
|
236
|
+
"input_changed": len(entry["inputs"]) > 1, "cells": cells})
|
|
237
|
+
|
|
238
|
+
first = setups[0]
|
|
239
|
+
same = all((s["tools"], s["system_prompt"]) == (first["tools"], first["system_prompt"]) for s in setups)
|
|
240
|
+
return {"title": title, "same_inputs": same, "setups": setups, "cases": cases}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _setup(experiment: str, model: str, label: str, setup_runs: list[dict], show_experiment: bool) -> dict:
|
|
244
|
+
"""One column: its name, pass rate, cost, tokens and time.
|
|
245
|
+
|
|
246
|
+
Cost per run = the sum of recorded costs / the number of runs that recorded a cost.
|
|
247
|
+
Tokens per run works the same way. Both tokens and time leave out ERROR rows.
|
|
248
|
+
"""
|
|
249
|
+
all_cases = [c for run in setup_runs for c in run["cases"]]
|
|
250
|
+
judged = [c for c in all_cases if c["verdict"] != "ERROR"]
|
|
251
|
+
costs = [c["cost_usd"] for c in all_cases if c["cost_usd"] is not None]
|
|
252
|
+
total = sum(costs) if costs else None
|
|
253
|
+
costed_runs = sum(any(c["cost_usd"] is not None for c in run["cases"]) for run in setup_runs)
|
|
254
|
+
tokens = [c["tokens"] for c in judged if c["tokens"] is not None]
|
|
255
|
+
token_runs = sum(any(c["tokens"] is not None and c["verdict"] != "ERROR" for c in run["cases"])
|
|
256
|
+
for run in setup_runs)
|
|
257
|
+
latest = setup_runs[-1]
|
|
258
|
+
name = f"{model} · {label}"
|
|
259
|
+
return {
|
|
260
|
+
"name": f"{experiment} · {name}" if show_experiment else name,
|
|
261
|
+
"experiment": experiment, "model": model, "label": label,
|
|
262
|
+
"harness": " / ".join(sorted({run["harness"] for run in setup_runs})),
|
|
263
|
+
"runs": len(setup_runs),
|
|
264
|
+
"passed": sum(c["verdict"] == "PASS" for c in judged), "judged": len(judged),
|
|
265
|
+
"cost_total": total, "cost_per_run": None if total is None else total / costed_runs,
|
|
266
|
+
"tokens_per_run": sum(tokens) / token_runs if tokens else None,
|
|
267
|
+
"avg_seconds": _average(judged, "seconds"),
|
|
268
|
+
"system_prompt": latest["system_prompt"], "tools": latest["tools"],
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
PLACEHOLDER = "/*__REPORT_DATA__*/null"
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def render_html(report: dict) -> str:
|
|
276
|
+
"""Put the report data inside the page template. The result is one self-contained file."""
|
|
277
|
+
template = resources.files("agent_eval_dashboard").joinpath("template.html").read_text(encoding="utf-8")
|
|
278
|
+
if PLACEHOLDER not in template:
|
|
279
|
+
raise RuntimeError("template.html has no data placeholder")
|
|
280
|
+
# Escape every "<" so no user text can end or confuse the <script> block
|
|
281
|
+
# (for example "</script>" or "<!--<script>"). The data stays valid JSON and JS.
|
|
282
|
+
data = json.dumps(report, ensure_ascii=False).replace("<", "\\u003c")
|
|
283
|
+
return template.replace(PLACEHOLDER, data)
|