Code-based scorers and metrics
A scorer turns one model output into a verdict or a number. Code-based scorers do this with ordinary code: parsing, pattern matching, comparison with a reference, arithmetic. They are free, instant, perfectly reproducible and free of the biases of model judges, which makes them the first layer of every evaluation suite. Their limit is equally clear: they can only check what can be specified mechanically, and a badly designed scorer measures the wrong thing with great precision.
This chapter builds the common code-based scorers from first principles, shows exactly where each one fails, and treats scorers as software that needs its own tests and validation.
Prerequisites: Evaluation methodology and datasets, Structured output and validation.
What a code-based scorer is
A scorer is a function from a test case and an output to a score with a reason:
scorer(case, output) -> Score(passed: bool or value: float, reason: str)
case the input plus everything needed to judge it: reference answer, expected facts,
allowed sources, labels, tags for slicing
output what the system produced for that input
reason why the scorer decided as it did, so that a failure can be read without re-running anythingGood scorers share four properties:
- Deterministic: the same case and output always give the same score.
- Explainable: the reason names the rule that failed and the evidence ("found ['60']").
- Versioned: a change to a scorer changes every result it produces, so scorers live in version control and their version is stored with results.
- Tested: a scorer is code with its own unit tests and, for anything non-trivial, validation against human labels.
Assertions that need no reference
Many requirements can be checked from the output alone, or from the output and the input:
| Assertion | How to implement it | Example failure it catches |
|---|---|---|
| Valid JSON / schema | Parse and validate against the contract | Truncated object, missing field |
| Length limits | Count words, characters or tokens | A 300-word answer where 120 are allowed |
| Required and forbidden phrases | Patterns with accepted wordings | Missing link to the returns page; "guaranteed refund" |
| Language | Script detection and language-specific letters | English reply to a Ukrainian question |
| Personal data | Patterns for e-mail, phone, IBAN, card numbers | Another customer's e-mail address in a reply |
| Citations | Every cited ID is in the retrieved set | A citation that points to a document never retrieved |
| Links | Every URL is on an allow-list | A link to a look-alike domain |
| Numbers | Extract numbers with units and compare | "60 days" where the policy says 30 |
These checks were introduced in earlier chapters (Prompts as testable artifacts, Structured output and validation). The rest of this chapter covers scores that compare an output with a reference, and the infrastructure around scorers.
Exact match and token F1
For short factual answers, the classic metrics come from extractive question answering (the SQuAD benchmark):
normalize(text) lowercase, remove punctuation and the articles a/an/the, collapse whitespace
exact match (EM) 1 if normalize(prediction) == normalize(reference), else 0
token F1 precision = shared tokens / prediction tokens
recall = shared tokens / reference tokens
F1 = 2 · precision · recall / (precision + recall)Run the code to see the result.
Output:
EM=1 F1=1.00 '30 days from delivery'
EM=1 F1=1.00 'The 30 days, from delivery!'
EM=0 F1=0.60 'Within 30 days of the delivery date'
EM=0 F1=0.75 '60 days from delivery'
EM=0 F1=0.00 'You have a month after the parcel arrives'The last three lines contain the whole lesson. The wrong answer "60 days from delivery" scores higher F1 than a correct paraphrase, and a correct answer worded differently scores zero. Token overlap measures wording, not truth. Exact match and F1 are appropriate when the expected answer is short and its wording is fixed: labels, IDs, extracted values, names. For free-text answers, check facts instead.
Fact-based scoring
A fact-based scorer encodes what a correct answer must say, what it must not say, and how to recognise each fact in different wordings. For the question "Can I return shoes after 40 days?":
- Required: the return window is 30 days (accepted wordings: "30 days", "thirty days", "one month"); the window counts from delivery ("delivery", "delivered", "arrives").
- Forbidden: promising an exception; any day count other than the policy value.
The script below implements this scorer twice. The first version has a realistic bug, and the only way to find it is to compare the scorer with human judgement.
Run the code to see the result.
Output:
naive scorer
human=True scorer=False ["unsupported day count ['40']"]
human=True scorer=False ["unsupported day count ['40']"]
human=False scorer=False ['return window is 30 days', "unsupported day count ['60']"]
human=False scorer=False ['return window is 30 days', 'counted from delivery', 'promises an exception']
agreement with human labels: 2/4
fixed scorer
human=True scorer=True []
human=True scorer=True []
human=False scorer=False ['return window is 30 days', "unsupported day count ['60']"]
human=False scorer=False ['return window is 30 days', 'counted from delivery', 'promises an exception']
agreement with human labels: 4/4The naive rule "no day count other than 30" rejects both good answers, because good answers repeat the customer's own "40 days". The scorer looked reasonable and would have reported a false regression on every correct answer. Two practices prevent this:
- Design facts from real outputs. Read a sample of good and bad answers before writing patterns, and include the ways correct answers actually phrase things.
- Validate the scorer against human labels before trusting it, exactly as you would validate a model judge (LLM-as-a-judge). Keep the labelled answers as unit tests of the scorer.
BLEU and ROUGE, step by step
BLEU (from machine translation) and ROUGE (from summarization) compare n-grams, sequences of n consecutive words, between a candidate and a reference:
BLEU p_n = clipped n-gram matches / candidate n-grams (n = 1..4; clipping counts each
reference n-gram at most as often
as it occurs in the reference)
BP = 1 if candidate is longer than the reference, else exp(1 − reference length / candidate length)
BLEU = BP · exp( (1/4) Σ log p_n ) (precision-oriented)
ROUGE-n recall = n-gram overlap / reference n-grams (recall-oriented)
ROUGE-L = F1 of the longest common subsequence (LCS) of words
= 2 · LCS / (candidate length + reference length)Run the code to see the result.
Output:
same words BLEU=1.00 ROUGE-1 recall=1.00 ROUGE-2 recall=1.00 ROUGE-L F1=1.00
correct paraphrase BLEU=0.07 ROUGE-1 recall=0.10 ROUGE-2 recall=0.00 ROUGE-L F1=0.08
wrong number BLEU=0.70 ROUGE-1 recall=0.90 ROUGE-2 recall=0.78 ROUGE-L F1=0.90
opposite meaning BLEU=0.74 ROUGE-1 recall=0.90 ROUGE-2 recall=0.78 ROUGE-L F1=0.90The answer with the wrong number and the answer with the opposite meaning both score around 0.7 to 0.9; the correct paraphrase scores 0.1 or less. Research on natural-language generation found that these metrics correlate weakly with human judgement for open-ended text, and BLEU values are not even comparable across papers unless tokenization is standardized (the purpose of the sacreBLEU tool). Library defaults matter as well: the default tokenizer of the rouge-score package keeps only the characters a–z and 0–9, so Ukrainian text gets no tokens at all unless you pass your own tokenizer.
Where n-gram metrics remain useful:
- Regression smoke checks of near-deterministic outputs, where any large drop in overlap with the previous version is worth a look.
- Translation and text normalization tasks with several references, where wording is part of the requirement.
- Corpus-level trends across thousands of outputs, not single-case decisions. BLEU was originally defined for a whole test set, with n-gram counts summed over all sentences; the average of sentence scores is a different number.
Embedding similarity and BERTScore
Embedding similarity compares meaning rather than wording, so it rewards correct paraphrases. It still scores negation, wrong numbers and swapped roles as close (Embeddings and similarity). BERTScore matches each token of the candidate with its most similar token in the reference using contextual embeddings; it correlates better with human judgement than n-grams but inherits the same blindness to small, meaning-changing edits.
# Run on your own machine: pip install bert-score
from bert_score import score
candidates = ["you may send back shoes you have not worn for a month after they arrive"]
references = ["unworn shoes can be returned within 30 days of delivery"]
precision, recall, f1 = score(candidates, references, lang="en")
print(f"BERTScore F1 = {f1[0]:.3f}")Use similarity scorers as pre-filters and trend signals: an off-topic answer scores low and can fail early; a high score never proves correctness on its own.
Classification metrics
Many LLM features are classifiers in disguise: ticket triage, intent detection, guardrails, the "needs a human" flag, a judge's PASS/FAIL. For those, use classification metrics on a labelled set.
Run the code to see the result.
Output:
human vs model billing returns technical other
billing 5 1 0 0
returns 0 6 0 1
technical 0 0 3 2
other 0 1 0 1
billing precision=1.00 recall=0.83 F1=0.91 support=6
returns precision=0.75 recall=0.86 F1=0.80 support=7
technical precision=1.00 recall=0.60 F1=0.75 support=5
other precision=0.25 recall=0.50 F1=0.33 support=2
accuracy=0.75 macro F1=0.70 weighted F1=0.77How to read it:
- Accuracy (0.75) hides which classes fail. The confusion matrix shows that technical tickets leak into "other" (recall 0.60): those customers wait for the wrong team.
- Macro F1 averages classes equally, so small classes count as much as large ones; weighted F1 follows the class frequencies. Report the one that matches the business question, and always show per-class numbers.
- Precision versus recall is a cost decision: for the escalation flag, missing a case (low recall) is usually worse than escalating unnecessarily (low precision).
- Twenty cases are far too few for decisions; the point here is the method. Sample sizes are covered in Statistics for evaluation.
Execution-based scoring
When the output is code, a query or a calculation, the strongest scorer executes it:
- Generated code: run it against unit tests in a sandbox (an isolated container or process with no network, limited CPU, memory and time). The HumanEval benchmark popularized this, together with the pass@k measure for several attempts.
- Generated SQL: run the query on a fixed test database and compare result sets, not query text; two different queries can be equally correct. A wrong query can also return the right rows by coincidence on one small database, so run each query on several databases built to tell such queries apart (test-suite accuracy), read-only and with a time or step limit.
- Generated calculations or plans: recompute the answer with trusted code and compare values with an explicit tolerance.
Executing model-generated code is a security risk in its own right: never run it in the evaluation process itself or with access to secrets or the network.
Building a scoring harness
In practice several scorers run on every case, and results are aggregated overall and by slice (language, feature, difficulty). A slice that fails while the average looks fine is the most common way regressions hide.
Run the code to see the result.
Output:
all pass rate 3/5 = 60%
lang=en pass rate 2/3 = 67%
lang=uk pass rate 1/2 = 50%
FAIL ('r2', 'expected_days', "found ['60']")
FAIL ('r4', 'valid_json', 'Expecting value: line 1 column 1 (char 0)')
FAIL ('r4', 'max_40_words', 'not JSON')The harness design choices that matter: every failure carries its case ID, scorer name and reason; slices are computed from case tags, not hard-coded; scorers are plain functions, so each can be unit-tested and reused by evaluation frameworks such as promptfoo or DeepEval, which accept custom code assertions.
Testing and validating scorers
A scorer that is wrong produces confident, wrong evaluation results. Protect scorers like production code:
- Unit tests with adversarial outputs: for each scorer, outputs that must pass (including unusual correct wordings) and outputs that must fail (including near misses such as "60 days").
- Properties: scores stay within their range, identical text gets the maximum score, a scorer never crashes on empty, huge or malformed output.
- Linear time: a scorer runs on every output, including a runaway one of 200,000 characters; a regular expression that backtracks quadratically turns that output into a hung evaluation run.
- Agreement with human labels: for any scorer that interprets language, measure agreement on a labelled sample and keep that sample as a regression test of the scorer.
- Versioning: when a scorer changes, re-score the baseline with the new version before comparing; otherwise a scorer fix looks like a model regression or improvement.
Example project
The method of this chapter is implemented and tested in examples/llm-testing/09-code-based-scorers: exact match, token F1, BLEU and ROUGE with property-based tests, classification metrics for the triage example, a bilingual fact scorer validated against human labels, a scoring harness that compares two versions of a system slice by slice, and execution-based scoring of generated SQL on read-only fixture databases. All tests run offline, without a model or API keys:
uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/09-code-based-scorersCommon mistakes
- Using token overlap (F1, BLEU, ROUGE) to judge free-text correctness, which rewards wrong answers with familiar wording.
- Writing fact patterns from the reference answer only, without reading how correct outputs are actually phrased.
- Trusting a scorer that was never compared with human labels.
- Reporting only an average: no per-class or per-slice results, no failure reasons.
- Comparing results produced by different scorer versions.
- Running generated code in the evaluation process without a sandbox.
Summary
- Code-based scorers are the cheapest, fastest and most reproducible layer of evaluation; they must be deterministic, explainable, versioned and tested.
- Exact match and token F1 suit short answers with fixed wording; for free text they reward wording, not truth.
- Fact-based scorers encode required and forbidden facts with accepted wordings, and must be validated against human labels, as the "40 days" bug shows.
- BLEU and ROUGE score wrong numbers and opposite meanings highly; use them for trends and near-deterministic outputs only.
- Embedding similarity and BERTScore reward paraphrases but miss small meaning-changing edits; use them as filters.
- Classification features need confusion matrices and per-class precision and recall chosen by cost; executed code and queries are best scored by execution in a sandbox.
- A scoring harness reports every failure with its reason and every slice separately.