QA and Test Automation · Lab 29 of 35
Build an Eval Set for a Support Chatbot: ShopRung Lab
Build a real eval for ShopRung's support chat in Python: a golden set in JSON, checks with their own unit tests, a runner that saves raw answers, per-question scores with retrieval metrics, a baseline that catches a prompt regression, a pytest gate for CI, and a run on a real local model.
⏱ 75 minIntermediate💸 Free8 steps
Python 3.12pytesthttpxShopRung support chatOllama (optional)GitHub Actions
Overview video
What you will build
A folder chat-evals that measures the quality of ShopRung's support chat and fails when it gets worse:
- golden.json: 12 questions with required facts, forbidden facts, the help section that should be found, and one question that must be refused.
- evals/checks.py: the checks, with 6 unit tests of their own.
- evals/run.py and evals/score.py: ask every question N times, keep the raw answers, print a pass rate per question plus recall@3 and MRR for retrieval, and compare with a baseline.
- Real results: 30 of 36 on the fake model; a prompt regression drops it to 18 of 36 and the score exits with code 1. A pytest gate and a GitHub Actions workflow run it on every pull request, and an optional run on llama3.2:3b scores 31 of 36.
Before you start
- The episodes behind it: Why AI is hard to test, Golden sets and evals, Testing RAG and Guardrails and prompt regressions.
- Basic Python and pytest, as in lab 11. ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start and leave it running. Download it again if your copy has no Help chat link in the footer: the chat came with ShopRung's AI update. Out of the box it uses a fake model: a built-in stand-in that gives the same answer every time and needs nothing installed.
curl http://localhost:8080/api/support/infocurl http://localhost:8080/api/support/infocurl.exe http://localhost:8080/api/support/info {"model":"fake","ollamaUrl":null,"promptVersion":"v1","temperature":null,"pages":["account","community-tips","coupons","products","returns","shipping"],"sections":12} S2Check Python 3.12 or newer
On Windows use py where this lab says python3.
python3 --versionpython3 --versionpy --version Python 3.12.x (or newer)
S3Make the project and install the libraries
Make a folder with a virtual environment, as in lab 11. Create requirements.txt and pytest.ini with the contents below, then install. Run the activate line again in every new terminal.
mkdir -p chat-evals/evals chat-evals/tests
cd chat-evals
python3 -m venv .venv
source .venv/bin/activate
touch evals/__init__.py
pip install -r requirements.txtmkdir -p chat-evals/evals chat-evals/tests
cd chat-evals
python3 -m venv .venv
source .venv/bin/activate
touch evals/__init__.py
pip install -r requirements.txtmkdir chat-evals\evals, chat-evals\tests
cd chat-evals
py -m venv .venv
.venv\Scripts\Activate.ps1
New-Item evals\__init__.py
pip install -r requirements.txt Successfully installed ... httpx-0.28.1 ... pytest-8.3.4
Ask the chat and read the answer
See everything a response gives you to test with.
Before writing tests, look at one answer. The chat's endpoint is POST /api/support/chat with a message. The response has far more than the answer: sources (the help sections retrieval found, best first), refused, toolCalls, guardrails, the model and promptVersion, token usage and latencyMs.
Your eval will check the answer text and the sources. The model and prompt version say exactly what produced each answer, so scores from different versions can be compared. Ask the same question again: with the fake model the answer is identical every time.
curl -s http://localhost:8080/api/support/chat -H "Content-Type: application/json" -d '{"message": "How much is shipping?"}'curl -s http://localhost:8080/api/support/chat -H "Content-Type: application/json" -d '{"message": "How much is shipping?"}'curl.exe -s http://localhost:8080/api/support/chat -H "Content-Type: application/json" -d '{\"message\": \"How much is shipping?\"}' {"model":"fake","promptVersion":"v1","toolCalls":[],"guardrails":[],"answer":"Shipping is free when your subtotal after any discount is $75.00 or more. Below $75.00, shipping costs $4.99 per order.","refused":false,"sources":[{"page":"shipping","title":"Shipping","section":"Shipping costs","url":"/help/shipping.md"},{"page":"community-tips","title":"Tips from other shoppers","section":"Saving money","url":"/help/community-tips.md"}],"usage":{"promptTokens":272,"completionTokens":30},"latencyMs":1} Write the golden set
12 questions, each with what a good answer must and must not say.
Create golden.json. Each entry has an id, a category, the question q, the help source section that should be retrieved, the facts the answer must contain (all of them), must_any (at least one of several phrasings), and must_not (facts that make the answer wrong). The last entry is out of scope and must be refused.
Take the facts from ShopRung's help pages and requirements (open /help/returns.md and the others in the browser), not from what the chat currently says. Mix happy paths, rules and edge cases (12 mugs when the limit is 10, an expired coupon), and wrong answers that are common elsewhere, like 90 days for returns.
[
{"id": "shipping-cost", "category": "happy path", "q": "How much is shipping?",
"source": "Shipping costs", "must": ["$4.99", "$75.00"], "must_not": []},
{"id": "discount-code", "category": "happy path", "q": "Do you have a discount code?",
"source": "Coupon codes", "must": ["SAVE10"], "must_not": ["FREE100"]},
{"id": "return-window", "category": "rules", "q": "Can I return an item I bought last week?",
"source": "Return an item", "must": ["30 days"], "must_not": ["90 days"]},
{"id": "cancel-shipped", "category": "rules", "q": "Can I cancel an order that has shipped?",
"source": "Cancel an order", "must_any": ["no longer be cancelled", "cannot be cancelled", "can't be cancelled"], "must_not": []},
{"id": "coupon-case", "category": "rules", "q": "Is SAVE10 case sensitive?",
"source": "Using a coupon", "must_any": ["not case-sensitive", "not case sensitive"], "must_not": []},
{"id": "password-length", "category": "happy path", "q": "How long can my password be?",
"source": "Creating an account", "must": ["64"], "must_not": []},
{"id": "twelve-mugs", "category": "rules", "q": "Can I buy 12 mugs?",
"source": "Quantities and stock", "must": ["10"], "must_not": []},
{"id": "ship-time", "category": "happy path", "q": "When will my order ship?",
"source": "When your order ships", "must": ["2 business days"], "must_not": []},
{"id": "welcome15", "category": "rules", "q": "Does WELCOME15 still work?",
"source": "Coupon codes", "must": ["expired"], "must_not": []},
{"id": "refund-how", "category": "happy path", "q": "How do I get a refund?",
"source": "Return an item", "must": ["support@shoprung.test"], "must_not": ["90 days"]},
{"id": "two-coupons", "category": "rules", "q": "Can I use two coupons on one order?",
"source": "Using a coupon", "must_any": ["one coupon"], "must_not": []},
{"id": "off-topic", "category": "out of scope", "q": "What is the capital of France?",
"refuse": true, "must_not": ["Paris"]}
] - The help section retrieval should find. Used for recall@3 and MRR.line 3
- A plausible wrong answer: many shops allow 90 days. ShopRung does not.line 7
- Several correct phrasings; at least one must appear.line 9
- Out of scope: the chat must refuse, and must not answer anyway.line 25
Checks, with tests of their own
Turn every expectation into a reason the answer failed.
Create evals/checks.py. check() returns a list of problems, empty when the answer passes, so a failure says exactly what was wrong, not just false. It compares case-insensitively, checks refusals both ways, and flags raw <help> markup, which should never reach a customer. source_rank() returns where the expected section came in the sources: 1 is first, 0 is missing.
Checks are code that decides pass or fail, so they need tests too. Create tests/test_checks.py with hand-written responses: a good answer, a missing fact, a forbidden fact next to a correct one, a refusal, leaked markup and the source rank. These run without ShopRung.
"""Checks for one chat answer against one golden item. Each returns a list of problems; empty means it passed."""
def check(item: dict, response: dict) -> list[str]:
answer = response["answer"].lower()
problems = []
if item.get("refuse"):
if not response["refused"]:
problems.append("should refuse, but answered")
elif response["refused"]:
problems.append("refused a question it should answer")
for fact in item.get("must", []):
if fact.lower() not in answer:
problems.append(f"missing {fact!r}")
options = item.get("must_any", [])
if options and not any(o.lower() in answer for o in options):
problems.append(f"missing one of {options}")
for bad in item.get("must_not", []):
if bad.lower() in answer:
problems.append(f"says {bad!r}")
if "<help" in answer:
problems.append("shows <help> markup")
return problems
def source_rank(item: dict, response: dict) -> int:
"""Where the expected help section came in the sources: 1 is first, 0 means not found."""
sections = [s["section"] for s in response["sources"]]
return sections.index(item["source"]) + 1 if item["source"] in sections else 0 - A list of reasons, so the report can say why an answer failed.line 4
- Refusing a fair question is a failure too.line 10
- Internal markup must never be shown to a customer.line 21
from evals.checks import check, source_rank
SHIPPING = {"q": "How much is shipping?", "source": "Shipping costs", "must": ["$4.99", "$75.00"], "must_not": []}
RETURNS = {"q": "Can I return it?", "source": "Return an item", "must": ["30 days"], "must_not": ["90 days"]}
OFF_TOPIC = {"q": "What is the capital of France?", "refuse": True, "must_not": ["Paris"]}
def reply(answer, refused=False, sections=()):
return {"answer": answer, "refused": refused, "sources": [{"section": s} for s in sections]}
def test_a_good_answer_passes():
assert check(SHIPPING, reply("It costs $4.99, free from $75.00.")) == []
def test_a_missing_fact_fails():
assert check(SHIPPING, reply("Shipping is free on every order.")) == ["missing '$4.99'", "missing '$75.00'"]
def test_a_forbidden_fact_fails_even_next_to_the_right_one():
assert check(RETURNS, reply("Within 30 days, or 90 days for members.")) == ["says '90 days'"]
def test_out_of_scope_must_be_refused():
assert check(OFF_TOPIC, reply("The capital of France is Paris.")) == ["should refuse, but answered", "says 'Paris'"]
assert check(OFF_TOPIC, reply("I can only help with ShopRung.", refused=True)) == []
def test_leaked_markup_fails():
assert check(SHIPPING, reply('<help page="shipping">$4.99 ... $75.00</help>')) == ["shows <help> markup"]
def test_source_rank():
assert source_rank(SHIPPING, reply("", sections=["Saving money", "Shipping costs"])) == 2
assert source_rank(SHIPPING, reply("", sections=["Gift ideas"])) == 0 - A correct fact does not excuse a wrong one in the same answer.line 20
pytest -q tests/test_checks.py ...... [100%] 6 passed in 0.01s
A runner that keeps the raw answers
Ask every question N times and save everything.
Create evals/run.py. It reads the model and prompt version from /api/support/info, asks each golden question --runs times, and writes every full response to a JSON Lines file: one JSON object per line, with the question id and run number added.
Keeping raw answers separates asking from scoring. You can improve the checks and score the same file again without asking the model again, which on a real model costs time and money. Run all 12 questions 3 times.
"""Ask the support chat every golden question N times and save the raw responses, one JSON object per line.
python -m evals.run --runs 3 --out results/today.jsonl
"""
import argparse
import json
import os
from pathlib import Path
import httpx
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
GOLDEN = json.loads(Path("golden.json").read_text())
def ask(client: httpx.Client, question: str) -> dict:
r = client.post("/api/support/chat", json={"message": question})
r.raise_for_status()
return r.json()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--runs", type=int, default=1, help="how many times to ask each question")
parser.add_argument("--out", default="results/latest.jsonl")
args = parser.parse_args()
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
with httpx.Client(base_url=BASE_URL, timeout=120) as client, out.open("w") as f:
info = client.get("/api/support/info").json()
print(f"model {info['model']}, prompt {info['promptVersion']}: "
f"{len(GOLDEN)} questions x {args.runs} runs")
for item in GOLDEN:
for run in range(1, args.runs + 1):
response = ask(client, item["q"])
f.write(json.dumps({"id": item["id"], "run": run, **response}) + "\n")
print(".", end="", flush=True)
print(f"\nsaved {out}")
if __name__ == "__main__":
main() - Point it at another copy of ShopRung with BASE_URL.line 12
- A real local model can take seconds per answer, especially the first.line 30
- The whole response, not just the answer: sources, tokens and version too.line 37
python -m evals.run --runs 3 --out results/v1.jsonl model fake, prompt v1: 12 questions x 3 runs ............ saved results/v1.jsonl
Score it, and keep a baseline
A pass rate per question, retrieval metrics, and today's numbers saved.
Create evals/score.py. It runs the checks on every saved answer and prints passed/runs per question with the problems found, the overall rate, and two retrieval metrics: recall@3 (how often the expected section was in the sources) and MRR (the average of 1 / its rank). Retrieval is the same every run, so it uses the first run of each question.
Save the result as baseline.json. 30 of 36 passed. Read the two failures: twelve-mugs fails because retrieval never finds the "Quantities and stock" section: it is the one miss behind recall@3 of 0.91 (10 of the 11 questions that have a source). refund-how misses the support email: the fake model picks two sentences about refunds, not the one about how to ask. These are the chat's real weaknesses today; the baseline records them honestly instead of hiding them.
"""Score saved chat responses against the golden set, and compare with a baseline.
python -m evals.score results/today.jsonl # print the scores
python -m evals.score results/today.jsonl --save baseline.json # keep them as the baseline
python -m evals.score results/today.jsonl --baseline baseline.json # exit 1 if any question got worse
"""
import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path
from evals.checks import check, source_rank
GOLDEN = {item["id"]: item for item in json.loads(Path("golden.json").read_text())}
def score(rows: list[dict]) -> dict:
by_id = defaultdict(list)
for row in rows:
by_id[row["id"]].append(row)
questions, ranks = {}, []
for qid, item in GOLDEN.items():
results = by_id[qid]
problems = [check(item, r) for r in results]
questions[qid] = {"passed": sum(not p for p in problems), "runs": len(results),
"problems": sorted({p for ps in problems for p in ps})}
if item.get("source"):
ranks.append(source_rank(item, results[0])) # retrieval is the same every run
passed = sum(q["passed"] for q in questions.values())
runs = sum(q["runs"] for q in questions.values())
return {
"passed": passed, "runs": runs,
"recall_at_3": sum(r > 0 for r in ranks) / len(ranks),
"mrr": sum(1 / r for r in ranks if r) / len(ranks),
"questions": questions,
}
def report(s: dict) -> None:
for qid, q in s["questions"].items():
note = "; ".join(q["problems"])
print(f"{q['passed']}/{q['runs']} {qid:<16} {note}")
print(f"overall {s['passed']}/{s['runs']} = {s['passed'] / s['runs']:.0%}")
print(f"retrieval: recall@3 {s['recall_at_3']:.2f}, MRR {s['mrr']:.2f}")
def worse_than(s: dict, base: dict) -> list[str]:
worse = []
for qid, q in s["questions"].items():
old = base["questions"].get(qid)
if old and q["passed"] / q["runs"] < old["passed"] / old["runs"]:
worse.append(f"{qid}: {old['passed']}/{old['runs']} -> {q['passed']}/{q['runs']}")
return worse
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("results")
parser.add_argument("--save", help="write these scores as a new baseline")
parser.add_argument("--baseline", help="fail if any question scores lower than here")
args = parser.parse_args()
rows = [json.loads(line) for line in Path(args.results).read_text().splitlines()]
s = score(rows)
report(s)
if args.save:
Path(args.save).write_text(json.dumps(s, indent=2) + "\n")
print(f"saved baseline {args.save}")
if args.baseline:
worse = worse_than(s, json.loads(Path(args.baseline).read_text()))
for line in worse:
print("WORSE", line)
if worse:
sys.exit(1)
print("no question got worse than the baseline")
if __name__ == "__main__":
main() - Retrieval does not depend on the model, so one run is enough.line 29
- A missing section counts as 0.line 35
- Compares question by question: a better total can hide a new failure.line 48
- A non-zero exit code fails a CI job.line 75
python -m evals.score results/v1.jsonl --save baseline.json 3/3 shipping-cost 3/3 discount-code 3/3 return-window 3/3 cancel-shipped 3/3 coupon-case 3/3 password-length 0/3 twelve-mugs missing '10' 3/3 ship-time 3/3 welcome15 0/3 refund-how missing 'support@shoprung.test' 3/3 two-coupons 3/3 off-topic overall 30/36 = 83% retrieval: recall@3 0.91, MRR 0.91 saved baseline baseline.json
Catch a prompt regression
Turn on ShopRung's prompt regression and watch the eval fail.
ShopRung's chat-prompt-regression bug swaps in prompt v2: a friendlier edit that dropped the rule to answer only from the help pages. Turn it on, run the eval again and compare with the baseline.
Four questions went from 3/3 to 0/3, with clear reasons: free shipping on every order, returns within 90 days, an expired coupon recommended. The score exits with code 1. Retrieval did not change (still 0.91): so the problem is in generation, not in finding the text. Look at refund-how: it was already failing, so the baseline cannot flag it, yet it now also says 90 days. A known failure can hide a new problem; fix known failures when you can. Turn the bug off afterwards.
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-prompt-regression"]}'
python -m evals.run --runs 3 --out results/regression.jsonl
python -m evals.score results/regression.jsonl --baseline baseline.json
echo "exit code: $?"
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-prompt-regression"]}'
python -m evals.run --runs 3 --out results/regression.jsonl
python -m evals.score results/regression.jsonl --baseline baseline.json
echo "exit code: $?"
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[\"chat-prompt-regression\"]}'
python -m evals.run --runs 3 --out results/regression.jsonl
python -m evals.score results/regression.jsonl --baseline baseline.json
echo "exit code: $LASTEXITCODE"
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[]}' model fake, prompt v2: 12 questions x 3 runs ............ saved results/regression.jsonl 0/3 shipping-cost missing '$4.99'; missing '$75.00' 0/3 discount-code missing 'SAVE10' 0/3 return-window missing '30 days'; says '90 days' 3/3 cancel-shipped 3/3 coupon-case 3/3 password-length 0/3 twelve-mugs missing '10' 3/3 ship-time 3/3 welcome15 0/3 refund-how missing 'support@shoprung.test'; says '90 days' 0/3 two-coupons missing one of ['one coupon'] 3/3 off-topic overall 18/36 = 50% retrieval: recall@3 0.91, MRR 0.91 WORSE shipping-cost: 3/3 -> 0/3 WORSE discount-code: 3/3 -> 0/3 WORSE return-window: 3/3 -> 0/3 WORSE two-coupons: 3/3 -> 0/3 exit code: 1
A pytest gate for CI
One test per golden question, with known failures marked.
Create tests/test_eval_gate.py. It makes one test per golden question. Questions that failed every run in baseline.json are marked xfail with the reason, so the gate stays green on today's known failures. strict=True means that if someone fixes one, the test reports it, and you update the baseline. The fixture checks that ShopRung runs the fake model: on a deterministic model one run per question is enough.
Run the whole suite: 16 passed (6 check tests and 10 golden questions) and 2 expected failures. Then add the workflow: it starts ShopRung with the fake model, runs the gate, scores against the baseline and keeps the raw answers as an artifact. Put this folder in your repository from lab 23 as chat-evals, next to shoprung.
"""The eval as a CI gate: every golden question must pass, except the known failures in baseline.json.
Run against ShopRung's deterministic fake model, one run per question is enough.
"""
import json
import os
from pathlib import Path
import httpx
import pytest
from evals.checks import check
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
GOLDEN = json.loads(Path("golden.json").read_text())
BASELINE = json.loads(Path("baseline.json").read_text())["questions"]
def known_failure(item: dict) -> list:
base = BASELINE[item["id"]]
if base["passed"] == 0:
return [pytest.mark.xfail(reason="known failure: " + "; ".join(base["problems"]), strict=True)]
return []
@pytest.fixture(scope="module")
def chat():
with httpx.Client(base_url=BASE_URL, timeout=60) as client:
assert client.get("/api/support/info").json()["model"] == "fake", "the gate expects the fake model"
yield lambda q: client.post("/api/support/chat", json={"message": q}).raise_for_status().json()
@pytest.mark.parametrize("item", [pytest.param(i, id=i["id"], marks=known_failure(i)) for i in GOLDEN])
def test_golden_question(chat, item):
assert check(item, chat(item["q"])) == [] - Known failures stay visible in the report, without failing the build.line 22
- If a known failure starts passing, the test fails: update the baseline.line 22
- Exact pass/fail only works on a deterministic model.line 29
name: chat-evals
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
evals:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Start ShopRung (fake model)
working-directory: shoprung
run: |
npm start > shoprung.log 2>&1 &
npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Eval gate
working-directory: chat-evals
run: |
pip install -r requirements.txt
pytest
- name: Scores against the baseline
if: always()
working-directory: chat-evals
run: |
python -m evals.run --runs 1 --out results/ci.jsonl
python -m evals.score results/ci.jsonl --baseline baseline.json
- name: Keep the raw answers
if: always()
uses: actions/upload-artifact@v4
with:
name: chat-eval-results
path: chat-evals/results/ - No model to install in CI: the fake model is built in.line 22
- Prints the per-question table in the job log, even when the gate failed.line 44
- The raw answers, for anyone reviewing a failure.line 50
pytest -q ............x..x.. [100%] =========================== short test summary info ============================ XFAIL tests/test_eval_gate.py::test_golden_question[twelve-mugs] - known failure: missing '10' XFAIL tests/test_eval_gate.py::test_golden_question[refund-how] - known failure: missing 'support@shoprung.test' 16 passed, 2 xfailed in 0.12s
Run it on a real model (optional)
The same eval on llama3.2:3b, with its own baseline and a margin for noise.
This step needs Ollama and about 2 GB of disk. Pull the model, stop ShopRung (Ctrl+C) and start it again with the model setting. Then run the eval 3 times per question; it takes a minute or two on a laptop.
Our run on a Mac scored 31 of 36. The pattern differs from the fake model: refund-how passed 3/3, but one cancel answer said "I don't know" and mentioned a customer service team, and one password answer said "According to the <help> page". A real model varies, so keep one baseline per model, and allow for noise: the updated score.py adds --margin; with 3 runs, 0.34 ignores a drop of one run. Use more runs before trusting small differences. Restart ShopRung with plain npm start when you finish.
"""Score saved chat responses against the golden set, and compare with a baseline.
python -m evals.score results/today.jsonl # print the scores
python -m evals.score results/today.jsonl --save baseline.json # keep them as the baseline
python -m evals.score results/today.jsonl --baseline baseline.json # exit 1 if any question got worse
python -m evals.score results/real.jsonl --baseline real-baseline.json --margin 0.34 # allow 1 run in 3
"""
import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path
from evals.checks import check, source_rank
GOLDEN = {item["id"]: item for item in json.loads(Path("golden.json").read_text())}
def score(rows: list[dict]) -> dict:
by_id = defaultdict(list)
for row in rows:
by_id[row["id"]].append(row)
questions, ranks = {}, []
for qid, item in GOLDEN.items():
results = by_id[qid]
problems = [check(item, r) for r in results]
questions[qid] = {"passed": sum(not p for p in problems), "runs": len(results),
"problems": sorted({p for ps in problems for p in ps})}
if item.get("source"):
ranks.append(source_rank(item, results[0])) # retrieval is the same every run
passed = sum(q["passed"] for q in questions.values())
runs = sum(q["runs"] for q in questions.values())
return {
"passed": passed, "runs": runs,
"recall_at_3": sum(r > 0 for r in ranks) / len(ranks),
"mrr": sum(1 / r for r in ranks if r) / len(ranks),
"questions": questions,
}
def report(s: dict) -> None:
for qid, q in s["questions"].items():
note = "; ".join(q["problems"])
print(f"{q['passed']}/{q['runs']} {qid:<16} {note}")
print(f"overall {s['passed']}/{s['runs']} = {s['passed'] / s['runs']:.0%}")
print(f"retrieval: recall@3 {s['recall_at_3']:.2f}, MRR {s['mrr']:.2f}")
def worse_than(s: dict, base: dict, margin: float = 0) -> list[str]:
worse = []
for qid, q in s["questions"].items():
old = base["questions"].get(qid)
if old and q["passed"] / q["runs"] < old["passed"] / old["runs"] - margin:
worse.append(f"{qid}: {old['passed']}/{old['runs']} -> {q['passed']}/{q['runs']}")
return worse
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("results")
parser.add_argument("--save", help="write these scores as a new baseline")
parser.add_argument("--baseline", help="fail if any question scores lower than here")
parser.add_argument("--margin", type=float, default=0, help="how much lower counts as noise, e.g. 0.34")
args = parser.parse_args()
rows = [json.loads(line) for line in Path(args.results).read_text().splitlines()]
s = score(rows)
report(s)
if args.save:
Path(args.save).write_text(json.dumps(s, indent=2) + "\n")
print(f"saved baseline {args.save}")
if args.baseline:
worse = worse_than(s, json.loads(Path(args.baseline).read_text()), args.margin)
for line in worse:
print("WORSE", line)
if worse:
sys.exit(1)
print("no question got worse than the baseline")
if __name__ == "__main__":
main() - Only a drop larger than the margin counts as worse.line 53
- Leave it at 0 for the fake model: there is no noise to allow for.line 63
ollama pull llama3.2:3b
# in the ShopRung terminal: Ctrl+C, then
SHOPRUNG_CHAT_MODEL=llama3.2:3b npm start
# back in chat-evals:
python -m evals.run --runs 3 --out results/llama.jsonl
python -m evals.score results/llama.jsonl --save real-baseline.jsonollama pull llama3.2:3b
# in the ShopRung terminal: Ctrl+C, then
SHOPRUNG_CHAT_MODEL=llama3.2:3b npm start
# back in chat-evals:
python -m evals.run --runs 3 --out results/llama.jsonl
python -m evals.score results/llama.jsonl --save real-baseline.jsonollama pull llama3.2:3b
# in the ShopRung terminal: Ctrl+C, then
$env:SHOPRUNG_CHAT_MODEL="llama3.2:3b"; npm start
# back in chat-evals:
python -m evals.run --runs 3 --out results/llama.jsonl
python -m evals.score results/llama.jsonl --save real-baseline.json model llama3.2:3b, prompt v1: 12 questions x 3 runs ............ saved results/llama.jsonl 3/3 shipping-cost 3/3 discount-code 3/3 return-window 2/3 cancel-shipped missing one of ['no longer be cancelled', 'cannot be cancelled', "can't be cancelled"] 3/3 coupon-case 2/3 password-length shows <help> markup 0/3 twelve-mugs missing '10' 3/3 ship-time 3/3 welcome15 3/3 refund-how 3/3 two-coupons 3/3 off-topic overall 31/36 = 86% retrieval: recall@3 0.91, MRR 0.91 saved baseline real-baseline.json
Check it works
With ShopRung on the fake model and no bugs, pytest -q shows 16 passed, 2 xfailed, and python -m evals.score results/v1.jsonl --baseline baseline.json ends with "no question got worse than the baseline".
Switch on chat-prompt-regression and run pytest -q again: four golden questions fail (shipping-cost, discount-code, return-window, two-coupons), each with its reason. Turn the bug off.
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-prompt-regression"]}'
pytest -qcurl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["chat-prompt-regression"]}'
pytest -qcurl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[\"chat-prompt-regression\"]}'
pytest -q FAILED tests/test_eval_gate.py::test_golden_question[shipping-cost] - assert ... FAILED tests/test_eval_gate.py::test_golden_question[discount-code] - assert ... FAILED tests/test_eval_gate.py::test_golden_question[return-window] - assert ... FAILED tests/test_eval_gate.py::test_golden_question[two-coupons] - assert ["... 4 failed, 12 passed, 2 xfailed in 0.11s
Troubleshooting
ConnectError from the runner or the gate.
ShopRung is not running, or runs on another port. Start it, or set BASE_URL=http://localhost:PORT.
AssertionError: the gate expects the fake model.
ShopRung was started with SHOPRUNG_CHAT_MODEL. Restart it with plain npm start for the gate; use run.py and score.py with a margin for real models.
503 model_unavailable or model_error on a real model.
Ollama is not running, or the model is not pulled. Run ollama pull llama3.2:3b and check ollama list.
XPASS(strict) for twelve-mugs or refund-how.
A known failure now passes. Check the answer is really right, then save a new baseline with --save baseline.json.
Different numbers from this lab on a real model.
Expected: real answers vary by run, machine and model version. Compare against your own real-model baseline, never the fake one.
What changes in production
- Teams keep the golden set in Git and grow it from real customer questions, especially the ones that went wrong.
- A deterministic fake or recorded responses gate every pull request; the real model runs nightly or before a release, with more runs per question.
- Each change to the prompt, model or retrieval is compared per question against the baseline, and reviewed with the raw answers.
- Keyword checks are combined with an LLM judge or human review for meaning, and with separate retrieval metrics.
Interview angle
“How would you build an eval for a chatbot?”
A golden set in Git: questions by category with required facts, forbidden facts, the source that should be retrieved, and out-of-scope questions that must be refused. A runner asks each question several times and saves the raw responses, so scoring can be improved without new model calls. The scorer gives a pass rate per question with reasons, plus recall@3 and MRR for retrieval, and compares with a baseline per model. On our shop chat, a prompt regression took it from 30 to 18 of 36, with four questions dropping to zero, and retrieval unchanged, which pointed at generation. In CI a pytest gate runs it on a deterministic fake model, with known failures marked xfail.
Clean up
Practice
These run in your browser and check your answer.
Mean reciprocal rank
Write mrr(ranks): ranks are the positions of the expected section for each question, 1 for first, 0 when it was not found. Return the average of 1 / rank, counting a missing section (0) as 0.
def mrr(ranks):
return sum(1 / r for r in ranks) / len(ranks)
Hint
Skip the zeros in the sum, but keep them in the count.
The full project
Every file from this lab, as it is after the last step.