Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 12 / 20

Generative AI & LLM

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 anything

Good 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:

AssertionHow to implement itExample failure it catches
Valid JSON / schemaParse and validate against the contractTruncated object, missing field
Length limitsCount words, characters or tokensA 300-word answer where 120 are allowed
Required and forbidden phrasesPatterns with accepted wordingsMissing link to the returns page; "guaranteed refund"
LanguageScript detection and language-specific lettersEnglish reply to a Ukrainian question
Personal dataPatterns for e-mail, phone, IBAN, card numbersAnother customer's e-mail address in a reply
CitationsEvery cited ID is in the retrieved setA citation that points to a document never retrieved
LinksEvery URL is on an allow-listA link to a look-alike domain
NumbersExtract 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)
Python
editable · browser sandbox
Result
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.

Python
editable · browser sandbox
Result
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/4

The 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)
Python
editable · browser sandbox
Result
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.90

The 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.

Python
editable · browser sandbox
Result
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.77

How 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.

Python
editable · browser sandbox
Result
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-scorers

Common 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.

Source registry

18 chapter references
SQuAD: 100,000+ Questions for Machine Comprehension of Text

Exact match and token F1 with answer normalization, the classic metrics for short factual answers.

Rajpurkar et al. — arXiv / EMNLP 2016 · paper
Source ↗
BLEU: a Method for Automatic Evaluation of Machine Translation

Clipped n-gram precision, the brevity penalty and BLEU as a corpus-level metric.

Papineni et al. — ACL 2002 · paper
Source ↗
ORANGE: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation

Add-one smoothing of the higher-order n-gram precisions used for sentence-level BLEU.

Lin and Och — COLING 2004 · paper
Source ↗
A Systematic Comparison of Smoothing Techniques for Sentence-Level BLEU

Why sentence-level BLEU needs smoothing and how the smoothing methods compare.

Chen and Cherry — WMT 2014 · paper
Source ↗
ROUGE: A Package for Automatic Evaluation of Summaries

ROUGE-N recall and ROUGE-L based on the longest common subsequence.

Chin-Yew Lin — ACL 2004 Workshop · paper
Source ↗
rouge-score

Widely used ROUGE implementation; its default tokenizer keeps only a-z and 0-9, so non-Latin text needs a custom tokenizer.

Google Research · tool
Source ↗
A Call for Clarity in Reporting BLEU Scores

BLEU values are comparable only with standardized tokenization; introduces the sacreBLEU tool.

Matt Post — WMT 2018 · paper
Source ↗
Why We Need New Evaluation Metrics for NLG

Word-overlap metrics correlate weakly with human judgements of generated text.

Novikova et al. — EMNLP 2017 · paper
Source ↗
BERTScore: Evaluating Text Generation with BERT

Token matching with contextual embeddings as a similarity metric for generated text.

Zhang et al. — arXiv / ICLR 2020 · paper
Source ↗
Metrics and scoring: quantifying the quality of predictions

Precision, recall and F1 per class, and the macro, weighted and micro averages.

scikit-learn · official docs
Source ↗
Evaluating Large Language Models Trained on Code

HumanEval: functional correctness of generated code by executing unit tests, and the pass@k estimator.

Chen et al. — arXiv 2021 · paper
Source ↗
Semantic Evaluation for Text-to-SQL with Distilled Test Suites

Executing queries on several databases catches SQL that is right only by coincidence (test-suite accuracy).

Zhong, Yu and Klein — arXiv / EMNLP 2020 · paper
Source ↗
sqlite3 — DB-API 2.0 interface for SQLite databases

set_authorizer and set_progress_handler for read-only, step-limited execution of generated SQL.

Python documentation · official docs
Source ↗
Define success criteria and build evaluations

Compares code-based, human and model-based grading and shows when exact and string matching are enough.

Anthropic · official docs
Source ↗
Assertions and metrics

Deterministic assertions such as contains, regex and is-json, plus custom JavaScript and Python assertions.

promptfoo · tool
Source ↗
Custom metrics

Wrapping your own code-based scorer as a metric with BaseMetric.

DeepEval · tool
Source ↗
Hypothesis documentation

Property-based testing library used to fuzz the validation pipeline.

Hypothesis · tool
Source ↗
Your AI Product Needs Evals

Practitioner account of evaluation-driven development, error analysis and the levels of LLM evaluation.

Hamel Husain · article
Source ↗