diffscore 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.
- diffscore/__init__.py +3 -0
- diffscore/api.py +729 -0
- diffscore/calibration.py +374 -0
- diffscore/cli.py +867 -0
- diffscore/config.py +88 -0
- diffscore/db/__init__.py +27 -0
- diffscore/db/base.py +25 -0
- diffscore/db/migrate.py +61 -0
- diffscore/db/models.py +257 -0
- diffscore/db/session.py +37 -0
- diffscore/diffing.py +292 -0
- diffscore/graders.py +281 -0
- diffscore/jobs.py +161 -0
- diffscore/judge.py +355 -0
- diffscore/labeling.py +167 -0
- diffscore/llm.py +120 -0
- diffscore/migrations/README +1 -0
- diffscore/migrations/env.py +84 -0
- diffscore/migrations/script.py.mako +28 -0
- diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
- diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
- diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
- diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
- diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
- diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
- diffscore/queries.py +165 -0
- diffscore/runner.py +393 -0
- diffscore/secrets.py +130 -0
- diffscore/stats.py +83 -0
- diffscore/suite.py +329 -0
- diffscore/templates/env.example +14 -0
- diffscore/templates/example-prompt.md +14 -0
- diffscore/templates/example.yaml +75 -0
- diffscore-0.1.0.dist-info/METADATA +351 -0
- diffscore-0.1.0.dist-info/RECORD +38 -0
- diffscore-0.1.0.dist-info/WHEEL +4 -0
- diffscore-0.1.0.dist-info/entry_points.txt +2 -0
- diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
diffscore/diffing.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Compare two runs of the same suite and decide whether anything really changed.
|
|
2
|
+
|
|
3
|
+
Runs are immutable snapshots, so a diff is a join on the case key, not a
|
|
4
|
+
recomputation. The verdict comes from McNemar's test on the pass/fail flips;
|
|
5
|
+
raw counts are the detail, never the headline.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections import Counter
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Literal
|
|
13
|
+
|
|
14
|
+
from sqlalchemy import select
|
|
15
|
+
from sqlalchemy.orm import Session
|
|
16
|
+
|
|
17
|
+
from diffscore.db import Result, Run, Suite
|
|
18
|
+
from diffscore.queries import failures_of, with_results
|
|
19
|
+
from diffscore.runner import Outcome, outcome_of
|
|
20
|
+
from diffscore.stats import Interval, bootstrap_mean_ci, format_p, mcnemar_test
|
|
21
|
+
|
|
22
|
+
Change = Literal["regressed", "improved", "unchanged", "new", "removed", "excluded"]
|
|
23
|
+
Verdict = Literal["regression", "improvement", "no_change", "nothing_to_compare"]
|
|
24
|
+
|
|
25
|
+
DEFAULT_ALPHA = 0.05
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DiffError(ValueError):
|
|
29
|
+
"""Two runs that cannot be compared, or a baseline that cannot be found."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class RunInfo:
|
|
34
|
+
id: int
|
|
35
|
+
suite_id: int
|
|
36
|
+
suite: str
|
|
37
|
+
model: str
|
|
38
|
+
prompt_version_id: int
|
|
39
|
+
status: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class CaseDiff:
|
|
44
|
+
key: str
|
|
45
|
+
change: Change
|
|
46
|
+
before: Outcome | None
|
|
47
|
+
after: Outcome | None
|
|
48
|
+
score_before: float | None
|
|
49
|
+
score_after: float | None
|
|
50
|
+
why: list[str] = field(default_factory=list)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class Diff:
|
|
55
|
+
a: RunInfo
|
|
56
|
+
b: RunInfo
|
|
57
|
+
cases: list[CaseDiff]
|
|
58
|
+
alpha: float
|
|
59
|
+
p_value: float
|
|
60
|
+
method: str
|
|
61
|
+
interval: Interval | None
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def counts(self) -> Counter[Change]:
|
|
65
|
+
return Counter(c.change for c in self.cases)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def regressed(self) -> int:
|
|
69
|
+
return self.counts["regressed"]
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def improved(self) -> int:
|
|
73
|
+
return self.counts["improved"]
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def paired(self) -> int:
|
|
77
|
+
c = self.counts
|
|
78
|
+
return c["regressed"] + c["improved"] + c["unchanged"]
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def verdict(self) -> Verdict:
|
|
82
|
+
if self.paired == 0:
|
|
83
|
+
return "nothing_to_compare"
|
|
84
|
+
if self.p_value >= self.alpha:
|
|
85
|
+
return "no_change"
|
|
86
|
+
return "regression" if self.regressed > self.improved else "improvement"
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def headline(self) -> str:
|
|
90
|
+
p = format_p(self.p_value)
|
|
91
|
+
match self.verdict:
|
|
92
|
+
case "regression":
|
|
93
|
+
return f"regression on {_cases(self.regressed)} ({p})"
|
|
94
|
+
case "improvement":
|
|
95
|
+
return f"improvement on {_cases(self.improved)} ({p})"
|
|
96
|
+
case "no_change":
|
|
97
|
+
return f"no significant change ({p})"
|
|
98
|
+
case "nothing_to_compare":
|
|
99
|
+
return "nothing to compare: the runs share no graded cases"
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def exit_code(self) -> int:
|
|
103
|
+
"""1 only for a significant regression, so CI fails on real breakage alone."""
|
|
104
|
+
return 1 if self.verdict == "regression" else 0
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def too_small_note(self) -> str | None:
|
|
108
|
+
"""Why a lopsided result still isn't significant, when the suite is the reason.
|
|
109
|
+
|
|
110
|
+
The most lopsided outcome possible is every comparable case flipping the
|
|
111
|
+
same way. If even that can't get under alpha, no prompt change on this
|
|
112
|
+
suite ever could, and the user should hear that rather than "no change".
|
|
113
|
+
"""
|
|
114
|
+
if self.verdict != "no_change" or self.regressed + self.improved == 0:
|
|
115
|
+
return None
|
|
116
|
+
needed = min_flips_for_significance(self.alpha)
|
|
117
|
+
if self.paired >= needed:
|
|
118
|
+
return None
|
|
119
|
+
return (
|
|
120
|
+
f"only {self.paired} comparable cases: at least {needed} must flip the same way "
|
|
121
|
+
f"before any change can be significant at alpha {self.alpha:g}. Add more cases."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def what_changed(self) -> str:
|
|
126
|
+
parts = []
|
|
127
|
+
if self.a.prompt_version_id != self.b.prompt_version_id:
|
|
128
|
+
parts.append("prompt changed")
|
|
129
|
+
if self.a.model != self.b.model:
|
|
130
|
+
parts.append(f"model {self.a.model} -> {self.b.model}")
|
|
131
|
+
return ", ".join(parts) or "same prompt and model"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _cases(n: int) -> str:
|
|
135
|
+
return f"{n} case" if n == 1 else f"{n} cases"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def min_flips_for_significance(alpha: float) -> int:
|
|
139
|
+
"""Smallest n where n flips in one direction and none in the other give p < alpha."""
|
|
140
|
+
n = 1
|
|
141
|
+
while mcnemar_test(n, 0).p_value >= alpha:
|
|
142
|
+
n += 1
|
|
143
|
+
return n
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ------------------------------------------------------------------ loading
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _load(session: Session, run_id: int) -> Run:
|
|
150
|
+
run = session.scalars(select(Run).options(*with_results()).where(Run.id == run_id)).first()
|
|
151
|
+
if run is None:
|
|
152
|
+
raise DiffError(f"no run with id {run_id}")
|
|
153
|
+
return run
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _info(run: Run) -> RunInfo:
|
|
157
|
+
return RunInfo(
|
|
158
|
+
run.id, run.suite_id, run.suite.name, run.model, run.prompt_version_id, run.status
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _score(result: Result) -> float | None:
|
|
163
|
+
if result.error is not None or not result.grades:
|
|
164
|
+
return None
|
|
165
|
+
return sum(g.score for g in result.grades) / len(result.grades)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _failures(result: Result) -> list[str]:
|
|
169
|
+
return failures_of(result)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ------------------------------------------------------------------ diff
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def diff_runs(
|
|
176
|
+
session: Session,
|
|
177
|
+
a_id: int,
|
|
178
|
+
b_id: int,
|
|
179
|
+
*,
|
|
180
|
+
alpha: float = DEFAULT_ALPHA,
|
|
181
|
+
seed: int = 0,
|
|
182
|
+
) -> Diff:
|
|
183
|
+
"""Compare run `a_id` (the baseline) with run `b_id` (the candidate)."""
|
|
184
|
+
if a_id == b_id:
|
|
185
|
+
raise DiffError("cannot diff a run against itself")
|
|
186
|
+
if not 0 < alpha < 1:
|
|
187
|
+
raise DiffError("alpha must be between 0 and 1")
|
|
188
|
+
run_a, run_b = _load(session, a_id), _load(session, b_id)
|
|
189
|
+
if run_a.suite_id != run_b.suite_id:
|
|
190
|
+
raise DiffError(
|
|
191
|
+
f"run #{a_id} is suite {run_a.suite.name!r} but run #{b_id} is "
|
|
192
|
+
f"{run_b.suite.name!r}; only runs of the same suite can be compared"
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
before = {r.case.key: r for r in run_a.results}
|
|
196
|
+
after = {r.case.key: r for r in run_b.results}
|
|
197
|
+
order = [r.case.key for r in sorted(run_b.results, key=lambda r: r.id)]
|
|
198
|
+
order += [k for k in sorted(before) if k not in after]
|
|
199
|
+
|
|
200
|
+
cases: list[CaseDiff] = []
|
|
201
|
+
deltas: list[float] = []
|
|
202
|
+
for key in order:
|
|
203
|
+
ra, rb = before.get(key), after.get(key)
|
|
204
|
+
oa = outcome_of(ra) if ra else None
|
|
205
|
+
ob = outcome_of(rb) if rb else None
|
|
206
|
+
sa = _score(ra) if ra else None
|
|
207
|
+
sb = _score(rb) if rb else None
|
|
208
|
+
|
|
209
|
+
change: Change
|
|
210
|
+
why: list[str] = []
|
|
211
|
+
if ra is None:
|
|
212
|
+
change = "new"
|
|
213
|
+
elif rb is None:
|
|
214
|
+
change = "removed"
|
|
215
|
+
elif oa in {"error", "ungraded"} or ob in {"error", "ungraded"}:
|
|
216
|
+
change = "excluded"
|
|
217
|
+
why = [f"{side} run: {o}" for side, o in (("baseline", oa), ("new", ob))
|
|
218
|
+
if o in {"error", "ungraded"}] # fmt: skip
|
|
219
|
+
elif oa == "pass" and ob == "fail":
|
|
220
|
+
change, why = "regressed", _failures(rb)
|
|
221
|
+
elif oa == "fail" and ob == "pass":
|
|
222
|
+
change, why = "improved", [f"was: {w}" for w in _failures(ra)]
|
|
223
|
+
else:
|
|
224
|
+
change = "unchanged"
|
|
225
|
+
if ob == "fail":
|
|
226
|
+
why = _failures(rb)
|
|
227
|
+
|
|
228
|
+
if change in {"regressed", "improved", "unchanged"} and sa is not None and sb is not None:
|
|
229
|
+
deltas.append(sb - sa)
|
|
230
|
+
cases.append(CaseDiff(key, change, oa, ob, sa, sb, why))
|
|
231
|
+
|
|
232
|
+
counts = Counter(c.change for c in cases)
|
|
233
|
+
test = mcnemar_test(counts["regressed"], counts["improved"])
|
|
234
|
+
return Diff(
|
|
235
|
+
a=_info(run_a),
|
|
236
|
+
b=_info(run_b),
|
|
237
|
+
cases=cases,
|
|
238
|
+
alpha=alpha,
|
|
239
|
+
p_value=test.p_value,
|
|
240
|
+
method=test.method,
|
|
241
|
+
interval=bootstrap_mean_ci(deltas, seed=seed),
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ------------------------------------------------------------------ baselines
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def suite_baseline(session: Session, run_id: int) -> int | None:
|
|
249
|
+
"""The baseline of `run_id`'s suite, unless that baseline is the run itself."""
|
|
250
|
+
run = session.get(Run, run_id)
|
|
251
|
+
if run is None:
|
|
252
|
+
raise DiffError(f"no run with id {run_id}")
|
|
253
|
+
base = run.suite.baseline_run_id
|
|
254
|
+
return base if base != run_id else None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def previous_run(session: Session, run_id: int) -> int | None:
|
|
258
|
+
"""The most recent completed run of the same suite before `run_id`."""
|
|
259
|
+
run = session.get(Run, run_id)
|
|
260
|
+
if run is None:
|
|
261
|
+
raise DiffError(f"no run with id {run_id}")
|
|
262
|
+
return session.scalar(
|
|
263
|
+
select(Run.id)
|
|
264
|
+
.where(Run.suite_id == run.suite_id, Run.id < run_id, Run.status == "completed")
|
|
265
|
+
.order_by(Run.id.desc())
|
|
266
|
+
.limit(1)
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def set_baseline(session: Session, run_id: int) -> str:
|
|
271
|
+
"""Make `run_id` its suite's baseline. Returns the suite name."""
|
|
272
|
+
run = session.get(Run, run_id)
|
|
273
|
+
if run is None:
|
|
274
|
+
raise DiffError(f"no run with id {run_id}")
|
|
275
|
+
if run.status != "completed":
|
|
276
|
+
raise DiffError(f"run #{run_id} is {run.status}; only a completed run can be a baseline")
|
|
277
|
+
run.suite.baseline_run_id = run_id
|
|
278
|
+
session.commit()
|
|
279
|
+
return run.suite.name
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def adopt_if_no_baseline(session: Session, run_id: int) -> bool:
|
|
283
|
+
"""The first completed run of a suite becomes its baseline. True if it did."""
|
|
284
|
+
run = session.get(Run, run_id)
|
|
285
|
+
if run is None or run.status != "completed" or run.suite.baseline_run_id is not None:
|
|
286
|
+
return False
|
|
287
|
+
set_baseline(session, run_id)
|
|
288
|
+
return True
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def baseline_ids(session: Session) -> set[int]:
|
|
292
|
+
return {b for b in session.scalars(select(Suite.baseline_run_id)).all() if b is not None}
|
diffscore/graders.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Graders and the registry they live in.
|
|
2
|
+
|
|
3
|
+
A grader is built once from its config (`factory(arg)`), which is where bad
|
|
4
|
+
config is rejected — so a typo in a regex fails when the suite loads, not 40
|
|
5
|
+
cases into a run. The built grader is a plain function `Output -> Grade`.
|
|
6
|
+
|
|
7
|
+
Adding a grader is one decorated function. The deterministic ones live here;
|
|
8
|
+
the LLM judge (`diffscore.judge`) registers itself the same way, with
|
|
9
|
+
`uses_model=True` so it is handed a way to call a model.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Any, Literal
|
|
19
|
+
|
|
20
|
+
from jsonschema import Draft202012Validator
|
|
21
|
+
from jsonschema.exceptions import SchemaError
|
|
22
|
+
|
|
23
|
+
from diffscore.llm import CompleteFn
|
|
24
|
+
|
|
25
|
+
Verdict = Literal["pass", "fail"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Grade:
|
|
30
|
+
score: float # 0..1
|
|
31
|
+
verdict: Verdict
|
|
32
|
+
reason: str
|
|
33
|
+
details: dict[str, Any] = field(default_factory=dict) # e.g. the judge's evidence
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def of(cls, ok: bool, reason: str, score: float | None = None) -> Grade:
|
|
37
|
+
if score is None:
|
|
38
|
+
score = 1.0 if ok else 0.0
|
|
39
|
+
return cls(score=score, verdict="pass" if ok else "fail", reason=reason)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Output:
|
|
44
|
+
"""Everything a grader may look at. Deliberately excludes the prompt and model."""
|
|
45
|
+
|
|
46
|
+
text: str
|
|
47
|
+
expect: str | None = None
|
|
48
|
+
latency_ms: int | None = None
|
|
49
|
+
cost_usd: float | None = None
|
|
50
|
+
input: str = "" # the case's user message, for graders that judge relevance
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
Grader = Callable[[Output], Grade]
|
|
54
|
+
Factory = Callable[..., Grader] # (arg) or, with uses_model, (arg, deps)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class GraderConfigError(ValueError):
|
|
58
|
+
"""Raised by a factory when its config is unusable."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class GraderRuntimeError(RuntimeError):
|
|
62
|
+
"""A grader could not produce a verdict (e.g. the judge model failed).
|
|
63
|
+
|
|
64
|
+
Distinct from a failing grade: the output under test is not at fault, so
|
|
65
|
+
the case is reported as an error and kept out of the significance test.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class GraderDeps:
|
|
71
|
+
"""What a model-using grader needs at run time."""
|
|
72
|
+
|
|
73
|
+
ask: CompleteFn | None = None # cached, budgeted model access
|
|
74
|
+
candidate_model: str | None = None # the model whose outputs are being graded
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class GraderDef:
|
|
79
|
+
name: str
|
|
80
|
+
version: str
|
|
81
|
+
factory: Factory
|
|
82
|
+
summary: str
|
|
83
|
+
uses_model: bool = False
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
REGISTRY: dict[str, GraderDef] = {}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def register(
|
|
90
|
+
name: str, version: str = "1", *, uses_model: bool = False
|
|
91
|
+
) -> Callable[[Factory], Factory]:
|
|
92
|
+
def deco(factory: Factory) -> Factory:
|
|
93
|
+
doc = (factory.__doc__ or "").strip()
|
|
94
|
+
REGISTRY[name] = GraderDef(name, version, factory, doc, uses_model)
|
|
95
|
+
return factory
|
|
96
|
+
|
|
97
|
+
return deco
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def build(name: str, arg: Any, deps: GraderDeps | None = None) -> Grader:
|
|
101
|
+
"""Build a grader. Without `deps`, a model-using grader only validates its config."""
|
|
102
|
+
if name not in REGISTRY:
|
|
103
|
+
raise GraderConfigError(f"unknown grader {name!r}")
|
|
104
|
+
definition = REGISTRY[name]
|
|
105
|
+
if definition.uses_model:
|
|
106
|
+
return definition.factory(arg, deps or GraderDeps())
|
|
107
|
+
return definition.factory(arg)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------------ helpers
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _texts(arg: Any, what: str) -> tuple[list[str], bool]:
|
|
114
|
+
"""Accept `"x"`, `["x", "y"]` or `{values: [...], ignore_case: true}`."""
|
|
115
|
+
ignore_case = False
|
|
116
|
+
if isinstance(arg, dict):
|
|
117
|
+
extra = set(arg) - {"value", "values", "ignore_case"}
|
|
118
|
+
if extra:
|
|
119
|
+
raise GraderConfigError(f"unknown option(s) {sorted(extra)} for {what}")
|
|
120
|
+
ignore_case = bool(arg.get("ignore_case", False))
|
|
121
|
+
arg = arg.get("values", arg.get("value"))
|
|
122
|
+
if isinstance(arg, str):
|
|
123
|
+
arg = [arg]
|
|
124
|
+
if (
|
|
125
|
+
not isinstance(arg, list)
|
|
126
|
+
or not arg
|
|
127
|
+
or not all(isinstance(v, str | int | float) for v in arg)
|
|
128
|
+
):
|
|
129
|
+
raise GraderConfigError(f"{what} needs a string or a non-empty list of strings")
|
|
130
|
+
return [str(v) for v in arg], ignore_case
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _fold(s: str, ignore_case: bool) -> str:
|
|
134
|
+
return s.casefold() if ignore_case else s
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _positive_number(arg: Any, what: str) -> float:
|
|
138
|
+
if isinstance(arg, bool) or not isinstance(arg, int | float) or arg <= 0:
|
|
139
|
+
raise GraderConfigError(f"{what} needs a positive number, got {arg!r}")
|
|
140
|
+
return float(arg)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
_FENCE = re.compile(r"^\s*```[\w-]*\s*\n(.*?)\n\s*```\s*$", re.DOTALL)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _strip_fence(text: str) -> str:
|
|
147
|
+
"""Models love wrapping JSON in ```json fences; graders shouldn't care."""
|
|
148
|
+
found = _FENCE.match(text)
|
|
149
|
+
return found.group(1) if found else text
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ------------------------------------------------------------------ graders
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@register("equals")
|
|
156
|
+
def equals(arg: Any) -> Grader:
|
|
157
|
+
"""Output equals a string (default: the case's `expect`), ignoring outer whitespace."""
|
|
158
|
+
ignore_case = False
|
|
159
|
+
if isinstance(arg, dict):
|
|
160
|
+
ignore_case = bool(arg.get("ignore_case", False))
|
|
161
|
+
arg = arg.get("value")
|
|
162
|
+
if arg is not None and not isinstance(arg, str | int | float):
|
|
163
|
+
raise GraderConfigError("equals needs a string, or nothing to compare against `expect`")
|
|
164
|
+
fixed = None if arg is None else str(arg)
|
|
165
|
+
|
|
166
|
+
def grade(out: Output) -> Grade:
|
|
167
|
+
want = fixed if fixed is not None else out.expect
|
|
168
|
+
if want is None:
|
|
169
|
+
return Grade.of(False, "no expected value to compare against")
|
|
170
|
+
ok = _fold(out.text.strip(), ignore_case) == _fold(want.strip(), ignore_case)
|
|
171
|
+
return Grade.of(ok, "matches" if ok else f"expected {want.strip()!r}")
|
|
172
|
+
|
|
173
|
+
return grade
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@register("contains")
|
|
177
|
+
def contains(arg: Any) -> Grader:
|
|
178
|
+
"""Output contains every listed string. Score is the fraction found."""
|
|
179
|
+
needles, ignore_case = _texts(arg, "contains")
|
|
180
|
+
|
|
181
|
+
def grade(out: Output) -> Grade:
|
|
182
|
+
hay = _fold(out.text, ignore_case)
|
|
183
|
+
missing = [n for n in needles if _fold(n, ignore_case) not in hay]
|
|
184
|
+
score = 1 - len(missing) / len(needles)
|
|
185
|
+
if not missing:
|
|
186
|
+
return Grade.of(True, "all present", score)
|
|
187
|
+
return Grade.of(False, f"missing {', '.join(map(repr, missing))}", score)
|
|
188
|
+
|
|
189
|
+
return grade
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@register("not_contains")
|
|
193
|
+
def not_contains(arg: Any) -> Grader:
|
|
194
|
+
"""Output contains none of the listed strings. Score is the fraction absent."""
|
|
195
|
+
needles, ignore_case = _texts(arg, "not_contains")
|
|
196
|
+
|
|
197
|
+
def grade(out: Output) -> Grade:
|
|
198
|
+
hay = _fold(out.text, ignore_case)
|
|
199
|
+
found = [n for n in needles if _fold(n, ignore_case) in hay]
|
|
200
|
+
score = 1 - len(found) / len(needles)
|
|
201
|
+
if not found:
|
|
202
|
+
return Grade.of(True, "none present", score)
|
|
203
|
+
return Grade.of(False, f"found forbidden {', '.join(map(repr, found))}", score)
|
|
204
|
+
|
|
205
|
+
return grade
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@register("regex")
|
|
209
|
+
def regex(arg: Any) -> Grader:
|
|
210
|
+
"""Output matches a regular expression anywhere (re.search). Use (?i) for case-insensitive."""
|
|
211
|
+
if not isinstance(arg, str) or not arg:
|
|
212
|
+
raise GraderConfigError("regex needs a pattern string")
|
|
213
|
+
try:
|
|
214
|
+
pattern = re.compile(arg)
|
|
215
|
+
except re.error as exc:
|
|
216
|
+
raise GraderConfigError(f"invalid regex {arg!r}: {exc}") from exc
|
|
217
|
+
|
|
218
|
+
def grade(out: Output) -> Grade:
|
|
219
|
+
found = pattern.search(out.text)
|
|
220
|
+
if found:
|
|
221
|
+
return Grade.of(True, f"matched {found.group(0)!r}")
|
|
222
|
+
return Grade.of(False, f"no match for /{arg}/")
|
|
223
|
+
|
|
224
|
+
return grade
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@register("json_schema")
|
|
228
|
+
def json_schema(arg: Any) -> Grader:
|
|
229
|
+
"""Output parses as JSON (code fences allowed) and validates against a JSON Schema."""
|
|
230
|
+
if arg is None:
|
|
231
|
+
arg = {}
|
|
232
|
+
if not isinstance(arg, dict):
|
|
233
|
+
raise GraderConfigError("json_schema needs a JSON Schema object ({} accepts any JSON)")
|
|
234
|
+
try:
|
|
235
|
+
Draft202012Validator.check_schema(arg)
|
|
236
|
+
except SchemaError as exc:
|
|
237
|
+
raise GraderConfigError(f"invalid JSON Schema: {exc.message}") from exc
|
|
238
|
+
validator = Draft202012Validator(arg)
|
|
239
|
+
|
|
240
|
+
def grade(out: Output) -> Grade:
|
|
241
|
+
try:
|
|
242
|
+
data = json.loads(_strip_fence(out.text))
|
|
243
|
+
except json.JSONDecodeError as exc:
|
|
244
|
+
return Grade.of(False, f"not valid JSON: {exc.msg} at line {exc.lineno}")
|
|
245
|
+
errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
|
|
246
|
+
if not errors:
|
|
247
|
+
return Grade.of(True, "valid")
|
|
248
|
+
first = errors[0]
|
|
249
|
+
where = "/".join(map(str, first.path)) or "(root)"
|
|
250
|
+
more = f" (+{len(errors) - 1} more)" if len(errors) > 1 else ""
|
|
251
|
+
return Grade.of(False, f"{where}: {first.message}{more}")
|
|
252
|
+
|
|
253
|
+
return grade
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@register("max_latency_ms")
|
|
257
|
+
def max_latency_ms(arg: Any) -> Grader:
|
|
258
|
+
"""Model call took at most this many milliseconds."""
|
|
259
|
+
limit = _positive_number(arg, "max_latency_ms")
|
|
260
|
+
|
|
261
|
+
def grade(out: Output) -> Grade:
|
|
262
|
+
if out.latency_ms is None:
|
|
263
|
+
return Grade.of(False, "latency unknown")
|
|
264
|
+
ok = out.latency_ms <= limit
|
|
265
|
+
return Grade.of(ok, f"{out.latency_ms} ms (limit {limit:g})")
|
|
266
|
+
|
|
267
|
+
return grade
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@register("max_cost")
|
|
271
|
+
def max_cost(arg: Any) -> Grader:
|
|
272
|
+
"""Model call cost at most this many US dollars. Fails if the cost is unknown."""
|
|
273
|
+
limit = _positive_number(arg, "max_cost")
|
|
274
|
+
|
|
275
|
+
def grade(out: Output) -> Grade:
|
|
276
|
+
if out.cost_usd is None:
|
|
277
|
+
return Grade.of(False, "cost unknown for this model; cannot check")
|
|
278
|
+
ok = out.cost_usd <= limit
|
|
279
|
+
return Grade.of(ok, f"${out.cost_usd:.6f} (limit ${limit:g})")
|
|
280
|
+
|
|
281
|
+
return grade
|