Learning path: LLM Evals: Test an AI Feature Before and After You Ship · Step 3 of 3
Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
A teammate changes one prompt line to make answers shorter, and four of ten golden questions lose their facts. A pytest eval on saved answers catches it: 12 passed for the old prompt, 2 failed gates and 4 xfailed cases for the new one, exit code 1, and the pull request check turns red.
What you will learn
- Grade saved answers against a golden set with must-include and must-not-include rules
- Turn single cases into a pass rate with two gates: a threshold and a baseline
- Report weak cases with xfail while only the gates decide red or green
- Run the eval on every pull request with a GitHub Actions workflow that reads the exit code
Before you start
- Why You Cannot Ship Without an Eval
- CI with GitHub Actions
- pytest basics
A prompt edit can make answers worse without a single line of code changing. The fix is to run an eval on every pull request, so quality drops turn the check red before they merge. Three pieces make it work: a golden set, pytest and GitHub Actions.
One line changed, four answers worse
The support bot of a coffee gear shop, Brewline, follows this prompt (prompts/v1.txt):
You are the support assistant for Brewline, a coffee gear shop.
Answer the customer's question using the shop policies.
Give the exact numbers and conditions (days, prices, steps) so the customer can act on them.
Never ask for passwords or full card numbers.
A teammate wants shorter answers and opens a pull request that changes just line three (prompts/v2.txt):
Keep every answer to one short, friendly sentence.
No code changed at all. But four of our ten test questions now get a worse answer. Who notices before it merges?
A smoke detector in every room
You don't walk around sniffing for smoke; the detector sounds the alarm on its own. Our pipeline works the same way.
One golden case
The golden set (golden.json) has ten questions, each with a simple rule for a good answer:
{"id": "refund-window", "question": "How many days do I have to return an item?",
"must_include": ["30 days"], "must_not_include": ["cannot be returned"]}
The bot's answers are saved in files, one per prompt version: answers/v1.json and answers/v2.json. For this case:
- v1: You can return any item within 30 days of delivery for a full refund. Passes.
- v2: Returns are possible, please check our returns page. Fails: missing '30 days'.
Because the answers are saved, the check needs no model call and no API key. That keeps it cheap enough to run on every pull request.
Two tiny graders
def must_include(answer, phrases):
return [f"missing '{p}'" for p in phrases if p.lower() not in answer.lower()]
def must_not_include(answer, phrases):
return [f"contains '{p}'" for p in phrases if p.lower() in answer.lower()]
def grade(case, answer):
"""Return a list of problems. An empty list means the case passed."""
problems = must_include(answer, case["must_include"])
problems += must_not_include(answer, case["must_not_include"])
return problems
A grader returns its problems as readable text, so a failing case tells the author exactly what to fix.
Pass rate and two gates
One weak case shouldn't decide everything. So we grade all ten, turn them into a pass rate, and let two gates decide:
import json
import os
import pathlib
import pytest
from graders import grade
HERE = pathlib.Path(__file__).parent
THRESHOLD = 0.90 # at least 9 of 10 golden cases must pass
MAX_DROP = 0.05 # and no real drop from the last accepted baseline
def load(name):
return json.loads((HERE / name).read_text(encoding="utf-8"))
CASES = load("golden.json")
ANSWERS = load(os.environ.get("ANSWERS_FILE", "answers/v1.json"))
BASELINE = load("baseline.json")
def pass_rate():
return sum(not grade(c, ANSWERS[c["id"]]) for c in CASES) / len(CASES)
@pytest.mark.parametrize("case", CASES, ids=lambda c: c["id"])
def test_case(case):
problems = grade(case, ANSWERS[case["id"]])
if problems:
pytest.xfail("; ".join(problems)) # listed in the report; the gates decide
def test_pass_rate_meets_threshold():
rate = pass_rate()
assert rate >= THRESHOLD, f"pass rate {rate:.0%} is below the {THRESHOLD:.0%} threshold"
def test_not_worse_than_baseline():
rate, base = pass_rate(), BASELINE["pass_rate"]
assert rate >= base - MAX_DROP, f"pass rate {rate:.0%} dropped from the baseline {base:.0%}"
- Single cases are reported with
pytest.xfail: listed with their reason, but they don't fail the run on their own. - Gate 1, the threshold: the pass rate must be at least 90%.
- Gate 2, the baseline:
baseline.jsonholds the pass rate of the last accepted version, 1.0. We may drop by at most 5 points, so the floor is 95%.
The environment variable ANSWERS_FILE picks which saved answers to grade.
Green, then red
The v1 answers:
python -m pytest -q
............ [100%]
12 passed
Ten cases plus the two gates, exit code 0. Now the v2 answers, with the flags the CI job uses:
ANSWERS_FILE=answers/v2.json pytest -q -rfx --tb=no
x.x.xx....FF [100%]
=========================== short test summary info ===========================
FAILED test_regression.py::test_pass_rate_meets_threshold - AssertionError: p...
FAILED test_regression.py::test_not_worse_than_baseline - AssertionError: pas...
XFAIL test_regression.py::test_case[refund-window] - missing '30 days'
XFAIL test_regression.py::test_case[shipping-time] - missing '3 to 5 business days'
XFAIL test_regression.py::test_case[password-reset] - missing 'reset link'; contains 'your old password'
XFAIL test_regression.py::test_case[cancel-order] - missing 'before it ships'
2 failed, 6 passed, 4 xfailed
Six of ten pass, a 60% pass rate. The two FAILED lines are the gates: 60% is below the 90% threshold, and below the 95% floor from the baseline. Under them, the four weak cases, each with its reason. One of them is worse than vague: the password answer now contains "your old password". The exit code is 1, and that's the thing CI reads.
CI on every pull request
The project's workflow, .github/workflows/eval.yml:
name: eval
on:
pull_request:
paths: ["prompts/**", "answers/**", "golden.json", "graders.py", "test_regression.py"]
jobs:
regression:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements.txt
- name: Run the golden set
env:
ANSWERS_FILE: answers/v2.json
run: pytest -q -rfx --tb=no
It wakes up on every pull request that touches the prompts, the saved answers, the golden cases or the test code. Then it does what we'd do by hand: check out, install Python and the pinned requirements, run pytest. Here it grades the pull request's answers, answers/v2.json, so the demo check goes red. Exit code 0 turns the check green; exit code 1 turns it red, and if the main branch requires this check, merging is blocked until someone fixes the answers. (Setting up a workflow from scratch: CI with GitHub Actions. The same gate idea for a trained model: an ML quality gate.)
Rules that keep the alarm useful
- A threshold: a floor for the pass rate, here 0.9.
- A baseline: compare with the last accepted result in
baseline.json. - Flaky answers: a real model can answer the same question differently each time. When you call one, set the temperature to 0 and grade a few samples per case.
- Cost: run the cheap saved-answer check on every pull request, and call the real model on a schedule, say nightly.
- One habit: update the baseline only in a reviewed pull request, so the bar moves up on purpose, never by accident.
Common mistakes
- Failing the build on any single weak case. One flaky case then blocks everything; let the gates decide.
- Only a threshold, no baseline. A drop from 100% to 91% passes 90% quietly.
- Calling a live model on every pull request. Slow, costly and flaky; use saved answers there.
- Bumping the baseline in the same pull request that lowered quality.
- A workflow with no
pathsfilter around prompts. Prompt-only changes are exactly the ones you need to catch.
Quick recap
| Piece | Role | In this project |
|---|---|---|
| Golden set | Questions plus rules for a good answer | 10 cases in golden.json |
| Graders | must_include / must_not_include | Problems as readable text |
| Gates | Threshold and baseline | 0.90, and at most 0.05 below 1.0 |
| pytest | Exit code 0 or 1 | v1: 12 passed; v2: 2 failed, 6 passed, 4 xfailed |
| GitHub Actions | Runs it on every pull request | eval.yml, red blocks the merge |
Try it yourself
Put "30 days" back into the refund-window answer in answers/v2.json and grade it again. What's the pass rate now, and is the check still red?
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
From ML Metrics to LLM Evals: Same Ruler, New Targets
Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.
Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.
Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.