✦ GHINOVA

GHINOVA / RAG evaluation tutorial

FREE PYTHON TUTORIAL

How to evaluate a RAG chatbot in Python

By Ginwa Fakih, PhD in Computer Science ·

When a document chatbot gives a bad answer, two things can go wrong. The retriever can miss the supporting passage, or the chatbot can misuse the passage it found. This Python exercise measures the two stages separately. It runs with Python 3.10 or later and uses a small, fixed dataset.

1. Build a labeled set of questions

For each question, record the passages that can support a correct answer. The examples below use a fictional lab handbook. Passage p1 says visitors sign in at reception. Passage p2 requires eye protection at the drill press. Passage p3 lists opening hours. Passage p4 says the lab supervisor trains new volunteers. The handbook contains no Wi-Fi password.

Keep a mix of answerable and unanswerable questions. Give each passage a stable ID. When you test your own chatbot, replace the sample ranked lists with the passage IDs returned by your retriever, in order.

2. Score retrieval with Hit@k and MRR

Hit@k counts how often at least one supporting passage appears in the first k results. Mean reciprocal rank (MRR@k) also rewards placing that passage higher. A match at rank 1 scores 1, a match at rank 2 scores 0.5, and a miss scores 0. Compute both over answerable questions.

cases = [
    {"question": "Where do visitors sign in?", "gold": {"p1"}, "ranked": ["p3", "p1"]},
    {"question": "Is eye protection required?", "gold": {"p2"}, "ranked": ["p2", "p3"]},
    {"question": "Who trains new volunteers?", "gold": {"p4"}, "ranked": ["p3", "p2"]},
    {"question": "What is the Wi-Fi password?", "gold": set(), "ranked": ["p3", "p1"]},
]

def first_hit(ranked, gold, k):
    return next((rank for rank, pid in enumerate(ranked[:k], 1) if pid in gold), None)

for k in (1, 2):
    ranks = [first_hit(c["ranked"], c["gold"], k) for c in cases if c["gold"]]
    hit_rate = sum(rank is not None for rank in ranks) / len(ranks)
    mrr = sum(1 / rank for rank in ranks if rank is not None) / len(ranks)
    print(f"Hit@{k}={hit_rate:.2f}  MRR@{k}={mrr:.2f}")

Expected output is Hit@1=0.33, MRR@1=0.33, Hit@2=0.67 and MRR@2=0.50. Expanding from one result to two recovers the sign-in passage. The volunteer training question still misses because p4 never appears.

3. Review evidence and abstentions

For each response, record whether the chatbot declined to answer, which passage it cited and whether that passage supports the claim. Mark support by reading the answer alongside its citation. In this example the answer about eye protection cites the opening hours, even though the retriever ranked the correct passage first.

replies = [
    {"abstained": False, "citation": "p1", "supported": True},
    {"abstained": False, "citation": "p3", "supported": False},
    {"abstained": True, "citation": None, "supported": False},
    {"abstained": True, "citation": None, "supported": False},
]

paired = list(zip(cases, replies, strict=True))
answered = [(case, reply) for case, reply in paired if not reply["abstained"]]
valid = sum(
    reply["citation"] in case["ranked"]
    and reply["citation"] in case["gold"]
    and reply["supported"]
    for case, reply in answered
)
unanswerable = [reply for case, reply in paired if not case["gold"]]
print(f"Evidence-backed answers: {valid}/{len(answered)}")
print(f"Correct abstentions: {sum(r['abstained'] for r in unanswerable)}/{len(unanswerable)}")

The example produces one evidence-backed answer out of two attempts and correctly abstains on the one unanswerable question. It also abstains on an answerable question after missing the source. Report that missed answer separately when you compare systems. For responses with multiple factual claims, check the evidence for each claim.

4. Compare changes on the same questions

Try changing chunk size or the retriever, then rerun the same questions. Keep a separate test set for your final comparison if you tune on the examples. Review cases where higher Hit@k did not improve answers and cases where a threshold rejected questions that had evidence.

Try the lab with a working notebook

Download the free Retrieval Evaluation Lab →

Explore the €9 RAG Retrieval & Evidence workshop →

Start with the free Python PDF chatbot tutorial →