AI Hints
Home›RAG Tutorial›Errors and Regressions
RAG · Lesson 80 of 120

Regression Tests

Don't go backwards.

⏱ 2 min read▶ Video at 1:18:43🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Once retrieval is good, we want to keep it that way. A regression test runs the test set automatically, and fails if the score drops below a target. It stops a bad change before it reaches customers.

Regression Tests
From the video: Regression Tests
  • Keep it good
  • Run automatically
  • Fail on a drop

A retrieval test

Check builds an index, measures hit rate, and asserts it's at least eighty percent. We run it twice, with chunk size six hundred, then with three hundred, as if someone changed the setting. Run it. The first passes. The second fails, and says why.

regression.pypython
import json
from rag_kit import load_docs, make_chunks, Index

tests = json.load(open("eval_set.json"))

def check(size):
    index = Index(make_chunks(load_docs(), size=size, overlap=size // 6))
    rate = sum(any(t["fact"] in c["text"] for s, c in index.search(t["question"], 3))
               for t in tests) / len(tests)
    assert rate >= 0.8, f"hit rate fell to {rate:.0%}"
    print(f"size {size}: passed at {rate:.0%}")

for size in [600, 300]:
    try: check(size)
    except AssertionError as e: print(f"size {size}: FAILED,", e)
Output
size 600: passed at 90%
size 300: FAILED, hit rate fell to 60%
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses eval_set.json
[
 {"question": "What does E03 mean?", "source": "ebike_errors.md", "fact": "speed sensor"},
 {"question": "What is the APR?", "source": "finance.md", "fact": "9.9"},
 {"question": "Can I spread the payments?", "source": "finance.md", "fact": "spread the cost"},
 {"question": "How many hours until my e-bike is full again?", "source": "ebike_battery.md", "fact": "4 hours"},
 {"question": "How long until my money comes back?", "source": "returns.md", "fact": "7 working days"},
 {"question": "Can I get next-day delivery on a bike?", "source": "shipping.md", "fact": "Next-day"},
 {"question": "How much is a rental deposit?", "source": "rentals.md", "fact": "£150"},
 {"question": "When is the York shop open?", "source": "stores.md", "fact": "5:30pm"},
 {"question": "How much is a Basic service?", "source": "servicing.md", "fact": "£49"},
 {"question": "Do you deliver bikes to France?", "source": "shipping.md", "fact": "complete bikes"}
]

In your project

Put the check in your test suite, and run it on every change, with pytest or in CI. Keep the test set in version control. And raise the target as your system improves.

keyvalue
Runon every change
Wherepytest, CI
Test setin git
Targetraise it over time

Summary

Regression tests run the test set automatically, and fail when quality drops. Next, the evaluation quiz.

Key takeaways
  • Assert a target
  • Run on every change
  • No going backwards
Next up: Evaluation Quiz — test yourself