10A.3 Deterministic Metrics and Code-Based Graders
An eval is only as good as its graders, and the cheapest, fastest, most trustworthy grader is almost always code. This lesson is the complete engineering reference for deterministic evaluation: every way to score an LLM output without asking another model — exact and fuzzy matching, classification metrics, text-overlap metrics, structural checks, operational metrics, property-based and metamorphic tests — plus how to combine them into gates and reports. By the end you will have evalkit/scorers.py, a stdlib-only library of graders you can run on any dataset with zero API keys, and a decision table for choosing the right grader for every task type.
What you'll learn
- Why deterministic graders beat model-graded ones wherever they apply — and the rule "always try code first"
- Exact and fuzzy matching: normalisation, contains/regex, numeric tolerance, unit and date normalisation, set matching, JSON field-level comparison, schema validity, tool-call argument matching, SQL equivalence by execution, and code correctness by running tests
- Classification metrics from scratch: accuracy, precision, recall, F1 (micro/macro/weighted), confusion matrices, class imbalance, ROC/AUC, calibration (reliability bins, Brier score, ECE), threshold selection and cost-sensitive metrics — cross-checked against scikit-learn
- Text-overlap and embedding metrics: BLEU, ROUGE, METEOR, chrF, BERTScore, embedding cosine, edit distance/WER/CER — what each measures, where they correlate with human judgement and where they fail
- Structural and format checks: length, language, forbidden and required patterns, citations, link validity, well-formedness, readability, PII scanning, toxicity classifiers — as hard gates vs soft scores
- Operational metrics as first-class citizens: latency percentiles, TTFT, tokens, cost per example, retries, error and refusal rates
- Property-based and metamorphic testing for LLM features: invariance, directional and consistency checks
- How to combine graders into per-example verdicts, gates and aggregate reports — and the full
evalkit/scorers.pylibrary
What you don't need
- API keys. Every scorer in this lesson is pure Python (standard library only) and every output shown is real output from running it. The only optional dependencies are called out per section (
jsonschema,scikit-learn,sacrebleu,rouge-score,bert-score,jiwer,hypothesis,langdetect); each has a stdlib fallback or is marked optional. - LLM-as-judge methodology. That is 10A.4; this lesson deliberately covers only graders that need no model.
- Statistics (confidence intervals, bootstrap, kappa). 10A.2 and 10A.5 own those; this lesson links where they matter.
Setup
The core library is standard library only — Python 3.11+, nothing to install:
uv init evalkit --bare --python 3.13 && cd evalkit
mkdir -p evalkit testsOptional packages (named without versions, so you get the newest release of each):
uv add jsonschema scikit-learn sacrebleu \
rouge-score bert-score jiwer \
hypothesis langdetect nltk pytest
# or: pip install <same names>The samples were written and checked against jsonschema 4.26.0, scikit-learn 1.9.1, sacrebleu 2.6.0, rouge-score 0.1.2, bert-score 0.3.13, jiwer 4.0.0, hypothesis 6.170.14, langdetect 1.0.9, nltk 3.10.4 and pytest 9.2.0 as of November 2026. Metric libraries can change tokenisation, defaults or normalisation between releases, so a score from a newer release may differ slightly from the printed numbers; record the library versions next to any score you report.
Each optional dependency is used in exactly one place and the code degrades gracefully or says what to install. The .env file is not needed for this lesson — no sample calls a provider.
What you must be able to do after this lesson#
- Choose a deterministic grader before reaching for an LLM judge
- Write exact, fuzzy, regex and field-level matchers with normalisation
- Compute accuracy, precision, recall and F1 and read a confusion matrix
- Add structural, format and operational checks such as latency and cost
- Write a metamorphic or property-based test for an LLM feature
- Combine several graders into one per-example verdict and report
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Just use an LLM judge for everything." | Part 1: why code first |
| "The answer says 'Paris' but the expected is 'paris'." | 2.1 Normalisation |
| "The invoice total is €1,299.50, expected 1299.5." | 2.3 Numeric, quantity and date matching |
| "Two different SQL queries, same result." | 2.5 SQL equivalence by execution |
| "Accuracy is 95% but the rare class is broken." | 3.3 Class imbalance |
| "The model is 90% confident and wrong half the time." | 3.4 ROC/AUC and calibration |
| "BLEU says the summary is terrible but a human loves it." | 4.3 Where they correlate and where they fail |
| "The output must never contain a phone number." | 5.2 The checks, and their limits |
| "p95 latency doubled after the prompt change." | Part 6: operational metrics |
| "Same question, different answer each run." | 7.2 Self-consistency and agreement |
| "Which grader do I use for ticket triage?" | 8.4 The decision table |
Part 1: Why deterministic graders come first#
1.1 The grader ladder#
Every eval scorer sits on a ladder of trustworthiness. The lower rungs are cheaper, faster, deterministic and debuggable; climb only when the lower rungs genuinely can't express the criterion.
| Rung | Grader | Cost per example | Deterministic? | Debuggable? | Use when |
|---|---|---|---|---|---|
| 1 | Code (this lesson) | ~µs, free | Yes | Yes — you can print why | The criterion is checkable mechanically: format, schema, exact value, classification label, test passage, citation presence, length, banned content |
| 2 | Small classifier / rules + embeddings | ~ms, near-free | Yes | Mostly | Semantic similarity at scale (embedding cosine), toxicity/Pii classifiers, language ID |
| 3 | LLM-as-judge (10A.4) | cents, seconds | No (unless seeded/cached) | Partially | Open-ended quality: helpfulness, tone, faithfulness nuance — and only after code graders have had their chance |
| 4 | Human review (10A.2, 10A.5) | dollars, days | N/A | Gold standard | Calibration of judges, high-stakes sign-off, ambiguous cases |
The working rule, borrowed from Hamel Husain's evals writing and echoed across Modules 03–09: if a code check can express the criterion, write the code check. A regex that verifies "the answer cites at least one source" costs nothing and never drifts; a judge asked the same question costs money, adds variance, and needs its own validation (10A.5 is entirely about that). Code graders also produce explainable failures — detail tells you exactly which field mismatched — which is what makes error analysis (10A.1) tractable.
1.2 What "deterministic" buys you#
- Speed and cost. A scorer over 10,000 examples runs in milliseconds on a laptop; a judge run costs real money and rate limits (03.8, 03.9).
- Repeatability. The same input gives the same score forever, so diffs between runs are real signal, not judge noise (02.5, Part 7 explains why even temperature-0 model calls aren't deterministic).
- Debuggability. Every
Scorecarries adetaildict — which n-gram missed, which field differed, which pattern matched. You can sort failures by cause instead of reading 500 outputs. - CI fitness. Deterministic graders belong in the smoke suite on every commit (10A.8); judges belong in the nightly suite.
1.3 The score contract#
Everything in evalkit/scorers.py returns one of two shapes:
@dataclass(frozen=True)
class Score:
name: str # which grader produced this
value: float # 0.0–1.0: graded metrics give fractions, checks give 0/1
passed: bool | None # True/False = hard verdict; None = measurement only
detail: dict # why — the explainability payloadpassed=False is a hard failure: the example fails no matter what the other graders say. passed=None is a measurement: it feeds averages and reports but can't fail an example on its own. value is always in [0,1] so weighted aggregation is meaningful. This contract is what lets you mix "must parse as JSON" (hard) with "token-F1 vs reference" (soft) in one suite — Part 8 formalises the combination.
The whole pipeline, end to end:
flowchart LR
A[Model output + case] --> B[Grader suite<br/>run_graders]
B --> C{Any hard<br/>passed=False?}
C -- yes --> D[Verdict: failed]
C -- no --> E[Verdict: passed<br/>value = mean of scores]
D --> F[aggregate:<br/>mean · pass_rate · worst_slice]
E --> F
F --> G[Run report +<br/>regression gate 10A.8]1.4 Graders vs metrics vs judges — the vocabulary#
- A metric is a number computed over outputs (accuracy, BLEU, p95 latency).
- A grader (or scorer) is the function that produces a
Scorefor one example — this lesson's unit of work. - A judge is a grader that calls a model (10A.4).
- A gate is a threshold applied to aggregated scores that blocks a merge or deploy (10A.8).
Confusing "the metric" with "the grader" leads to the classic bug: computing accuracy per-example (meaningless — it's 0 or 1) instead of per-dataset. Classification metrics in Part 3 are dataset-level by nature; the lesson shows how the harness aggregates them.
Part 2: Exact and fuzzy matching#
2.1 Normalisation before any comparison#
The single most common cause of "the eval says wrong but the answer is right" is comparing raw strings. "Paris" vs "paris." vs "The capital is Paris." are the same answer to a human and different strings to ==. The fix is a normalisation step — the same discipline 05.5 applies to ingestion: Unicode normalise first (NFKC folds full-width letters and ligatures), then casefold, then strip punctuation, then collapse whitespace. normalize_text in evalkit/scorers.py does exactly this, and every text scorer below uses it.
The first section of evalkit/scorers.py — the Score/Verdict contract and the normalisation helpers:
# ===========================================================================
# evalkit/scorers.py — deterministic graders (stdlib only).
# Copy each numbered section below, in order, into evalkit/scorers.py.
# ===========================================================================
# evalkit/scorers.py — section 1 of 11: core types + normalisation
from __future__ import annotations
import json
import math
import re
import sqlite3
import statistics
import subprocess
import sys
import tempfile
import unicodedata
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Iterable, Mapping, Sequence
@dataclass(frozen=True)
class Score:
"""One grader's verdict on one example.
`value` is always in [0.0, 1.0]. `passed` is the verdict: True/False for
hard checks (the example fails if any hard check fails), None for pure
measurements that only feed aggregation.
"""
name: str
value: float
passed: bool | None = None
detail: Mapping[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"name": self.name,
"value": round(self.value, 6),
"passed": self.passed,
"detail": dict(self.detail),
}
@dataclass(frozen=True)
class Verdict:
"""The combined result of running a suite of graders on one example."""
passed: bool
value: float
scores: tuple[Score, ...] = ()
def to_dict(self) -> dict[str, Any]:
return {
"passed": self.passed,
"value": round(self.value, 6),
"scores": [s.to_dict() for s in self.scores],
}
def _score(name: str, ok: bool, **detail: Any) -> Score:
return Score(name=name, value=1.0 if ok else 0.0, passed=ok, detail=detail)
def _frac(name: str, numer: float, denom: float, **detail: Any) -> Score:
value = numer / denom if denom else 0.0
return Score(name=name, value=value, detail={"numerator": numer, "denominator": denom, **detail})
# ---------------------------------------------------------------------------
# Normalisation helpers (lesson 05.5 owns the full cleaning pipeline)
# ---------------------------------------------------------------------------
_PUNCT_RE = re.compile(r"[^\w\s]", re.UNICODE)
def normalize_text(
text: str,
*,
casefold: bool = True,
strip_punct: bool = True,
collapse_ws: bool = True,
unicode_form: str = "NFKC",
) -> str:
"""Canonicalise text before comparing it.
NFKC folds compatibility characters (full-width letters, ligatures) and
composed/decomposed accents into one form — the same first step 05.5's
cleaning pipeline applies. Order matters: normalise Unicode first, then
case, then punctuation, then whitespace.
"""
s = unicodedata.normalize(unicode_form, text)
if casefold:
s = s.casefold()
if strip_punct:
s = _PUNCT_RE.sub(" ", s)
if collapse_ws:
s = " ".join(s.split())
return s
def word_tokens(text: str) -> list[str]:
"""Lowercased alphanumeric tokens — the unit for token-level metrics."""
return re.findall(r"[\w]+", normalize_text(text, strip_punct=False), flags=re.UNICODE)
def char_ngrams(text: str, n: int = 6) -> Counter[str]:
"""Character n-gram multiset over the normalised, space-padded string."""
s = f" {normalize_text(text)} "
return Counter(s[i : i + n] for i in range(len(s) - n + 1))2.2 The matching family#
Section 2 of evalkit/scorers.py — string matching: exact, normalised, contains, regex, and numeric extraction:
# evalkit/scorers.py — section 2 of 11: exact and fuzzy string matching
def exact_match(output: str, expected: str) -> Score:
"""1.0 iff the raw strings are identical. For canonical answers only —
dates, codes, yes/no. Harmless variation ('Paris' vs 'paris') fails."""
return _score("exact_match", output == expected)
def normalized_match(output: str, expected: str, **norm: Any) -> Score:
"""1.0 iff the strings match after `normalize_text`. The workhorse for
short answers: absorbs case, punctuation, whitespace and Unicode form."""
ok = normalize_text(output, **norm) == normalize_text(expected, **norm)
return _score("normalized_match", ok)
def contains_any(output: str, needles: Sequence[str], *, ignore_case: bool = True) -> Score:
"""1.0 iff the output contains at least one needle. For 'must mention X'
checks — but see the failure gallery: a negated mention still matches."""
hay = output.casefold() if ignore_case else output
hits = [n for n in needles if (n.casefold() if ignore_case else n) in hay]
return _score("contains_any", bool(hits), matched=hits, needles=list(needles))
def regex_match(output: str, pattern: str, *, flags: int = re.IGNORECASE) -> Score:
"""1.0 iff `pattern` matches anywhere in the output. Escape user data;
a pattern built from model output is a regex-injection risk."""
m = re.search(pattern, output, flags)
return _score("regex_match", m is not None, pattern=pattern,
match=m.group(0) if m else None)
_NUMBER_RE = re.compile(r"[-+]?\d[\d,]*(?:\.\d+)?")
def extract_numbers(text: str) -> list[float]:
"""All numbers in a string, commas stripped. '€1,299.50' -> [1299.5]."""
return [float(m.group(0).replace(",", "")) for m in _NUMBER_RE.finditer(text)]
def numeric_match(
output: str,
expected: str,
*,
rel_tol: float = 0.0,
abs_tol: float = 0.0,
which: str = "first",
) -> Score:
"""Compare one number from each string within a tolerance.
`which` picks the candidate: 'first' or 'last' number in each string —
answers like 'The total is €1,299.50 (incl. VAT)' put the figure
mid-text, and 'first' is the better default because LLM answers
usually lead with the figure. Neither choice survives trailing
numerals — 'The answer is 42 (see §3.2)' extracts [42, 3, 2]; for
those, extract the field (json_field_match) and numeric_match it
directly. rel_tol is relative to |expected|; abs_tol is absolute.
"""
if which not in ("first", "last"):
raise ValueError(f"which must be 'first' or 'last', got {which!r}")
out_nums, exp_nums = extract_numbers(output), extract_numbers(expected)
if not out_nums or not exp_nums:
return _score("numeric_match", False, reason="missing_number",
output_numbers=out_nums, expected_numbers=exp_nums)
idx = -1 if which == "last" else 0
got, want = out_nums[idx], exp_nums[idx]
ok = abs(got - want) <= max(abs_tol, rel_tol * abs(want))
return _score("numeric_match", ok, got=got, want=want,
rel_tol=rel_tol, abs_tol=abs_tol)Every Real output: block in this lesson is a slice of what one script prints, demo_scorers.py, listed in full in 8.6 (its -- banners match the lesson's sections). The inputs behind each line are in that script, so you can change them and re-run.
Real output:
exact_match('Paris','Paris') value=1.000 passed=True
exact_match('Paris','paris') value=0.000 passed=False
normalized_match case+punct value=1.000 passed=True
contains_any refund value=1.000 passed=True {"matched": ["refund"]}
regex_match ISO date value=1.000 passed=True {"match": "2026-03-04"}
numeric_match '1,299.50' value=1.000 passed=True {"got": 1299.5, "want": 1299.5}
numeric_match rel_tol 1% value=1.000 passed=True {"got": 1299.5, "want": 1310.0}2.3 Numeric, quantity and date matching#
Section 3 — numbers with units and dates with formats. 5 km and 5000 m are the same quantity; March 5, 2026 and 2026-03-05 are the same date. Code normalises to canonical units (metres, grams, Celsius) and ISO dates before comparing:
# evalkit/scorers.py — section 3 of 11: unit, quantity and date matching
# Canonical units: distance -> metres, mass -> grams, temperature -> Celsius.
_DIST = {"mm": 0.001, "cm": 0.01, "m": 1.0, "km": 1000.0,
"in": 0.0254, "ft": 0.3048, "mi": 1609.344, "yd": 0.9144}
_MASS = {"mg": 0.001, "g": 1.0, "kg": 1000.0, "oz": 28.3495, "lb": 453.5924, "lbs": 453.5924}
# Units are matched longest-first AND with a trailing letter boundary:
# without `(?![A-Za-z])`, the bare 'm' alternative wins over 'mi'/'mg'
# and '5 mi'/'500 mg'/'30 min' all silently parse as metres.
_QUANTITY_RE = re.compile(
r"([-+]?\d[\d,]*(?:\.\d+)?)\s*"
r"(km|cm|mm|mi|mg|m|ft|in|yd|kg|g|oz|lbs?|"
r"fahrenheit|celsius|kelvin|°?[cfk]|%)"
r"(?![A-Za-z])",
re.IGNORECASE,
)
def _find_quantity(text: str) -> tuple[float, str] | None:
"""First '<number> <unit>' pair anywhere in the text -> (canonical
value, canonical unit). Returns None when no unit-bearing quantity
appears. A bare number ('42') has no unit and is not a quantity — use
numeric_match for that. Time units (min, hr, s) are deliberately not
quantities here: 'the meeting is 30 min' finds nothing, so
quantity_match reports no_unit_found rather than a wrong verdict.
Single-letter units are genuinely ambiguous with English ('5 in stock'
reads as inches) — for those, compare the extracted field instead."""
m = _QUANTITY_RE.search(text)
if not m:
return None
value = float(m.group(1).replace(",", ""))
unit = m.group(2).lower().lstrip("°")
if unit in ("km", "m", "cm", "mm", "mi", "ft", "in", "yd"):
return value * _DIST[unit], "m"
if unit in ("kg", "g", "mg", "oz", "lb", "lbs"):
return value * _MASS[unit], "g"
if unit in ("c", "celsius"):
return value, "°c"
if unit in ("f", "fahrenheit"):
return (value - 32.0) * 5.0 / 9.0, "°c"
if unit in ("k", "kelvin"):
return value - 273.15, "°c"
return value, unit
def quantity_match(output: str, expected: str) -> Score:
"""1.0 iff both texts contain the same quantity in different units —
'5 km' vs '5000 m', '68°F' vs '20°C'. Compares the FIRST unit-bearing
quantity found in each text."""
a, b = _find_quantity(output), _find_quantity(expected)
if a is None or b is None:
return _score("quantity_match", False, reason="no_unit_found",
output=output, expected=expected)
ok = a[1] == b[1] and math.isclose(a[0], b[0], rel_tol=1e-9)
return _score("quantity_match", ok, output=(a[0], a[1]), expected=(b[0], b[1]))
_DATE_FORMATS = (
"%Y-%m-%d", "%Y/%m/%d", "%d %B %Y", "%B %d, %Y", "%B %d %Y",
"%d %b %Y", "%b %d, %Y", "%b %d %Y",
"%d-%m-%Y", "%m/%d/%Y", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S",
)
def parse_flexible_date(text: str):
"""Best-effort date parse across common formats -> datetime.date | None.
ISO dates win first; then a list of strptime formats. The conventions
are deliberately mixed to cover real outputs, which makes ambiguous
dates genuinely ambiguous: slash dates are read month-first (US) but
dash dates day-first — '03/04/2026' is 4 March while '03-04-2026' is
3 April. When the distinction matters, compare ISO strings or pin a
convention; don't assume one global order."""
from datetime import datetime
s = text.strip()
for fmt in _DATE_FORMATS:
try:
return datetime.strptime(s, fmt).date()
except ValueError:
continue
# trailing time on ISO dates, e.g. '2026-03-04 14:22'
try:
return datetime.fromisoformat(s).date()
except ValueError:
return None
_ISO_DATE_RE = re.compile(r"\b\d{4}-\d{2}-\d{2}\b")
_LONG_DATE_RE = re.compile(
r"\b(?:\d{1,2}\s+[A-Za-z]+\s+\d{4}|[A-Za-z]+\s+\d{1,2},?\s+\d{4}|"
r"\d{1,2}/\d{1,2}/\d{4}|\d{1,2}-\d{1,2}-\d{4})\b")
def _find_date(text: str):
"""Locate a date inside free text: ISO first, then the long-form
candidates, each tried against the strptime table."""
from datetime import datetime
m = _ISO_DATE_RE.search(text)
if m:
try:
return datetime.strptime(m.group(0), "%Y-%m-%d").date()
except ValueError:
pass
for m in _LONG_DATE_RE.finditer(text):
for fmt in _DATE_FORMATS:
try:
return datetime.strptime(m.group(0), fmt).date()
except ValueError:
continue
return parse_flexible_date(text.strip())
def date_match(output: str, expected: str) -> Score:
"""1.0 iff both texts contain the same calendar date, whatever the
surface format ('Due March 5, 2026' vs '2026-03-05'). When a text
holds several dates the FIRST parseable one wins — 'from 2026-01-01
to 2026-03-05' grades the start date, not the deadline."""
a, b = _find_date(output), _find_date(expected)
if a is None or b is None:
return _score("date_match", False, reason="no_date_found",
output=output, expected=expected)
return _score("date_match", a == b, output=str(a), expected=str(b))Real output:
quantity_match 5km vs 5000m value=1.000 passed=True {"output": [5000.0, "m"]}
quantity_match 5mi vs 8046.72m value=1.000 passed=True {"output": [8046.72, "m"]}
quantity_match 500mg vs 0.5g value=1.000 passed=True {"output": [0.5, "g"]}
quantity_match 30min (no unit) value=0.000 passed=False {"reason": "no_unit_found"}
quantity_match 68F vs 20C value=1.000 passed=True {"output": [20.0, "°c"]}
date_match 'March 5, 2026' value=1.000 passed=True {"output": "2026-03-05"}
date_match 'March 5 2026' value=1.000 passed=True {"output": "2026-03-05"}
date_match unparseable value=0.000 passed=False {"reason": "no_date_found"}2.4 Set matching and structured comparison#
Section 4 — sets, canonical JSON, per-field object comparison, schema validation and tool-call matching:
# evalkit/scorers.py — section 4 of 11: sets, JSON, schema, tool calls
def _canon(obj: Any) -> str:
"""Canonical JSON for structural comparison: sorted keys, tight
separators, and integral floats folded to ints — JSON treats 5 and
5.0 as the same number, so {"total": 5} must equal {"total": 5.0}.
Non-integral floats (5.5) and strings ("5") stay distinct."""
def _norm(o: Any) -> Any:
if isinstance(o, bool) or o is None or isinstance(o, str):
return o
if isinstance(o, float) and o.is_integer():
return int(o)
if isinstance(o, dict):
return {k: _norm(v) for k, v in o.items()}
if isinstance(o, (list, tuple)):
return [_norm(v) for v in o]
return o
return json.dumps(_norm(obj), sort_keys=True, separators=(",", ":"),
ensure_ascii=False)
def set_match(output: Iterable[Any], expected: Iterable[Any], *, exact: bool = True) -> Score:
"""Set equality over items (order ignored). Items are compared by
canonical JSON, so unhashable items — dicts, lists — work, and 5
equals 5.0. Items must be JSON-serialisable. exact=False returns the
Jaccard overlap |A∩B|/|A∪B| as a graded score instead of a verdict."""
a, b = {_canon(x) for x in output}, {_canon(x) for x in expected}
if exact:
return _score("set_match", a == b, output_size=len(a), expected_size=len(b))
union = a | b
value = len(a & b) / len(union) if union else 1.0
return Score("jaccard", value,
detail={"intersection": len(a & b), "union": len(union)})
def json_equal(output: Any, expected: Any) -> Score:
"""1.0 iff two parsed JSON values are structurally equal (key order and
whitespace don't matter; list order does)."""
return _score("json_equal", _canon(output) == _canon(expected))
def json_field_match(output: Mapping[str, Any], expected: Mapping[str, Any],
*, ignore: Iterable[str] = ()) -> Score:
"""Per-field accuracy over two objects. Every expected key must match
(via `json_equal`); extra output keys are reported but don't fail.
`ignore` skips volatile fields like 'generated_at'. Returns the fraction
of expected fields that matched, with per-field detail. Comparison is
structural via `_canon`: 5 equals 5.0 (same JSON number) but "5" does
not equal 5 — for numeric tolerance grade the field with numeric_match."""
skip = set(ignore)
per_field: dict[str, bool] = {}
for key, want in expected.items():
if key in skip:
continue
per_field[key] = _canon(output.get(key)) == _canon(want)
matched = sum(per_field.values())
total = len(per_field)
return _frac("json_field_match", matched, total, fields=per_field,
extra_keys=sorted(set(output) - set(expected) - skip))
_JSON_TYPES = {
"object": dict, "array": list, "string": str,
"number": (int, float), "integer": int,
"boolean": bool, "null": type(None),
}
def _minischema_errors(instance: Any, schema: Mapping[str, Any],
path: str = "$") -> list[str]:
"""Stdlib validator for the JSON Schema subset evalkit needs:
type, required, properties, additionalProperties, items, enum.
Deliberately NOT a full JSON Schema implementation — install
`jsonschema` for the complete spec (draft 2020-12). The one
spec-alignment it does keep: 'integer' accepts integral floats
(5.0 is an integer per JSON Schema, matching jsonschema's behaviour)."""
errors: list[str] = []
if "enum" in schema and instance not in schema["enum"]:
errors.append(f"{path}: {instance!r} not in enum {schema['enum']}")
t = schema.get("type")
if t is not None:
types = t if isinstance(t, list) else [t]
def _type_ok(tt: str) -> bool:
if tt == "integer":
return (isinstance(instance, int)
and not isinstance(instance, bool)) or \
(isinstance(instance, float) and instance.is_integer())
if tt == "number":
return isinstance(instance, (int, float)) \
and not isinstance(instance, bool)
cls = _JSON_TYPES.get(tt)
return cls is not None and isinstance(instance, cls)
ok = any(_type_ok(tt) for tt in types if tt in _JSON_TYPES)
if not ok:
errors.append(f"{path}: expected type {t}, got {type(instance).__name__}")
return errors
if isinstance(instance, dict):
for key in schema.get("required", ()):
if key not in instance:
errors.append(f"{path}: missing required property {key!r}")
props = schema.get("properties", {})
addl = schema.get("additionalProperties", True)
for key, val in instance.items():
if key in props:
errors += _minischema_errors(val, props[key], f"{path}.{key}")
elif addl is False:
errors.append(f"{path}: unexpected property {key!r}")
elif isinstance(addl, dict):
errors += _minischema_errors(val, addl, f"{path}.{key}")
if isinstance(instance, list) and "items" in schema:
for i, item in enumerate(instance):
errors += _minischema_errors(item, schema["items"], f"{path}[{i}]")
return errors
def schema_valid(instance: Any, schema: Mapping[str, Any]) -> Score:
"""Validate a parsed value against a JSON Schema (03.4 owns schema
design). Uses `jsonschema` (uv add jsonschema) for the full
spec when installed; otherwise falls back to `_minischema_errors`,
which covers the common subset — `detail["validator"]` says which ran."""
try:
import jsonschema
validator = jsonschema.Draft202012Validator(schema)
errors = sorted(validator.iter_errors(instance), key=lambda e: list(e.path))
first = errors[0] if errors else None
return _score(
"schema_valid", not errors,
error=f"{first.json_path}: {first.message}" if first else None,
error_count=len(errors), validator="jsonschema")
except ImportError:
errors = _minischema_errors(instance, schema)
return _score("schema_valid", not errors,
error=errors[0] if errors else None,
error_count=len(errors), validator="minischema")
def _call_args(c: Mapping[str, Any]) -> Any:
"""Extract a tool call's arguments across provider shapes:
OpenAI `arguments` (JSON string), Anthropic `input` (dict),
generic `args`, or Chat-Completions `function.arguments`."""
args = c.get("arguments", c.get("args",
c.get("input", c.get("function", {}).get("arguments", {}))))
if isinstance(args, str):
try:
args = json.loads(args)
except json.JSONDecodeError:
pass
return args
def _call_name(c: Mapping[str, Any]) -> Any:
return c.get("name") or c.get("function", {}).get("name")
def _call_key(c: Mapping[str, Any]) -> str:
return _canon({"name": _call_name(c), "arguments": _call_args(c)})
def tool_calls_match(output_calls: Sequence[Mapping[str, Any]],
expected_calls: Sequence[Mapping[str, Any]]) -> Score:
"""1.0 iff the model made exactly the expected tool calls: same names in
the same order, with canonically-equal arguments. Strict on purpose —
for 'right tool, approximately right args' use tool_call_prf."""
got = [_call_key(c) for c in output_calls]
want = [_call_key(c) for c in expected_calls]
return _score("tool_calls_match", got == want, output=got, expected=want)
def tool_call_prf(output_calls: Sequence[Mapping[str, Any]],
expected_calls: Sequence[Mapping[str, Any]]) -> Score:
"""Precision/recall/F1 over tool calls treated as a multiset of
(name, canonical-args) pairs — order-free. Use for trajectories where
the right calls in a different order still count (10A.7 goes deeper)."""
pred, gold = Counter(_call_key(c) for c in output_calls), \
Counter(_call_key(c) for c in expected_calls)
tp = sum((pred & gold).values())
p = tp / sum(pred.values()) if pred else 0.0
r = tp / sum(gold.values()) if gold else 0.0
f1 = 2 * p * r / (p + r) if p + r else 0.0
return Score("tool_call_prf", f1, detail={"precision": p, "recall": r,
"tp": tp, "pred": sum(pred.values()),
"gold": sum(gold.values())})Key points:
json_field_matchis per-field accuracy — the workhorse for extraction tasks (invoices, forms). It tells you which field broke, not just that the object differed.ignoreskips volatile fields like timestamps.schema_validchecks a parsed value against a JSON Schema — the "does the shape match" gate from 03.4. Schema validity is necessary but never sufficient: a schema-valid invoice can still have the wrong total. Pair it withjson_field_matchornumeric_match.tool_calls_matchvstool_call_prf: exact ordered sequence match vs order-free multiset F1. For agent trajectories, order-free is usually right — the model may legitimately call tools in a different order; 10A.7 owns trajectory grading in depth.- Set matching covers "list the three ingredients", "which tags apply", "which files were modified" — anywhere order shouldn't matter but membership should.
Real output:
set_match tags value=1.000 passed=True
jaccard near-miss value=0.500 passed=None {"intersection": 2, "union": 4}
json_field_match value=0.750 passed=None {"fields": {"total": true, "currency": true, "lines": true, "note": false}}
schema_valid good value=1.000 passed=True {"validator": "minischema"}
tool_calls_match (key order) value=1.000 passed=True
tool_call_prf openai-style value=1.000 passed=None {"precision": 1.0}2.5 SQL equivalence by execution#
Two SQL queries can be textually different and semantically identical — SELECT dept, COUNT(*) AS n ... GROUP BY dept ORDER BY dept vs the same without aliases. Comparing strings fails; comparing results works. sql_equivalent builds an in-memory SQLite database, runs both queries and compares result sets:
# evalkit/scorers.py — section 5 of 11: executable graders (SQL + code)
def sql_equivalent(sql_a: str, sql_b: str, *,
schema_sql: str, rows_sql: Sequence[str]) -> Score:
"""1.0 iff two SQL statements return the same rows on the same data.
Equivalence-by-execution: create an in-memory SQLite database from
`schema_sql` + `rows_sql`, run both queries, compare result multisets.
This is how you grade 'SELECT dept, AVG(salary) ... GROUP BY dept' when
a thousand syntactically different queries are all correct. For real
workloads run this in a sandbox (08A.15's guarded execution; Module 12
owns the security treatment) — never against production data.
Results are compared as Counters, never sorted — sorting tuples with
NULLs or mixed types raises TypeError, and Counter equality is a
multiset match (duplicates count, order doesn't). Two caveats:
`LIMIT`/`TOP` without `ORDER BY` can make two 'equivalent' queries
return different rows run-to-run (a flaky grader — add ORDER BY to
the fixture queries), and column order matters: swapping two columns
changes the tuples and reports 'not equivalent'."""
con = sqlite3.connect(":memory:")
try:
con.executescript(schema_sql)
for stmt in rows_sql:
con.execute(stmt)
try:
a = Counter(tuple(r) for r in con.execute(sql_a).fetchall())
except sqlite3.Error as e:
return _score("sql_equivalent", False, reason=f"query_a_error: {e}")
try:
b = Counter(tuple(r) for r in con.execute(sql_b).fetchall())
except sqlite3.Error as e:
return _score("sql_equivalent", False, reason=f"query_b_error: {e}")
return _score("sql_equivalent", a == b,
rows_a=sum(a.values()), rows_b=sum(b.values()))
finally:
con.close()
def run_code_tests(code: str, test_code: str, *, timeout: float = 30.0) -> Score:
"""Grade a code answer by executing its unit tests.
Writes `code` and `test_code` into a fresh temp dir and runs
`python -m pytest` there. Returns 1.0 only if every test passes.
This is the 'code correctness by execution' grader: for HumanEval-style
tasks it's the gold standard because it checks behaviour, not text.
⚠️ This executes model-written code. In production this MUST run in a
sandbox (container, seccomp, no network, CPU/memory limits) — see
08A.15's guarded-shell discussion and Module 12. The demo and tests in
this lesson only run trusted fixture code.
"""
with tempfile.TemporaryDirectory(prefix="evalkit-code-") as d:
Path(d, "candidate.py").write_text(code)
Path(d, "test_candidate.py").write_text(test_code)
try:
proc = subprocess.run(
[sys.executable, "-m", "pytest", "-q", "test_candidate.py"],
cwd=d, capture_output=True, text=True, timeout=timeout,
)
except subprocess.TimeoutExpired:
return _score("run_code_tests", False, reason="timeout", timeout=timeout)
if proc.returncode != 0 and "No module named pytest" in proc.stderr:
# pytest isn't installed: run the test_* functions ourselves —
# works for plain assert-style tests with no fixtures.
runner = (
"import sys, traceback\n"
"import candidate, test_candidate\n"
"fns = [getattr(test_candidate, n) for n in dir(test_candidate)\n"
" if n.startswith('test_') and callable(getattr(test_candidate, n))]\n"
"fails = 0\n"
"for fn in fns:\n"
" try:\n"
" fn()\n"
" except Exception:\n"
" fails += 1\n"
" traceback.print_exc()\n"
"print(f'{len(fns) - fails}/{len(fns)} tests passed')\n"
"sys.exit(1 if fails or not fns else 0)\n"
)
proc = subprocess.run(
[sys.executable, "-c", runner],
cwd=d, capture_output=True, text=True, timeout=timeout,
)
tail = "\n".join((proc.stdout + proc.stderr).strip().splitlines()[-5:])
return _score("run_code_tests", proc.returncode == 0,
runner="assert-fallback", returncode=proc.returncode,
output_tail=tail)
passed = proc.returncode == 0
tail = "\n".join((proc.stdout + proc.stderr).strip().splitlines()[-5:])
return _score("run_code_tests", passed, returncode=proc.returncode,
output_tail=tail)run_code_tests is the strongest deterministic grader there is for code tasks — it checks behaviour. The pass@k/pass^k reliability math for repeated code attempts is owned by 08A.14, 4.4 and deepened in 10A.7; this lesson supplies the per-attempt grader they aggregate.
Real output:
sql_equivalent value=1.000 passed=True {"rows_a": 2, "rows_b": 2}
run_code_tests (pass) value=1.000 passed=True {"output_tail": "2/2 tests passed"}
run_code_tests (fail) value=0.000 passed=False {"output_tail": "AssertionError"}from evalkit import scorers as s
SCHEMA = "CREATE TABLE emp (name TEXT, dept TEXT);"
GOLD = "SELECT name FROM emp WHERE dept = 'eng'"
CAND = "SELECT name FROM emp WHERE name = 'a'" # wrong logic that happens to fit one fixture
fixtures = {
"fixture 1: only 'a' is in eng": ["INSERT INTO emp VALUES ('a','eng'),('b','ops')"],
"fixture 2: 'c' is also in eng": ["INSERT INTO emp VALUES ('a','eng'),('b','ops'),('c','eng')"],
"fixture 3: 'a' moved to ops": ["INSERT INTO emp VALUES ('a','ops'),('b','eng')"],
}
verdicts = {}
for label, rows in fixtures.items():
r = s.sql_equivalent(GOLD, CAND, schema_sql=SCHEMA, rows_sql=rows)
verdicts[label] = r.passed
print(f"{label:34s} equivalent={r.passed}")
print("equivalent on ALL fixtures:", all(verdicts.values()))fixture 1: only 'a' is in eng equivalent=True
fixture 2: 'c' is also in eng equivalent=False
fixture 3: 'a' moved to ops equivalent=False
equivalent on ALL fixtures: FalseThe same logic applies to every executable grader: a single test input is a sample, so a code answer needs tests that include edge cases (empty input, ties, negative numbers), not only the happy path.
Part 3: Classification metrics#
When the output is a label — ticket category, sentiment, intent, "is this answer correct?" — you need the classification toolkit. All of it is implemented from scratch below and cross-checked against scikit-learn; the maths is the same either way.
3.1 The confusion matrix first#
Before any aggregate number, look at the confusion matrix: rows are true labels, columns predicted, cell (i,j) counts examples truly-i predicted-j. Everything else derives from it. Section 6 of evalkit/scorers.py:
# evalkit/scorers.py — section 6 of 11: classification metrics
# (implemented from scratch; sklearn cross-check below)
def confusion_matrix(y_true: Sequence[str], y_pred: Sequence[str],
labels: Sequence[str] | None = None) -> dict[str, Any]:
"""Counts of (true, predicted) label pairs. `labels` fixes the class order;
default is sorted union of observed labels — pass it explicitly when a
class is absent from a slice, or it silently vanishes from the report."""
if labels is None:
labels = sorted(set(y_true) | set(y_pred))
idx = {lab: i for i, lab in enumerate(labels)}
n = len(labels)
mat = [[0] * n for _ in range(n)]
for t, p in zip(y_true, y_pred):
mat[idx[t]][idx[p]] += 1
return {"labels": list(labels), "matrix": mat}
def _prf_counts(tp: int, fp: int, fn: int) -> tuple[float, float, float]:
p = tp / (tp + fp) if tp + fp else 0.0
r = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * p * r / (p + r) if p + r else 0.0
return p, r, f1
def classification_prf(
y_true: Sequence[str],
y_pred: Sequence[str],
*,
labels: Sequence[str] | None = None,
average: str = "macro", # binary | micro | macro | weighted | None(per-class)
) -> Score:
"""Precision/recall/F1 for classification.
average:
'binary' — positive class is labels[1] (or the second sorted label)
'micro' — global TP/FP/FN; dominated by big classes
'macro' — mean of per-class scores; treats rare classes equally
'weighted' — per-class scores weighted by support
None — return per-class detail only, value = macro F1
This is the same computation sklearn's
`precision_recall_fscore_support` does — see `sklearn_prf` below.
"""
if labels is None:
labels = sorted(set(y_true) | set(y_pred))
if average == "binary" and len(labels) != 2:
raise ValueError("binary average needs exactly 2 labels")
cm = confusion_matrix(y_true, y_pred, labels)
lab, mat = cm["labels"], cm["matrix"]
per_class: dict[str, dict[str, float]] = {}
for i, name in enumerate(lab):
tp = mat[i][i]
fp = sum(row[i] for row in mat) - tp
fn = sum(mat[i]) - tp
p, r, f1 = _prf_counts(tp, fp, fn)
per_class[name] = {"precision": p, "recall": r, "f1": f1,
"support": sum(mat[i])}
if average is None:
macro = sum(c["f1"] for c in per_class.values()) / len(per_class)
return Score("classification_prf", macro,
detail={"per_class": per_class, "average": "per-class"})
if average == "binary":
pos = lab[1]
c = per_class[pos]
return _frac("classification_prf", c["f1"], 1.0,
average="binary", positive_class=pos, **c)
if average == "micro":
# Single-label multiclass: pooled TP = correct predictions, and every
# wrong prediction is one FP (for its predicted class) and one FN
# (for its true class), so micro P = R = F1 = accuracy.
tp = sum(mat[i][i] for i in range(len(lab)))
total = sum(sum(row) for row in mat)
p, r, f1 = _prf_counts(tp, total - tp, total - tp)
return _frac("classification_prf", f1, 1.0, average="micro",
precision=p, recall=r)
weights = [per_class[n]["support"] for n in lab]
total = sum(weights)
if average == "macro":
w = [1.0] * len(lab)
else: # weighted
w = weights
denom = sum(w)
agg = {k: sum(per_class[n][k] * wi for n, wi in zip(lab, w)) / denom
for k in ("precision", "recall", "f1")}
return _frac("classification_prf", agg["f1"], 1.0, average=average, **agg,
per_class=per_class)
def accuracy(y_true: Sequence[str], y_pred: Sequence[str]) -> Score:
"""Fraction of exact label matches. Misleading under class imbalance —
a model that always says 'billing' scores 90% on a 90%-billing set."""
if len(y_true) != len(y_pred):
raise ValueError("y_true and y_pred must be the same length")
n = len(y_true)
ok = sum(t == p for t, p in zip(y_true, y_pred))
return _frac("accuracy", ok, n)
def roc_auc(y_true: Sequence[int], scores: Sequence[float]) -> Score:
"""Area under the ROC curve via the Mann-Whitney U statistic — the
probability that a random positive outranks a random negative.
Pure stdlib, exact for small sets (average ranks for ties)."""
pairs = sorted(zip(scores, y_true), key=lambda t: t[0])
n_pos = sum(y_true)
n_neg = len(y_true) - n_pos
if n_pos == 0 or n_neg == 0:
raise ValueError("roc_auc needs both classes present")
# average ranks for ties, rank 1 = lowest score
ranks = [0.0] * len(pairs)
i = 0
while i < len(pairs):
j = i
while j + 1 < len(pairs) and pairs[j + 1][0] == pairs[i][0]:
j += 1
avg = (i + j) / 2 + 1
for k in range(i, j + 1):
ranks[k] = avg
i = j + 1
rank_pos = sum(r for r, (_, y) in zip(ranks, pairs) if y == 1)
u = rank_pos - n_pos * (n_pos + 1) / 2
auc = u / (n_pos * n_neg)
return Score("roc_auc", auc, detail={"n_pos": n_pos, "n_neg": n_neg})
def brier_score(y_true: Sequence[float], probs: Sequence[Sequence[float]]) -> Score:
"""Brier score: mean squared error between predicted probabilities and
0/1 outcomes. Multiclass form: sum over classes of (p - y)^2 per row,
averaged over rows (range 0..2 for multiclass, 0..1 binary)."""
if len(y_true) != len(probs):
raise ValueError("length mismatch")
total = 0.0
for y, row in zip(y_true, probs):
total += sum((p - (1.0 if c == y else 0.0)) ** 2 for c, p in enumerate(row))
return _frac("brier_score", total / len(y_true), 1.0, n=len(y_true))
def reliability_bins(y_true: Sequence[int], probs: Sequence[float],
n_bins: int = 10) -> tuple[list[dict[str, Any]], float]:
"""Calibration data for a reliability diagram + the Expected Calibration
Error (ECE): sum over bins of (bin_size/N) * |accuracy - confidence|.
Returns (bins, ece). Each bin dict has: lo, hi, count, mean_confidence,
accuracy — everything a plotting layer needs."""
bins = [{"lo": i / n_bins, "hi": (i + 1) / n_bins, "count": 0,
"conf_sum": 0.0, "correct": 0} for i in range(n_bins)]
for y, p in zip(y_true, probs):
b = min(int(p * n_bins), n_bins - 1)
bins[b]["count"] += 1
bins[b]["conf_sum"] += p
bins[b]["correct"] += int(y == 1)
n = len(y_true)
ece = 0.0
out = []
for b in bins:
if b["count"] == 0:
out.append({"lo": b["lo"], "hi": b["hi"], "count": 0})
continue
conf = b["conf_sum"] / b["count"]
acc = b["correct"] / b["count"]
ece += (b["count"] / n) * abs(acc - conf)
out.append({"lo": b["lo"], "hi": b["hi"], "count": b["count"],
"mean_confidence": conf, "accuracy": acc})
return out, ece
def best_f1_threshold(y_true: Sequence[int], scores: Sequence[float]) -> Score:
"""Sweep candidate thresholds and return the F1-best for the positive
class. Candidates are every unique score PLUS one above the maximum —
the predict-all-negative operating point, which is exactly the case
`expected_cost` exists for and is otherwise unreachable. In `detail`,
`threshold=None` means 'flag nothing'."""
if len(y_true) != len(scores):
raise ValueError("length mismatch")
if not scores:
return Score("best_f1_threshold", 0.0, detail={"note": "empty"})
candidates: list[float | None] = [None] + sorted(set(scores))
best_t: float | None = None
best_f1 = -1.0
for t in candidates:
preds = [1 if (t is not None and s >= t) else 0 for s in scores]
tp = sum(p == 1 and y == 1 for p, y in zip(preds, y_true))
fp = sum(p == 1 and y == 0 for p, y in zip(preds, y_true))
fn = sum(p == 0 and y == 1 for p, y in zip(preds, y_true))
_, _, f1 = _prf_counts(tp, fp, fn)
if f1 > best_f1:
best_t, best_f1 = t, f1
return Score("best_f1_threshold", best_f1,
detail={"threshold": best_t, "f1": best_f1})
def expected_cost(y_true: Sequence[int], preds: Sequence[int], *,
fp_cost: float = 1.0, fn_cost: float = 1.0) -> Score:
"""Cost-aware error metric for 'false positive is cheap, false negative
is expensive' (or vice versa). Accuracy treats both errors as equal;
this prices them.
`value` is the fraction of worst-case cost incurred —
total_cost / (n * max(fp_cost, fn_cost)) — bounded [0,1] so it can
feed aggregation like every other score. The raw cost figures (a
natural unit, not a score) stay in `detail`: `mean_cost` per example,
`total_cost`, and the fp/fn counts."""
if len(y_true) != len(preds):
raise ValueError("length mismatch")
n = len(y_true)
if n == 0:
return Score("expected_cost", 0.0, detail={"note": "empty"})
fp = sum(p == 1 and y == 0 for p, y in zip(preds, y_true))
fn = sum(p == 0 and y == 1 for p, y in zip(preds, y_true))
cost = fp * fp_cost + fn * fn_cost
worst = n * max(fp_cost, fn_cost)
return Score("expected_cost", cost / worst if worst else 0.0,
detail={"n": n, "fp": fp, "fn": fn, "fp_cost": fp_cost,
"fn_cost": fn_cost, "total_cost": cost,
"mean_cost": cost / n})
def multilabel_prf(y_true_rows: Sequence[Sequence[int]],
y_pred_rows: Sequence[Sequence[int]],
*, average: str = "macro") -> Score:
"""P/R/F1 for multi-label data (each example has several 0/1 labels).
'micro' pools all label decisions; 'macro' averages per-label binary
F1s. Same computation as sklearn's multilabel-indicator path."""
if len(y_true_rows) != len(y_pred_rows):
raise ValueError("y_true_rows and y_pred_rows must align")
if not y_true_rows:
return Score("multilabel_prf", 0.0, detail={"note": "empty input"})
n_labels = len(y_true_rows[0])
per_label = []
tp = fp = fn = 0
for c in range(n_labels):
yt = [row[c] for row in y_true_rows]
yp = [row[c] for row in y_pred_rows]
tpc = sum(t == 1 and p == 1 for t, p in zip(yt, yp))
fpc = sum(t == 0 and p == 1 for t, p in zip(yt, yp))
fnc = sum(t == 1 and p == 0 for t, p in zip(yt, yp))
tp += tpc
fp += fpc
fn += fnc
p, r, f1 = _prf_counts(tpc, fpc, fnc)
per_label.append({"label": c, "precision": p, "recall": r, "f1": f1})
if average == "micro":
p, r, f1 = _prf_counts(tp, fp, fn)
return _frac("multilabel_prf", f1, 1.0, average="micro",
precision=p, recall=r)
f1s = [l["f1"] for l in per_label]
return Score("multilabel_prf", sum(f1s) / len(f1s),
detail={"average": "macro", "per_label": per_label})
def sklearn_prf(y_true: Sequence[str], y_pred: Sequence[str], *,
labels: Sequence[str] | None = None,
average: str = "macro") -> Score:
"""Cross-check hook: the same metrics via scikit-learn. Requires
`uv add scikit-learn`. Use it to validate your from-scratch numbers —
the lesson's `classification_prf` should match this exactly.
`average="binary"` mirrors classification_prf's convention: the
positive class is the second sorted label (or labels[1] when `labels`
is given), passed to sklearn as `pos_label` — without it sklearn
assumes label 1 and raises on string labels. `average=None` is not
supported here (sklearn returns arrays); use classification_prf."""
try:
from sklearn.metrics import precision_recall_fscore_support
except ImportError as e: # pragma: no cover
raise RuntimeError("sklearn_prf needs scikit-learn: uv add scikit-learn") from e
if average is None:
raise ValueError("sklearn_prf needs an average; use classification_prf for per-class")
extra: dict[str, Any] = {}
if average == "binary":
labs = list(labels) if labels is not None else sorted(set(y_true) | set(y_pred))
if len(labs) != 2:
raise ValueError("binary average needs exactly 2 labels")
extra["pos_label"] = labs[1]
p, r, f1, _sup = precision_recall_fscore_support(
y_true, y_pred, labels=labels, average=average, zero_division=0, **extra)
return Score("sklearn_prf", float(f1), detail={"precision": float(p),
"recall": float(r),
"average": average})
classification_prf supports average="binary" | "micro" | "macro" | "weighted" | None (per-class detail). Real output on an imbalanced 10-example set (8 billing, 2 technical; predictions 9 billing, 1 technical):
accuracy (imbalanced) value=0.700 passed=None {"numerator": 7, "denominator": 10}
prf macro value=0.412 passed=None {"average": "macro"}
prf micro value=0.700 passed=None {"average": "micro"}
prf weighted value=0.659 passed=None {"average": "weighted"}
confusion labels=['billing', 'technical'] matrix=[[7, 1], [2, 0]]Read that carefully: accuracy 0.70, but macro F1 is 0.41 — the technical class scores 0 because the model never predicted it. Micro F1 equals accuracy for single-label data. This is the whole argument for per-class reporting in one table.
3.2 Choosing the average#
average |
What it weights | Use when |
|---|---|---|
micro |
Every example equally (≈ accuracy for single-label) | Imbalanced data where big classes dominate and that's fine |
macro |
Every class equally | Rare classes matter as much as common ones (defect detection, fraud) |
weighted |
Classes by frequency | You want per-class quality but weighted by real prevalence |
binary |
The positive class only | One-vs-rest: "did it flag the bad case?" |
None |
Per-class table only | Diagnostics and slicing |
3.3 Class imbalance#
Accuracy lies under imbalance: a model predicting the majority class every time scores the majority share. The fix is never "balance the test set" (that lies differently) — it's reporting precision/recall/F1 per class and choosing the average that matches the cost of each error. expected_cost handles asymmetric costs directly: fp_cost=5, fn_cost=1 says a false positive costs five times a false negative.
3.4 ROC/AUC and calibration#
roc_auc computes the area under the ROC curve as a Mann-Whitney U statistic — the probability a random positive outranks a random negative. It needs scores, not just labels: your model's confidence, a judge's score, a classifier's probability. brier_score and reliability_bins measure calibration: does "80% confident" mean right 80% of the time? reliability_bins returns per-bin count/mean-confidence/accuracy — the data for a reliability diagram — plus the ECE.
Real output:
roc_auc value=0.750 passed=None {"n_pos": 2, "n_neg": 2}
brier value=0.173 passed=None {"n": 3}
reliability bins (first two of four occupied) [{"count": 1, "mean_confidence": 0.1, "accuracy": 0.0}, {"count": 1, "mean_confidence": 0.7, "accuracy": 1.0}] ...
ECE = 0.175
best_f1_threshold value=1.000 passed=None {"threshold": 0.7, "f1": 1.0}
expected_cost fp=5 fn=1 value=0.300 passed=None {"mean_cost": 1.5, "fp": 1, "fn": 1}
multilabel_prf value=0.900 passed=None {"average": "macro"}3.5 The sklearn cross-check#
sklearn_prf wraps sklearn.metrics.precision_recall_fscore_support (scikit-learn 1.9.1 as of November 2026). Its job is verification: your from-scratch numbers must match it exactly on the same inputs. If they don't, your bug is in the implementation, not the metric. Use it in tests/test_scorers.py as a property test over random label sets.
Part 4: Text-overlap and embedding metrics#
Deep-dive
For open-ended text — summaries, answers, translations — the temptation is to grab BLEU or a cosine score. This part covers what each metric actually measures, where they correlate with human judgement, and where they fail badly enough to mislead you.
4.1 What each metric measures#
Section 7 of evalkit/scorers.py implements the inspectable versions; the libraries implement the production versions:
# evalkit/scorers.py — section 7 of 11: text-overlap metrics
def token_f1(prediction: str, reference: str) -> Score:
"""Token-level F1 with multiplicity (SQuAD-style). The cheap stand-in for
semantic similarity on short answers — numbers, names, yes/no. Same
computation as 07.9's docs_qa/eval/metrics.py."""
p, r = word_tokens(prediction), word_tokens(reference)
if not p or not r:
return _score("token_f1", False, reason="empty_side")
counts: Counter[str] = Counter()
for t in p:
counts[t] += 1
common = 0
for t in r:
if counts[t] > 0:
counts[t] -= 1
common += 1
if common == 0:
return _frac("token_f1", 0.0, 1.0)
prec, rec = common / len(p), common / len(r)
return _frac("token_f1", 2 * prec * rec / (prec + rec), 1.0,
precision=prec, recall=rec, overlap=common)
def _ngram_counts(tokens: Sequence[str], n: int) -> Counter[tuple[str, ...]]:
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
def bleu_score(hypothesis: str, references: Sequence[str], *, max_n: int = 4) -> Score:
"""Sentence-level BLEU: geometric mean of modified n-gram precisions
(n=1..max_n) times a brevity penalty.
Clipping is the standard 'effective reference' approximation: each
hypothesis n-gram counts at most as many times as its maximum count in
ANY single reference; the brevity penalty compares against the
reference closest in length to the hypothesis.
⚠️ No smoothing: one missing 4-gram zeroes the whole score. That is
exactly why sacreBLEU exists (`uv add sacrebleu`, `BLEU().corpus_score`)
— use it for real reporting; this implementation is here so the metric
is inspectable and unit-testable."""
hyp = word_tokens(hypothesis)
refs = [word_tokens(r) for r in references]
if not hyp or not refs or not any(refs):
return _score("bleu", False, reason="empty_input")
precisions = []
for n in range(1, max_n + 1):
hyp_counts = _ngram_counts(hyp, n)
if not hyp_counts:
precisions.append(0.0)
continue
# max count of each n-gram across all references
max_ref: Counter[tuple[str, ...]] = Counter()
for ref in refs:
for g, c in _ngram_counts(ref, n).items():
if c > max_ref[g]:
max_ref[g] = c
clipped = sum(min(c, max_ref[g]) for g, c in hyp_counts.items())
precisions.append(clipped / sum(hyp_counts.values()))
if any(p == 0.0 for p in precisions):
return Score("bleu", 0.0, detail={"precisions": precisions,
"note": "zero n-gram precision; sacrebleu would smooth"})
log_avg = sum(math.log(p) for p in precisions) / max_n
# brevity penalty vs the reference closest in length to the hypothesis
ref_len = min(refs, key=lambda r: abs(len(r) - len(hyp)))
ref_len = len(ref_len)
bp = 1.0 if len(hyp) > ref_len else math.exp(1 - ref_len / max(len(hyp), 1))
return Score("bleu", bp * math.exp(log_avg),
detail={"precisions": precisions, "brevity_penalty": bp,
"hyp_len": len(hyp), "ref_len": ref_len})
def _lcs_len(a: Sequence[str], b: Sequence[str]) -> int:
"""Longest common subsequence length (order preserved, gaps allowed)."""
if len(a) < len(b):
a, b = b, a
prev = [0] * (len(b) + 1)
for x in a:
cur = [0]
for j, y in enumerate(b, 1):
cur.append(prev[j - 1] + 1 if x == y else max(prev[j], cur[-1]))
prev = cur
return prev[-1]
def rouge_l(prediction: str, reference: str) -> Score:
"""ROUGE-L: F1 over the longest common subsequence of word tokens.
Rewards answers that keep the reference's phrasing order; bag-of-words
overlap (token_f1) ignores order entirely."""
p, r = word_tokens(prediction), word_tokens(reference)
if not p or not r:
return _score("rouge_l", False, reason="empty_side")
lcs = _lcs_len(p, r)
prec, rec = lcs / len(p), lcs / len(r)
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
return _frac("rouge_l", f1, 1.0, precision=prec, recall=rec, lcs=lcs)
def rouge_n(prediction: str, reference: str, n: int = 1) -> Score:
"""ROUGE-N recall: fraction of reference n-grams present in the
prediction. ROUGE-1 = unigram recall (bag overlap, order-free)."""
p, r = word_tokens(prediction), word_tokens(reference)
if not p or not r:
return _score(f"rouge{n}", False, reason="empty_side")
ref_grams = Counter(tuple(r[i:i + n]) for i in range(len(r) - n + 1))
pred_grams = Counter(tuple(p[i:i + n]) for i in range(len(p) - n + 1))
hit = sum(min(c, pred_grams[g]) for g, c in ref_grams.items())
total = sum(ref_grams.values())
return _frac(f"rouge{n}", hit / total if total else 0.0, 1.0,
recall=hit / total if total else 0.0, matched=hit, total=total)
def chrf_score(prediction: str, reference: str, *, n: int = 6, beta: float = 2.0) -> Score:
"""chrF: character n-gram F-score (beta=2 favours recall). Robust to
morphology and word-order noise that word-level metrics miss; the WMT
favourite for morphologically rich languages. sacrebleu ships it too."""
p_grams, r_grams = char_ngrams(prediction, n), char_ngrams(reference, n)
if not p_grams or not r_grams:
return _score("chrf", False, reason="empty_side")
hit = sum((p_grams & r_grams).values())
prec = hit / sum(p_grams.values())
rec = hit / sum(r_grams.values())
if prec + rec == 0:
return _frac("chrf", 0.0, 1.0)
f = (1 + beta**2) * prec * rec / (beta**2 * prec + rec)
return _frac("chrf", f, 1.0, precision=prec, recall=rec, n=n, beta=beta)
def _levenshtein(a: Sequence[Any], b: Sequence[Any]) -> int:
"""Edit distance over any hashable sequence (chars or words)."""
if len(a) < len(b):
a, b = b, a
prev = list(range(len(b) + 1))
for i, x in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, y in enumerate(b, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y))
prev = cur
return prev[-1]
def edit_distance_score(prediction: str, reference: str, *,
level: str = "char") -> Score:
"""Normalised edit SIMILARITY: 1 - distance/max(len), in [0,1].
level='char' is the complement of a CER-style error rate, level='word'
the complement of a WER-style one — note the direction: WER/CER are
error rates (edits/reference length, can exceed 1.0) and this returns
similarity, so don't compare the numbers directly. For true WER/CER
see 09.4."""
a = list(prediction) if level == "char" else word_tokens(prediction)
b = list(reference) if level == "char" else word_tokens(reference)
denom = max(len(a), len(b), 1)
dist = _levenshtein(a, b)
return _frac(f"edit_sim_{level}", 1 - dist / denom, 1.0,
distance=dist, level=level)
def embedding_cosine(vec_a: Sequence[float], vec_b: Sequence[float]) -> Score:
"""Cosine similarity between two embedding vectors, rescaled to [0, 1]
(02.3 owns the concept). Pass real embeddings from your provider's
embedding API — verify current model IDs and dimensions on the
provider's official page; they are not in the module's model table.
A measurement, not a verdict: pick the pass threshold on labelled data."""
if len(vec_a) != len(vec_b) or not vec_a:
raise ValueError("vectors must be non-empty and same length")
dot = sum(x * y for x, y in zip(vec_a, vec_b))
na = math.sqrt(sum(x * x for x in vec_a))
nb = math.sqrt(sum(y * y for y in vec_b))
if na == 0 or nb == 0:
return _score("embedding_cosine", False, reason="zero_vector")
sim = dot / (na * nb)
return Score("embedding_cosine", (sim + 1) / 2, passed=None,
detail={"cosine": sim})
def embedding_scorer(embed_fn: Callable[[str], Sequence[float]],
*, threshold: float = 0.8) -> Callable[..., Score]:
"""Factory: a case-level grader for 'semantically equivalent' answers.
`embed_fn` maps text -> vector (your provider's embedding client).
The grader embeds the output and the case's expected/reference text and
returns 1.0 iff cosine similarity >= threshold. Tune `threshold` on
labelled pairs — 0.8 is a starting guess, not a fact."""
def grade(case: Mapping[str, Any], output: Any) -> Score:
expected = case_value(case, "expected", "reference", "answer", default="")
a, b = embed_fn(str(output)), embed_fn(str(expected))
sim = embedding_cosine(a, b).detail["cosine"]
return _score("embedding_equivalence", sim >= threshold,
cosine=sim, threshold=threshold)
return grade
| Metric | What it counts | Strength | Blind spot |
|---|---|---|---|
token_f1 |
Bag-of-words overlap with multiplicity | Cheap, explainable | Ignores order and meaning; punishes correct verbose answers |
rouge_l |
LCS-based F1 | Rewards kept phrasing order | Still lexical, not semantic |
bleu_score |
Modified n-gram precision + brevity penalty | Standard for MT | Zero on any missing 4-gram; hates paraphrase |
chrf_score |
Character n-gram F (β=2) | Morphology/order robust | Still surface-form |
edit_distance_score |
Normalised Levenshtein similarity (char/word) | Intuitive "how different" | No notion of meaning; similarity, not an error rate |
embedding_cosine |
Vector angle between embeddings | Captures paraphrase | Needs an embedding model; threshold is a guess |
meteor_score (nltk) |
Unigram alignment w/ stem+synonym match + fragmentation penalty | Credits paraphrase BLEU misses | Needs WordNet; still surface-bound, slower |
4.2 The libraries#
For real reporting, use the maintained implementations — all verified on PyPI as of November 2026:
# text_metrics_libs.py — optional dependencies, each in its own try/except.
# Versions these samples were checked against are listed in Setup; verify on PyPI.
# sacrebleu 2.6.0 — corpus BLEU/chrF/TER with signatures for reproducibility
from sacrebleu.metrics import BLEU, CHRF
bleu = BLEU()
# corpus_score(hypotheses, references): `references` is one stream PER
# REFERENCE, each holding that reference for every hypothesis — so 1
# hypothesis x 2 references is [[ref1], [ref2]], NOT [ref1, ref2].
score = bleu.corpus_score(
["The cat sat on the mat."],
[["The cat sat on the mat."], ["A cat sat on a mat."]],
)
print(score.score) # e.g. 100.0 for an identical hypothesis
print(bleu.get_signature()) # 'nrefs:2|case:mixed|eff:no|tok:13a|...'
# sentence-level BLEU takes references as a plain list instead:
# score = bleu.sentence_score(hyp, [ref1, ref2])
# rouge-score 0.1.2 — ROUGE-N/L with optional Porter stemming
from rouge_score import rouge_scorer
scorer = rouge_scorer.RougeScorer(["rouge1", "rougeL"], use_stemmer=True)
scores = scorer.score("the cat sat on the mat", "a cat sat on a mat")
print(scores["rouge1"].fmeasure, scores["rougeL"].fmeasure)
# bert-score 0.3.13 — contextual-embedding similarity (needs torch+transformers,
# downloads a multi-GB model; slow but the best lexical-overlap correlate)
# from bert_score import score
# P, R, F1 = score(["the cat sat"], ["a cat sat"], lang="en",
# model_type="microsoft/deberta-xlarge-mnli",
# rescale_with_baseline=True)
# nltk 3.10.4 — METEOR (unigram alignment + WordNet synonyms/stemming +
# fragmentation penalty). Needs the WordNet corpus once:
# import nltk; nltk.download("wordnet")
# from nltk.translate.meteor_score import meteor_score
# meteor_score([[ref.split()]], hyp.split()) # pre-tokenised -> float in [0,1]
# sacreBLEU ships BLEU/chrF/TER only — METEOR lives here, in nltk.
# jiwer 4.0.0 — WER/CER for transcription evals (09.4 owns WER in depth)
# from jiwer import wer
# print(wer("the cat sat", "the cat sat"))
# evaluate 0.4.6 — Hugging Face's metric hub (wraps many of the above)4.3 Where they correlate and where they fail#
They work for: machine translation (their native habitat), summarisation baselines (catch gross regressions), regression tripwires ("did this prompt change tank the overlap score?"), and short canonical answers where lexical overlap ≈ correctness.
They fail for open-ended generation, and the failure modes are predictable:
- BLEU hates paraphrase. "a fast brown fox jumps" vs reference "the quick brown fox" scores 0.0 — every 3/4-gram misses. A correct, fluent answer in different words is indistinguishable from gibberish.
- token_f1 punishes helpful verbosity. "The capital of France is Paris" vs reference "Paris" scores 0.29 — precision 1/6 — because the extra correct words count against it.
- All lexical metrics miss negation and factuality. "The sky is green" and "The sky is not green" share almost all n-grams.
- BERTScore helps but isn't a judge. It correlates better with human judgement than n-gram metrics (the ICLR 2020 paper reports this across WMT metrics), but it still can't verify facts — a fluent hallucination scores high.
METEOR is the paraphrase-aware middle ground. nltk.translate.meteor_score.meteor_score (nltk 3.10.4 as of November 2026) aligns hypothesis and reference unigrams in order, but counts a match when words share a stem or a WordNet synonym, then applies a fragmentation penalty for aligned words scattered across the sentence. That is precisely the machinery BLEU lacks: "a fast brown fox" vs "the quick brown fox" still shares most content words through synonyms, so METEOR gives partial credit where BLEU gives 0.0. The costs are real — it needs the WordNet corpus (nltk.download("wordnet") once), is slower than counting n-grams, and its synonym resources are English-centric — but for summarisation and QA answers where legitimate paraphrase is common, it is the strongest lexical metric short of an embedding or a judge. sacreBLEU ships BLEU/chrF/TER only, so METEOR comes from nltk, not the reproducible-MT stack. Treat it like the others: a better tripwire, never a verdict.
Learned metrics. A third family trains a model to predict human quality ratings: COMET (Rei et al., EMNLP 2020, the unbabel-comet package) and BLEURT (Sellam et al., ACL 2020) for translation, and BERTScore-style embedding comparison for general text. They correlate better with human judgement than n-gram overlap on the tasks they were trained for, but they are models: heavier to run, tied to the languages and domains they were trained on, and still unable to verify facts. In this module's ladder they sit between code and judges (rung 2); validate any of them against your own human labels exactly as 10A.5 validates a judge before you let it gate anything.
Real output showing both sides:
token_f1 value=0.286 passed=None {"precision": 0.167, "recall": 1.0}
bleu identical value=1.000 passed=None {"precisions": [1.0, 1.0, 1.0, 1.0]}
bleu paraphrase value=0.000 passed=None {"note": "zero n-gram precision; sacrebleu would smooth"}
chrf value=1.000 passed=None
edit char kitten/sitting value=0.571 passed=None {"distance": 3}
embedding_cosine value=0.994 passed=None {"cosine": 0.989}Part 5: Structural and format checks#
The cheapest graders of all: assertions about the shape of the output, not its content. These run before any semantic scoring — a response that isn't valid JSON never reaches the accuracy metric.
Section 8 of evalkit/scorers.py:
# evalkit/scorers.py — section 8 of 11: structural and format checks
def length_within(text: str, *, min_chars: int = 0, max_chars: int | None = None,
max_words: int | None = None) -> Score:
"""Length budget check. Word limit uses `word_tokens` — punctuation-only
'words' don't count."""
n_chars = len(text)
n_words = len(word_tokens(text))
ok = n_chars >= min_chars and (max_chars is None or n_chars <= max_chars) \
and (max_words is None or n_words <= max_words)
return _score("length_within", ok, chars=n_chars, words=n_words,
min_chars=min_chars, max_chars=max_chars, max_words=max_words)
def language_is(text: str, expected: str, *,
detect: Callable[[str], str]) -> Score:
"""1.0 iff the detected language equals `expected` (ISO 639-1 code).
`detect` is injectable: production uses `langdetect` or `lingua`
(uv add langdetect / lingua-language-detector — both pure-ish and local);
tests pass a stub. Never vendor a hand-rolled detector — they fail on
short texts, which is exactly what eval outputs are."""
got = detect(text)
return _score("language_is", got == expected, expected=expected, detected=got)
def langdetect_language(text: str) -> str:
"""Convenience detector via `langdetect` (uv add langdetect).
Short texts are unreliable — langdetect itself warns about < ~30 chars."""
try:
from langdetect import detect, DetectorFactory
except ImportError as e: # pragma: no cover
raise RuntimeError("language_is needs `langdetect`: uv add langdetect") from e
DetectorFactory.seed = 0 # deterministic: same text -> same guess
return detect(text)
def forbidden_terms(text: str, terms: Sequence[str], *,
ignore_case: bool = True) -> Score:
"""1.0 iff NONE of the forbidden terms appear. Word-boundary matching:
'ass' must not flag 'class'. For substring semantics use contains_any
inverted, or banned_patterns."""
hay = text.casefold() if ignore_case else text
hits = []
for t in terms:
needle = t.casefold() if ignore_case else t
for m in re.finditer(r"\b" + re.escape(needle) + r"\b", hay):
hits.append(t)
break
return _score("forbidden_terms", not hits, hits=hits)
def banned_patterns(text: str, patterns: Sequence[str], *,
flags: int = re.IGNORECASE) -> Score:
"""1.0 iff none of the regex patterns match. For topic bans use
word-boundary patterns; for format bans (e.g. no markdown tables) a
looser pattern is fine. Compile errors raise — a broken pattern is a
broken grader, not a failed example."""
hits = []
for pat in patterns:
m = re.search(pat, text, flags)
if m:
hits.append({"pattern": pat, "match": m.group(0)})
return _score("banned_patterns", not hits, hits=hits)
def required_patterns(text: str, patterns: Sequence[str], *,
flags: int = re.IGNORECASE) -> Score:
"""1.0 iff EVERY pattern matches — 'must cite [1]', 'must include a URL',
'must end with a disclaimer'. The positive counterpart of banned_patterns."""
missing = [p for p in patterns if not re.search(p, text, flags)]
return _score("required_patterns", not missing, missing=missing)
def citation_check(text: str, *, min_citations: int = 1,
pattern: str = r"\[\d+\]|https?://\S+") -> Score:
"""Citation presence: counts marker-style ([1], [2,3]) or URL citations.
This checks SHAPE only — whether the cited source supports the claim is
07.5's entailment problem and 10A.6's faithfulness judge."""
found = re.findall(pattern, text)
ok = len(found) >= min_citations
return _score("citation_check", ok, citations=len(found),
min_citations=min_citations)
def links_valid(text: str, *, check: Callable[[str], bool] | None = None) -> Score:
"""1.0 iff every http(s) URL in the text passes `check` (default: skip —
inject an HTTP-HEAD checker in production; tests pass a stub). Dead or
hallucinated links are a top LLM failure mode in RAG answers."""
urls = re.findall(r"https?://[^\s)\]>\"']+", text)
if check is None:
return Score("links_valid", 0.0, passed=None,
detail={"skipped": True, "urls": urls,
"note": "no link checker injected"})
bad = [u for u in urls if not check(u)]
return _score("links_valid", not bad, urls=urls, dead_links=bad)
def json_well_formed(text: str) -> Score:
"""1.0 iff the text is parseable JSON or contains one JSON document.
Tries the whole text first, then the OUTERMOST {...} or [...] span —
'Sure! {"a": 1} done' passes. Two separate JSON blobs fail: which one
is 'the' answer is ambiguous, and 03.4's extractor owns that
disambiguation."""
try:
json.loads(text)
return _score("json_well_formed", True)
except json.JSONDecodeError:
pass
for open_ch, close_ch in (("{", "}"), ("[", "]")):
i, j = text.find(open_ch), text.rfind(close_ch)
if i != -1 and j > i:
try:
json.loads(text[i:j + 1])
return _score("json_well_formed", True, extracted=True)
except json.JSONDecodeError:
continue
return _score("json_well_formed", False)
def markdown_well_formed(text: str) -> Score:
"""Cheap structural lint for Markdown answers: balanced code fences and
brackets, no unclosed bold/italic runs. Not a full parser — catches the
'the model stopped mid-table' class of breakage."""
problems = []
fence = chr(96) * 3
if text.count(fence) % 2 != 0:
problems.append("unbalanced_code_fence")
if text.count("**") % 2 != 0:
problems.append("unbalanced_bold")
# unclosed markdown link [text](url
if re.search(r"\[[^\]]*\]\([^)]*$", text):
problems.append("unclosed_link")
return _score("markdown_well_formed", not problems, problems=problems)
_PII_PATTERNS: dict[str, str] = {
"email": r"\b[\w.+-]+@[\w-]+\.[\w.]+\b",
# Phone shapes need separator-delimited groups, so ISO dates
# ('2026-03-04'), slash dates, order IDs and dash-separated card
# numbers don't trip it. Residual false positives remain —
# space-separated cards ('4111 1111 1111 1111') are phone-shaped —
# and bare 7-digit local numbers are missed; tune via `patterns`.
"phone": r"(?<![\d-])(?:\+\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)|\d{2,4})[\s.-]\d{3,4}[\s.-]\d{4}(?![\d-])",
"ssn_like": r"\b\d{3}-\d{2}-\d{4}\b",
"card_like": r"\b(?:\d[ -]?){13,19}\b",
"api_key_like": r"\b(?:sk|pk|api|key|token)[-_][A-Za-z0-9]{16,}\b",
}
def pii_scan(text: str, *, patterns: Mapping[str, str] | None = None) -> Score:
"""Regex PII scan — the deterministic floor. Catches emails,
separator-delimited phone shapes, SSN-shaped and card-shaped numbers,
key-shaped strings. It does NOT catch names or addresses; 05.5 Part 8
covers Presidio and LLM-based detection for that. Known limits: the
phone pattern still flags space-separated card numbers and some
international formats, and misses bare local numbers — pass `patterns`
to tune for your data. Use as a hard gate before anything leaves your
perimeter."""
pats = dict(_PII_PATTERNS if patterns is None else patterns)
findings = {kind: len(re.findall(p, text)) for kind, p in pats.items()}
findings = {k: v for k, v in findings.items() if v}
return _score("pii_scan", not findings, findings=findings)
_SYLLABLE_GROUPS = re.compile(r"[aeiouy]+")
def _syllables(word: str) -> int:
w = word.lower().strip(".,;:!?()\"'")
groups = _SYLLABLE_GROUPS.findall(w)
n = len(groups) or 1
if w.endswith("e") and not w.endswith(("le", "ee", "ye")) and n > 1:
n -= 1
return max(n, 1)
def flesch_reading_ease(text: str) -> Score:
"""Flesch Reading Ease: 206.835 - 1.015*(words/sentences)
- 84.6*(syllables/words). 60-70 is plain English; below ~30 is
academic. Syllable counting is heuristic — treat as a tripwire, not a
precise instrument."""
words = word_tokens(text)
sentences = max(len(re.findall(r"[.!?]+", text)), 1)
if not words:
return Score("flesch", 0.0, passed=None, detail={"note": "empty text"})
syl = sum(_syllables(w) for w in words)
raw = 206.835 - 1.015 * (len(words) / sentences) - 84.6 * (syl / len(words))
# value stays in [0,1] per the contract: the 0-100 Flesch score is
# rescaled and the raw figure kept in detail.
return Score("flesch", max(0.0, min(1.0, raw / 100.0)), passed=None,
detail={"flesch_reading_ease": round(raw, 2),
"words": len(words), "sentences": sentences,
"syllables": syl})
def toxicity_score(text: str, *, classifier: Callable[[str], float]) -> Score:
"""Injectable toxicity classifier: pass a function returning a score in
[0,1]. Verified options as of November 2026:
- `detoxify` (https://github.com/unitaryai/detoxify, PyPI `detoxify`) —
local torch models trained on the Jigsaw challenges
(original/unbiased/multilingual heads); free and private but heavy,
and English-centric unless you pick the multilingual head.
- OpenAI's moderation endpoint (`client.moderations.create`, model
`omni-moderation-latest`, free per OpenAI's docs) — returns
per-category flags rather than one score; needs an OpenAI key and a
network call per output.
- A judge rubric ([10A.4](04-llm-as-judge.md)) — most flexible for
product-specific definitions of 'toxic', at judge cost.
The 0.5 threshold is a placeholder — tune it on labelled outputs, and
expect the detector's own biases (detoxify's card warns that profanity
alone trips it regardless of tone)."""
s = float(classifier(text))
return Score("toxicity", s, passed=s < 0.5,
detail={"threshold": 0.5, "raw": s})
5.1 Hard vs soft checks#
Every check above returns passed=True/False — a hard gate. When you combine graders (Part 8), any hard failure fails the example regardless of soft scores. Soft measurements (length, flesch, token_f1, embedding_cosine) return passed=None and only feed aggregates. The discipline: gate on invariants (must be valid JSON, must not contain PII, must cite a source), measure on quality (length, readability, overlap).
5.2 The checks, and their limits#
length_within— word/char budgets. Catches rambling and empty answers; says nothing about content.language_is— needs an injectable detector (langdetect1.0.9 orlingua2.2.0, both local). Unreliable under ~30 chars — eval outputs often are.forbidden_terms/banned_patterns/required_patterns— word-boundary vs regex semantics matter:forbidden_terms(["guarantee"])does NOT match "guaranteed";banned_patterns(r"\bguarantee\w*\b")does. Choose deliberately.citation_check/links_valid— verify citation shape ([1], URLs), not whether the source supports the claim (that's 07.5's entailment problem and 10A.6's faithfulness judge).json_well_formed/markdown_well_formed/schema_valid— parse-level validity; the first step of the validation layers from 03.4, Part 6.pii_scan— regex floor for emails/phone shapes/SSN/card/key patterns. The phone pattern requires separator-delimited groups so dates and IDs don't trip it, but space-separated cards and international formats still can — tune viapatterns. Catches the obvious; names and addresses need Presidio or an LLM detector (05.5, Part 8). Run it as a hard gate before outputs leave your perimeter.flesch_reading_ease— readability tripwire; syllable counting is heuristic.valueis the 0–100 score rescaled to [0,1]; the raw figure is indetail["flesch_reading_ease"].toxicity_score— injectable classifier returning [0,1]; verified options aredetoxify(local torch models), OpenAI's free moderation endpoint (omni-moderation-latest), or a judge rubric — the detector itself is a model call behind your budget.
Real output:
length_within fail value=0.000 passed=False {"words": 30}
language_is stub es value=0.000 passed=False {"detected": "en"}
forbidden_terms stem-miss value=1.000 passed=True {"hits": []}
banned_patterns stem value=0.000 passed=False {"hits": [{"pattern": "\\bguarantee\\w*\\b", "match": "guaranteed"}]}
citation_check value=1.000 passed=True {"citations": 1}
json_well_formed prose-wrapped value=1.000 passed=True {"extracted": true}
pii_scan date-only value=1.000 passed=True {"findings": {}}
pii_scan dirty value=0.000 passed=False {"findings": {"email": 1, "phone": 1}}Part 6: Operational metrics as first-class#
Quality isn't the only axis — a correct answer that takes 30 s and costs $0.05 is a different product than one that takes 1 s and costs $0.001. The harness should record operational metrics per example and aggregate them per run.
Section 9 of evalkit/scorers.py:
# evalkit/scorers.py — section 9 of 11: operational metrics
def percentile(values: Sequence[float], p: float) -> float:
"""p-th percentile (0-100) with linear interpolation between closest
ranks — the same convention numpy.percentile uses."""
xs = sorted(values)
if not xs:
raise ValueError("empty")
if len(xs) == 1:
return xs[0]
k = (len(xs) - 1) * p / 100.0
f, c = math.floor(k), math.ceil(k)
return xs[f] + (xs[c] - xs[f]) * (k - f)
@dataclass(frozen=True)
class RunRecord:
"""One example's operational footprint, as the runner should record it.
Fields the provider didn't report stay None — never fake them."""
example_id: str
ttft_ms: float | None = None # time to first token (streaming only)
total_ms: float | None = None
tokens_in: int | None = None
tokens_out: int | None = None
cost_usd: float | None = None
retries: int = 0
error: str | None = None # infra failure kind, None = clean run
timeout: bool = False
refused: bool = False
def operational_summary(records: Sequence[RunRecord]) -> dict[str, Any]:
"""Aggregate a run's operational metrics: latency percentiles, token and
cost totals, and the rates that decide whether the eval itself was
healthy (error/timeout/refusal/retry rates)."""
n = len(records)
if n == 0:
return {"n": 0}
def pct(field_name: str, p: float) -> float | None:
vals = [getattr(r, field_name) for r in records
if getattr(r, field_name) is not None]
return round(percentile(vals, p), 1) if vals else None
def total(field_name: str) -> float | None:
vals = [getattr(r, field_name) for r in records
if getattr(r, field_name) is not None]
return sum(vals) if vals else None
cost_vals = [r.cost_usd for r in records if r.cost_usd is not None]
cost_total = sum(cost_vals) if cost_vals else None
cost_n = len(cost_vals)
return {
"n": n,
"ttft_p50_ms": pct("ttft_ms", 50), "ttft_p95_ms": pct("ttft_ms", 95),
"total_p50_ms": pct("total_ms", 50), "total_p95_ms": pct("total_ms", 95),
"total_p99_ms": pct("total_ms", 99),
"tokens_in": total("tokens_in"), "tokens_out": total("tokens_out"),
"cost_usd": cost_total,
# Cost is averaged over the records that actually reported it —
# missing cost is not zero. cost_coverage shows the fraction.
"cost_reported_examples": cost_n,
"cost_per_reported_example_usd": (cost_total / cost_n) if cost_n else None,
"cost_coverage": round(cost_n / n, 4),
"error_rate": sum(r.error is not None for r in records) / n,
"timeout_rate": sum(r.timeout for r in records) / n,
"refusal_rate": sum(r.refused for r in records) / n,
"retry_rate": sum(r.retries > 0 for r in records) / n,
"mean_retries": statistics.mean(r.retries for r in records),
}
RunRecord captures what the runner knows per example: TTFT and total latency (streaming vs non-streaming), token counts, cost (from 03.7's cost calculator), retries, and failure kinds. operational_summary rolls them into p50/p95/p99 latencies, totals, cost per reported example (with coverage), and the rates that tell you whether the eval itself was healthy — error rate, timeout rate, refusal rate, retry rate. An eval run with 25% infra errors isn't measuring quality; it's measuring your rate limits.
Where refused comes from. Fill it from the provider's own refusal signal first (Anthropic's stop_reason == "refusal", OpenAI's refusal content item or field; 02.10, 14.3 shows the exact shapes for each provider), and add a pattern check (banned_patterns over phrases such as "I can't help with") for the polite declines that arrive as ordinary text. Treat a refusal as its own outcome: it is not an "incorrect answer", and on a case labelled should_refuse (10A.2, 3.4) it is the correct one, so the grader must read refused rather than scoring the prose.
Real output on the four RunRecords built in demo_scorers.py (one rate-limited with no usage reported, one retried):
{'cost_coverage': 0.75,
'cost_per_reported_example_usd': 0.0022,
'cost_reported_examples': 3,
'cost_usd': 0.0066,
'error_rate': 0.25,
'mean_retries': 0.25,
'n': 4,
'refusal_rate': 0.0,
'retry_rate': 0.25,
'timeout_rate': 0.25,
'tokens_in': 2520,
'tokens_out': 295,
'total_p50_ms': 1215.0,
'total_p95_ms': 2002.5,
'total_p99_ms': 2080.5,
'ttft_p50_ms': 320.0,
'ttft_p95_ms': 401.0}cost_usd totals only the three records that reported cost — the errored run returned no usage — so cost_per_reported_example_usd divides by 3, not 4, and cost_coverage (0.75) shows how much of the run the figure actually covers. Missing is not zero; treat a low coverage as "cost unknown for part of the run", not "cheap".
Part 7: Property-based and metamorphic testing#
Deep-dive
Unit tests check that code does what you wrote. For LLM features you also need tests that check invariants — properties that should hold no matter what the model says. Two families:
7.1 Property-based tests#
03.10 introduced Hypothesis for code properties (6.170.14 as of November 2026). For LLM outputs the same idea applies one level up: generate many inputs, assert the output satisfies a property — valid JSON, no PII, cites a source, under N words. The scorer library above gives you the property functions; Hypothesis gives you the input generation and shrinking. Example property: @given(st.text()) → "output is always schema-valid" — run over 100 generated inputs, not 3 hand-picked ones.
# tests/test_properties.py — Hypothesis property checks (tests/ sits in the project root, beside evalkit/).
# Requires: uv add hypothesis 03.10 owns the full treatment;
# this is the LLM-output-shaped sketch.
import json
from hypothesis import given, settings, strategies as st
from evalkit import scorers as s
@given(st.fixed_dictionaries({"answer": st.text(), "n": st.integers()}))
@settings(max_examples=50, deadline=None)
def test_generated_payloads_stay_in_range(obj):
"""Whatever shape the payload takes, structural scorers must return a
Score with value in [0,1] — the contract Part 1 defines."""
text = f"Result: {json.dumps(obj)}"
for score in (s.json_well_formed(text), s.pii_scan(text),
s.length_within(text, max_words=5000)):
assert 0.0 <= score.value <= 1.0
@given(st.text())
@settings(max_examples=50, deadline=None)
def test_scorers_never_crash_on_arbitrary_text(text):
"""Robustness property: no input may raise out of the scorer library —
a grader that crashes kills the whole eval run."""
s.normalize_text(text)
s.word_tokens(text)
s.json_well_formed(text)
s.pii_scan(text)
s.flesch_reading_ease(text)
s.forbidden_terms(text, ["refund"])
s.banned_patterns(text, [r"\bguarantee\w*\b"])7.2 Metamorphic and invariance checks#
When there's no single "right" answer, test relationships between answers instead:
- Invariance: a paraphrase, reordered list, or typo'd input should give the same answer.
- Directional: adding a constraint ("answer in under 50 words", "mention refunds") should change the output in the expected direction.
- Cross-lingual consistency: the same question asked in English, French and German should produce the same substance of answer — the answer's language is a separate property (
language_is, Part 5). Whether the reply should be in the question's language or a fixed canonical language is a product spec decision; either way, the substance must not change with the input language. - Consistency: N runs of the same input should mostly agree — the self-consistency rate, which is also how you measure non-determinism (02.5, 7.3).
Section 10 of evalkit/scorers.py:
# evalkit/scorers.py — section 10 of 11: property-based and metamorphic checks
def agreement_rate(outputs: Sequence[str], *,
same: Callable[[str, str], bool] | None = None) -> Score:
"""Self-consistency: fraction of unordered output pairs that agree under
`same` (default: normalised text equality). For k samples per input this
is C(k,2) comparisons — the 'do repeated runs agree?' number that
non-determinism makes essential (02.5 Part 7)."""
eq = same or (lambda a, b: normalize_text(a) == normalize_text(b))
pairs = [(a, b) for i, a in enumerate(outputs) for b in outputs[i + 1:]]
if not pairs:
return Score("agreement_rate", 1.0, passed=None,
detail={"note": "fewer than 2 outputs"})
agree = sum(eq(a, b) for a, b in pairs)
return _frac("agreement_rate", agree, len(pairs), pairs=len(pairs))
def invariance_check(base_output: str, variant_outputs: Sequence[str], *,
same: Callable[[str, str], bool] | None = None) -> Score:
"""Metamorphic/invariance test: paraphrases, reordering, typos of the
same input SHOULD give the same answer. Returns the fraction of variants
matching the base output. A drop here is a robustness bug, not a
correctness bug — the answers may all be 'right' but inconsistent."""
eq = same or (lambda a, b: normalize_text(a) == normalize_text(b))
if not variant_outputs:
return Score("invariance", 1.0, passed=None, detail={"note": "no variants"})
agree = sum(eq(base_output, v) for v in variant_outputs)
return _frac("invariance", agree, len(variant_outputs),
variants=len(variant_outputs))
def directional_check(control_outputs: Sequence[str],
treatment_outputs: Sequence[str],
predicate: Callable[[str, str], bool]) -> Score:
"""Directional metamorphic test: pairs (control, treatment) where the
treatment input added a constraint — `predicate(control_out,
treatment_out)` should hold for every pair (e.g. 'treatment is shorter',
'treatment mentions X'). Returns the fraction of pairs satisfying it."""
if len(control_outputs) != len(treatment_outputs):
raise ValueError("control and treatment must pair up")
if not control_outputs:
return Score("directional", 1.0, passed=None, detail={"note": "empty"})
ok = sum(predicate(c, t) for c, t in zip(control_outputs, treatment_outputs))
return _frac("directional", ok, len(control_outputs), pairs=len(control_outputs))
Real output:
agreement_rate (norm eq) value=0.500 passed=None {"pairs": 6}
agreement_rate strict value=0.000 passed=None {"pairs": 6}
invariance_check value=0.667 passed=None {"variants": 3}
directional shorter value=1.000 passed=None {"pairs": 2}Read the first two lines: ["Paris", "paris", "Paris!", "The answer is Paris"] agrees with itself 3/6 pairs under normalised equality but 0/6 under strict ==. That gap is the non-determinism-and-formatting budget your product actually has. invariance_check is the paraphrase-robustness probe; directional_check verifies constraints actually constrain.
For the cross-lingual check, the helper is the same shape — generate the input variants (here: translations) and compare canonical answers, not raw wording:
# metamorphic_pairs.py — cross-lingual consistency probe.
import json
from evalkit import scorers as s
QUESTIONS = {
"en": "What is the refund window?",
"fr": "Quel est le délai de remboursement ?",
"de": "Wie lang ist die Rückerstattungsfrist?",
}
def canonical_answer(output: str) -> str:
"""The field the product actually compares. If the spec fixes ONE
answer language (e.g. always English), plain normalised equality
works; otherwise '30 days' vs '30 jours' are both correct and `same`
needs semantic comparison (embedding cosine) or a judge."""
try:
return str(json.loads(output).get("answer", ""))
except json.JSONDecodeError:
return ""
# outputs = {lang: call_model(q) for lang, q in QUESTIONS.items()} # real run
# score = s.agreement_rate(list(outputs.values()),
# same=lambda a, b: s.normalize_text(canonical_answer(a))
# == s.normalize_text(canonical_answer(b)))Part 8: Combining graders — evalkit/scorers.py complete#
Section 11 finishes the file: the (case, output) grader adapter, the suite runner with weights, aggregation, and the bridge into 10A.1's harness.
# evalkit/scorers.py — section 11 of 11: combining graders + 10A.1 bridge
GraderFn = Callable[..., Score]
def case_scorer(fn: Callable[..., Score], *names: str,
default: Any = None) -> GraderFn:
"""Adapt a `(output, expected)` scorer to the `(case, output)` grader
signature `run_graders` expects — the same (case, output) order as
10A.1's `Scorer.score(example, output)`. `names` are the case fields to
try for the expected value, in order — e.g. case_scorer(
normalized_match, "expected", "reference", "answer")."""
def grade(case: Any, output: Any) -> Score:
return fn(output, case_value(case, *names, default=default))
return grade
def run_graders(case: Any, output: Any,
graders: Mapping[str, GraderFn], *,
weights: Mapping[str, float] | None = None) -> Verdict:
"""Run a named suite of graders on one example and combine the results.
`graders` maps suite name -> callable invoked as `fn(case, output)` —
the same (case, output) order as 10A.1's `Scorer.score(example,
output)`, so the convention is consistent across the module. Each
callable must return a Score or a list[Score]; a grader that raises
becomes a hard failure rather than killing the run — a crashed grader
is a broken grader, not a broken example. The suite key replaces the
grader's own Score.name (the original is kept as detail["score_name"]).
Hard failures (passed=False) fail the example no matter the weights.
Every non-failed score — hard-pass True and measurement None alike —
feeds `value`, the weighted mean of score values. `weights` maps suite
name -> weight (default 1.0; names not listed get 1.0; must be >= 0);
a grader emitting k scores splits its weight k ways, so each grader's
total influence equals its weight. This is weighted SCORES vs hard
GATES: weights tune the soft aggregate, they can never outvote a
hard failure.
`case` is the eval case — a dict following 10A.2's EvalExample field
names, a dataclass, or a 10A.1 Example; graders read what they need via
`case_value()`.
"""
wmap = weights or {}
scores: list[Score] = []
weighted: list[tuple[float, float]] = [] # (value, weight) per non-failed score
for name, fn in graders.items():
w = float(wmap.get(name, 1.0))
if w < 0:
raise ValueError(f"weight for grader {name!r} must be >= 0")
try:
result = fn(case, output)
except Exception as exc:
result = Score(name=name, value=0.0, passed=False,
detail={"grader_error": repr(exc)})
produced = [result] if isinstance(result, Score) else list(result)
if not produced:
produced = [Score(name=name, value=0.0, passed=False,
detail={"note": "grader returned no scores"})]
share = w / len(produced)
for s in produced:
named = s if s.name == name else Score(
name=name, value=s.value, passed=s.passed,
detail={**dict(s.detail), "score_name": s.name})
scores.append(named)
if named.passed is not False:
weighted.append((named.value, share))
hard_fail = any(s.passed is False for s in scores)
denom = sum(w for _, w in weighted)
value = sum(v * w for v, w in weighted) / denom if denom else 0.0
return Verdict(passed=not hard_fail, value=value, scores=tuple(scores))
def case_value(case: Any, *names: str, default: Any = None) -> Any:
"""Read a field from an eval case whether it's a dict, an object, or a
10A.1 Example — `.reference`/`.input`/`.metadata` resolve via the
'reference'/'input'/'metadata' names. Tries each name in order — the
dataset schema (10A.2) may call the reference 'expected', 'reference'
or 'answer'."""
for n in names:
if isinstance(case, Mapping) and n in case:
return case[n]
if hasattr(case, n):
return getattr(case, n)
return default
def aggregate(verdicts: Sequence[Verdict], *,
slices: Mapping[str, Sequence[int]] | None = None) -> dict[str, Any]:
"""Roll per-example verdicts into run-level numbers: mean score, pass
rate, and — the numbers that catch 'average hides the tail' — the
worst-slice pass rate and the macro slice score (unweighted mean of
per-slice mean_scores, so a huge easy slice can't dominate the
headline). `slices` maps slice name -> example indices."""
n = len(verdicts)
if n == 0:
return {"n": 0}
mean_score = statistics.mean(v.value for v in verdicts)
pass_rate = sum(v.passed for v in verdicts) / n
out: dict[str, Any] = {
"n": n,
"mean_score": round(mean_score, 4),
"pass_rate": round(pass_rate, 4),
}
if slices:
slice_rates = {}
for name, idxs in slices.items():
sub = [verdicts[i] for i in idxs if i < n]
if sub:
slice_rates[name] = {
"n": len(sub),
"pass_rate": round(sum(v.passed for v in sub) / len(sub), 4),
"mean_score": round(statistics.mean(v.value for v in sub), 4),
}
out["slices"] = slice_rates
out["worst_slice"] = min(
((k, v["pass_rate"]) for k, v in slice_rates.items()),
key=lambda kv: kv[1], default=None)
out["macro_slice_score"] = (
round(statistics.mean(v["mean_score"] for v in slice_rates.values()), 4)
if slice_rates else None)
return out
def to_core_score(score: Score):
"""Convert a grader Score to 10A.1's `core.Score` (evalkit/core.py):
`passed=None` measurements become `passed=True` — in the harness a row
passes iff EVERY scorer passes, so a measurement must not gate — and
`detail` (a mapping here) is JSON-serialised to core's string form.
The richer record stays available via Verdict.to_dict for reporting."""
from evalkit.core import Score as CoreScore
return CoreScore(
name=score.name, value=score.value,
passed=score.passed is not False,
detail=json.dumps(dict(score.detail), default=str) if score.detail else "")
def as_scorer(name: str, fn: GraderFn):
"""Adapt a `(case, output)` grader to 10A.1's `Scorer` protocol
(`score(example, output) -> core.Score`) so run_graders-style graders
plug into `run_eval` from 01-why-evals-matter.md. The Example itself
becomes `case` — `case_value` reads `.reference`/`.input`/`.metadata`
off it. A grader returning several Scores collapses to one core
Score: any hard failure wins; otherwise the mean value with
passed=True (core.Score has no 'measurement' state). Requires
evalkit/core.py from 10A.1; the import is lazy so scorers.py still
runs standalone."""
class _Scorer:
def score(self, example: Any, output: Any):
result = fn(example, output)
produced = [result] if isinstance(result, Score) else list(result)
if not produced:
return to_core_score(Score(
name=name, value=0.0, passed=False,
detail={"note": "grader returned no scores"}))
fails = [s for s in produced if s.passed is False]
if fails:
s = fails[0]
return to_core_score(Score(
name=name, value=s.value, passed=False,
detail={**dict(s.detail), "grader": name}))
value = statistics.mean(s.value for s in produced)
return to_core_score(Score(
name=name, value=value, passed=True,
detail={"n_scores": len(produced)}))
_Scorer.name = name
return _Scorer()run_graders runs a named dict of graders on one case: each grader is called fn(case, output) — the same order as 10A.1's Scorer.score(example, output). Hard failures (passed=False) fail the verdict regardless of weights; every non-failed score feeds value as a weighted mean (weights={"fields": 3.0} triples that grader's influence; a grader emitting k scores splits its weight k ways). case_scorer adapts any (output, expected) function to the grader signature, trying expected/reference/answer field names via case_value — which also reads .reference/.input/.metadata off a 10A.1 Example or 10A.2 EvalExample. aggregate rolls verdicts into mean score, pass rate, per-slice rates, worst-slice and macro_slice_score (the unweighted mean across slices). to_core_score/as_scorer bridge into 10A.1's run_eval — see the contract note in §1.3.
8.1 The whole library in one place#
The eleven sections above assemble evalkit/scorers.py (≈1,500 lines, stdlib only). tests/test_scorers.py (in the project root, beside the evalkit/ package — the tests folder from Setup) exercises the contract — every public scorer on fixtures with known answers, plus the [0,1] value invariant:
# tests/test_scorers.py — run from the project root: python -m pytest tests/
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1])) # project root (tests/ is one level down)
from evalkit import scorers as s
def test_exact_and_normalised():
assert s.exact_match("Paris", "Paris").passed is True
assert s.exact_match("Paris", "paris").passed is False
assert s.normalized_match("Invoice INV-2042!", "invoice inv-2042").passed is True
def test_numeric_and_quantity():
assert s.numeric_match("Total €1,299.50", "1299.5").passed is True
assert s.numeric_match("Total €1,299.50", "1199.50").passed is False
assert s.quantity_match("5 km", "5000 m").passed is True
assert s.quantity_match("68°F", "20°C").passed is True
def test_dates():
assert s.date_match("Due March 5, 2026", "2026-03-05").passed is True
assert s.date_match("due soon", "2026-03-05").passed is False
def test_structured():
out = {"total": 1299.5, "currency": "EUR"}
exp = {"total": 1299.5, "currency": "EUR", "lines": 3}
assert s.json_field_match(out, exp).value == 2 / 3
schema = {"type": "object", "required": ["total"],
"properties": {"total": {"type": "number"}}}
assert s.schema_valid({"total": 5}, schema).passed is True
assert s.schema_valid({"total": "five"}, schema).passed is False
def test_tool_calls():
a = [{"name": "get_weather", "arguments": {"city": "Paris"}}]
b = [{"name": "get_weather", "input": {"city": "Paris"}}]
assert s.tool_call_prf(a, b).value == 1.0
def test_classification():
yt = ["billing"] * 8 + ["technical"] * 2
yp = ["billing"] * 7 + ["technical"] + ["billing"] * 2
assert s.accuracy(yt, yp).value == 0.7
assert s.classification_prf(yt, yp, average="micro").value == 0.7
# confusion matrix orientation: rows=true, cols=pred
cm = s.confusion_matrix(yt, yp)
assert cm["matrix"] == [[7, 1], [2, 0]]
def test_executable_graders():
schema_sql = "CREATE TABLE emp (name TEXT, dept TEXT);"
rows = ["INSERT INTO emp VALUES ('a','eng'),('b','ops')"]
assert s.sql_equivalent(
"SELECT dept, COUNT(*) FROM emp GROUP BY dept",
"SELECT dept, COUNT(*) AS n FROM emp GROUP BY dept ORDER BY dept",
schema_sql=schema_sql, rows_sql=rows).passed is True
code = "def add(a, b):\n return a + b\n"
tests = ("from candidate import add\n\n"
"def test_add():\n assert add(2, 3) == 5\n")
assert s.run_code_tests(code, tests).passed is True
def test_text_overlap():
assert s.token_f1("the cat", "the cat").value == 1.0
# BLEU needs >=4 tokens for the 4-gram — a 3-token sentence scores 0.0
assert s.bleu_score("the cat sat down", ["the cat sat down"]).value == 1.0
assert s.chrf_score("hello", "hello").value == 1.0
assert s.edit_distance_score("kitten", "sitting", level="char").value < 1.0
def test_structural_and_pii():
assert s.length_within("short", max_words=5).passed is True
assert s.pii_scan("mail jane@example.com").passed is False
assert s.json_well_formed('ok {"a": 1} done').passed is True
assert s.required_patterns("see [1]", [r"\[\d+\]"]).passed is True
def test_operational_and_metamorphic():
recs = [s.RunRecord("a", total_ms=100), s.RunRecord("b", total_ms=300)]
summ = s.operational_summary(recs)
assert summ["total_p50_ms"] == 200.0
assert s.agreement_rate(["Paris", "paris"]).value == 1.0
assert s.invariance_check("x", ["x", "y"]).value == 0.5
def test_regressions():
# unit regex: mi/mg must not collapse to metres; 'min' is not a unit
assert s.quantity_match("5 mi", "8046.72 m").passed is True
assert s.quantity_match("500 mg", "0.5 g").passed is True
assert s.quantity_match("the meeting is 30 min", "1800 s").passed is False
# numeric_match validates `which`
try:
s.numeric_match("1", "1", which="middle")
assert False, "expected ValueError"
except ValueError:
pass
# best_f1_threshold reaches the predict-all-negative point
t = s.best_f1_threshold([0, 0, 0], [0.1, 0.5, 0.9])
assert t.detail["threshold"] is None # flag-nothing wins on all-negative data
# json canon: 5 == 5.0, "5" != 5
assert s.json_equal({"a": 5}, {"a": 5.0}).passed is True
assert s.json_equal({"a": 5}, {"a": "5"}).passed is False
# minischema: 5.0 satisfies "integer" like jsonschema
assert s.schema_valid({"n": 5.0}, {"type": "object",
"properties": {"n": {"type": "integer"}}}).passed is True
# multilabel_prf handles empty input
assert s.multilabel_prf([], []).value == 0.0
# sql_equivalent survives NULLs and mixed types
schema_sql = "CREATE TABLE t (a TEXT, b INT);"
rows = ["INSERT INTO t VALUES ('x', NULL), (NULL, 1)"]
assert s.sql_equivalent("SELECT * FROM t", "SELECT a, b FROM t",
schema_sql=schema_sql, rows_sql=rows).passed is True
# pii_scan: ISO dates are not phones
assert s.pii_scan("due 2026-03-04").passed is True
assert s.pii_scan("call +1 415 555 0132").passed is False
# every public scorer keeps value in [0,1]
fixtures = [
s.exact_match("a", "a"), s.normalized_match("A!", "a"),
s.contains_any("x", ["y"]), s.numeric_match("1", "1"),
s.quantity_match("5 km", "5000 m"), s.date_match("2026-01-01", "Jan 1 2026"),
s.set_match([1], [1]), s.json_field_match({"a": 1}, {"a": 1}),
s.json_equal(1, 1.0), s.schema_valid({}, {}),
s.tool_call_prf([], []), s.accuracy(["a"], ["a"]),
s.classification_prf(["a", "b"], ["a", "b"]),
s.multilabel_prf([[1]], [[1]]), s.token_f1("a b", "a b"),
s.bleu_score("a b", ["a b"]), s.rouge_l("a b", "a b"),
s.chrf_score("a", "a"), s.edit_distance_score("a", "a"),
s.length_within("x"), s.json_well_formed("{}"),
s.markdown_well_formed("x"), s.pii_scan("clean"),
s.flesch_reading_ease("Short sentence. Another one."),
s.agreement_rate(["a", "a"]), s.invariance_check("a", ["a"]),
s.directional_check(["a"], ["b"], lambda c, t: True),
s.expected_cost([0, 1], [0, 1], fp_cost=5, fn_cost=1),
s.best_f1_threshold([0, 1], [0.1, 0.9]),
]
for score in fixtures:
assert 0.0 <= score.value <= 1.0, f"{score.name} value={score.value}"
def test_combining():
case = {"expected": "Paris"}
graders = {"exact": s.case_scorer(s.exact_match, "expected")}
assert s.run_graders(case, "Paris", graders).passed is True
assert s.run_graders(case, "paris", graders).passed is False
verdicts = [s.run_graders(case, "Paris", graders),
s.run_graders(case, "London", graders)]
agg = s.aggregate(verdicts)
assert agg["pass_rate"] == 0.5 and agg["mean_score"] == 0.5
# weights move the soft aggregate but never outvote a hard gate
soft = {"f1": s.case_scorer(s.token_f1, "expected"),
"edit": lambda case, out: s.edit_distance_score(out, case["expected"])}
v_eq = s.run_graders(case, "Paris!", soft)
v_w = s.run_graders(case, "Paris!", soft, weights={"f1": 3.0})
assert v_eq.value != v_w.value # f1=1.0 vs edit≈0.83 — weighting moved the mean
gated = {"exact": s.case_scorer(s.exact_match, "expected"),
"f1": s.case_scorer(s.token_f1, "expected")}
v_gate = s.run_graders(case, "Paris extra", gated, weights={"f1": 100.0})
assert v_gate.passed is False # exact hard-fails despite f1's huge weight8.2 Worked example: grading a ticket-triage output#
# grade_triage.py — one case through the whole suite, three ways:
# equal weights, a weighted suite, and a non-JSON output that must fail.
# Run from the project root (the folder that contains evalkit/).
from evalkit import scorers as s
CASE = {"input": "My invoice shows two charges for March.",
"expected": {"category": "billing", "priority": "P2"},
"slice": "billing"}
# the model returned parsed JSON — right category, WRONG priority (P3, not P2)
OUTPUT = {"category": "billing", "priority": "P3", "summary": "Duplicate charge"}
graders = {
"schema": lambda case, out: s.schema_valid(out, {
"type": "object", "required": ["category", "priority"],
"properties": {"category": {"type": "string"},
"priority": {"enum": ["P1", "P2", "P3"]}}}),
"fields": lambda case, out: s.json_field_match(
out, case["expected"], ignore=["summary"]),
"priority_enum": lambda case, out: s.regex_match(
str(out.get("priority", "")), r"^P[123]$"),
"length": lambda case, out: s.length_within(
str(out.get("summary", "")), max_words=30),
}
v = s.run_graders(CASE, OUTPUT, graders)
v_weighted = s.run_graders(CASE, OUTPUT, graders, weights={"fields": 3.0})
v_bad = s.run_graders(CASE, "I cannot help with that.", graders)
for label, verdict in (("equal", v), ("fields x3", v_weighted), ("non-JSON", v_bad)):
print(label, "->", verdict.passed, round(verdict.value, 3))
for sc in verdict.scores:
print(f" {sc.name:16s} value={sc.value:.2f} passed={sc.passed}")equal -> True 0.875
schema value=1.00 passed=True
fields value=0.50 passed=None
priority_enum value=1.00 passed=True
length value=1.00 passed=True
fields x3 -> True 0.75
schema value=1.00 passed=True
fields value=0.50 passed=None
priority_enum value=1.00 passed=True
length value=1.00 passed=True
non-JSON -> False 0.0
schema value=0.00 passed=False
fields value=0.00 passed=False
priority_enum value=0.00 passed=False
length value=0.00 passed=FalseThree lessons in one run. priority_enum passes on "P3" — the enum check verifies shape, not correctness; only fields catches that P3 ≠ expected P2, which is why field-level grading exists. fields x3 drops the soft aggregate (0.875 → 0.75) because fields is the grader that actually measures correctness — weighting the dimension that matters makes the score more sensitive to the miss, not less. And non-JSON fails hard on every grader: a grader that raises becomes a failed score rather than crashing the run, and no weight can outvote a hard failure — that is the whole point of gates vs scores.
8.3 Aggregation: mean vs pass rate vs worst slice#
aggregate gives you four numbers that answer different questions: mean_score (graded quality), pass_rate (fraction fully passing all hard gates), slices/worst_slice (the tail the average hides), and macro_slice_score — the unweighted mean of per-slice mean scores, so a huge easy slice can't dominate the headline the way it does in the pooled mean_score. Report them together — a 0.9 mean with a 0.4 worst-slice is a different product than a flat 0.9.
The last combination decision is weighted scores vs hard gates, and §8.2 just showed both halves. weights in run_graders is for soft measurements: when correctness matters more than format, triple the weight of the grader that measures it — the aggregate then reflects your priorities instead of an arbitrary equal split. But weights are a dial on the average, not a veto: an invariant (must parse, must not leak PII, must cite) stays a passed=False gate, because "95% of the time we emit PII but the score is high" is not a trade-off, it's a breach. Rule of thumb: weight the quality dimensions, gate the invariants.
8.4 The decision table: which grader for which task#
| Task shape | First-choice graders | Add when |
|---|---|---|
| Classification / routing | classification_prf (macro), confusion_matrix |
per-class thresholds, expected_cost |
| Extraction to JSON | schema_valid + json_field_match |
numeric_match/date_match/quantity_match per field, grounding checks |
| Short canonical answers | normalized_match → numeric_match/date_match/quantity_match |
token_f1 for near-miss diagnostics |
| SQL / code generation | sql_equivalent, run_code_tests |
tool_call_prf for the trajectory |
| Tool-use trajectories | tool_call_prf, tool_calls_match |
step-level checks (10A.7) |
| Summaries / open answers | rouge_l/chrf/token_f1 as tripwires + meteor_score (nltk) for paraphrase + embedding_scorer |
LLM judge (10A.4) for quality |
| Format/contract | json_well_formed, schema_valid, required_patterns, length_within |
— |
| Safety/compliance | pii_scan, forbidden_terms/banned_patterns, toxicity_score, citation_check, links_valid |
judge for nuance (10A.4, Module 12) |
| Robustness | invariance_check, directional_check, agreement_rate |
perturbation suites (10A.5 covers judge variance) |
| Operations | operational_summary on RunRecords |
cost/latency budgets (10A.8) |
8.5 Failure gallery#
- BLEU on chatty outputs: a correct, thorough answer scores 0.0 against a terse reference — paraphrase kills n-gram precision. Use overlap metrics as tripwires only.
- Exact match on harmless variation:
"Paris"vs"paris."failsexact_match; usenormalized_matchfor short answers and reserveexact_matchfor canonical values (codes, yes/no, IDs). - Accuracy on imbalanced data: 95% accuracy with macro-F1 0.41 — the model never predicts the rare class. Report per-class and choose the right
average. - Regex too strict:
required_patterns(r"\[\d+\]")fails a perfectly good answer citing "(see source 1)". Too loose:forbidden_terms(["guarantee"])misses "guaranteed". Match the pattern to the real contract, and test both directions. contains_anynegation blindness: "You will not receive a refund" passes a "must mention refund" check. Presence ≠ correctness.json_field_matchon volatile fields: agenerated_attimestamp fails every comparison — useignore=[...].run_code_testswithout a sandbox: fine for trusted fixtures; a hard no for untrusted model code in production.- Operational metrics faked: reporting
ttft_ms=0for non-streaming calls instead ofNonecorrupts your p95. Record what the provider actually returned. - Unit regex substring matches: an unanchored
malternative reads "5 mi" as 5 metres (about 8 km in truth), "500 mg" as 500 metres and "30 min" as 30 metres, so wrong answers pass or right ones fail with no visible symptom. The unit alternation is longest-first with a trailing letter boundary; time units are deliberately not quantities. pii_scanon dates: the old loose phone pattern flagged "2026-03-04" as a phone number. The current pattern needs separator-delimited groups — but space-separated card numbers are still phone-shaped, so don't assume zero false positives.sql_equivalenton NULLs: sorting result tuples crashed onNonemixed with values; results now compare as multisets (Counter) — duplicates count, order doesn't, NULLs are fine. ButLIMITwithoutORDER BYmakes even correct query pairs flaky.
8.6 Reproducing the Real output blocks: demo_scorers.py#
Save this as demo_scorers.py in the project root (beside evalkit/) and run python3 demo_scorers.py. It needs only the standard library and the evalkit/scorers.py you assembled in Parts 2 to 8. show() prints one line per score with a hand-picked slice of detail, which is how the earlier blocks keep each line short.
# demo_scorers.py — reproduces the "Real output" blocks of lesson 10A.3.
# Run from the project root (the folder that contains evalkit/): python3 demo_scorers.py
import json
from pprint import pprint
from evalkit import scorers as s
def show(label, score, *keys):
"""One line per score: label, value, passed, and a hand-picked slice of detail."""
picked = {k: score.detail[k] for k in keys if k in score.detail}
picked = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in picked.items()}
if "output_tail" in picked: # keep only the last line of a long test log
picked["output_tail"] = picked["output_tail"].splitlines()[-1]
extra = f" {json.dumps(picked, ensure_ascii=False)}" if picked else ""
print(f"{label:34s} value={score.value:.3f} passed={score.passed}{extra}")
print("-- 2.2 matching")
show("exact_match('Paris','Paris')", s.exact_match("Paris", "Paris"))
show("exact_match('Paris','paris')", s.exact_match("Paris", "paris"))
show("normalized_match case+punct", s.normalized_match("Paris.", "paris"))
show("contains_any refund", s.contains_any("Your refund was issued.", ["refund", "credit"]), "matched")
show("regex_match ISO date", s.regex_match("Due 2026-03-04.", r"\d{4}-\d{2}-\d{2}"), "match")
show("numeric_match '1,299.50'", s.numeric_match("Total: €1,299.50", "1299.5"), "got", "want")
show("numeric_match rel_tol 1%", s.numeric_match("Total: €1,299.50", "1310", rel_tol=0.01), "got", "want")
print("-- 2.3 quantities and dates")
show("quantity_match 5km vs 5000m", s.quantity_match("5 km", "5000 m"), "output")
show("quantity_match 5mi vs 8046.72m", s.quantity_match("5 mi", "8046.72 m"), "output")
show("quantity_match 500mg vs 0.5g", s.quantity_match("500 mg", "0.5 g"), "output")
show("quantity_match 30min (no unit)", s.quantity_match("30 min", "1800 s"), "reason")
show("quantity_match 68F vs 20C", s.quantity_match("68°F", "20°C"), "output")
show("date_match 'March 5, 2026'", s.date_match("Due March 5, 2026", "2026-03-05"), "output")
show("date_match 'March 5 2026'", s.date_match("March 5 2026", "2026-03-05"), "output")
show("date_match unparseable", s.date_match("due soon", "2026-03-05"), "reason")
print("-- 2.4 sets, JSON, schema, tool calls")
show("set_match tags", s.set_match(["a", "b"], ["b", "a"]))
show("jaccard near-miss", s.set_match(["a", "b", "c"], ["a", "b", "d"], exact=False), "intersection", "union")
show("json_field_match", s.json_field_match(
{"total": 1299.5, "currency": "EUR", "lines": 3, "note": "x"},
{"total": 1299.5, "currency": "EUR", "lines": 3, "note": "y"}), "fields")
show("schema_valid good", s.schema_valid({"total": 5}, {"type": "object", "required": ["total"]}), "validator")
show("tool_calls_match (key order)", s.tool_calls_match(
[{"name": "get_weather", "arguments": {"city": "Paris", "unit": "c"}}],
[{"name": "get_weather", "arguments": {"unit": "c", "city": "Paris"}}]))
show("tool_call_prf openai-style", s.tool_call_prf(
[{"function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}],
[{"name": "get_weather", "input": {"city": "Paris"}}]), "precision")
print("-- 2.5 SQL and code tests")
SCHEMA = "CREATE TABLE emp (name TEXT, dept TEXT);"
ROWS = ["INSERT INTO emp VALUES ('a','eng'),('b','ops')"]
show("sql_equivalent", s.sql_equivalent(
"SELECT dept, COUNT(*) FROM emp GROUP BY dept",
"SELECT dept, COUNT(*) AS n FROM emp GROUP BY dept ORDER BY dept",
schema_sql=SCHEMA, rows_sql=ROWS), "rows_a", "rows_b")
CODE = "def add(a, b):\n return a + b\n"
TESTS = ("from candidate import add\n\n"
"def test_add():\n assert add(2, 3) == 5\n\n"
"def test_zero():\n assert add(0, 0) == 0\n")
BAD = "def add(a, b):\n return a - b\n"
show("run_code_tests (pass)", s.run_code_tests(CODE, TESTS), "output_tail")
show("run_code_tests (fail)", s.run_code_tests(BAD, TESTS), "output_tail")
print("-- 3 classification, calibration, threshold, cost")
yt = ["billing"] * 8 + ["technical"] * 2
yp = ["billing"] * 7 + ["technical"] + ["billing"] * 2
show("accuracy (imbalanced)", s.accuracy(yt, yp), "numerator", "denominator")
for avg in ("macro", "micro", "weighted"):
show(f"prf {avg}", s.classification_prf(yt, yp, average=avg), "average")
cm = s.confusion_matrix(yt, yp)
print(f"confusion labels={cm['labels']} matrix={cm['matrix']}")
show("roc_auc", s.roc_auc([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]), "n_pos", "n_neg")
show("brier", s.brier_score([0, 1, 0], [[0.9, 0.1], [0.3, 0.7], [0.6, 0.4]]), "n")
bins, ece = s.reliability_bins([0, 1, 1, 1], [0.1, 0.8, 0.9, 0.7])
occupied = [{k: v for k, v in b.items() if k in ("count", "mean_confidence", "accuracy")} for b in bins if b["count"]]
print("reliability bins (first two of four occupied)", json.dumps(occupied[:2]), "...")
print(f"ECE = {ece:.3f}")
show("best_f1_threshold", s.best_f1_threshold([0, 0, 1, 1], [0.2, 0.5, 0.7, 0.9]), "threshold", "f1")
show("expected_cost fp=5 fn=1", s.expected_cost([0, 0, 1, 1], [1, 0, 0, 1], fp_cost=5, fn_cost=1), "mean_cost", "fp", "fn")
show("multilabel_prf", s.multilabel_prf([[1, 0], [0, 1], [1, 1], [0, 1]], [[1, 0], [0, 1], [1, 0], [0, 1]]), "average")
print("-- 4.3 text overlap")
show("token_f1", s.token_f1("The capital of France is Paris", "Paris"), "precision", "recall")
show("bleu identical", s.bleu_score("the cat sat on the mat", ["the cat sat on the mat"]), "precisions")
show("bleu paraphrase", s.bleu_score("a fast brown fox jumps", ["the quick brown fox"]), "note")
show("chrf", s.chrf_score("the cat sat on the mat", "the cat sat on the mat"))
show("edit char kitten/sitting", s.edit_distance_score("kitten", "sitting"), "distance")
show("embedding_cosine", s.embedding_cosine([0.2, 0.9, 0.4], [0.25, 0.8, 0.5]), "cosine")
print("-- 5.2 structural checks")
show("length_within fail", s.length_within("word " * 30, max_words=25), "words")
show("language_is stub es", s.language_is("Where is my order?", "es", detect=lambda text: "en"), "detected")
show("forbidden_terms stem-miss", s.forbidden_terms("We guaranteed delivery.", ["guarantee"]), "hits")
show("banned_patterns stem", s.banned_patterns("We guaranteed delivery.", [r"\bguarantee\w*\b"]), "hits")
show("citation_check", s.citation_check("Refunds take 30 days [1]."), "citations")
show("json_well_formed prose-wrapped", s.json_well_formed('Sure! {"a": 1} done'), "extracted")
show("pii_scan date-only", s.pii_scan("Invoice due 2026-03-04."), "findings")
show("pii_scan dirty", s.pii_scan("Mail jane@example.com or call +1 415 555 0132."), "findings")
print("-- 6 operational summary")
records = [
s.RunRecord("a", ttft_ms=250, total_ms=980, tokens_in=700, tokens_out=90, cost_usd=0.0021),
s.RunRecord("b", ttft_ms=320, total_ms=1450, tokens_in=820, tokens_out=110, cost_usd=0.0024, retries=1),
s.RunRecord("c", ttft_ms=410, total_ms=2100, tokens_in=1000, tokens_out=95, cost_usd=0.0021),
s.RunRecord("d", total_ms=600, error="rate_limited", timeout=True), # no usage reported
]
pprint(s.operational_summary(records))
print("-- 7.2 metamorphic")
outs = ["Paris", "paris", "Paris!", "The answer is Paris"]
show("agreement_rate (norm eq)", s.agreement_rate(outs), "pairs")
show("agreement_rate strict", s.agreement_rate(outs, same=lambda a, b: a == b), "pairs")
show("invariance_check", s.invariance_check("30 days", ["30 days", "30 Days.", "thirty days"]), "variants")
show("directional shorter", s.directional_check(
["A long answer with many words in it.", "Another fairly long answer."],
["Short.", "Brief."], lambda c, t: len(t) < len(c)), "pairs")-- 2.2 matching
exact_match('Paris','Paris') value=1.000 passed=True
exact_match('Paris','paris') value=0.000 passed=False
normalized_match case+punct value=1.000 passed=True
contains_any refund value=1.000 passed=True {"matched": ["refund"]}
regex_match ISO date value=1.000 passed=True {"match": "2026-03-04"}
numeric_match '1,299.50' value=1.000 passed=True {"got": 1299.5, "want": 1299.5}
numeric_match rel_tol 1% value=1.000 passed=True {"got": 1299.5, "want": 1310.0}
-- 2.3 quantities and dates
quantity_match 5km vs 5000m value=1.000 passed=True {"output": [5000.0, "m"]}
quantity_match 5mi vs 8046.72m value=1.000 passed=True {"output": [8046.72, "m"]}
quantity_match 500mg vs 0.5g value=1.000 passed=True {"output": [0.5, "g"]}
quantity_match 30min (no unit) value=0.000 passed=False {"reason": "no_unit_found"}
quantity_match 68F vs 20C value=1.000 passed=True {"output": [20.0, "°c"]}
date_match 'March 5, 2026' value=1.000 passed=True {"output": "2026-03-05"}
date_match 'March 5 2026' value=1.000 passed=True {"output": "2026-03-05"}
date_match unparseable value=0.000 passed=False {"reason": "no_date_found"}
-- 2.4 sets, JSON, schema, tool calls
set_match tags value=1.000 passed=True
jaccard near-miss value=0.500 passed=None {"intersection": 2, "union": 4}
json_field_match value=0.750 passed=None {"fields": {"total": true, "currency": true, "lines": true, "note": false}}
schema_valid good value=1.000 passed=True {"validator": "minischema"}
tool_calls_match (key order) value=1.000 passed=True
tool_call_prf openai-style value=1.000 passed=None {"precision": 1.0}
-- 2.5 SQL and code tests
sql_equivalent value=1.000 passed=True {"rows_a": 2, "rows_b": 2}
run_code_tests (pass) value=1.000 passed=True {"output_tail": "2/2 tests passed"}
run_code_tests (fail) value=0.000 passed=False {"output_tail": "AssertionError"}
-- 3 classification, calibration, threshold, cost
accuracy (imbalanced) value=0.700 passed=None {"numerator": 7, "denominator": 10}
prf macro value=0.412 passed=None {"average": "macro"}
prf micro value=0.700 passed=None {"average": "micro"}
prf weighted value=0.659 passed=None {"average": "weighted"}
confusion labels=['billing', 'technical'] matrix=[[7, 1], [2, 0]]
roc_auc value=0.750 passed=None {"n_pos": 2, "n_neg": 2}
brier value=0.173 passed=None {"n": 3}
reliability bins (first two of four occupied) [{"count": 1, "mean_confidence": 0.1, "accuracy": 0.0}, {"count": 1, "mean_confidence": 0.7, "accuracy": 1.0}] ...
ECE = 0.175
best_f1_threshold value=1.000 passed=None {"threshold": 0.7, "f1": 1.0}
expected_cost fp=5 fn=1 value=0.300 passed=None {"mean_cost": 1.5, "fp": 1, "fn": 1}
multilabel_prf value=0.900 passed=None {"average": "macro"}
-- 4.3 text overlap
token_f1 value=0.286 passed=None {"precision": 0.167, "recall": 1.0}
bleu identical value=1.000 passed=None {"precisions": [1.0, 1.0, 1.0, 1.0]}
bleu paraphrase value=0.000 passed=None {"note": "zero n-gram precision; sacrebleu would smooth"}
chrf value=1.000 passed=None
edit char kitten/sitting value=0.571 passed=None {"distance": 3}
embedding_cosine value=0.994 passed=None {"cosine": 0.989}
-- 5.2 structural checks
length_within fail value=0.000 passed=False {"words": 30}
language_is stub es value=0.000 passed=False {"detected": "en"}
forbidden_terms stem-miss value=1.000 passed=True {"hits": []}
banned_patterns stem value=0.000 passed=False {"hits": [{"pattern": "\\bguarantee\\w*\\b", "match": "guaranteed"}]}
citation_check value=1.000 passed=True {"citations": 1}
json_well_formed prose-wrapped value=1.000 passed=True {"extracted": true}
pii_scan date-only value=1.000 passed=True {"findings": {}}
pii_scan dirty value=0.000 passed=False {"findings": {"email": 1, "phone": 1}}
-- 6 operational summary
{'cost_coverage': 0.75,
'cost_per_reported_example_usd': 0.0022,
'cost_reported_examples': 3,
'cost_usd': 0.0066,
'error_rate': 0.25,
'mean_retries': 0.25,
'n': 4,
'refusal_rate': 0.0,
'retry_rate': 0.25,
'timeout_rate': 0.25,
'tokens_in': 2520,
'tokens_out': 295,
'total_p50_ms': 1215.0,
'total_p95_ms': 2002.5,
'total_p99_ms': 2080.5,
'ttft_p50_ms': 320.0,
'ttft_p95_ms': 401.0}
-- 7.2 metamorphic
agreement_rate (norm eq) value=0.500 passed=None {"pairs": 6}
agreement_rate strict value=0.000 passed=None {"pairs": 6}
invariance_check value=0.667 passed=None {"variants": 3}
directional shorter value=1.000 passed=None {"pairs": 2}Two environment notes. run_code_tests tries python -m pytest first: the output_tail shown here (2/2 tests passed, then the last line of an assertion log) comes from the built-in fallback runner that takes over when pytest is not installed, so with pytest installed the tail is pytest's own summary instead (for example 2 passed in 0.02s) while value and passed are unchanged. And schema_valid reports "validator": "minischema" unless the optional jsonschema package is installed, in which case it says "jsonschema".
What this means for you#
Try code before you try a judge: every criterion that can be checked mechanically should be — normalise before comparing, match the grader to the task shape, hard-gate the invariants and let soft scores carry the quality dimensions. evalkit/scorers.py is that layer — stdlib-only, every score inspectable — and its to_core_score/as_scorer bridge drops the same graders into 10A.1's run_eval unchanged. What remains for a judge is exactly what code can't express, which is 10A.4's subject — and 10A.5 is where an unvalidated judge becomes a validated instrument. However good the graders, keep the operational metrics (latency percentiles, tokens, cost, error and refusal rates) in every report beside the quality scores, and read worst_slice next to every mean: a quality number on a broken run is a rumour, and the tail is where the failures live.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "An LLM judge is the gold standard for everything." | It's rung 3 of the grader ladder. Code graders are cheaper, deterministic and debuggable — use them wherever the criterion is mechanically checkable, and reserve judges for what code can't express. |
| "Exact match is fine for short answers." | "Paris" vs "paris." fails. Use normalized_match for surface variation; reserve exact_match for canonical values (codes, IDs, yes/no). |
| "High accuracy means the classifier is good." | Under imbalance, predicting the majority class scores the majority share. Report per-class precision/recall/F1 and pick the average that matches error costs. |
| "BLEU/ROUGE measure quality." | They measure n-gram overlap. They correlate with human judgement on MT and summarisation baselines, fail on paraphrase, and are blind to factuality — tripwires, not verdicts. METEOR narrows the paraphrase gap via stems and WordNet synonyms, but stays lexical. |
| "Valid JSON means correct output." | Schema validity is the shape check, not the content check. Pair schema_valid with json_field_match/numeric_match — a schema-valid invoice can have the wrong total. |
| "A contains-check proves the answer mentions X correctly." | contains_any sees presence, not correctness — "You will not receive a refund" contains "refund". Negation and context need patterns or a judge. |
| "p95 latency is the average." | Percentiles describe the tail. Report p50/p95/p99, and keep None for metrics the provider didn't return (e.g. TTFT on non-streaming) rather than faking zeros. |
| "Metamorphic tests prove correctness." | They prove consistency and invariance — a necessary property, never a sufficient one. A model can be consistently wrong. |
| "More graders always means a better eval." | Every grader is a place to be wrong. A brittle regex that fails correct answers poisons your data faster than no grader. Gate on invariants, measure on quality, and audit failures. |
Key takeaways#
- Try code first. Every criterion that can be checked mechanically should be — it's free, instant, deterministic and explainable. LLM judges (10A.4) are for what remains.
- Normalise before comparing. Case, punctuation, whitespace and Unicode form are surface noise;
normalize_textcanonicalises them so"Paris"and"paris."compare equal. - Match the grader to the task shape. Classification → P/R/F1 + confusion matrix. Extraction → schema + per-field. SQL/code → execute. Trajectories → tool-call P/R/F1. Open text → overlap tripwires + judges.
- Imbalance and cost change the metric. Accuracy lies on skewed data;
expected_costprices asymmetric errors. Chooseaverageand thresholds deliberately. - Overlap metrics are tripwires. BLEU/ROUGE/chrF catch regressions and format breaks; they cannot judge open-ended quality.
- Operational metrics are quality metrics. Latency percentiles, tokens, cost per example, error/refusal/retry rates belong in every run report — a "good" score on a broken run is meaningless.
- One test input is a sample. Execution-based graders (SQL, code) need several fixtures or tests that include edge cases, or a wrong answer that fits one fixture passes.
- Test invariants, not just outputs. Invariance, directional and agreement checks catch robustness bugs that single-example correctness misses.
- Combine with gates, weights and slices. Hard failures veto;
weightstune the soft aggregate;worst_sliceandmacro_slice_scoreexpose the tail the mean hides.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Normalisation | Canonicalising text — Unicode form, case, punctuation, whitespace — before comparison so surface variation doesn't read as difference |
| Confusion matrix | A table of true-vs-predicted label counts; rows are truth, columns are predictions, and every classification metric derives from it |
| Micro / macro / weighted averaging | Three ways to pool per-class scores: micro pools all decisions (≈ accuracy), macro averages classes equally, weighted averages by class frequency |
| Expected Calibration Error (ECE) | The average gap between a model's stated confidence and its actual accuracy across confidence bins — 0 is perfectly calibrated |
| Brier score | Mean squared error between predicted probabilities and 0/1 outcomes — a proper scoring rule that penalises both wrong answers and overconfidence |
| Brevity penalty | The BLEU factor that discounts hypotheses shorter than the reference — without it, "cat" would outscore a full sentence |
| Modified n-gram precision | BLEU's clipping rule: a hypothesis n-gram counts at most as many times as it appears in any single reference, so repetition can't game the score |
| METEOR | Unigram alignment allowing stem and WordNet-synonym matches plus a fragmentation penalty — partial credit for paraphrase that BLEU zeroes |
| Invariance test | A metamorphic check asserting that semantically equivalent inputs (paraphrases, reorders, typos) produce equivalent outputs |
| Directional test | A metamorphic check asserting that a controlled input change (adding a constraint) moves the output in the expected direction |
| Cross-lingual consistency | A metamorphic check asserting the same question in different languages yields the same substance of answer |
| Self-consistency rate | The fraction of repeated-run output pairs that agree — a direct measure of how non-deterministic a feature is in practice |
| Hard gate vs soft score | A hard gate (passed=False) fails the example outright; a soft score (passed=None) only feeds aggregates — the split between invariants and quality measurements |
| Weighted aggregation | run_graders(weights=...) — per-grader weights on the soft mean; they tune the aggregate but can never outvote a hard gate |
| Worst-slice metric | The minimum pass rate across data slices — exposes the tail that an overall mean conceals |
| Macro slice score | The unweighted mean of per-slice mean scores — stops a huge easy slice dominating the headline number |
| Execution accuracy / test-suite accuracy | Grading SQL (or code) by running it: on one database (execution accuracy, can over-credit) or on several databases built to tell wrong queries apart (test-suite accuracy) |
| Learned metric | A model trained to predict human quality ratings (COMET, BLEURT, BERTScore-style): better correlated than n-gram overlap, but still a model to validate |
Exercises#
All exercises run locally with uv run python — no API keys. The evalkit package is the one you built in Parts 2–8.
- Normalisation trap. Using
evalkit.scorers, show thatnormalized_match("Paris.", "paris")passes whileexact_matchfails. Then show what NFKC does and does not do:normalized_match("Café", "Cafe\u0301")passes (composed and decomposed forms of é are unified) butnormalized_match("Café", "cafe")fails, because normalisation does not strip accents. Would you want it to for your task, and how would you do it (hint:unicodedata.normalize("NFD", ...)then drop combining marks)? Finally find an input wherenormalize_textover-normalises — e.g. it strips a meaningful punctuation distinction ("C++" versus "C") — and argue whether that's acceptable. - Numeric tolerance. Grade three outputs against expected
"1299.5":"Total: €1,299.50","about 1300 euros","€1,299.51". Withrel_tol=0.001, which pass? Explain why"about 1300"failing atrel_tol=0is correct behaviour, not a bug. - Imbalance audit. Build a 20-example binary set with 18 negatives. Show
accuracyfor a model that always predicts negative, thenclassification_prf(average="macro")andconfusion_matrix. Write two sentences a PM would understand explaining why the second number matters more. - Calibration by hand. Using
reliability_binson 10 examples with confidences[0.9]*5 + [0.6]*5and outcomes[1,1,0,1,0, 1,0,0,1,0], compute the ECE and identify which bin is miscalibrated. (Hint: print the bins. Check: the 0.9 bin has accuracy 0.6 and the 0.6 bin has accuracy 0.4, so ECE = 0.5 × 0.3 + 0.5 × 0.2 = 0.25; both bins are over-confident.) - BLEU's blind spot. Score
"a fast brown fox jumps over the lazy dog"against reference"the quick brown fox jumps over the lazy dog"withbleu_score. Then against"the quick brown fox". Explain the difference in scores using the precisions indetail. - Structural gates. Write a
run_graderssuite for a "refund policy answer" case that hard-gates on: valid JSON, schema witheligible: boolean, no PII, at least one citation marker, ≤40 words. Run it against three outputs: perfect, schema-valid-but-no-citation, and non-JSON prose. - Metamorphic probe. Take 5 inputs, generate 2 paraphrases each (hand-write them), and run
invariance_checkwithnormalized_matchas thesamefunction. Report the agreement rate and identify which paraphrase broke it. - Operational summary. Construct 6
RunRecords simulating a run with 1 timeout, 1 refusal, 2 retries and realistic latencies. Printoperational_summaryand circle the number that would most worry you in a production deploy review.
Check yourself#
- Why is "always try code graders first" the right default, and what's the counter-argument?Code graders are free, instant, deterministic and explainable — the counter-argument is coverage: code can only check what you can express mechanically, so open-ended quality still needs judges and humans.
exact_match("Paris", "paris")fails butnormalized_matchpasses. What does normalisation strip, and when could that stripping be wrong?Case, punctuation, whitespace and Unicode compatibility forms. Over-normalisation hurts when the distinction is meaningful — "C++" and "C" both collapse to "c", and "don't" loses its apostrophe.- A classifier gets 95% accuracy on data that's 95% negative. What's wrong with that number, and which two metrics fix it?It hides the minority class — a model predicting only the majority scores the majority share. Per-class precision/recall/F1 and the confusion matrix expose it; macro F1 weights classes equally.
bleu_scorereturns 0.0 withnote: "zero n-gram precision"on a fluent paraphrase. Is the answer wrong? What should you use instead?No — the answer may be a correct paraphrase; zero n-gram precision means no shared n-grams, not wrongness. Use it as a tripwire; judge or human-review for quality.- What's the difference between
passed=False,passed=Trueandpassed=Nonein aScore, and how doesrun_graderstreat each?passed=Falsehard-fails the example;passed=Truepasses the gate;passed=Noneis a measurement feeding only aggregates.run_gradersfails the verdict if any score is False and averages every non-failed value. schema_validpasses butjson_field_matchscores 0.6. What does that combination tell you?The output has the right shape but wrong or missing field values — schema checks structure, field match checks content. Pair them: shape first, then per-field accuracy.- Why does
run_code_testsneed a sandbox in production even though it has a timeout?A timeout stops hangs, not adversaries — model-written code is remote-code-execution; it can exhaust memory, spawn processes or reach the network before the timeout matters. Production needs a container with no network and resource caps. agreement_rate(["Paris", "paris", "Paris!"])is 1.0 under normalised equality and lower under==. What does that gap measure?It measures formatting and non-determinism slack — how much surface variation your equality check tolerates. The gap is the difference between "same answer" and "same bytes".- Which is worse for a support bot: high mean score with low worst-slice, or low mean with high worst-slice? Why report both?For a support bot, low worst-slice means some user segment gets broken answers — usually worse than a mediocre mean. Report both because the mean hides exactly that tail.
- Name three operational metrics that belong in every eval run report alongside quality scores.Error rate, timeout rate and refusal rate (plus retries, latency percentiles and cost per example) — they tell you whether the run measured quality or infrastructure.
sql_equivalentsays a candidate query is equivalent to the gold query. Why might that be wrong, and what is the cheap fix?Equivalence by execution only proves the same rows on that one database; a wrong query can coincide on a small fixture. Run the pair against two or three fixtures with deliberately different data (test-suite accuracy) and require all to pass.
Further resources#
- sacreBLEU — the reproducible BLEU/chrF/TER implementation (
sacrebleu2.6.0): https://github.com/mjpost/sacrebleu - scikit-learn metrics guide — the reference for classification metrics: https://scikit-learn.org/stable/modules/model_evaluation.html
- JSON Schema — the spec behind
schema_valid(03.4 covers usage): https://json-schema.org/ - Hypothesis — property-based testing (
hypothesis6.170.15): https://hypothesis.readthedocs.io/ - BERTScore — contextual-embedding similarity (
bert-score0.3.13): https://github.com/Tiiiger/bert_score - ROUGE — the original summarisation metrics paper: Lin, "ROUGE: A Package for Automatic Evaluation of Summaries" (2004)
- Papineni et al., "BLEU: a Method for Automatic Evaluation of Machine Translation" (ACL 2002)
- JiWER — WER/CER library (
jiwer4.0.0): https://jitsi.github.io/jiwer/
← 10A.2 — Building Evaluation Datasets | Module 10A overview | 10A.4 — LLM-as-Judge →