LLM Evals for Beginners: Test Sets, Metrics, LLM-as-Judge and Regression Testing (with Python)
A free, hands-on course on evaluating LLM applications: how to tell whether your chatbot, RAG system, extractor or agent actually got better after you changed a prompt or a model, instead of trusting a few manual tries. You will build test sets, choose metrics, use an LLM as a judge without fooling yourself, put error bars on results, and gate releases on regression tests.
Every lesson comes with runnable Python that needs no installs (standard library only), a small toolkit (evalkit/) you can reuse, and an offline demo where a “new version” of a support bot fixes five cases and silently breaks two, which the eval catches. Plug in a real model through any OpenAI-compatible API (Ollama, vLLM or a hosted provider) when you are ready. It is for developers, product engineers and data scientists shipping LLM features.
Last reviewed: December 2026. Tools and frameworks are mentioned as examples; check their docs for current features.
Contents
- Why evals matter
- Setup
- The demo in 30 seconds
- Lesson 1: What to evaluate
- Lesson 2: Building a test set
- Lesson 3: Deterministic checks
- Lesson 4: Text similarity metrics and their traps
- Lesson 5: LLM-as-judge
- Lesson 6: Can you trust the judge?
- Lesson 7: Statistics for evals
- Lesson 8: Regression testing and release gates
- Lesson 9: Evaluating RAG and agents
- Lesson 10: Evals in production
- Metric chooser
- Eval tools compared
- Common mistakes
- FAQ
- Where to go next
- Repository layout
- Contributing
- License
- More free resources
Why evals matter
LLM outputs are non-deterministic, open-ended and sensitive to tiny prompt changes. A change that fixes the bug you were looking at can break three things you were not. Without evals, teams end up “vibe checking”: trying five prompts by hand and shipping if they look fine.
An eval is a repeatable test: a set of inputs, the behaviour you expect, a way to score outputs, and a number you can compare across versions. Good evals let you:
- change prompts, models and retrieval settings with confidence
- compare a cheaper model against the current one with evidence
- catch regressions before users do
- talk about quality in numbers instead of anecdotes
Setup
Python 3.10 or newer. Nothing to install.
git clone https://github.com/Ralpberry-Labs/llm-evals-for-beginners.git
cd llm-evals-for-beginners
python examples/run_eval.py # the full demo
python lessons/lesson03_metrics.py # any lesson
python -m unittest discover -s tests -v # 18 tests
To use real models for the system or the judge, run any OpenAI-compatible server (for example Ollama locally) and set APP_BASE_URL / APP_MODEL for the system under test or JUDGE_BASE_URL / JUDGE_MODEL / JUDGE_API_KEY for the judge.
The demo in 30 seconds
examples/systems.py contains two versions of a support bot for an invented note-taking app. They are deterministic stand-ins, so results are reproducible. bot_v2 is “the new prompt”: safer and more honest, but it renamed a JSON key in the order-extraction feature.
$ python examples/run_eval.py
v1: pass rate 0.67 (95% CI 0.40-0.87), mean correctness 0.70
by tag: abstain=0.00, facts=1.00, format=1.00, safety=0.00, tone=0.00
v2: pass rate 0.87 (95% CI 0.67-1.00), mean correctness 0.97
by tag: abstain=1.00, facts=1.00, format=0.00, safety=1.00, tone=1.00
regressions (passed in v1, fail in v2): ['format-01', 'format-02']
fixes (failed in v1, pass in v2): ['unknown-01', 'unknown-02', 'safety-01', 'safety-02', 'tone-01']
paired difference v2 - v1: +0.20 (95% CI -0.13 to +0.53)
McNemar exact test: 5 fixed, 2 broken, p = 0.453
release gate: FAIL (2 regression(s): format-01, format-02)
Four lessons in one output:
- The headline number went up (0.67 to 0.87), and the mean correctness looks great (0.97).
- Per-tag results show the whole
formatcategory broke. Averages hide this. - With 15 cases, the improvement is not statistically clear: the interval for the difference includes zero.
- The regression gate fails on the two broken cases, so this version does not ship until the JSON key is fixed or the change is accepted on purpose.
Lesson 1: What to evaluate
Start from what “good” means for your users, not from a list of metrics.
| Product | Quality dimensions | Example checks |
|---|---|---|
| Support chatbot | Correct facts, says “I don’t know”, polite, safe | Required facts present, abstains on unknowns, refuses prompt-injection |
| RAG / document Q&A | Finds the right source, faithful answer, citations | Retrieval hit rate, groundedness, citation accuracy |
| Data extraction | Valid JSON, right fields and types, correct values | Schema check, field-level accuracy |
| Summarization | Covers key points, no invented facts, right length | Key-point coverage, judge for faithfulness, length bounds |
| Code generation | Compiles, passes tests, follows style | Run unit tests on generated code |
| Agent | Completes the task, uses tools correctly, efficient | Final state check, tool-call correctness, step and cost limits |
Also decide what must never happen (leaking another user’s data, following injected instructions, unsafe advice). Those become zero-tolerance safety cases.
Write success criteria that are specific and measurable: not “the bot should be accurate” but “at least 95 percent of factual questions contain the correct fact, and 100 percent of out-of-scope questions get an ‘I don’t know’”.
Lesson 2: Building a test set
A test set is a list of cases. This course uses JSON Lines, one case per line (examples/support_cases.jsonl):
{"id": "fact-01", "input": "What is your refund window for annual plans?", "expected": ["14 days"], "tags": ["facts"]}
{"id": "unknown-01", "input": "Does the app have a built-in calendar?", "expected": "abstain", "tags": ["abstain"]}
{"id": "format-01", "input": "Extract as JSON: 'Order 1182 from Dana Ruiz, 3 items, express shipping'", "expected": {"required": ["order_id", "customer", "items", "express"], "properties": {"order_id": {"type": "integer"}}}, "tags": ["format"]}
evalkit/dataset.py loads and validates this (missing fields, duplicate IDs, invalid JSON), splits it into dev and test sets, and groups cases by tag.
Where cases come from, best first:
- Real user inputs from logs, support tickets and search queries (anonymized).
- Failures you have seen: every bug report becomes a test case.
- Edge cases you can think of: empty input, very long input, other languages, typos, ambiguous questions, adversarial prompts.
- Synthetic cases generated by an LLM to fill gaps, reviewed by a human before use.
Good test set habits:
| Habit | Why |
|---|---|
| Tag every case (topic, difficulty, risk) | Per-tag results reveal what broke |
| Include cases with no right answer in your data | Measures abstention and hallucination |
| Include safety and injection cases | Zero tolerance needs explicit tests |
| Keep a held-out test split | Tuning prompts on the same cases you report on overfits |
| Version the file in git | Results are only comparable on the same set |
| Start small (20 to 50), grow continuously | A small real set beats no set |
Lesson 3: Deterministic checks
Use code, not models, whenever the expected behaviour can be checked mechanically. Code checks are free, fast, and never disagree with themselves. evalkit/metrics.py:
| Check | Function | Use for |
|---|---|---|
| Exact match (normalized) | exact_match |
Short answers, labels, classifications |
| Required phrases | contains_all |
Key facts that must appear |
| Forbidden phrases | contains_none |
Secrets, competitor names, banned claims |
| Pattern | regex_match |
IDs, dates, formats |
| JSON and schema | extract_json, json_schema_score |
Structured output; tolerates code fences, gives partial credit per field |
| Refusal or abstention | is_refusal |
“I don’t know” and safety refusals |
| Length | length_within |
Conciseness requirements |
python lessons/lesson03_metrics.py
Normalization matters: exact_match("14 days.", "14 days") is 1.0 because punctuation, case and articles are normalized (the approach popularized by the SQuAD benchmark). But contains_all("14 days", ["14 days."]) is 0, because the expected phrase includes a period. Write expected phrases carefully, or normalize both sides.
For code generation, the best deterministic check is running the generated code against tests in a sandbox.
Lesson 4: Text similarity metrics and their traps
When there is a reference answer but many valid phrasings, people reach for similarity metrics:
| Metric | Measures | Trap |
|---|---|---|
| Token F1 | Word overlap with the reference | Rewards copying words, punishes correct paraphrases |
| Edit similarity | Character edits needed | Same problem, plus sensitive to formatting |
| BLEU / ROUGE | n-gram overlap (translation, summarization) | Weak correlation with human judgment for open-ended answers |
| Embedding similarity | Closeness of meaning vectors | “The refund window is 14 days” and “is 30 days” look very similar |
The lesson script shows the classic failure: “Fourteen days” is a correct answer to “14 days”, yet exact match is 0, token F1 is 0.50 and edit similarity is 0.38.
output expected EM F1 edit contains
The refund window is 14 days. 14 days 0 0.57 0.29 1
Fourteen days 14 days 0 0.50 0.38 0
14 days 14 days. 1 1.00 1.00 0
Use similarity metrics as cheap signals for drift (“outputs changed a lot”), not as your definition of correct. For meaning, use required facts (Lesson 3) or a judge (Lesson 5).
Lesson 5: LLM-as-judge
For qualities code cannot check (helpfulness, faithfulness, tone, whether a paraphrase is correct), ask another model to grade the output. evalkit/judge.py provides:
POINTWISE_PROMPT: grade one answer on a 1 to 5 rubric, against an optional reference, with brief reasoning before the scorePAIRWISE_PROMPT: pick the better of two answers- robust parsers (
parse_score,parse_winner) that handle JSON, code fences and loose formats, and raise on garbage instead of guessing grade(judge, question, answer, reference, samples=n): normalized 0 to 1, optionally averaged over several samplescompare(judge, question, a, b): runs the comparison twice with positions swapped and returns a tie when the two orders disagreeopenai_compatible_judge(): a judge backed by any OpenAI-compatible endpoint at temperature 0
python lessons/lesson05_judge.py # toy judge, offline
python lessons/lesson05_judge.py --llm # a real model as judge
Writing a good judge prompt:
| Do | Why |
|---|---|
| Give a specific rubric with anchored levels | “4 = correct, minor omissions” beats “rate quality 1-10” |
| Provide a reference answer when you have one | Judges are much more reliable checking against a reference than from their own knowledge |
| Ask for short reasoning before the score | Tends to make scores more consistent, and helps you debug disagreements |
| Ask for one dimension per prompt | “Faithfulness” and “tone” in one score is hard to interpret |
| Use binary or small scales where possible | Pass/fail with clear criteria is easier to make reliable than fine-grained scores |
| Force a parseable output format | Then fail loudly when parsing fails |
Known judge biases (documented in research such as Judging LLM-as-a-Judge and Large Language Models are not Fair Evaluators):
| Bias | Description | Mitigation |
|---|---|---|
| Position bias | Prefers the first (or second) answer in pairwise comparisons | Swap positions and require agreement (compare does this) |
| Verbosity bias | Prefers longer answers | Say length is not a criterion; include concise reference answers; check with length-matched pairs |
| Self-preference | Prefers outputs from its own model family | Use a different model as judge, or several judges |
| Leniency | Gives high scores to everything | Anchored rubrics, binary criteria, calibration against humans |
The lesson’s toy judge is deliberately length-biased: position swapping does not save you from that, which is why Lesson 6 exists.
Lesson 6: Can you trust the judge?
A judge is itself a model you must evaluate. Before relying on one:
- Have humans label 50 to 100 outputs on the same rubric.
- Run the judge on the same outputs.
- Measure agreement, and read the disagreements.
python lessons/lesson06_agreement.py
raw agreement: 80%
Cohen's kappa: 0.52 (1 = perfect, 0 = chance level)
a judge that always says pass: agreement 70%, kappa 0.00
Raw agreement is misleading when most cases pass: a useless judge that always says “pass” agrees 70 percent of the time here. Cohen’s kappa corrects for chance agreement (cohens_kappa in evalkit/stats.py). Commonly used rough interpretation bands put 0.4 to 0.6 as moderate and above 0.6 as substantial, but what is good enough depends on the stakes.
When agreement is low: tighten the rubric, add examples of each score level to the prompt, split the criterion into simpler binary checks, or use a stronger judge model. Re-check agreement whenever you change the judge prompt or model.
Lesson 7: Statistics for evals
Eval scores are measurements with noise. Small test sets give wide error bars.
python lessons/lesson07_stats.py
n= 20: a pass rate near 80% is uncertain by about +/-17.5%
n= 50: a pass rate near 80% is uncertain by about +/-11.1%
n= 100: a pass rate near 80% is uncertain by about +/-7.8%
n= 300: a pass rate near 80% is uncertain by about +/-4.5%
n= 1000: a pass rate near 80% is uncertain by about +/-2.5%
Tools in evalkit/stats.py:
| Function | Answers |
|---|---|
bootstrap_ci(scores) |
What range is the true mean plausibly in? (percentile bootstrap) |
paired_bootstrap(a, b) |
Is system B better than A on the same cases, and by how much? |
mcnemar_exact(a_pass, b_pass) |
For pass/fail results on the same cases: is the difference more than chance? Only cases where the systems disagree count |
cohens_kappa(r1, r2) |
Agreement between two raters beyond chance |
min_detectable_difference(n, p) |
Roughly how small a difference this many cases can resolve |
Rules of thumb:
- Compare systems on the same cases (paired tests). It removes the noise from case difficulty.
- Report intervals, not just point estimates: “87% (67 to 100%)” tells the truth about 15 cases.
- Run non-deterministic systems several times if you cannot use temperature 0, and average.
- Do not peek and stop: deciding the sample size after seeing a favourable result inflates false positives.
Anthropic’s research note A statistical approach to model evaluations and the accompanying paper Adding Error Bars to Evals go deeper.
Lesson 8: Regression testing and release gates
The most valuable eval habit: every change runs the test set, and newly failing cases block the release. evalkit/runner.py:
from evalkit.dataset import load_cases
from evalkit.runner import run, summarize, compare_runs, gate, save, load
cases = load_cases("examples/support_cases.jsonl")
baseline = load("results/main.jsonl") # saved from the last release
candidate = run(my_app, cases, SCORERS) # your app: str -> str
save(candidate, "results/candidate.jsonl")
cmp = compare_runs(baseline, candidate) # regressions, fixes, new cases
ok, reason = gate(cmp, max_regressions=0, min_pass_rate=0.85)
raise SystemExit(0 if ok else 1) # non-zero exit fails CI
Design choices built in:
- A crash is a failed case, not a crashed eval: the error message is recorded and the run continues.
- Results are saved per case (JSON Lines), so you can diff two runs and read actual outputs.
- Regressions are listed by ID, so the conversation is “why did
format-01break?”, not “the score went down 3 points”. - Latency is recorded per case, because a slower model can be a regression too.
Wire it into CI on every pull request that touches prompts, models, retrieval or tools. Keep the baseline results in version control or as a CI artifact. When a regression is intended (for example a deliberate behaviour change), update the expected values in the same pull request, which makes the change explicit in review.
Lesson 9: Evaluating RAG and agents
RAG: evaluate retrieval and generation separately, or you will not know which half to fix.
| Stage | Metric | How |
|---|---|---|
| Retrieval | Hit@k, recall@k, MRR | Label the source document(s) for each question |
| Generation | Correctness | Required facts or a reference-based judge |
| Generation | Faithfulness (groundedness) | Judge whether every claim is supported by the retrieved text |
| Generation | Citation accuracy | Do the cited passages contain the claim? |
| End to end | Abstention | Questions whose answer is not in the documents |
The companion course Generative AI for Beginners: RAG implements these metrics on a small dataset. For larger projects, Ragas packages common RAG metrics.
Agents (multi-step, tool-using systems) need more than output checks:
| Aspect | What to check |
|---|---|
| Outcome | Did the final state match? (file changed correctly, ticket created, test suite passes) |
| Tool use | Right tools, valid arguments, no forbidden calls |
| Efficiency | Steps, tokens, time and cost per task, within limits |
| Safety | Asked for confirmation before destructive actions; resisted injected instructions |
| Robustness | Same task with rephrased instructions or noisy tool outputs |
Prefer checking outcomes in a sandbox over matching an exact sequence of steps: there are usually many valid paths. Run each task several times, since agent behaviour varies between runs, and report the success rate.
Lesson 10: Evals in production
Offline test sets drift away from what users actually do. Close the loop:
- Log inputs, outputs, retrieved context, model version and latency (respecting privacy and retention rules).
- Collect feedback: thumbs up/down, edits, escalations to humans, abandoned sessions.
- Sample and grade a small share of production traffic with your judges and deterministic checks (“online evals”).
- Monitor pass rates, refusal rates, latency and cost over time, by segment.
- Promote interesting production failures into the offline test set, so they can never silently return.
Observability platforms such as Langfuse and Arize Phoenix (both open source) help with tracing and scoring production traffic.
Model or provider updates are releases too: re-run your test set whenever the underlying model version changes, even if your code did not.
Metric chooser
| You want to know… | Use | Cost |
|---|---|---|
| Is the answer exactly this label or value? | Exact match | Free |
| Are the key facts present? | Required phrases | Free |
| Is it valid JSON with the right fields? | Schema check | Free |
| Does the code work? | Run tests in a sandbox | Low |
| Did it refuse or abstain when it should? | Refusal patterns, then a judge for edge cases | Free to low |
| Is a paraphrased answer correct? | Reference-based judge | Medium |
| Is it faithful to the sources? | Faithfulness judge | Medium |
| Which of two versions do users prefer? | Pairwise judge with swaps, then human review | Medium |
| Do users like it? | Production feedback, A/B tests | High |
Eval tools compared
This course’s evalkit is for learning. When you outgrow it, these open-source tools are widely used (descriptions are ours; check each project for current features):
| Tool | Best for | Notes |
|---|---|---|
| promptfoo | Prompt and model comparisons, red teaming, CI | Config-driven (YAML), CLI and web viewer |
| DeepEval | Unit-test style LLM evals in Python | pytest-like API with many built-in metrics |
| Inspect (repo) | Rigorous evals including agents and tools | From the UK AI Security Institute |
| OpenAI Evals | A framework and registry of evals | One of the earlier open eval frameworks |
| Ragas | RAG-specific metrics | Faithfulness, answer relevance, context precision and more |
| lm-evaluation-harness | Benchmarking base models on academic tasks | Model-level, not application-level |
| HELM (repo) | Holistic benchmark reports across many scenarios | Research-oriented |
| Langfuse, Phoenix | Tracing plus online evaluation | Production observability |
Picks: start with plain code (this course) plus your own test set; add promptfoo or DeepEval when you want a framework in CI; reach for Inspect for agent evaluations; use Ragas if your app is RAG-heavy. Public leaderboards measure models on generic tasks; they do not replace evals on your own data.
Common mistakes
- Vibe checks instead of a test set. Five manual tries are not evidence.
- Only reporting the average. Per-tag and per-case results show what actually broke.
- Tuning on the test set. Keep a held-out split.
- Trusting string similarity for meaning. Correct paraphrases score low; wrong answers with the right words score high.
- Trusting an unvalidated judge. Measure agreement with humans first.
- Ignoring noise. A 3-point change on 30 cases is usually noise.
- No negative cases. Without unanswerable and adversarial inputs you cannot measure hallucination or safety.
- Evaluating once. Evals are a regression suite that runs on every change, including model upgrades.
FAQ
What is an LLM eval? A repeatable test that runs your LLM application on a fixed set of inputs and scores the outputs, so you can compare versions objectively.
How many test cases do I need? Start with 20 to 50 real cases to catch obvious regressions. To detect differences of a few percentage points you need hundreds (see Lesson 7). Grow the set continuously from production failures.
Is LLM-as-judge reliable? It can be, for well-defined criteria with a clear rubric and reference answers, after you verify agreement with human labels. It has known biases (position, verbosity, self-preference) that you must control for.
Should the judge be a stronger model than the one being tested? Usually that helps, but the real requirement is that the judge agrees with careful human labels on your criteria. Measure it.
What is the difference between benchmarks and evals? Benchmarks are standardized public tests of model capabilities. Application evals test your system on your users’ tasks. A model that tops a benchmark can still fail your use case.
How do I evaluate non-deterministic outputs? Use temperature 0 where possible, check properties rather than exact strings, run several samples and report pass rates with intervals.
Can I use synthetic test data? Yes, to fill gaps (edge cases, rare intents), but review it by hand and keep real user data as the core of your set.
How do I evaluate hallucinations? Include questions that the system cannot answer from its data and check that it abstains; for RAG, judge faithfulness of claims against retrieved sources.
How often should evals run? On every change to prompts, models, retrieval or tools (in CI), and on a schedule against production samples.
Where to go next
- Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (2023)
- G-Eval: NLG Evaluation using GPT-4 with Better Human Alignment (2023)
- Large Language Models are not Fair Evaluators (2023), on position bias
- Adding Error Bars to Evals (2024) and Anthropic’s summary A statistical approach to model evaluations
- SQuAD (2016), the origin of the normalized exact-match and F1 conventions
- Claude docs: Define success criteria and build evaluations
- Your AI Product Needs Evals, a practitioner’s essay on building eval systems
- Wikipedia on McNemar’s test and Cohen’s kappa
- Companion course: Generative AI for Beginners: RAG
Repository layout
llm-evals-for-beginners/
├── evalkit/
│ ├── dataset.py # JSONL cases, validation, splits, tags
│ ├── metrics.py # exact match, F1, contains, regex, JSON schema, refusal, length
│ ├── judge.py # judge prompts, parsing, pointwise grade, pairwise compare with swaps
│ ├── stats.py # bootstrap CI, paired bootstrap, McNemar, Cohen's kappa
│ └── runner.py # run, summarize, save/load, compare runs, release gate
├── examples/
│ ├── support_cases.jsonl # 15 tagged test cases
│ ├── systems.py # bot_v1 and bot_v2 (offline stand-ins) + real-model wrapper
│ ├── scorers.py # per-case-type scoring
│ └── run_eval.py # the end-to-end demo
├── lessons/ # lesson03_metrics, lesson05_judge, lesson06_agreement, lesson07_stats
├── tests/test_evalkit.py # 18 tests
├── LICENSE
└── README.md
Contributing
Pull requests are welcome: new metrics with tests, better judge prompts (with agreement data), more realistic example datasets, exercises, and translations. Please keep evalkit dependency-free, explain the trade-offs of any metric you add, and only cite sources you have checked.
License
MIT.
If this course made your evals more trustworthy, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.