AI Engineering · Build lab 12 of 14

Build an LLM evals pipeline in Python: golden dataset, retrieval metrics, LLM-as-judge and a CI gate

Stop eyeballing your RAG app and measure it. Write a golden dataset in JSONL, score retrieval with recall@k and MRR, add rule-based checks, grade faithfulness with a calibrated LLM judge, save a JSON report, and fail the build when scores drop, with pytest and GitHub Actions.

⏱ 75 minIntermediate💸 Free (local models)10 steps

Python 3.12uvOllamallama3.2:3bnomic-embed-textPydantic 2pytestGitHub Actions

Overview video

1 / 7

0 of 10 steps done

What you will build

An evals pipeline for the handbook question-answering app from lab 6. Today you probably test a change like that by asking three questions and reading the answers. That tells you nothing about the other questions you did not ask. An eval asks all of them, every time, and gives you numbers.

You build it in layers, from cheapest to most expensive: a golden dataset of 15 questions in JSONL with the facts and the source file each answer needs (and three questions the app must refuse); retrieval metrics (recall@4 and MRR) that need no chat model at all; rule-based checks (is there a citation, is it the right file, are the required facts in the answer, did it refuse the off-topic question); and an LLM judge that grades faithfulness and relevance with a strict rubric and JSON output validated by Pydantic. Before you trust the judge, you calibrate it against answers you graded by hand.

Every run prints a results table and writes a JSON report. A regression gate compares the scores with a saved baseline and fails when one drops: uv run pytest -m evals runs it, and a GitHub Actions workflow runs the fast tests on every push and the evals when you press a button. The fast tests use fakes, so they need no model.

Before you start

  • Lab 6 helps: RAG from scratch. This lab evaluates that app. Every file is shown again in step 2, so you can also start here.
  • Lab 3 for the judge: Structured output. The judge uses the same response_format JSON Schema and Pydantic validation.
  • pytest basics: Testing with pytest. Markers and fixtures are explained here as they come up.
  • The ideas in 10 minutes each: Evaluating RAG and LLM evals in practice.
  • About 3 GB of free disk space for the two models. A GitHub account if you want to try the CI workflow in step 10 (optional).

Setup

S1Install uv (skip if you did lab 1)

uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
everything's installed!

S2Check uv works

The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.

Run
uv --version
You should see
uv 0.x.y

S3Install Ollama (skip if you did lab 1)

Download it from ollama.com/download and open it once. It runs a small server on port 11434 with the same API as the hosted providers, for chat and for embeddings. JSON Schema output (the judge in step 6 uses it) needs Ollama 0.5 or newer.

Run
ollama --version
You should see
ollama version is 0.x.y

S4Pull the chat model and the embedding model

llama3.2:3b (about 2 GB) answers the questions and, at first, also grades them. nomic-embed-text (about 270 MB) turns text into vectors for retrieval. Both are the same models as lab 6. ollama list should show both afterwards.

Run
ollama pull llama3.2:3b
ollama pull nomic-embed-text
ollama list
You should seeyour text will differ: the model writes it
NAME                       ID              SIZE      MODIFIED
nomic-embed-text:latest    0a109f422b47    274 MB    2 seconds ago
llama3.2:3b                a80c4f17acd5    2.0 GB    3 days ago

S5Optional: a stronger judge model

A judge should be at least as strong as the model it grades. A 3B model grading itself works for learning, and step 7 shows you how far to trust it. If you have about 5 GB more disk, pull an 8B model now and try it as the judge in step 7.

Run
ollama pull llama3.1:8b
You should see
pulling manifest
...
success
1

Create the project

A fresh project with NumPy, the SDK, Pydantic and pytest, plus lab 6's settings and one new one: the judge model.

uv init creates the project folder and pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them, so anyone (and the CI server in step 10) can recreate it with uv sync. --dev marks pytest as a development-only dependency, like testImplementation in Gradle.

The settings are lab 6's (without the database) plus JUDGE_MODEL: the model that grades the answers. It is a separate setting because in real projects the judge is often a different, stronger model than the one that answers.

.env
# Local models through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
EMBED_MODEL=nomic-embed-text

# Retrieval: below this cosine similarity a chunk does not count as relevant (lab 6).
MIN_SCORE=0.65

# The model that grades answers (step 6). Empty means: the same as LLM_MODEL.
JUDGE_MODEL=
  1. Ollama's OpenAI-compatible API. Chat and embeddings both live under this URL.line 2
  2. Lab 6's minimum cosine similarity: below it, a chunk does not count as relevant, and with no relevant chunk the app refuses without asking the model. Step 9 changes it on purpose to break the app.line 8
  3. Empty: grade with the same model that answers. Set it to llama3.1:8b (or a hosted model) for a stronger judge.line 11
config.py 4 new or changed lines
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    embed_model: str
    min_score: float
    judge_model: str


def settings() -> Settings:
    model = os.environ.get("LLM_MODEL", "llama3.2:3b")
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=model,
        embed_model=os.environ.get("EMBED_MODEL", "nomic-embed-text"),
        min_score=float(os.environ.get("MIN_SCORE", "0.65")),
        judge_model=os.environ.get("JUDGE_MODEL") or model,
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell win, so MIN_SCORE=0.99 uv run ... overrides the file for one command (step 9 does that).line 6
  2. frozen=True makes the settings read-only, like a Java record.line 9
  3. Read the model once, so the judge can fall back to it.line 20
  4. Environment variables are always strings: float(...) turns "0.65" into a number, like Double.parseDouble.line 26
  5. JUDGE_MODEL= in .env gives an empty string. "" or model is model: in Python an empty string counts as false, and a or b returns b when a is false.line 27
.gitignore
.venv/
__pycache__/
.env
reports/
  1. Never commit .env: one day it holds a real key.line 3
  2. Every eval run writes reports/latest.json. It is a result, not source code. The **baseline** you save in step 8 lives in evals/ and **is** committed.line 4
llm.py
from openai import OpenAI

from config import settings


def make_client() -> OpenAI:
    s = settings()
    return OpenAI(base_url=s.base_url, api_key=s.api_key, timeout=120, max_retries=2)
  1. A function, not a global: the app and the judge receive the client as a parameter, so tests can hand them a fake (step 10).line 6
  2. Generous timeout for a local model on a laptop CPU. max_retries=2 retries network errors, 429 and 5xx for you.line 8
Run
uv init rag-evals
cd rag-evals
uv add numpy openai pydantic python-dotenv
uv add --dev pytest
You should seeyour text will differ: the model writes it
Initialized project `rag-evals` at `.../rag-evals`
Resolved 20 packages in 460ms
Installed 18 packages in 40ms
 + numpy==2.5.5
 + openai==3.60.0
 + pydantic==2.14.4
 + python-dotenv==1.2.4
 ...
Stuck on this step?
uv: command not found
Run export PATH="$HOME/.local/bin:$PATH" (macOS and Linux), or open a new terminal so the installer's PATH change applies.
uv also created main.py
Newer uv versions write a hello-world main.py. This lab does not use it: delete it or leave it.
2

The app under test: lab 6's handbook RAG

The system you are going to measure: eight Markdown files, chunking, embeddings, an in-memory vector store and answers with citations.

Evals need something to evaluate. This is the RAG app from lab 6, with two small changes: the store lives only in memory (the eval builds a fresh index on every run, which takes a couple of seconds for 30 chunks), and the whole pipeline sits in one HandbookRag object in app.py, so the eval can create it once and ask it 15 questions.

Make a folder called handbook and save the eight files in it. They describe Larkspur, a made-up company, on purpose: the model cannot know these rules from training, so a correct answer must come from retrieval.

If you did lab 6, the Python files are the same except store.py (no saving to disk) and the new app.py and ask.py. The notes only cover what matters for the evals; lab 6 explains every line.

handbook/expenses.md
# Travel and expenses

## Booking travel
Book all work travel in TravelDesk, at least 14 days ahead when you can. Fly economy class. For trips under four hours, take the train instead of flying.

Your manager approves each trip in TravelDesk before you book. Trips to a customer also need the account owner's approval.

## Hotels
Hotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.

Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.

If a conference hotel costs more than the limit, ask your manager before booking. Approved exceptions are noted on the trip in TravelDesk, so finance can see them when you submit the bill.

## Meals
On a work trip, meals are covered up to 60 euros a day. Alcohol is not covered.

## Submitting expenses
Submit expenses in Peoplebase within 30 days, with a photo of every receipt. They are paid with your next salary.
  1. The answer to the first golden question: 250 euros a night in London. Most golden questions point at one fact like this.line 9
handbook/time-off.md
# Time off

## Vacation
Everyone gets 25 vacation days a year, plus the public holidays of the country you work from. The year runs from January to December.

You can carry up to 5 unused days into the next year. Carried days expire on 31 March.

## Sick leave
There is no fixed number of sick days. Tell your manager before 10:00 on the first day. From the fourth day in a row, send a doctor's note to the People team.

## Parental leave
Every parent gets 16 weeks of fully paid leave, to take within the first year after a birth or adoption. You can split it into up to three blocks.

## How to request time off
Request time off in Peoplebase. For more than three days in a row, ask at least two weeks ahead.
handbook/remote-work.md
# Remote work

## Where you can work
You can work from any country where Larkspur has a company: Portugal, Spain, Germany or the United Kingdom.

Working from another country is allowed for up to 30 days a year. Tell the People team before you go, because of tax and insurance rules.

## Core hours
Be available from 11:00 to 15:00 Lisbon time. Outside core hours, plan your day as you like.

## Home office budget
New joiners get a one-time budget of 1,000 euros for a desk, a chair and a screen. Internet at home is paid with 40 euros a month on top of your salary.
handbook/security.md
# Security

## Your laptop
Laptops use full-disk encryption and lock after 5 minutes. Never leave your laptop in a car, not even in the trunk.

## Passwords and two-factor login
Use the company password manager for every work account. Turn on two-factor login with the hardware key you get on your first day.

## Lost or stolen devices
If a laptop, phone or hardware key is lost or stolen, report it in the #security-help channel within one hour, or email security@larkspur.example. The security team locks the device remotely.

## Phishing
Forward suspicious emails to phishing@larkspur.example and delete them. The finance team never asks for payments by email or chat.
handbook/onboarding.md
# Your first week

## Before day one
Your laptop and hardware key arrive at your home address a few days before you start. Do not set them up yet.

## Day one
The welcome call starts at 10:00 Lisbon time. You meet your onboarding buddy, who sets up the laptop with you and answers questions for your first month.

## First week checklist
Read this handbook, set up the password manager, book a coffee chat with each person on your team, and ship one small change to production.
handbook/on-call.md
# On-call

## The rotation
Engineers join the on-call rotation after three months at Larkspur. A shift lasts one week, from Monday 10:00 to the next Monday 10:00.

## On-call pay
You get 300 euros for each week on call, plus 50 euros for each incident you handle outside working hours.

## Responding to a page
Acknowledge a page within 15 minutes. If you cannot fix it within 30 minutes, escalate to the secondary on-call engineer.

## After an incident
Write a blameless postmortem within five working days and share it in the #incidents channel.
handbook/benefits.md
# Benefits

## Health insurance
Private health insurance covers you, your partner and your children from your first day.

## Learning budget
Each person has 1,500 euros a year for books, courses and conferences. Spending over 500 euros at once needs your manager's approval.

## Equipment
You get a new laptop every three years. A broken laptop is replaced straight away.

## Wellbeing
Larkspur pays up to 50 euros a month towards a gym, a sports club or a meditation app.
handbook/offices.md
# Offices

## The Lisbon office
The Lisbon office is open from 08:00 to 20:00 on working days. Guests sign in at reception and wear a visitor badge.

## Meeting rooms
Book meeting rooms in the office calendar. Free a room you no longer need, so others can use it.

## Team weeks
Each team meets in Lisbon for one week, twice a year. Larkspur pays the travel and the hotel for team weeks.
chunking.py
import re
from dataclasses import dataclass
from pathlib import Path

HEADING = re.compile(r"^(#{1,6})\s+(.+)$")


@dataclass(frozen=True)
class Chunk:
    id: str  # "expenses.md#3": the file name and the chunk's position, unique
    source: str  # "expenses.md"
    heading: str  # "Travel and expenses > Hotels"
    text: str

    def for_embedding(self) -> str:
        """What the embedding model sees: the heading path gives a short chunk its context."""
        return f"{self.heading}\n\n{self.text}"


def split_sections(markdown: str) -> list[tuple[str, list[str]]]:
    """Cut a Markdown file at its headings. Returns [(heading path, [paragraph, ...]), ...]."""
    sections = []
    path: list[str] = []  # the headings above the current line, one per level
    paragraphs: list[str] = []
    lines: list[str] = []

    def end_paragraph():
        if lines:
            paragraphs.append("\n".join(lines))
            lines.clear()

    def end_section():
        end_paragraph()
        if paragraphs:
            sections.append((" > ".join(path), paragraphs.copy()))
            paragraphs.clear()

    for line in markdown.splitlines():
        match = HEADING.match(line)
        if match:
            end_section()
            level = len(match.group(1))
            path[level - 1:] = [match.group(2).strip()]
        elif line.strip():
            lines.append(line.strip())
        else:
            end_paragraph()
    end_section()
    return sections


def pack(paragraphs: list[str], max_chars: int, overlap: int) -> list[str]:
    """Group paragraphs into pieces of about max_chars. Each new piece repeats the last
    "overlap" paragraphs of the piece before, so a fact on the border is in both."""
    pieces = []
    current: list[str] = []
    for paragraph in paragraphs:
        if current and len("\n\n".join(current + [paragraph])) > max_chars:
            pieces.append(current)
            current = current[-overlap:] if overlap > 0 else []
        current.append(paragraph)
    if current:
        pieces.append(current)
    return ["\n\n".join(piece) for piece in pieces]


def chunk_markdown(markdown: str, source: str, max_chars: int = 400, overlap: int = 1) -> list[Chunk]:
    chunks = []
    for heading, paragraphs in split_sections(markdown):
        for text in pack(paragraphs, max_chars, overlap):
            chunks.append(Chunk(id=f"{source}#{len(chunks)}", source=source, heading=heading, text=text))
    return chunks


def load_handbook(folder: str = "handbook") -> list[Chunk]:
    chunks = []
    for path in sorted(Path(folder).glob("*.md")):
        chunks.extend(chunk_markdown(path.read_text(encoding="utf-8"), path.name))
    return chunks
  1. Every chunk knows its source file and its heading path. The evals use source to check retrieval and citations.line 9
  2. The id (expenses.md#1) changes when you change the chunking. That is why the golden set in step 3 names a **file**, not a chunk id.line 10
  3. Sections are split at headings; long ones into pieces of about 400 characters with one paragraph of overlap (lab 6, step 3).line 67
embedder.py
import numpy as np

# nomic-embed-text was trained with a task prefix on every text: one for documents, one for questions.
DOC_PREFIX = "search_document: "
QUERY_PREFIX = "search_query: "


def normalize(v: np.ndarray) -> np.ndarray:
    """Scale every row to length 1, so a dot product is the cosine similarity."""
    norms = np.linalg.norm(v, axis=-1, keepdims=True)
    return v / np.where(norms == 0, 1, norms)


class Embedder:
    def __init__(self, client, model: str, batch_size: int = 16):
        self.client = client
        self.model = model
        self.batch_size = batch_size

    def embed(self, texts: list[str]) -> np.ndarray:
        """One row per text, in the same order, each of length 1."""
        rows = []
        for start in range(0, len(texts), self.batch_size):
            batch = texts[start:start + self.batch_size]
            resp = self.client.embeddings.create(model=self.model, input=batch)
            rows.extend(item.embedding for item in sorted(resp.data, key=lambda d: d.index))
        return normalize(np.array(rows, dtype=np.float32))

    def embed_documents(self, texts: list[str]) -> np.ndarray:
        return self.embed([DOC_PREFIX + t for t in texts])

    def embed_query(self, text: str) -> np.ndarray:
        return self.embed([QUERY_PREFIX + text])[0]
  1. nomic-embed-text expects these task prefixes, one for documents and one for questions.line 4
  2. Every vector is scaled to length 1, so a dot product is the cosine similarity.line 11
  3. One request per batch of 16 texts, through the same SDK as chat.line 25
store.py
from dataclasses import dataclass
from typing import Protocol

import numpy as np

from chunking import Chunk


@dataclass(frozen=True)
class Hit:
    chunk: Chunk
    score: float  # cosine similarity: 1.0 means the same direction, near 0 means unrelated


class VectorStore(Protocol):
    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None: ...

    def search(self, vector: np.ndarray, k: int) -> list[Hit]: ...

    def count(self) -> int: ...


class InMemoryStore:
    """All vectors in one NumPy matrix, one row per chunk. Lab 6's store, without saving to disk."""

    def __init__(self):
        self.chunks: list[Chunk] = []
        self.vectors = np.zeros((0, 0), dtype=np.float32)

    def add(self, chunks: list[Chunk], vectors: np.ndarray) -> None:
        self.vectors = np.vstack([self.vectors, vectors]) if self.chunks else vectors
        self.chunks = self.chunks + list(chunks)

    def search(self, vector: np.ndarray, k: int) -> list[Hit]:
        if not self.chunks:
            return []
        scores = self.vectors @ vector
        best = np.argsort(-scores, kind="stable")[:k]
        return [Hit(self.chunks[i], float(scores[i])) for i in best]

    def count(self) -> int:
        return len(self.chunks)
  1. A search result: the chunk and its cosine score.line 10
  2. Protocol is Python's structural interface: any class with these methods fits, without implements.line 15
  3. Lab 6's in-memory store without the save and load code: the eval rebuilds the index every run.line 24
  4. @ is matrix multiplication: one score per chunk in one call. argsort(-scores) sorts from best to worst.line 37
prompt.py
from store import Hit

NOT_FOUND = "I don't know. The handbook does not say."

SYSTEM = f"""You answer questions about the Larkspur employee handbook.
Rules:
- Use only the numbered sources in the user message. Do not use outside knowledge.
- After each fact, cite the number of its source in square brackets, like [1] or [2].
- If the sources do not answer the question, reply exactly: {NOT_FOUND}
- Keep the answer short: one to three sentences."""


def format_sources(hits: list[Hit]) -> str:
    """[1] file > heading path, then the chunk text. Numbered from 1, in ranking order."""
    blocks = []
    for n, hit in enumerate(hits, start=1):
        c = hit.chunk
        blocks.append(f"[{n}] {c.source} > {c.heading}\n{c.text}")
    return "\n\n".join(blocks)


def build_messages(question: str, hits: list[Hit]) -> list[dict]:
    user = f"Sources:\n\n{format_sources(hits)}\n\nQuestion: {question}"
    return [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": user},
    ]
  1. The fixed "not in the handbook" sentence. The refusal check in step 5 looks for it.line 3
  2. The citation rule. The cited check in step 5 tests whether the model follows it.line 8
  3. Turns the hits into numbered sources. Step 8 reuses it to show the judge exactly what the model saw.line 13
rag.py
import re
from dataclasses import dataclass, field

from prompt import NOT_FOUND, build_messages
from store import Hit, VectorStore

CITATION = re.compile(r"\[(\d+)\]")


@dataclass
class Answer:
    text: str
    sources: list[Hit]  # what the model was given, numbered from 1
    cited: list[int]  # the source numbers the answer really cites
    retrieved: list[Hit] = field(default_factory=list)  # everything the search returned
    refused: bool = False  # True when retrieval found nothing relevant and the model was not called


def cited_numbers(text: str, n_sources: int) -> list[int]:
    """The source numbers cited in the text, in order, without repeats or made-up numbers."""
    found = []
    for match in CITATION.finditer(text):
        n = int(match.group(1))
        if 1 <= n <= n_sources and n not in found:
            found.append(n)
    return found


def answer(question: str, store: VectorStore, embedder, client, model: str,
           k: int = 4, min_score: float = 0.65) -> Answer:
    retrieved = store.search(embedder.embed_query(question), k)
    relevant = [hit for hit in retrieved if hit.score >= min_score]
    if not relevant:
        return Answer(NOT_FOUND, [], [], retrieved, refused=True)

    resp = client.chat.completions.create(
        model=model,
        messages=build_messages(question, relevant),
        temperature=0,
    )
    text = resp.choices[0].message.content
    return Answer(text, relevant, cited_numbers(text, len(relevant)), retrieved)
  1. retrieved keeps everything the search returned, even chunks below the minimum score. The retrieval metrics use it.line 15
  2. refused is True when the code refused without calling the model.line 16
  3. Reads the [n] markers and keeps only real source numbers.line 19
  4. Nothing scored high enough: refuse with the fixed sentence, and never call the model.line 33
  5. Temperature 0: the most likely words, so two runs of the eval give (almost) the same answers.line 39
app.py
from chunking import load_handbook
from config import settings
from embedder import Embedder
from llm import make_client
from rag import Answer, answer
from store import InMemoryStore


class HandbookRag:
    """The lab 6 app as one object: index the handbook once, then answer many questions."""

    def __init__(self, client, embedder, model: str, min_score: float, k: int = 4, folder: str = "handbook"):
        self.client, self.embedder, self.model = client, embedder, model
        self.min_score, self.k = min_score, k
        chunks = load_handbook(folder)
        self.store = InMemoryStore()
        self.store.add(chunks, embedder.embed_documents([c.for_embedding() for c in chunks]))

    def ask(self, question: str) -> Answer:
        return answer(question, self.store, self.embedder, self.client, self.model,
                      k=self.k, min_score=self.min_score)


def make_app() -> HandbookRag:
    s = settings()
    client = make_client()
    return HandbookRag(client, Embedder(client, s.embed_model), s.model, s.min_score)
  1. The whole app in one object, so the eval treats it as a black box: question in, Answer out. Any app with an ask() method could be evaluated the same way.line 9
  2. Everything it needs comes in as parameters (dependency injection, like constructor injection in Spring). The tests in step 10 never build one: they use a fake app instead.line 12
  3. Several assignments in one line: a, b = 1, 2 sets a to 1 and b to 2.line 13
  4. Indexing happens once, in the constructor: chunk, embed, store.line 17
  5. One question, the full RAG pipeline from lab 6.line 19
  6. A factory that wires the real client and settings together. Only the scripts call it.line 24
ask.py
import sys

from app import make_app

question = " ".join(sys.argv[1:]) or "How much can I spend on a hotel in London?"
result = make_app().ask(question)
print(result.text)
for n in result.cited:
    c = result.sources[n - 1].chunk
    print(f"  [{n}] {c.source} > {c.heading}")
if result.refused:
    print("  (refused: no chunk reached the minimum score)")
  1. The words after the script name, joined into one question. With none, a default question.line 5
  2. Citation [n] is sources[n - 1]: the list starts at 0, the numbers at 1.line 9
Run
uv run ask.py "How much can I spend on a hotel in London?"
You should seeyour text will differ: the model writes it
You can spend up to 250 euros a night on a hotel in London [1].
  [1] expenses.md > Travel and expenses > Hotels
Why this way? Treat the app as a black box with one entry point. The eval then measures what users get, and it keeps working when you swap the chunking, the store or the model inside, which are exactly the changes you will want to measure.
Stuck on this step?
openai.NotFoundError: ... model "nomic-embed-text" not found
You have not pulled the embedding model: run ollama pull nomic-embed-text.
APIConnectionError: Connection error.
Ollama is not running. Open the Ollama app or run ollama serve.
FileNotFoundError or an answer that always refuses
Run the command from the project folder, next to the handbook folder: load_handbook("handbook") uses a relative path, and with no files there are no chunks to find.
3

A golden dataset in JSONL

Fifteen questions with the facts and the source file each answer needs, including three the app must refuse, validated by Pydantic.

A golden dataset is a fixed list of inputs with what a good output must contain. It is the eval's equivalent of the expected values in a unit test. Each case here has an id, the question, the facts a correct answer must mention, and the source file that holds the answer. For an off-topic question source is null: the right behaviour is to refuse.

The format is JSONL (JSON Lines): one JSON object per line. It is the usual format for eval sets and model training data, because you can append a case with one line, a git diff shows exactly which case changed, and you can read it line by line without loading the whole file.

Labels are deliberately loose where wording varies and strict where it matters. A fact is a short string that must appear in the answer ("250"), and | separates spellings that all count ("31 March|March 31"). The source is a file name, not a chunk id, so the dataset survives a change to the chunking.

Write cases the way users ask, not the way the handbook is written: "My laptop was stolen. What should I do?" rather than "lost or stolen devices". And include the questions you must not answer. The third off-topic case mentions Larkspur on purpose: it sounds on-topic, but the handbook has no share price.

evals/golden.jsonl
{"id": "hotel-london", "question": "How much can I spend on a hotel in London?", "facts": ["250"], "source": "expenses.md"}
{"id": "hotel-limit", "question": "What is the normal hotel limit per night?", "facts": ["180"], "source": "expenses.md"}
{"id": "meals", "question": "How much is covered for meals on a work trip?", "facts": ["60"], "source": "expenses.md"}
{"id": "expense-deadline", "question": "How long do I have to submit my expenses?", "facts": ["30 days"], "source": "expenses.md"}
{"id": "vacation-days", "question": "How many vacation days do I get each year?", "facts": ["25"], "source": "time-off.md"}
{"id": "carry-over", "question": "When do vacation days carried over from last year expire?", "facts": ["31 March|March 31"], "source": "time-off.md"}
{"id": "parental-leave", "question": "How many weeks of parental leave do I get?", "facts": ["16"], "source": "time-off.md"}
{"id": "stolen-laptop", "question": "My laptop was stolen. What should I do?", "facts": ["one hour|1 hour|an hour", "security-help|security@larkspur.example"], "source": "security.md"}
{"id": "core-hours", "question": "What are the core hours?", "facts": ["11:00|11 am|11am", "15:00|3 pm|3pm"], "source": "remote-work.md"}
{"id": "home-office", "question": "What is the home office budget for new joiners?", "facts": ["1,000|1000"], "source": "remote-work.md"}
{"id": "on-call-pay", "question": "How much do I get paid for a week on call?", "facts": ["300"], "source": "on-call.md"}
{"id": "learning-budget", "question": "How big is the yearly learning budget?", "facts": ["1,500|1500"], "source": "benefits.md"}
{"id": "off-topic-capital", "question": "What is the capital of Australia?", "facts": [], "source": null}
{"id": "off-topic-poem", "question": "Write a short poem about the sea.", "facts": [], "source": null}
{"id": "off-topic-stock", "question": "What is Larkspur's share price today?", "facts": [], "source": null}
  1. One case per line. facts: ["250"]: the answer must contain 250. source: the file a correct answer cites.line 1
  2. Two spellings of the same date, separated by |. Either one counts.line 6
  3. Two facts: both must be in the answer (within one hour, and where to report it).line 8
  4. "source": null (JSON's null, Python's None): the handbook does not cover this, so the app must refuse.line 13
  5. The tricky refusal: the company name makes it sound like a handbook question.line 15
dataset.py
import json
from pathlib import Path

from pydantic import BaseModel, Field, ValidationError


class GoldenCase(BaseModel):
    id: str = Field(min_length=1)
    question: str = Field(min_length=1)
    facts: list[str] = Field(default_factory=list, description='each fact must appear in the answer; "a|b" means a or b')
    source: str | None = Field(description="the handbook file that answers it; null means the app must refuse")

    @property
    def answerable(self) -> bool:
        return self.source is not None


def load_jsonl(path: str, model: type[BaseModel]) -> list:
    """One JSON object per line, each validated. Errors name the file and the line number."""
    rows = []
    for n, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), start=1):
        if not line.strip():
            continue
        try:
            rows.append(model.model_validate_json(line))
        except ValidationError as e:
            err = e.errors()[0]
            where = ".".join(str(part) for part in err["loc"]) or "line"
            raise ValueError(f"{path} line {n}: {where}: {err['msg']}") from e
    return rows


def load_golden(path: str = "evals/golden.jsonl") -> list[GoldenCase]:
    cases = load_jsonl(path, GoldenCase)
    ids = [c.id for c in cases]
    duplicates = sorted({i for i in ids if ids.count(i) > 1})
    if duplicates:
        raise ValueError(f"{path}: duplicate ids {duplicates}")
    return cases


if __name__ == "__main__":
    cases = load_golden()
    answerable = [c for c in cases if c.answerable]
    print(f"{len(cases)} cases: {len(answerable)} answerable, {len(cases) - len(answerable)} must be refused")
    for source in sorted({c.source for c in answerable}):
        print(f"  {source:<15} {sum(c.source == source for c in answerable)}")
  1. One golden case as a Pydantic model: like a Java record with validation (lab 3 and [Type hints and Pydantic](/ai/python/type-hints-and-pydantic)).line 7
  2. default_factory=list: a case without facts gets its own new empty list.line 10
  3. str | None with no default: the key is **required**, but may be null. A forgotten source is an error, a deliberate null is fine.line 11
  4. @property makes a method read like a field: case.answerable, no parentheses. Like a getter.line 13
  5. model: type[BaseModel] means "a Pydantic class" (not an object), like Class<T> in Java. The same loader reads the judge labels in step 7.line 18
  6. enumerate(..., start=1) counts the lines from 1, so the error message matches what your editor shows.line 21
  7. Parse and validate one line. A typo in the file stops the eval at once, instead of producing a silently wrong score.line 25
  8. raise ... from e keeps the original error attached, like passing a cause to a Java exception.line 29
  9. A set comprehension: the ids that appear more than once. Duplicate ids would make two report rows impossible to tell apart.line 36
  10. This block runs only when you start the file directly (uv run dataset.py), not when another file imports it. Python sets __name__ to "__main__" for the file you run, like a public static void main that only one class gets to use.line 42
Run
uv run dataset.py
You should see
15 cases: 12 answerable, 3 must be refused
  benefits.md     1
  expenses.md     4
  on-call.md      1
  remote-work.md  2
  security.md     1
  time-off.md     3
Why this way? Fifteen cases is a starting point that fits in one screen. Grow it from reality: every bug report and every surprising answer in production becomes a new line. A real eval set has a hundred or more cases, and each one is a question you never have to check by hand again.
Stuck on this step?
ValueError: evals/golden.jsonl line 4: Invalid JSON: ...
That line is not valid JSON. Common causes: single quotes instead of double quotes, a trailing comma, or one case split over two lines. JSONL needs each object on one line.
4

Measure retrieval first: recall@k and MRR

Score the search on its own, with no chat model: is the right file in the top 4, and how high?

In RAG, a wrong answer has two possible causes: the search did not find the right chunk, or the model did not use it. Measure them separately, so you know which half to fix. Retrieval is also the cheap half: it needs only the embedding model, no answers.

recall@k: is the expected source among the first k results? 1 or 0 per question, averaged over all questions. With k = 4, a recall@4 of 0.92 means that for 11 of 12 questions the right file was somewhere in the top 4.

MRR (mean reciprocal rank): one divided by the position of the first correct result, averaged. First place scores 1, second 0.5, third 0.33, not found 0. It rewards putting the right chunk first, which matters because models pay most attention to the first sources.

Off-topic questions are skipped here: there is nothing to find. Whether the app refuses them is checked in step 5.

metrics.py
def recall_at_k(retrieved: list[str], expected: str, k: int) -> float:
    """1.0 if the expected source is among the first k retrieved sources, else 0.0."""
    return 1.0 if expected in retrieved[:k] else 0.0


def reciprocal_rank(retrieved: list[str], expected: str) -> float:
    """1 / the position of the first retrieved chunk from the expected source; 0.0 if it is missing."""
    for position, source in enumerate(retrieved, start=1):
        if source == expected:
            return 1 / position
    return 0.0


def mean(values: list[float]) -> float | None:
    """The average, or None when there is nothing to average (so 'no data' never looks like 0)."""
    return round(sum(values) / len(values), 3) if values else None
  1. retrieved[:k] is the first k items (a slice, like subList(0, k)). in checks whether the list contains the value.line 3
  2. enumerate(..., start=1) gives positions from 1: the first result is position 1, so it scores 1 / 1.line 8
  3. / always gives a float in Python: 1 / 2 is 0.5, not 0 as in Java integer division.line 10
  4. float | None: a number, or None when no case had this metric (for example the judge scores when the judge did not run).line 14
  5. Rounded to 3 decimals so the JSON report and the baseline stay readable. x if cond else y is Java's cond ? x : y.line 16
eval_retrieval.py
from app import make_app
from dataset import load_golden
from metrics import mean, recall_at_k, reciprocal_rank

app = make_app()
recalls, ranks = [], []
for case in load_golden():
    if not case.answerable:
        continue  # nothing to find for a question the handbook does not cover
    hits = app.store.search(app.embedder.embed_query(case.question), app.k)
    retrieved = [hit.chunk.source for hit in hits]
    recalls.append(recall_at_k(retrieved, case.source, app.k))
    ranks.append(reciprocal_rank(retrieved, case.source))
    print(f"{case.id:<17} RR {ranks[-1]:.2f}  {' '.join(hit.chunk.id for hit in hits)}")
print(f"\nrecall@{app.k} {mean(recalls):.2f}  MRR {mean(ranks):.2f}  over {len(ranks)} questions")
  1. continue skips to the next case, as in Java.line 9
  2. Search directly with the app's store and embedder. No chat model is called, so this runs in seconds.line 10
  3. Compare by **file**: any chunk from expenses.md counts for an expenses question.line 11
  4. ranks[-1] is the last item of the list, the one just added. The line shows the chunk ids in rank order, so you can see where the right one landed.line 14
Run
uv run eval_retrieval.py
You should see
hotel-london      RR 1.00  expenses.md#1 expenses.md#2 expenses.md#0 expenses.md#3
hotel-limit       RR 1.00  expenses.md#1 expenses.md#2 expenses.md#3 offices.md#2
meals             RR 1.00  expenses.md#3 expenses.md#1 expenses.md#0 expenses.md#2
expense-deadline  RR 1.00  expenses.md#4 expenses.md#0 expenses.md#2 remote-work.md#0
vacation-days     RR 1.00  time-off.md#0 remote-work.md#0 offices.md#2 expenses.md#3
carry-over        RR 1.00  time-off.md#0 remote-work.md#0 expenses.md#0 time-off.md#1
parental-leave    RR 1.00  time-off.md#2 time-off.md#0 offices.md#2 remote-work.md#0
stolen-laptop     RR 1.00  security.md#2 security.md#0 benefits.md#2 onboarding.md#0
core-hours        RR 1.00  remote-work.md#1 on-call.md#0 offices.md#0 on-call.md#1
home-office       RR 1.00  remote-work.md#2 benefits.md#1 expenses.md#3 benefits.md#3
on-call-pay       RR 1.00  on-call.md#1 offices.md#2 on-call.md#0 onboarding.md#1
learning-budget   RR 1.00  benefits.md#1 remote-work.md#2 benefits.md#3 expenses.md#3

recall@4 1.00  MRR 1.00  over 12 questions
Why this way? Read the two numbers together. recall@4 of 1.00 says the right file was always among the sources the model will see, and MRR of 1.00 says it was always first. This output is a real run with nomic-embed-text on Ollama. Perfect scores are good news, and also a warning: 12 questions written by the person who wrote the handbook are easy. A real set needs the questions users actually type, and it will show weak spots. A run on another embedding build put a benefits.md chunk first for "home office budget" (MRR 0.96). Either way it is a retrieval problem, and you see it before a single answer is written. Lab 7 (Hybrid search and reranking) is all about raising these two numbers.
Stuck on this step?
My ranks and chunk ids differ from the ones shown
Normal: scores depend on the exact model build. What matters is the summary line, and that you can now see each change you make move it.
5

Rule-based checks on the answers

Run every golden question through the app and check the answers with plain code: answered, cited, right source, facts present, refused when it should.

Now the answers. Start with checks that are plain code: they are free, instant, and give the same result every time. Many teams find that these catch most regressions before an LLM judge is ever needed.

For an answerable question, four checks: answered (it did not refuse), cited (at least one [n] marker), right_source (one of the cited sources is the expected file), and facts (every required fact is in the text). For an off-topic question one check: refused, either by the code (no chunk reached the minimum score) or by the model (it wrote the fixed not-found sentence).

suite.py runs the cases and collects one row per case: the answer, the retrieved chunk ids, the checks and the retrieval scores. summarize turns the rows into one number per metric: the share of cases that passed. run_evals.py prints a table as the rows come in (the chat model is slow, so you see progress) and the summary at the end.

checks.py
from dataset import GoldenCase
from prompt import NOT_FOUND
from rag import Answer


def has_fact(text: str, fact: str) -> bool:
    """True if any spelling of the fact ("31 March|March 31") is in the text, ignoring case."""
    return any(option.strip().lower() in text.lower() for option in fact.split("|"))


def refused(result: Answer) -> bool:
    """The code refused (no relevant chunk), or the model gave the fixed not-found sentence."""
    return result.refused or NOT_FOUND.lower() in result.text.lower()


def run_checks(case: GoldenCase, result: Answer) -> dict[str, bool]:
    """Rule-based checks: fast, free and repeatable. Only the checks that apply to this case."""
    if not case.answerable:
        return {"refused": refused(result)}
    cited_sources = [result.sources[n - 1].chunk.source for n in result.cited]
    return {
        "answered": not refused(result),
        "cited": bool(result.cited),
        "right_source": case.source in cited_sources,
        "facts": all(has_fact(result.text, fact) for fact in case.facts),
    }
  1. any(...) is True if at least one spelling is in the text, like stream().anyMatch(...). .lower() on both sides ignores case.line 8
  2. Two ways to refuse, both correct: the code refused before calling the model, or the model followed the prompt's not-found rule.line 13
  3. An off-topic case has one job: refuse. A returned dict holds only the checks that apply, so off-topic cases do not drag down "cited".line 19
  4. The files of the sources the answer really cites. n - 1 because citations count from 1 and lists from 0.line 20
  5. bool([]) is False and bool([1]) is True: an empty list counts as false.line 23
  6. all(...): every fact must be found, like allMatch. A case with two facts fails when either one is missing.line 25
suite.py
from checks import run_checks
from dataset import GoldenCase
from metrics import mean, recall_at_k, reciprocal_rank

# report column: short label for the table
COLUMNS = {"answered": "answered", "cited": "cited", "right_source": "source", "facts": "facts",
           "refused": "refused"}


def evaluate_case(case: GoldenCase, app) -> dict:
    """Ask one golden question and grade the result. Returns one row of the report."""
    result = app.ask(case.question)
    row = {"id": case.id, "question": case.question, "answer": result.text,
           "retrieved": [hit.chunk.id for hit in result.retrieved],
           "checks": run_checks(case, result)}
    if case.answerable:
        sources = [hit.chunk.source for hit in result.retrieved]
        row["recall"] = recall_at_k(sources, case.source, app.k)
        row["rr"] = reciprocal_rank(sources, case.source)
    return row


def summarize(rows: list[dict], k: int) -> dict:
    """Average every metric over the rows it applies to. None means no row had it."""
    def check(name):
        return [float(r["checks"][name]) for r in rows if name in r["checks"]]

    summary = {f"recall@{k}": mean([r["recall"] for r in rows if "recall" in r]),
               "mrr": mean([r["rr"] for r in rows if "rr" in r])}
    for name in ["answered", "cited", "right_source", "facts", "refused"]:
        summary[name] = mean(check(name))
    return summary


def run_suite(app, cases: list[GoldenCase], on_row=None) -> dict:
    rows = []
    for case in cases:
        row = evaluate_case(case, app)
        rows.append(row)
        if on_row:
            on_row(row)
    return {"summary": summarize(rows, app.k), "cases": rows}


def mark(value) -> str:
    return "-" if value is None else "ok" if value else "FAIL"


def header() -> str:
    return f"{'case':<18} {'rr':>4}  " + " ".join(f"{label:<8}" for label in COLUMNS.values()).rstrip()


def format_row(row: dict) -> str:
    grades = row["checks"]
    rr = f"{row['rr']:.2f}" if "rr" in row else "-"
    return (f"{row['id']:<18} {rr:>4}  " + " ".join(f"{mark(grades.get(c)):<8}" for c in COLUMNS)).rstrip()


def format_summary(summary: dict) -> str:
    lines = []
    for name, value in summary.items():
        lines.append(f"  {name:<13} {'-' if value is None else format(value, '.2f')}")
    return "\n".join(lines)
  1. The table columns, in order, with a short label each. Python dicts keep insertion order.line 6
  2. app has no type on purpose: anything with an ask() method and a k works. The real HandbookRag, or a fake in the tests (duck typing).line 10
  3. A row is a plain dict, so it goes straight into the JSON report in step 8.line 13
  4. The retrieved chunk ids are kept in the report: when a case fails, you can see what the model was given without running it again.line 14
  5. Retrieval scores only for answerable cases, from result.retrieved (all k hits, before the minimum score filter).line 16
  6. A function inside a function, used as a small helper. It reads rows from the outer function, like a Java lambda capturing a variable.line 25
  7. float(True) is 1.0 and float(False) is 0.0, so the mean of the passes is the pass rate.line 26
  8. The metric name includes k (recall@4). If you change k, the baseline in step 9 no longer matches, which is right: the numbers are not comparable.line 28
  9. on_row is an optional callback, called after each case. The script uses it to print progress; tests leave it out.line 35
  10. A chained conditional: - when the check does not apply, else ok or FAIL. Read it as v == null ? "-" : v ? "ok" : "FAIL".line 46
  11. :<8 pads to 8 characters, left-aligned. .rstrip() removes the trailing spaces at the end of the line.line 56
  12. format(value, ".2f") is the same as f"{value:.2f}": two decimals.line 62
run_evals.py
import sys

import openai

from app import make_app
from dataset import load_golden
from suite import format_row, format_summary, header, run_suite

print(header())
try:
    result = run_suite(make_app(), load_golden(), on_row=lambda row: print(format_row(row)))
except openai.APITimeoutError:
    sys.exit("The model took too long. Try again, or use a smaller model.")
except openai.APIConnectionError:
    sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
print(f"\nsummary ({len(result['cases'])} cases):")
print(format_summary(result["summary"]))
  1. lambda row: print(...) is an anonymous function, like row -> System.out.println(...) in Java.line 11
  2. Timeout before connection error, on purpose: APITimeoutError is a subclass of APIConnectionError, and Python uses the first except that matches.line 12
Run
uv run run_evals.py
You should seeyour text will differ: the model writes it
case                 rr  answered cited    source   facts    refused
hotel-london       1.00  ok       ok       ok       ok       -
hotel-limit        1.00  ok       ok       ok       ok       -
meals              1.00  ok       ok       ok       ok       -
expense-deadline   1.00  ok       ok       ok       ok       -
vacation-days      1.00  ok       ok       ok       ok       -
carry-over         1.00  ok       ok       ok       ok       -
parental-leave     1.00  ok       ok       ok       ok       -
stolen-laptop      1.00  ok       ok       ok       ok       -
core-hours         1.00  ok       ok       ok       ok       -
home-office        1.00  ok       ok       ok       ok       -
on-call-pay        1.00  ok       ok       ok       ok       -
learning-budget    1.00  ok       ok       ok       ok       -
off-topic-capital     -  -        -        -        -        ok
off-topic-poem        -  -        -        -        -        ok
off-topic-stock       -  -        -        -        -        ok

summary (15 cases):
  recall@4      1.00
  mrr           1.00
  answered      1.00
  cited         1.00
  right_source  1.00
  facts         1.00
  refused       1.00
Why this way? On a real run with llama3.2:3b every rule passed on every case, as above. Your run may show a FAIL or two, because small models vary between runs, and every FAIL is a concrete lead, not a vague feeling. "cited FAIL" means the right fact with no [n] (a prompt-following problem); "facts FAIL" means a required fact is missing, for example "report it right away" instead of "within one hour". Read the answer of a failing row (step 8 saves them all) before you change anything: sometimes the check is too strict, and the fix is a new spelling in facts. And all ok does not mean all good: rules only check what you wrote down. Step 6 adds a judge for what they cannot see.
Stuck on this step?
It takes a minute or more
Normal on a laptop CPU: twelve questions reach the chat model (the off-topic ones are mostly refused without a call). Use --no-judge later in step 8 when you only need these checks.
Every answerable case shows answered FAIL
All of them were refused: no chunk reached MIN_SCORE. Check that EMBED_MODEL is nomic-embed-text (other models score on a different scale) and that MIN_SCORE in .env is 0.65.
6

An LLM as the judge

Grade what rules cannot: is every claim in the answer supported by the sources (faithfulness), and does it answer the question (relevance)?

The rule checks cannot see an answer that contains the right number and a made-up rule next to it, or one that is true but answers a different question. Reading for meaning needs a model. So a second model call grades each answer: that is an LLM-as-judge.

A judge is only as good as its rubric. This one is strict and narrow: two yes/no questions with exact definitions, not "rate the answer from 1 to 10". Yes/no grades are easier for a model to apply consistently and easier for you to check by hand. The judge sees the same numbered sources the app's model saw, so "faithful" means "supported by what it was given", which is exactly the RAG promise.

The verdict is JSON in a fixed shape: the same pattern as lab 3. A Pydantic class generates the JSON Schema, response_format asks the server to follow it, and Pydantic validates the reply. unsupported_claims comes first in the schema on purpose: the model writes fields in schema order, so it lists the evidence before it gives the grades. An invalid reply gets one retry with the error message, then JudgeError.

judge.py
from pydantic import BaseModel, Field, ValidationError

JUDGE_SYSTEM = """You grade the answers of a question-answering bot for a company handbook.
You get the sources the bot was given, the question, and the bot's answer. Grade strictly, using only the sources.

faithful: true only if every factual claim in the answer is stated in the sources.
  Numbers, names, limits and deadlines must match the sources exactly.
  A claim from general knowledge that the sources do not state makes it false.
  Citation markers like [1] are not claims.
relevant: true only if the answer directly answers the question that was asked.
  An answer about something else, or one that leaves out part of what was asked, is false.
unsupported_claims: copy every claim from the answer that the sources do not state. Empty if there are none.
reason: one short sentence that explains the grades.
Reply with JSON only."""


class Verdict(BaseModel):
    unsupported_claims: list[str] = Field(description="claims in the answer that the sources do not state")
    faithful: bool = Field(description="every claim in the answer is stated in the sources")
    relevant: bool = Field(description="the answer directly answers the whole question")
    reason: str = Field(description="one short sentence")


RESPONSE_FORMAT = {
    "type": "json_schema",
    "json_schema": {"name": "verdict", "schema": Verdict.model_json_schema()},
}


class JudgeError(Exception):
    pass


class Judge:
    """An LLM that grades one answer against a strict rubric and returns a validated Verdict."""

    def __init__(self, client, model: str, max_attempts: int = 2):
        self.client, self.model, self.max_attempts = client, model, max_attempts

    def grade(self, question: str, sources: str, answer: str) -> Verdict:
        messages = [
            {"role": "system", "content": JUDGE_SYSTEM},
            {"role": "user", "content": f"Sources:\n\n{sources}\n\nQuestion: {question}\n\nAnswer: {answer}"},
        ]
        problem = ""
        for _ in range(self.max_attempts):
            resp = self.client.chat.completions.create(
                model=self.model, messages=messages, response_format=RESPONSE_FORMAT, temperature=0
            )
            reply = resp.choices[0].message.content or ""
            try:
                return Verdict.model_validate_json(reply)
            except ValidationError as e:
                problem = e.errors()[0]["msg"]
            messages.append({"role": "assistant", "content": reply})
            messages.append({"role": "user", "content": f"That is not a valid verdict: {problem}. Reply with the JSON only."})
        raise JudgeError(f"no valid verdict after {self.max_attempts} attempts: {problem}")


if __name__ == "__main__":
    from config import settings
    from llm import make_client

    SOURCES = "[1] expenses.md > Travel and expenses > Hotels\nHotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night."
    QUESTION = "How much can I spend on a hotel in London?"
    judge = Judge(make_client(), settings().judge_model)
    for answer in ["You can spend up to 250 euros a night in London [1].",
                   "You can spend up to 300 euros a night in London, and breakfast is extra [1]."]:
        v = judge.grade(QUESTION, SOURCES, answer)
        print(f"{answer}\n  faithful={v.faithful} relevant={v.relevant} unsupported={v.unsupported_claims}\n  {v.reason}")
  1. The rubric is the system message. Every rule is a definition the model can apply, not a vibe like "is this a good answer?".line 3
  2. The most common RAG error is a wrong number. Saying "exactly" makes the judge compare, not skim.line 7
  3. This catches answers padded from the model's own memory: true in the world, but not in your handbook.line 8
  4. A half answer (core hours start at 11:00, but when do they end?) is not relevant. Step 7 tests whether the judge really applies this.line 11
  5. The verdict shape. The descriptions go into the JSON Schema, so the model reads them too.line 17
  6. First field: the evidence. Writing out unsupported claims before deciding faithful makes the grade more consistent.line 18
  7. The OpenAI-compatible way to say "reply with JSON matching this schema". Ollama 0.5+ enforces it while the model writes (constrained decoding).line 24
  8. A custom exception. pass means "no body", like an empty class in Java.line 30
  9. The client is a parameter, so tests can pass a fake.line 38
  10. Sources first, then the question, then the answer to grade.line 43
  11. for _ in range(2) repeats twice. _ is the usual name for a loop variable you do not use.line 46
  12. Temperature 0: a judge must give the same grade for the same answer every time.line 48
  13. Parse and validate in one step. Returns a Verdict or raises ValidationError.line 52
  14. Keep the bad reply in the conversation and say what was wrong, like the retry loop in lab 3.line 55
  15. A quick demo when you run the file directly. The imports are inside the block, so importing judge in tests does not need them.line 60
Run
uv run judge.py
You should seeyour text will differ: the model writes it
You can spend up to 250 euros a night in London [1].
  faithful=True relevant=True unsupported=[]
  The 250 euro limit for London is stated in source 1.
You can spend up to 300 euros a night in London, and breakfast is extra [1].
  faithful=False relevant=True unsupported=['up to 300 euros a night in London', 'breakfast is extra']
  The sources say 250 euros in London and that breakfast is included.
Why this way? The judge is the most expensive and least predictable part of the pipeline, so it only grades what code cannot: meaning. Facts, citations and refusals stay rule-based. And a judge is a model, so it can be wrong. The next step measures how often.
Stuck on this step?
JudgeError: no valid verdict after 2 attempts
The server ignored the schema. Check ollama --version is 0.5 or newer, and that LLM_BASE_URL ends in /v1.
The second answer comes back faithful=True
A 3B model is a weak judge: it sometimes misses a changed number. That is exactly what calibration in step 7 measures. Try JUDGE_MODEL=llama3.1:8b uv run judge.py.
7

Calibrate the judge against your own labels

Grade eight answers by hand, run the judge on the same eight, and measure how often it agrees with you.

Never trust a judge you have not checked. Write a few answers, good and bad, grade them yourself, and see whether the judge gives the same grades. The share of matches is the agreement rate. If it is low for a criterion, the score for that criterion is noise, whatever it says.

The eight labels below each test one rubric rule: a right answer, a wrong limit, a fact from outside the sources, a true answer to a different question, a half answer, and a made-up approval rule. Grade them by reading the sources yourself and compare with the faithful and relevant values in the file. Disagreeing with a label is useful too: it means the rubric is unclear, and the judge will be confused by the same thing.

Agreement has a weakness: a judge that always says "faithful" agrees on 5 of these 8 labels without reading anything. With few "false" labels, a lazy judge looks good. That is why the set has several of each, and why the Practice section asks you to compute Cohen's kappa, which corrects for agreement by chance.

evals/judge_labels.jsonl
{"id": "hotel-right", "question": "How much can I spend on a hotel in London?", "sources": "[1] expenses.md > Travel and expenses > Hotels\nHotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.", "answer": "You can spend up to 250 euros a night in London [1].", "faithful": true, "relevant": true}
{"id": "hotel-wrong-limit", "question": "How much can I spend on a hotel in London?", "sources": "[1] expenses.md > Travel and expenses > Hotels\nHotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.", "answer": "In London you can spend up to 180 euros a night [1].", "faithful": false, "relevant": true}
{"id": "vacation-outside-knowledge", "question": "How many vacation days do I get each year?", "sources": "[1] time-off.md > Time off > Vacation\nEveryone gets 25 vacation days a year, plus the public holidays of the country you work from.", "answer": "You get 25 vacation days a year [1], plus 13 public holidays in Portugal.", "faithful": false, "relevant": true}
{"id": "on-call-other-topic", "question": "How much do I get paid for a week on call?", "sources": "[1] on-call.md > On-call > On-call pay\nYou get 300 euros for each week on call, plus 50 euros for each incident you handle outside working hours.\n\n[2] on-call.md > On-call > Responding to a page\nAcknowledge a page within 15 minutes.", "answer": "Acknowledge a page within 15 minutes [2].", "faithful": true, "relevant": false}
{"id": "core-hours-half", "question": "What are the core hours?", "sources": "[1] remote-work.md > Remote work > Core hours\nBe available from 11:00 to 15:00 Lisbon time.", "answer": "Core hours start at 11:00 Lisbon time [1].", "faithful": true, "relevant": false}
{"id": "laptop-right", "question": "My laptop was stolen. What should I do?", "sources": "[1] security.md > Security > Lost or stolen devices\nIf a laptop, phone or hardware key is lost or stolen, report it in the #security-help channel within one hour, or email security@larkspur.example.", "answer": "Report the stolen laptop in #security-help within one hour [1].", "faithful": true, "relevant": true}
{"id": "learning-invented-rule", "question": "How big is the yearly learning budget?", "sources": "[1] benefits.md > Benefits > Learning budget\nEach person has 1,500 euros a year for books, courses and conferences. Spending over 500 euros at once needs your manager's approval.", "answer": "Your learning budget is 1,500 euros a year [1]; anything over 200 euros needs approval.", "faithful": false, "relevant": true}
{"id": "parental-right", "question": "How many weeks of parental leave do I get?", "sources": "[1] time-off.md > Time off > Parental leave\nEvery parent gets 16 weeks of fully paid leave, to take within the first year after a birth or adoption.", "answer": "Every parent gets 16 weeks of fully paid leave [1].", "faithful": true, "relevant": true}
  1. The sources text is in the same format the judge sees in the pipeline: [1] file > heading, then the text.line 1
  2. Plausible and wrong: 180 is a real number from the source, but the London limit is 250. Not faithful.line 2
  3. The first half is cited; "13 public holidays" is not in the sources. Not faithful, even if it happens to be true.line 3
  4. Every word is supported, but it answers a different question. Faithful, not relevant.line 4
  5. Only half the answer: the end of core hours is missing. The rubric says that is not relevant.line 5
  6. A made-up rule (200 euros) next to a correct fact (1,500). The rule checks would pass this answer.line 7
calibrate.py
from pydantic import BaseModel

from dataset import load_jsonl
from judge import Judge

MIN_AGREEMENT = 0.75  # below this, do not trust the judge's scores


class JudgeLabel(BaseModel):
    """One answer graded by a person: what the judge should say."""

    id: str
    question: str
    sources: str
    answer: str
    faithful: bool
    relevant: bool


def agreement(judge_says: list[bool], human_says: list[bool]) -> float:
    """The share of examples where the judge and the person gave the same grade."""
    same = sum(j == h for j, h in zip(judge_says, human_says, strict=True))
    return same / len(human_says)


def calibrate(judge: Judge, labels: list[JudgeLabel]) -> dict:
    verdicts = [judge.grade(x.question, x.sources, x.answer) for x in labels]
    result = {}
    for criterion in ("faithful", "relevant"):
        judge_says = [getattr(v, criterion) for v in verdicts]
        human_says = [getattr(x, criterion) for x in labels]
        result[criterion] = {
            "agreement": round(agreement(judge_says, human_says), 3),
            "disagreements": [x.id for x, j in zip(labels, judge_says) if j != getattr(x, criterion)],
        }
    return result


if __name__ == "__main__":
    from config import settings
    from llm import make_client

    s = settings()
    labels = load_jsonl("evals/judge_labels.jsonl", JudgeLabel)
    result = calibrate(Judge(make_client(), s.judge_model), labels)
    print(f"judge {s.judge_model} on {len(labels)} hand-labelled answers")
    for criterion, r in result.items():
        verdict = "ok" if r["agreement"] >= MIN_AGREEMENT else "TOO LOW: do not trust this score"
        print(f"  {criterion:<9} agreement {r['agreement']:.2f}  {verdict}")
        for label_id in r["disagreements"]:
            print(f"    disagrees on {label_id}")
  1. Below 0.75 agreement, the judge is wrong on more than one in four answers: report the score, but do not gate on it.line 6
  2. One hand-graded example. Loaded with the same load_jsonl as the golden set, so a typo is caught with its line number.line 9
  3. zip pairs the two lists item by item. strict=True raises an error if they have different lengths, instead of silently stopping at the shorter one. j == h is True or False, and sum counts the Trues.line 22
  4. One judge call per label: eight calls.line 27
  5. getattr(v, "faithful") reads an attribute by name, like reflection in Java. It lets one loop handle both criteria.line 30
  6. Keep the ids where the judge disagreed: those are the examples to read.line 34
  7. Run directly: print the agreement. Imported (by the evals test in step 9): just the functions.line 39
Run
uv run calibrate.py
JUDGE_MODEL=llama3.1:8b uv run calibrate.py
You should seeyour text will differ: the model writes it
judge llama3.2:3b on 8 hand-labelled answers
  faithful  agreement 0.38  TOO LOW: do not trust this score
    disagrees on hotel-right
    disagrees on on-call-other-topic
    disagrees on core-hours-half
    disagrees on laptop-right
    disagrees on parental-right
  relevant  agreement 0.50  TOO LOW: do not trust this score
    disagrees on hotel-wrong-limit
    disagrees on vacation-outside-knowledge
    disagrees on core-hours-half
    disagrees on learning-invented-rule
judge llama3.1:8b on 8 hand-labelled answers
  faithful  agreement 1.00  ok
  relevant  agreement 0.88  ok
    disagrees on core-hours-half
Why this way? The first half is a real run, and it is the most important result in this lab. The 3B judge agrees with you on 3 of 8 faithfulness labels: worse than a coin, and it marks correct answers ("hotel-right", "laptop-right", "parental-right") as unfaithful. So the 0.50 faithful score from step 8 is noise, not a finding. That is exactly what calibration is for: it turns "the judge says 0.50" into "the judge is wrong more often than right, ignore it". The fix is a stronger judge: the second command uses llama3.1:8b (its output above is a sample; your numbers will differ), or a hosted model. Run calibration again whenever you change the judge model or the rubric, and only gate on criteria that pass MIN_AGREEMENT.
Stuck on this step?
The second command fails with model "llama3.1:8b" not found
You skipped the optional setup step. Run ollama pull llama3.1:8b, or just keep the 3B judge.
Windows: JUDGE_MODEL=... uv run is not recognised
In PowerShell run $env:JUDGE_MODEL="llama3.1:8b"; uv run calibrate.py, then Remove-Item Env:JUDGE_MODEL afterwards.
8

The full run: results table and JSON report

Add the judge to the suite, print one table with every grade, and save a JSON report you can diff, share and gate on.

suite.py gets the judge as an optional parameter. It grades every case that was answered; refusals are skipped, because there is nothing to grade. If the judge fails on one case, that row records the error and the run goes on: one bad reply must not stop a 15-minute eval.

run_evals.py is reorganised around one function, run_and_save(), which runs everything and writes reports/latest.json. The command-line part moves under if __name__ == "__main__":, so the pytest gate in step 9 can import and call run_and_save() without parsing arguments or printing a table.

The report has the time (in UTC), the settings that produced it (models and minimum score), the summary and every row. Two flags: --no-judge for a quick run with only the free metrics, and --save-baseline to store the current summary as evals/baseline.json, the numbers the gate will defend.

suite.py 21 new or changed lines
from checks import refused, run_checks
from dataset import GoldenCase
from judge import JudgeError
from metrics import mean, recall_at_k, reciprocal_rank
from prompt import format_sources

# report column: short label for the table
COLUMNS = {"answered": "answered", "cited": "cited", "right_source": "source", "facts": "facts",
           "refused": "refused", "faithful": "faithful", "relevant": "relevant"}


def evaluate_case(case: GoldenCase, app, judge=None) -> dict:
    """Ask one golden question and grade the result. Returns one row of the report."""
    result = app.ask(case.question)
    row = {"id": case.id, "question": case.question, "answer": result.text,
           "retrieved": [hit.chunk.id for hit in result.retrieved],
           "checks": run_checks(case, result)}
    if case.answerable:
        sources = [hit.chunk.source for hit in result.retrieved]
        row["recall"] = recall_at_k(sources, case.source, app.k)
        row["rr"] = reciprocal_rank(sources, case.source)
    if judge is not None and not refused(result):
        try:
            verdict = judge.grade(case.question, format_sources(result.sources), result.text)
            row["judge"] = verdict.model_dump()
        except JudgeError as e:
            row["judge_error"] = str(e)
    return row


def summarize(rows: list[dict], k: int) -> dict:
    """Average every metric over the rows it applies to. None means no row had it."""
    def check(name):
        return [float(r["checks"][name]) for r in rows if name in r["checks"]]

    def judged(name):
        return [float(r["judge"][name]) for r in rows if "judge" in r]

    summary = {f"recall@{k}": mean([r["recall"] for r in rows if "recall" in r]),
               "mrr": mean([r["rr"] for r in rows if "rr" in r])}
    for name in ["answered", "cited", "right_source", "facts", "refused"]:
        summary[name] = mean(check(name))
    for name in ["faithful", "relevant"]:
        summary[name] = mean(judged(name))
    return summary


def run_suite(app, cases: list[GoldenCase], judge=None, on_row=None) -> dict:
    rows = []
    for case in cases:
        row = evaluate_case(case, app, judge)
        rows.append(row)
        if on_row:
            on_row(row)
    return {"summary": summarize(rows, app.k), "cases": rows}


def mark(value) -> str:
    return "-" if value is None else "ok" if value else "FAIL"


def header() -> str:
    return f"{'case':<18} {'rr':>4}  " + " ".join(f"{label:<8}" for label in COLUMNS.values()).rstrip()


def format_row(row: dict) -> str:
    grades = dict(row["checks"])
    if "judge" in row:
        grades["faithful"] = row["judge"]["faithful"]
        grades["relevant"] = row["judge"]["relevant"]
    rr = f"{row['rr']:.2f}" if "rr" in row else "-"
    return (f"{row['id']:<18} {rr:>4}  " + " ".join(f"{mark(grades.get(c)):<8}" for c in COLUMNS)).rstrip()


def format_summary(summary: dict) -> str:
    lines = []
    for name, value in summary.items():
        lines.append(f"  {name:<13} {'-' if value is None else format(value, '.2f')}")
    return "\n".join(lines)
  1. judge=None: an optional parameter with a default, like an overload. Without a judge, only the free checks run.line 12
  2. Refused answers are not sent to the judge: the refused check already covers them, and they cost a call for nothing.line 22
  3. The judge sees exactly the numbered sources the app's model saw, built by the same format_sources from step 2.line 24
  4. model_dump() turns the Verdict into a plain dict for the JSON report.line 25
  5. A failed grade is recorded, not fatal. Search the report for judge_error after a run.line 26
  6. Judge scores are averaged over the judged rows only. Rows with a judge_error are left out.line 37
  7. dict(...) makes a copy, so adding the judge grades does not change the row's checks.line 67
run_evals.py
import argparse
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

import openai

from app import make_app
from config import settings
from dataset import load_golden
from judge import Judge
from llm import make_client
from suite import format_row, format_summary, header, run_suite

REPORT = "reports/latest.json"


def run_and_save(use_judge: bool = True, verbose: bool = False) -> dict:
    """Run the whole golden set, save the JSON report, return it."""
    s = settings()
    judge = Judge(make_client(), s.judge_model) if use_judge else None
    if verbose:
        print(header())
    on_row = (lambda row: print(format_row(row))) if verbose else None
    result = run_suite(make_app(), load_golden(), judge, on_row)
    report = {
        "created": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "settings": {"model": s.model, "embed_model": s.embed_model, "judge_model": s.judge_model if use_judge else None,
                     "min_score": s.min_score},
        **result,
    }
    Path(REPORT).parent.mkdir(exist_ok=True)
    Path(REPORT).write_text(json.dumps(report, indent=2))
    return report


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run the golden dataset through the RAG app and grade every answer.")
    parser.add_argument("--no-judge", action="store_true", help="skip the LLM judge: only the free checks and retrieval metrics")
    parser.add_argument("--save-baseline", action="store_true", help="also save the scores as evals/baseline.json")
    args = parser.parse_args()
    try:
        report = run_and_save(use_judge=not args.no_judge, verbose=True)
    except openai.APITimeoutError:
        sys.exit("The model took too long. Try again, or use a smaller model.")
    except openai.APIConnectionError:
        sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
    except openai.NotFoundError:
        s = settings()
        sys.exit(f"A model is missing. Run: ollama pull {s.model} and ollama pull {s.embed_model}")
    print(f"\nsummary ({len(report['cases'])} cases, report in {REPORT}):")
    print(format_summary(report["summary"]))
    if args.save_baseline:
        Path("evals/baseline.json").write_text(json.dumps(report["summary"], indent=2))
        print("saved as the new baseline: evals/baseline.json")
  1. One fixed path: the CI workflow in step 10 uploads this file.line 16
  2. The reusable part. pytest calls it in step 9; this script calls it below.line 19
  3. No judge when --no-judge is given: x if cond else y is cond ? x : y.line 22
  4. An ISO 8601 time in UTC, like 2026-11-29T14:03:11+00:00: unambiguous in any time zone.line 28
  5. The settings go into the report. A score without the model name and threshold that produced it is useless a month later.line 29
  6. **result copies the summary and cases keys into this dict, like the spread {...result} in JavaScript.line 31
  7. exist_ok=True: no error if reports/ already exists. Like Files.createDirectories.line 33
  8. Only when run as a script: parse the flags, print the table, handle errors. Importing this file runs none of it.line 38
  9. action="store_true": a flag with no value. --no-judge present means args.no_judge is True (argparse turns the dash into an underscore).line 40
  10. Save the summary as the new baseline. Do this on purpose, after you have looked at the results, never automatically.line 54
reports/latest.json
{
  "created": "2026-11-29T14:03:11+00:00",
  "settings": {"model": "llama3.2:3b", "embed_model": "nomic-embed-text", "judge_model": "llama3.2:3b", "min_score": 0.65},
  "summary": {"recall@4": 1.0, "mrr": 0.958, "answered": 1.0, "cited": 0.917, "...": "..."},
  "cases": [
    {
      "id": "hotel-london",
      "question": "How much can I spend on a hotel in London?",
      "answer": "You can spend up to 250 euros a night on a hotel in London [1].",
      "retrieved": ["expenses.md#1", "expenses.md#2", "expenses.md#3", "benefits.md#1"],
      "checks": {"answered": true, "cited": true, "right_source": true, "facts": true},
      "recall": 1.0,
      "rr": 1.0,
      "judge": {"unsupported_claims": [], "faithful": true, "relevant": true, "reason": "The 250 euro limit is in source 1."}
    }
  ]
}
  1. The summary: one number per metric. This is what the baseline stores and the gate compares.line 4
  2. The full answer for every case, so you can read why a row failed without running anything again.line 9
Run
uv run run_evals.py --save-baseline
You should seeyour text will differ: the model writes it
case                 rr  answered cited    source   facts    refused  faithful relevant
hotel-london       1.00  ok       ok       ok       ok       -        FAIL     ok
hotel-limit        1.00  ok       ok       ok       ok       -        FAIL     ok
meals              1.00  ok       ok       ok       ok       -        ok       ok
expense-deadline   1.00  ok       ok       ok       ok       -        ok       ok
vacation-days      1.00  ok       ok       ok       ok       -        ok       ok
carry-over         1.00  ok       ok       ok       ok       -        FAIL     FAIL
parental-leave     1.00  ok       ok       ok       ok       -        FAIL     ok
stolen-laptop      1.00  ok       ok       ok       ok       -        FAIL     ok
core-hours         1.00  ok       ok       ok       ok       -        ok       ok
home-office        1.00  ok       ok       ok       ok       -        ok       ok
on-call-pay        1.00  ok       ok       ok       ok       -        FAIL     FAIL
learning-budget    1.00  ok       ok       ok       ok       -        ok       ok
off-topic-capital     -  -        -        -        -        ok       -        -
off-topic-poem        -  -        -        -        -        ok       -        -
off-topic-stock       -  -        -        -        -        ok       -        -

summary (15 cases, report in reports/latest.json):
  recall@4      1.00
  mrr           1.00
  answered      1.00
  cited         1.00
  right_source  1.00
  facts         1.00
  refused       1.00
  faithful      0.50
  relevant      0.83
saved as the new baseline: evals/baseline.json
Why this way? Read the rows where the rules and the judge disagree. This is a real run on llama3.2:3b: every rule passes on every case (the right number, cited, from the right file), yet the judge calls half the answers unfaithful. Who is right? Open reports/latest.json and read "hotel-london": the rules confirm the answer has the 250 euros and cites expenses.md, so read its unsupported_claims and decide whether the judge has a point. Here the judge is the problem, and the next step proves it: this 3B judge agrees with a person on only 3 of 8 labelled answers. Rules cannot catch an answer that adds something the handbook does not say; a judge can, but only a judge you have checked. Never gate on judge scores before calibrating them.
Stuck on this step?
A row shows - for faithful and relevant, but it was answered
The judge failed on that case. Search reports/latest.json for judge_error to see why.
It takes several minutes
Every answered case costs two model calls now: the answer and the grade. Use uv run run_evals.py --no-judge while you work on retrieval or the prompt, and the full run before you save a baseline.
9

A regression gate with pytest

Fail loudly when a score drops below the baseline: `uv run pytest -m evals` runs the evals as a test.

A report is only useful if someone looks at it. A gate looks at it for you: it compares every metric with the saved baseline and fails when one drops by more than a small tolerance (0.05 here). Higher scores always pass; then you can save a new baseline on purpose.

The gate runs as a pytest test, so it fits every tool that already runs tests. But it is slow and needs Ollama, so it must not run with the fast tests. A pytest marker solves that: @pytest.mark.evals labels the two eval tests, and addopts = "-m 'not evals'" in pyproject.toml makes a plain uv run pytest skip them. uv run pytest -m evals selects them: a -m on the command line comes after the one in addopts, and the last one wins.

The tolerance is a trade-off. With 12 answerable cases, one case flipping moves a score by 0.083, so 0.05 means "fail on any single regression". That is strict, and a small model can flip a borderline case between runs. Bigger eval sets let you use a smaller tolerance with less noise.

Then prove the gate works by breaking the app on purpose. MIN_SCORE=0.99 makes every chunk "not relevant", so the app refuses everything: the refusal score stays perfect, and every answer metric collapses.

gate.py
import json
import sys
from pathlib import Path

BASELINE = "evals/baseline.json"
TOLERANCE = 0.05  # allowed drop below the baseline before the gate fails


def load_baseline(path: str = BASELINE) -> dict:
    p = Path(path)
    if not p.exists():
        raise FileNotFoundError(f"{path} is missing. Create it with: uv run run_evals.py --save-baseline")
    return json.loads(p.read_text())


def compare(summary: dict, baseline: dict, tolerance: float = TOLERANCE) -> list[str]:
    """One line per metric that dropped more than the tolerance below its baseline."""
    failures = []
    for name, base in baseline.items():
        now = summary.get(name)
        if base is None:
            continue
        if now is None:
            failures.append(f"{name}: missing now, baseline {base:.2f}")
        elif now < base - tolerance:
            failures.append(f"{name}: {now:.2f}, baseline {base:.2f} (allowed drop {tolerance})")
    return failures


if __name__ == "__main__":
    summary = json.loads(Path("reports/latest.json").read_text())["summary"]
    failures = compare(summary, load_baseline())
    for line in failures:
        print("DROPPED", line)
    print("gate: FAIL" if failures else "gate: pass")
    sys.exit(1 if failures else 0)
  1. How far a score may fall below the baseline before the gate fails.line 6
  2. A missing baseline gets an error message that says how to create one, instead of a bare FileNotFoundError.line 12
  3. A pure function: two dicts in, a list of problems out. Easy to test without any model (step 10).line 16
  4. A metric that was None in the baseline (for example, no judge was run) is not compared.line 21
  5. A metric that existed in the baseline but is missing now is a failure too: for example the judge scores when every answer was refused.line 23
  6. The actual gate. now < base - tolerance: a drop of up to 0.05 is accepted as noise.line 25
  7. uv run gate.py checks the last saved report without running the evals again.line 30
  8. Exit code 1 on failure, 0 on success. CI systems and shell scripts read the exit code, not the text.line 36
test_evals.py
import pytest

from calibrate import MIN_AGREEMENT, JudgeLabel, calibrate
from config import settings
from dataset import load_jsonl
from gate import compare, load_baseline
from judge import Judge
from llm import make_client
from run_evals import run_and_save

# These tests call the real models: they are skipped by "uv run pytest" and run by "uv run pytest -m evals".


@pytest.mark.evals
def test_the_judge_agrees_with_the_hand_labels():
    labels = load_jsonl("evals/judge_labels.jsonl", JudgeLabel)
    result = calibrate(Judge(make_client(), settings().judge_model), labels)
    for criterion, r in result.items():
        assert r["agreement"] >= MIN_AGREEMENT, f"{criterion}: judge disagrees on {r['disagreements']}"


@pytest.mark.evals
def test_scores_do_not_drop_below_the_baseline():
    report = run_and_save(use_judge=True)
    failures = compare(report["summary"], load_baseline())
    assert not failures, "scores dropped (see reports/latest.json):\n" + "\n".join(failures)
  1. A **marker**: a label on the test, like a JUnit 5 @Tag("evals"). -m evals selects tests by it.line 14
  2. First: is the judge still trustworthy? If calibration fails, the judge scores in the other test mean nothing.line 15
  3. The text after the comma is shown when the assertion fails: the criterion and the labels it got wrong.line 19
  4. The same function the script uses: one code path for local runs and CI.line 24
  5. assert not failures: an empty list passes. The message lists every dropped metric.line 26
pyproject.toml 3 new or changed lines
[project]
name = "rag-evals"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["numpy>=2.5.5", "openai>=3.60.0", "pydantic>=2.14.4,<3", "python-dotenv>=1.2.4"]

[dependency-groups]
dev = ["pytest>=9.2.0"]

[tool.pytest.ini_options]
markers = ["evals: runs the eval suite against the configured model (slow, needs Ollama)"]
addopts = "-m 'not evals'"
  1. Written by uv add in step 1. <3 on Pydantic: a future major version may change the API this lab uses.line 5
  2. pytest reads its settings from this table in pyproject.toml.line 10
  3. Registers the marker. pytest warns about unregistered markers, so a typo like @pytest.mark.eval gets noticed. Unnoticed, that typo would put the slow test into the fast run, because not evals does not match it.line 11
  4. Options added to every pytest run: skip the evals unless you ask for them.line 12
Run
uv run pytest -m evals -q
MIN_SCORE=0.99 uv run pytest -m evals -q
You should seeyour text will differ: the model writes it
..                                                                       [100%]
2 passed, 18 deselected in 96.40s (0:01:36)
.F                                                                       [100%]
=================================== FAILURES ===================================
__________________ test_scores_do_not_drop_below_the_baseline __________________
...
E       AssertionError: scores dropped (see reports/latest.json):
E         answered: 0.00, baseline 1.00 (allowed drop 0.05)
E         cited: 0.00, baseline 1.00 (allowed drop 0.05)
E         right_source: 0.00, baseline 1.00 (allowed drop 0.05)
E         facts: 0.00, baseline 1.00 (allowed drop 0.05)
E         faithful: missing now, baseline 0.50
E         relevant: missing now, baseline 0.83
...
FAILED test_evals.py::test_scores_do_not_drop_below_the_baseline - AssertionE...
1 failed, 1 passed, 18 deselected in 24.85s
Why this way? Look at what the broken run kept: recall@4 and refused did not drop. Retrieval was still fine, and refusing everything is perfect at refusing. That is why you measure several things: any single metric can be gamed by a broken system. The second run was also much faster: the app refused every question without calling the chat model, so only the eight calibration calls were left.
Stuck on this step?
test_the_judge_agrees_with_the_hand_labels fails with faithful: judge disagrees on [...]
The gate is doing its job: with llama3.2:3b as the judge, agreement is below 0.75 (step 7 showed 0.38), so the eval suite refuses to trust its scores. Use a stronger judge for the evals, JUDGE_MODEL=llama3.1:8b uv run pytest -m evals -q (after ollama pull llama3.1:8b), and set JUDGE_MODEL in .env once it passes. The sample output above used a judge that passes calibration.
FileNotFoundError: evals/baseline.json is missing
Run uv run run_evals.py --save-baseline first (step 8).
2 deselected and no tests ran
You ran uv run pytest -m evals from another folder, or test_evals.py is missing. Run it from the project folder.
The gate fails on a run where nothing changed
One case flipped between runs. Look at reports/latest.json for the row that changed: if the answer is fine, the check or the label is too strict; if the model really is unstable on it, it is a real finding. Do not just raise the tolerance.
Windows: MIN_SCORE=0.99 uv run is not recognised
In PowerShell run $env:MIN_SCORE="0.99"; uv run pytest -m evals -q, then Remove-Item Env:MIN_SCORE afterwards.
10

Fast tests with fakes, and the GitHub Actions workflow

Test the pipeline itself in under a second with no model, then run the fast tests on every push and the evals at the press of a button.

The eval code is code: a bug in a check or in summarize gives wrong scores that look right. So it gets ordinary unit tests, with fakes instead of models: a fake client that returns scripted judge replies, a fake app that returns fixed Answers, and a fake judge. Python checks attributes when the code runs ("duck typing"), so a fake only needs the methods the code calls. No mocking library needed.

The workflow file has two jobs. tests runs on every push: install uv, uv sync, uv run pytest -q. evals runs only when you start the workflow by hand from the Actions tab (workflow_dispatch): it installs Ollama on the runner, pulls both models, runs uv run pytest -m evals, and uploads reports/latest.json as an artifact you can download, even when the gate fails.

To try it: create a GitHub repository, commit everything including evals/baseline.json and uv.lock (uv wrote it in step 1), and push. The tests job starts at once. For the evals, open Actions, pick tests and evals, and press Run workflow. A GitHub-hosted runner has no GPU, so expect the evals job to take several minutes.

test_metrics_and_checks.py
import pytest

from chunking import Chunk
from checks import has_fact, run_checks
from dataset import GoldenCase, load_golden, load_jsonl
from metrics import mean, recall_at_k, reciprocal_rank
from prompt import NOT_FOUND
from rag import Answer
from store import Hit

HOTELS = Hit(Chunk("expenses.md#1", "expenses.md", "Travel and expenses > Hotels", "Up to 250 euros in London."), 0.8)
MEALS = Hit(Chunk("expenses.md#3", "expenses.md", "Travel and expenses > Meals", "Meals up to 60 euros a day."), 0.7)
CASE = GoldenCase(id="hotel", question="Hotel limit in London?", facts=["250"], source="expenses.md")
OFF_TOPIC = GoldenCase(id="capital", question="Capital of Australia?", facts=[], source=None)


def test_recall_at_k_and_reciprocal_rank():
    retrieved = ["security.md", "expenses.md", "time-off.md"]
    assert recall_at_k(retrieved, "expenses.md", k=2) == 1.0
    assert recall_at_k(retrieved, "expenses.md", k=1) == 0.0
    assert reciprocal_rank(retrieved, "expenses.md") == 0.5
    assert reciprocal_rank(retrieved, "offices.md") == 0.0


def test_mean_of_nothing_is_none_not_zero():
    assert mean([1.0, 0.0, 0.5]) == 0.5
    assert mean([]) is None


def test_facts_accept_any_listed_spelling():
    assert has_fact("They expire on March 31.", "31 March|March 31")
    assert not has_fact("They expire in April.", "31 March|March 31")


def test_a_good_answer_passes_every_check():
    result = Answer("Up to 250 euros a night [1].", [HOTELS], [1], [HOTELS])
    assert run_checks(CASE, result) == {"answered": True, "cited": True, "right_source": True, "facts": True}


def test_citing_the_wrong_file_fails_right_source():
    other = Hit(Chunk("benefits.md#1", "benefits.md", "Benefits > Learning budget", "1,500 euros."), 0.7)
    result = Answer("250 euros [1].", [other, HOTELS], [1], [other, HOTELS])
    checks = run_checks(CASE, result)
    assert checks["cited"] and not checks["right_source"]


def test_off_topic_must_be_refused():
    by_code = Answer(NOT_FOUND, [], [], [MEALS], refused=True)
    by_model = Answer("I don't know. The handbook does not say.", [MEALS], [], [MEALS])
    from_memory = Answer("Canberra is the capital of Australia.", [MEALS], [], [MEALS])
    assert run_checks(OFF_TOPIC, by_code) == {"refused": True}
    assert run_checks(OFF_TOPIC, by_model) == {"refused": True}
    assert run_checks(OFF_TOPIC, from_memory) == {"refused": False}


def test_the_golden_file_is_valid():
    cases = load_golden()
    assert len(cases) == 15
    assert all(c.facts for c in cases if c.answerable)


def test_a_broken_line_names_the_line_number(tmp_path):
    path = tmp_path / "bad.jsonl"
    path.write_text('{"id": "a", "question": "q", "source": null}\n{"id": "b", "question": "q"}\n')
    with pytest.raises(ValueError, match="line 2: source: Field required"):
        load_jsonl(str(path), GoldenCase)
  1. A Hit built by hand: a chunk and a score. Positional arguments follow the field order of the dataclass.line 11
  2. Answer(text, sources, cited, retrieved): everything a check looks at, with no model involved.line 36
  3. Three ways an off-topic question can end: refused by the code, refused by the model, or answered from memory. Only the last one fails.line 48
  4. A test on the real golden file: 15 valid lines, and every answerable case has at least one fact. It catches a broken edit to the dataset in CI.line 56
  5. tmp_path is a pytest fixture: a fresh temporary folder for this test. Ask for it by naming a parameter.line 62
  6. pytest.raises(..., match=...): the block must raise this error, and its message must match the regex.line 65
test_judge.py
import json
from types import SimpleNamespace

import pytest

from calibrate import JudgeLabel, agreement, calibrate
from judge import Judge, JudgeError

GOOD = json.dumps({"unsupported_claims": [], "faithful": True, "relevant": True, "reason": "All in source 1."})
MISSING_FIELD = json.dumps({"faithful": True, "relevant": True})


class FakeClient:
    """Stands in for OpenAI(): hands out the given replies in order and records every request."""

    def __init__(self, *replies: str):
        self.replies = list(replies)
        self.requests = []
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))

    def create(self, **kwargs):
        self.requests.append(kwargs)
        message = SimpleNamespace(content=self.replies.pop(0))
        return SimpleNamespace(choices=[SimpleNamespace(message=message)])


def test_a_valid_verdict_is_parsed():
    client = FakeClient(GOOD)
    verdict = Judge(client, "judge-model").grade("Q?", "[1] a.md > A\ntext", "An answer [1].")
    assert verdict.faithful and verdict.relevant
    request = client.requests[0]
    assert request["response_format"]["json_schema"]["name"] == "verdict"
    assert request["temperature"] == 0
    assert request["messages"][1]["content"].endswith("Question: Q?\n\nAnswer: An answer [1].")


def test_an_invalid_verdict_is_retried_with_the_error():
    client = FakeClient(MISSING_FIELD, GOOD)
    assert Judge(client, "judge-model").grade("Q?", "S", "A").faithful
    assert "not a valid verdict: Field required" in client.requests[1]["messages"][-1]["content"]


def test_the_judge_gives_up():
    client = FakeClient("not json", "still not json")
    with pytest.raises(JudgeError):
        Judge(client, "judge-model", max_attempts=2).grade("Q?", "S", "A")
    assert len(client.requests) == 2


def test_agreement():
    assert agreement([True, True, False, False], [True, False, False, True]) == 0.5


def test_calibrate_lists_the_disagreements():
    labels = [JudgeLabel(id=f"x{i}", question="Q", sources="S", answer="A", faithful=f, relevant=True)
              for i, f in enumerate([True, False])]
    result = calibrate(Judge(FakeClient(GOOD, GOOD), "judge-model"), labels)
    assert result["faithful"] == {"agreement": 0.5, "disagreements": ["x1"]}
    assert result["relevant"] == {"agreement": 1.0, "disagreements": []}
  1. Valid JSON, invalid verdict: two required fields are missing.line 10
  2. The same fake client as lab 3: it hands out the given replies in order and records every request.line 13
  3. SimpleNamespace builds a quick object (like a JS object literal), so client.chat.completions.create ends at our method.line 19
  4. Checks the exact layout the judge receives: sources, question, then the answer at the end.line 34
  5. The second request must carry the validation error back to the model.line 40
  6. A list comprehension builds two labels: the human said faithful for x0, not faithful for x1.line 55
  7. The fake judge always says faithful, so it agrees on x0 and disagrees on x1.line 58
test_suite_and_gate.py
import pytest

from chunking import Chunk
from dataset import GoldenCase
from gate import compare, load_baseline
from judge import Verdict
from prompt import NOT_FOUND
from rag import Answer
from store import Hit
from suite import format_row, run_suite

HOTELS = Hit(Chunk("expenses.md#1", "expenses.md", "Travel and expenses > Hotels", "Up to 250 euros in London."), 0.8)
VACATION = Hit(Chunk("time-off.md#0", "time-off.md", "Time off > Vacation", "25 vacation days a year."), 0.6)
CASES = [
    GoldenCase(id="hotel", question="Hotel in London?", facts=["250"], source="expenses.md"),
    GoldenCase(id="vacation", question="Vacation days?", facts=["25"], source="time-off.md"),
    GoldenCase(id="capital", question="Capital of Australia?", facts=[], source=None),
]


class FakeApp:
    """Stands in for HandbookRag: a fixed Answer per question."""

    k = 4
    answers = {
        "Hotel in London?": Answer("Up to 250 euros [1].", [HOTELS], [1], [HOTELS, VACATION]),
        "Vacation days?": Answer(NOT_FOUND, [], [], [HOTELS, VACATION], refused=True),
        "Capital of Australia?": Answer(NOT_FOUND, [], [], [HOTELS], refused=True),
    }

    def ask(self, question):
        return self.answers[question]


class FakeJudge:
    def __init__(self):
        self.graded = []

    def grade(self, question, sources, answer):
        self.graded.append(question)
        return Verdict(unsupported_claims=[], faithful=True, relevant=True, reason="fine")


def test_run_suite_scores_every_case():
    judge = FakeJudge()
    report = run_suite(FakeApp(), CASES, judge)
    assert report["summary"] == {
        "recall@4": 1.0, "mrr": 0.75, "answered": 0.5, "cited": 0.5, "right_source": 0.5,
        "facts": 0.5, "refused": 1.0, "faithful": 1.0, "relevant": 1.0,
    }
    assert judge.graded == ["Hotel in London?"]  # refusals are not sent to the judge
    assert report["cases"][1]["retrieved"] == ["expenses.md#1", "time-off.md#0"]


def test_without_a_judge_the_judge_metrics_are_none():
    summary = run_suite(FakeApp(), CASES)["summary"]
    assert summary["faithful"] is None and summary["relevant"] is None


def test_a_table_row():
    row = run_suite(FakeApp(), CASES[:1], FakeJudge())["cases"][0]
    assert format_row(row) == "hotel              1.00  ok       ok       ok       ok       -        ok       ok"


def test_the_gate():
    baseline = {"recall@4": 1.0, "facts": 0.9, "faithful": None}
    assert compare({"recall@4": 0.96, "facts": 0.9, "faithful": 0.5}, baseline) == []
    assert compare({"recall@4": 0.9, "facts": 0.9}, baseline) == ["recall@4: 0.90, baseline 1.00 (allowed drop 0.05)"]
    assert compare({"recall@4": 1.0, "facts": None}, baseline) == ["facts: missing now, baseline 0.90"]


def test_a_missing_baseline_says_how_to_make_one(tmp_path):
    with pytest.raises(FileNotFoundError, match="--save-baseline"):
        load_baseline(str(tmp_path / "baseline.json"))
  1. A fake app: no index, no model. It only needs k and ask(), the two things run_suite uses.line 21
  2. A class attribute: shared by every instance, like a static field. Read as app.k.line 24
  3. An answerable question the app wrongly refused. It must count against answered, cited and facts.line 27
  4. A fake judge records what it was asked to grade, so the test can check that refusals were skipped.line 35
  5. Hand-computed: the vacation case found its file at rank 2, so MRR is (1 + 0.5) / 2 = 0.75.line 48
  6. The exact table row. If the formatting breaks, this test says so.line 62
  7. 0.96 is within 0.05 of 1.0: passes. A None baseline (faithful) is not compared.line 67
  8. A metric that vanished is a failure.line 69
.github/workflows/evals.yml
name: tests and evals

on:
  push:                # every push: the fast tests
  workflow_dispatch:   # the "Run workflow" button on the Actions tab: the evals too

jobs:
  tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv sync
      - run: uv run pytest -q

  evals:
    if: github.event_name == 'workflow_dispatch'
    needs: tests
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv sync
      - name: Start Ollama and pull the models
        run: |
          curl -fsSL https://ollama.com/install.sh | sh
          curl -sf http://localhost:11434/api/version || (ollama serve > ollama.log 2>&1 &)
          for i in $(seq 30); do curl -sf http://localhost:11434/api/version && break; sleep 1; done
          ollama pull llama3.2:3b
          ollama pull nomic-embed-text
      - name: Run the evals
        run: uv run pytest -m evals -q
      - name: Keep the report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: eval-report
          path: reports/latest.json
  1. What starts the workflow. GitHub reads every .yml file in .github/workflows/.line 3
  2. workflow_dispatch adds a **Run workflow** button on the Actions tab: evals on demand, not on every push.line 5
  3. A fresh Linux virtual machine per job, provided by GitHub.line 9
  4. Copies your repository onto the runner.line 11
  5. The official uv setup action. uv sync then finds or downloads a Python that matches requires-python and installs the exact versions from uv.lock.line 12
  6. The evals job is skipped on a push. It only runs when started by hand.line 17
  7. needs: tests: no point paying for evals when the fast tests already fail.line 18
  8. A safety net: a stuck model call cannot keep the runner busy for hours.line 20
  9. Ollama's official Linux install script.line 27
  10. The install script usually starts Ollama as a service already. If nothing answers on port 11434, start it in the background ourselves.line 28
  11. Wait up to 30 seconds for the server, checking once a second.line 29
  12. The gate from step 9. A failing gate fails the job, and GitHub shows it as a red cross.line 33
  13. if: always(): upload the report even when the gate failed, which is exactly when you want to read it.line 35
Run
uv run pytest -q
You should see
..................                                                       [100%]
18 passed, 2 deselected in 1.19s
Why this way? Two kinds of tests, two jobs. Unit tests check your code and run on every push in seconds. Evals check the system's behaviour with real models, cost minutes, and run when you change something that can move the numbers: the prompt, the model, the chunking, the retrieval settings. Keeping them apart is what lets you run both.
Stuck on this step?
The CI tests job fails with ModuleNotFoundError
A file is not committed. git status shows untracked files; commit all .py files, the handbook folder and evals/.
The CI evals job fails at the gate, but it passes on your laptop
A different machine can give slightly different answers, even at temperature 0. Download the eval-report artifact, compare the rows with your local report, and record the baseline on the machine that runs the gate (save the artifact's summary as evals/baseline.json).

Check it works

Three checks: the fast tests pass with no model, a full eval run prints the table and writes reports/latest.json, and the gate passes against the baseline you saved in step 8.

Test
uv run pytest -q && uv run run_evals.py && uv run gate.py
You should see
18 passed, 2 deselected in 1.19s
case                 rr  answered cited    source   facts    refused  faithful relevant
hotel-london       1.00  ok       ok       ok       ok       -        ok       ok
...
summary (15 cases, report in reports/latest.json):
  recall@4      1.00
  mrr           1.00
  ...
gate: pass

Troubleshooting

The scores change between two runs with no code change

Temperature 0 makes a model mostly, not perfectly, repeatable: batching and hardware can change a token, and a changed token can flip a check. Run the evals twice and look at which rows flip. Those borderline cases are worth reading; they are where users get inconsistent answers too.

facts fails, but the answer is clearly right

The answer used a spelling your label did not list ("1000" vs "1,000", "an hour" vs "one hour"). Add the spelling with | in evals/golden.jsonl. Keep facts short: a number or a name, not a sentence.

The judge marks almost everything faithful

A small judge tends to agree. Check uv run calibrate.py: if it misses the unfaithful labels, use a stronger judge (JUDGE_MODEL=llama3.1:8b or a hosted model). Do not gate on a criterion whose agreement is below MIN_AGREEMENT.

ValidationError or ValueError when loading a JSONL file

The message names the file, the line and the field. Each line must be one complete JSON object with double quotes, and source must be present (use null for off-topic questions).

recall@4 is high but facts is low

Retrieval found the right file, so the problem is the generation half: the prompt, the model, or a chunk that is right but cut in the wrong place. Read the rows in the report: retrieved shows which chunks the model saw.

What changes in production

  • Grow the golden set from real traffic. Every bug report, thumbs-down and surprising answer becomes a case. Keep it versioned in git next to the code, and review changes to it like code.
  • Run the cheap layers often and the judge less often. Retrieval metrics and rule checks can run on every change; the LLM judge on pull requests that touch prompts, models or retrieval, and nightly (add a schedule: trigger to the workflow).
  • Use a stronger, pinned judge, and re-calibrate when it changes. A hosted judge model version changes behind the same name. Store the judge model name in every report (this pipeline does) and keep the hand labels growing.
  • Watch for leakage between the eval set and the system. Do not paste golden questions into few-shot examples or the prompt: the app then looks perfect on the eval and is not.
  • Evaluate in production too. Offline evals catch regressions before release; sampling live answers through the same checks and judge catches what the golden set does not cover (see LLM evals in practice).

Interview angle

“How would you evaluate a RAG system before shipping a change to it?”

I keep a versioned golden dataset: real questions with the facts and the source document a correct answer needs, plus questions the system must refuse. I measure retrieval on its own with recall@k and MRR, because a wrong answer is either a retrieval miss or a generation problem and I want to know which. Then cheap deterministic checks on the answers: is there a citation, is it the right source, are the required facts present, did it refuse off-topic questions. For meaning I use an LLM judge with a strict yes/no rubric for faithfulness and relevance, JSON output validated with Pydantic, and I calibrate it against hand labels before trusting it. Every run writes a report with the settings that produced it, and a regression gate in CI fails when a metric drops below the stored baseline. Unit tests with fakes cover the pipeline code itself.

Clean up

Keep the project: the next lab (tracing and cost) adds observability to the same app, and the evals tell you whether those changes break anything. The models stay installed for later labs; to free disk space, remove them.

Run
ollama rm llama3.2:3b
ollama rm nomic-embed-text

Practice

No model needed: these run in your browser and check your answer.

Mean reciprocal rank

Write mrr(results). results is a list of (retrieved, expected) pairs: retrieved is a list of source names in rank order, expected is the one that answers the question. For each pair, score 1 divided by the position of the first match (positions start at 1), or 0 if it is not there. Return the average. An empty list returns 0.0.

Exercise
def mrr(results):
    total = 0.0
    for retrieved, expected in results:
        if expected in retrieved:
            total += 1
    return total / len(results) if results else 0.0


print(mrr([(["a.md", "b.md"], "b.md"), (["c.md"], "c.md")]))
Hint

`retrieved.index(expected)` gives the 0-based position of the first match. Add 1 to get the rank.

Cohen's kappa: agreement beyond chance

Agreement rate flatters a lazy judge: if 75% of answers are faithful, a judge that always says "faithful" agrees 75% of the time. Cohen's kappa corrects for that. Write kappa(judge, human) for two equal-length lists of booleans: p_o is the agreement rate; p_e is the agreement expected by chance, pj * ph + (1 - pj) * (1 - ph), where pj and ph are the shares of True in each list. Return (p_o - p_e) / (1 - p_e), or 1.0 when p_e is 1 (both lists are all the same value).

Exercise
def kappa(judge, human):
    p_o = sum(j == h for j, h in zip(judge, human)) / len(human)
    return p_o


print(kappa([True, True, True, True], [True, True, True, False]))
Hint

Compute `pj = sum(judge) / len(judge)` (True counts as 1), the same for `ph`, then `p_e`. Check `p_e == 1` before dividing.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip)