By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Your architecture review starts on Thursday. The retrieval team brings one slide for the policy assistant that Helio Assist runs for 40,000 customers a week. The slide says retrieval quality is 0.89, down from 0.94 last month. The team calls the drop noise and asks you to sign off the refresh.
Two facts sit outside the slide. Refund complaints rose 30% over the same period. The graded set behind 0.89 has nine cases, and the team wrote all nine itself. An average over nine cases cannot tell you which part of the traffic broke, because no part is reported on its own.
A slice is a group of graded cases that you score and report separately, such as refunds or damaged items. Per-slice reporting is the difference between a number you can act on and a number you can only forward.
In this lab you build one script with four parts: a small policy corpus, two chunkers over that corpus, a retrieval function, and a nine-case graded set that prints per-slice scores. You also run one bad chunking choice and watch it delete the phrase a verdict depends on.
A chunk is the unit you retrieve and cite. Its boundary decides what counts as a complete answer, for a reader and for a model. The two chunkers here differ only in that boundary, so any score gap between them comes from the boundary.
| Chunker | Unit | Keeps the heading | Gets right | Costs |
|---|---|---|---|---|
chunk_by_section | One numbered section | Yes | A rule and its exception stay together | Chunk length varies with the section |
chunk_fixed | 64 characters, no overlap | No | The chunk count is predictable | Rules, exceptions and words get cut in half |
The second row looks harmless in a review. It is the one that fails. A 64-character window ends wherever the 64th character lands, and in this corpus that is inside a word and inside a clause.
returns-policy-f02 "ms are not eligible for refund or exchange, except where the ite"
returns-policy-f03 "m arrived damaged. A damaged item may be refunded in full within"
returns-policy-f04 " 14 days of delivery, and the delivery fee is refunded with it."The damaged-item rule needs two phrases together: the word damaged and the 14-day limit. The window that holds the first phrase ends at the word within, and the 14-day limit opens the next window. Retrieval returns the first two windows, so the model never sees the limit and falls back to a general rule it can read.
Save this as lab1_rag_eval.py in an empty folder. It needs Python 3.10 or newer and nothing else: no key, no packages, no network. Run it from that folder.
"""Lab 1. A retrieval pipeline with a graded evaluation set.
Standard library only. Retrieval is a term counter with inverse document
frequency (idf) weighting. The "model" is a three-branch rule stand-in, so the
report measures chunking and retrieval instead of model variance.
"""
import math
import re
from collections import Counter
STOP = set(
"a an and are as at be by can did do does for from has have how i if in into "
"is it its my of on or that the their then there to was we what when where "
"which who why will with you your".split()
)
DOCS = [
{
"doc_id": "returns-policy",
"version": "2026-11",
"status": "current",
"sections": [
(
"4.1 Standard returns",
"Returns are accepted within 30 days of delivery. The item must "
"be unused, unopened and in its original packaging.",
),
(
"4.2 Final-sale items",
"Final-sale items are not eligible for refund or exchange, "
"except where the item arrived damaged.",
),
(
"4.3 Damaged items",
"A damaged item may be refunded in full within 14 days of "
"delivery, and the delivery fee is refunded with it.",
),
(
"4.4 Refund timing",
"A refund is issued to the original payment method within five "
"working days of approval.",
),
],
},
{
"doc_id": "refunds-2024",
"version": "2024-06",
"status": "retired",
"sections": [
(
"2.1 Returns",
"Final-sale items may be returned within 30 days for a credit note.",
),
],
},
]
# (case id, slice, question, expected verdict)
CASES = [
("f1", "final_sale", "Can I refund a final-sale jacket I bought last week?", "not_eligible"),
("f2", "final_sale", "A clearance coat arrived damaged. Can I get a refund?", "eligible"),
("f3", "final_sale", "Is a final sale dress returnable if it does not fit?", "not_eligible"),
("d1", "damaged", "My mug arrived damaged. Can I get a refund?", "eligible"),
("d2", "damaged", "Is the delivery fee refunded for a damaged item?", "eligible"),
("d3", "damaged", "Is the delivery fee refunded on a damaged return?", "eligible"),
("s1", "standard", "How long do I have to return an unused item?", "eligible"),
("s2", "standard", "Do I need the original packaging to return something?", "eligible"),
("s3", "standard", "Can I return an item I already opened?", "not_eligible"),
]
def tokens(text):
"""Lowercase, drop stop words, and strip one trailing plural s."""
words = []
for word in re.findall(r"[a-z0-9]+", text.lower()):
if word in STOP:
continue
words.append(word[:-1] if len(word) > 3 and word.endswith("s") else word)
return words
def chunk_by_section(docs):
"""One chunk per numbered section, heading kept, version carried."""
chunks = []
for doc in docs:
for number, (heading, body) in enumerate(doc["sections"], start=1):
chunks.append(
{
"chunk_id": "%s-%s-s%d" % (doc["doc_id"], doc["version"], number),
"status": doc["status"],
"version": doc["version"],
"text": heading + ". " + body,
}
)
return chunks
def chunk_fixed(docs, size=64):
"""A fixed character window with no overlap and no heading: the bad choice."""
chunks = []
for doc in docs:
text = " ".join(body for _, body in doc["sections"])
for start in range(0, len(text), size):
chunks.append(
{
"chunk_id": "%s-f%02d" % (doc["doc_id"], start // size),
"status": doc["status"],
"version": doc["version"],
"text": text[start : start + size],
}
)
return chunks
def index(chunks, current_only=True):
"""Keep live versions, count document frequency, and weight rare terms."""
kept = [c for c in chunks if c["status"] == "current"] if current_only else chunks
frequency = Counter()
for chunk in kept:
chunk["tokens"] = tokens(chunk["text"])
frequency.update(set(chunk["tokens"]))
idf = {
term: math.log((1 + len(kept)) / (1 + seen)) + 1
for term, seen in frequency.items()
}
return kept, idf
def retrieve(question, chunks, idf, k=2, floor=0.5):
"""Score by weighted term overlap, keep the best k that clear the floor."""
asked = set(tokens(question))
scored = [
(sum(idf.get(t, 1.0) for t in asked & set(c["tokens"])), c) for c in chunks
]
scored.sort(key=lambda pair: (-pair[0], pair[1]["chunk_id"]))
return [(score, chunk) for score, chunk in scored[:k] if score >= floor]
def answer(question, hits):
"""A stand-in for the model: route on intent, read the clause it needs."""
if not hits:
return "abstain"
text = " ".join(chunk["text"] for _, chunk in hits).lower()
asked = question.lower()
if "damaged" in asked or "cracked" in asked:
return "eligible" if ("damaged" in text and "14 days" in text) else "not_eligible"
if "final" in asked or "clearance" in asked:
return "eligible" if "not eligible" not in text else "not_eligible"
if "opened" in asked:
return "eligible" if "unopened" not in text else "not_eligible"
if "packaging" in asked:
return "eligible" if "packaging" in text else "abstain"
return "eligible" if "30 days" in text else "abstain"
def evaluate(chunks):
kept, idf = index(chunks)
rows = []
for case_id, slice_name, question, expected in CASES:
hits = retrieve(question, kept, idf)
rows.append(
{
"case": case_id,
"slice": slice_name,
"expected": expected,
"got": answer(question, hits),
"context": [chunk["chunk_id"] for _, chunk in hits],
}
)
return rows
def report(label, rows):
slices = sorted({row["slice"] for row in rows})
overall = sum(row["got"] == row["expected"] for row in rows) / len(rows)
cells = []
for name in slices:
group = [row for row in rows if row["slice"] == name]
cells.append(sum(row["got"] == row["expected"] for row in group) / len(group))
print("%-16s %7.2f %s" % (label, overall, " ".join("%10.2f" % c for c in cells)))
def main():
slices = sorted({case[1] for case in CASES})
live_section = sum(c["status"] == "current" for c in chunk_by_section(DOCS))
live_fixed = sum(c["status"] == "current" for c in chunk_fixed(DOCS))
print("live chunks section=%d fixed=%d" % (live_section, live_fixed))
print()
print("%-16s %7s %s" % ("variant", "overall", " ".join("%10s" % s for s in slices)))
report("section_chunks", evaluate(chunk_by_section(DOCS)))
fixed_rows = evaluate(chunk_fixed(DOCS))
report("fixed_windows", fixed_rows)
print()
print("fixed_windows misses")
for row in fixed_rows:
if row["got"] != row["expected"]:
print(
" %s got=%-12s expected=%-12s context=%s"
% (row["case"], row["got"], row["expected"], ", ".join(row["context"]))
)
if __name__ == "__main__":
main()Four parts carry the lesson. DOCS stores version and status, because a retrieved chunk must say which version it came from. index drops retired documents before scoring, which is the difference between citing the 2026 rule and the 2024 one. retrieve keeps two chunks that clear a score floor. answer is a rule stand-in for the model, so it answers only from the text it was handed.
The script prints a two-row table and the misses under the second row.
Check the good row first. section_chunks scores 1.00 in every slice. The retrieval code, the floor and the graded set are therefore sound enough to compare against.
Read the overall column next. fixed_windows scores 0.56, which is four misses out of nine.
Read the slices before the average. damaged is 0.33, final_sale 0.67, standard 0.67. The average sits above the worst slice, so a reviewer who reads only the average approves a broken chunker.
python lab1_rag_eval.pyEvery miss has one shape. The phrase the verdict depends on was cut in two, so the stand-in model answered from the fragment it could read. f2 is the clearest case: the damaged exception needs the 14-day limit, and that limit sits in a window retrieval never returned.
The context= column is the evidence, because it lists the chunk ids the model saw. Without it, a miss is an opinion about the model. With it, the miss is a retrieval finding you can reproduce and fix.
| Failure | What you see | Control |
|---|---|---|
| A window splits a rule from its exception | One slice collapses while the average moves a few points | Chunk by section, keep the heading, and assert that no chunk ends mid-sentence |
| The retired policy stays in the index | Answers cite a rule that was withdrawn last quarter | Filter on status and version at query time, and delete by chunk id before reindexing |
| The floor is low, so weak chunks are used | Confident answers built from an unrelated passage | Abstain when nothing clears the floor, and count abstentions beside the score |
| The set was written by the team that built the system | Scores rise while complaints rise too | Sample cases from traces, label them blind, keep a sealed holdout |
| The floor is tuned on the set you report | The score improves and production does not | Tune on a working split and report on the holdout |
Your lab is done when every row in this table is true.
| Check | Evidence |
|---|---|
| The script imports nothing outside the standard library | A clean machine runs it with no pip install |
| Both chunkers build chunks and the live counts print | The first line reads live chunks section=4 fixed=7 |
| The section chunker scores 1.00 in every slice | Four 1.00 values on the section_chunks row |
| The fixed chunker loses at least three cases, and the report names them | The fixed_windows row plus the misses lines |
| Every miss shows the chunk ids the model saw | A context= value on every miss line |
| You can explain one miss by the boundary that caused it | One paragraph in your decision log |
Run the verification command from the folder that holds the script.
python lab1_rag_eval.pyTwo new corpora arrive. The shipping policy has 14 sections, three tables and a carrier appendix. The supplier contract set has 400 clauses, each with a validity period. You have one sprint before the release gate.
A defensible answer chunks the shipping policy by section with the table header repeated, and the contracts by clause with the validity period on the chunk. It reports the damaged and final-sale slices first, because a wrong answer there moves money. It adds an assertion that no chunk ends mid-sentence, which is the exact failure this lab produced.
Stretch. Add a third chunker that splits on sentence boundaries. Run index(current_only=False) and add two graded cases about the retired 2024 credit-note rule. Report which slice the stale document corrupts, whether the sentence chunker recovers the damaged slice, and what the change cost you in chunk count.
Key takeaways
A chunk boundary decides which phrase a verdict can depend on, so it is a design decision and not a constant.
A per-slice report turns an average into a decision, because the average is weighted by the largest slice.
The fixed window cuts a rule from its exception, and the average hides a slice sitting at 0.33.
Filter retired versions at query time, and abstain when no chunk clears the floor.
Nine hand-written cases prove a mechanism; only a traced, held-out set proves quality.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.