Building a Labeled Query Set
Write 40 realistic queries for a help centre, label them with graded relevance, validate the files, split off a held-out test set by hashing ids, measure agreement with a second annotator, and freeze the set as versioned JSONL with a manifest.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: collect realistic queries
- Step 2: label relevance with grades
- Step 3: validate before you measure
- Step 4: split off a held-out test set
- Step 5: check agreement on a sample
- Step 6: freeze and version the set
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of RAG Retrieval Evaluation
- Why Retrieval Is Measured Separately Concept · 10 min
- Precision@k and Recall@k by Hand and in Code Worked example · 20 min
- Building a Labeled Query Set Lab · 20 min
- Lab: Compare Two Retrieval Configurations Lab · 25 min
- Rank-Aware Metrics and the Limits of Labels Concept · 15 min
- Check: Compute and Compare Retrieval Metrics Knowledge check · 10 questions
What you will learn
- Compare two retrieval configurations against a test set.
Prerequisites: RAG Foundations
01. Goal and setup
In this lab you build the evaluation set the rest of the skill uses: 40 realistic queries for the help centre from the hybrid search lab, labelled with graded relevance, validated, split into a development set and a held-out test set, spot-checked by a second annotator and frozen as versioned JSONL files. Every later number inherits the flaws of this set, so it deserves more care than the metric code.
You need: Python 3.12 or later with NumPy (corpus.py imports it), Git, and corpus.py from the hybrid-lab folder of Vector Search Foundations, lesson 5. If you skipped that lab, copy corpus.py from its step 1.
mkdir -p retrieval-eval/data && cd retrieval-eval
python3 -m venv .venv # Windows: py -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install numpy
cp ../hybrid-lab/corpus.py . # adjust the path to your hybrid-lab folder
python -c "from corpus import IDS; print(len(IDS), IDS[0], IDS[-1])"14 d01 d14retrieval-eval/
├── corpus.py from hybrid-lab: DOCS and IDS of the 14 articles
├── validate.py step 3
├── split.py step 4
├── sample.py step 5
├── agreement.py step 5
├── freeze.py step 6
└── data/
├── queries.jsonl step 1: the queries, as users wrote them
├── GUIDELINES.md step 2: what each relevance grade means
├── labels.jsonl step 2: graded labels, one line per query
├── dev.jsonl step 4: written by split.py
├── test.jsonl step 4: written by split.py
├── labels_b.jsonl step 5: a second annotator's labels for a sample
└── MANIFEST.json step 6: written by freeze.py02. Step 1: collect realistic queries
A query set is only useful if it looks like the traffic your system will get. Take queries from where users really ask (site-search logs, support-ticket subject lines, questions put to an existing assistant), keep their wording, and record each one's source so you can check the mix and break results down by it. Avoid three shortcuts:
- Writing queries while reading an article. They reuse its words, which flatters keyword search and hides the vocabulary mismatch real users create ("money taken twice" against "billed twice").
- Asking an LLM for one question per article. The same bias, plus every article covered exactly once, which real traffic rarely does. If generated queries fill gaps, give them the source
syntheticand read each one. - Only easy look-ups. They cannot separate two good retrievers. Mix keyword searches, full questions, exact strings such as error codes, and questions that need two articles.
Save the 40 queries below as data/queries.jsonl, one JSON object per line (JSON Lines). Ids are permanent: never renumber or reuse one, because labels, splits and results refer to them.
{"id": "q01", "query": "charged twice for the same order", "source": "ticket"}
{"id": "q02", "query": "money taken from my card two times", "source": "chat"}
{"id": "q03", "query": "how do I update my credit card", "source": "chat"}
{"id": "q04", "query": "where are my invoices for accounting", "source": "chat"}
{"id": "q05", "query": "forgot my password", "source": "search"}
{"id": "q06", "query": "password reset email link not working", "source": "ticket"}
{"id": "q07", "query": "locked out after too many login attempts", "source": "ticket"}
{"id": "q08", "query": "log in with fingerprint on my phone", "source": "chat"}
{"id": "q09", "query": "export dashboard to excel", "source": "search"}
{"id": "q10", "query": "ERR-7702", "source": "search"}
{"id": "q11", "query": "export fails with too many rows", "source": "ticket"}
{"id": "q12", "query": "API returns 413 on exports", "source": "ticket"}
{"id": "q13", "query": "not getting push notifications", "source": "ticket"}
{"id": "q14", "query": "does the app work on iOS 15", "source": "chat"}
{"id": "q15", "query": "refund for an in-app purchase on iPhone", "source": "chat"}
{"id": "q16", "query": "double charge after upgrading on Android", "source": "ticket"}
{"id": "q17", "query": "how do I cancel my subscription in the app", "source": "chat"}
{"id": "q18", "query": "money back for an iPhone purchase", "source": "chat"}
{"id": "q19", "query": "minimum Android version", "source": "search"}
{"id": "q20", "query": "pdf invoice download", "source": "search"}
{"id": "q21", "query": "unlock a user account as admin", "source": "chat"}
{"id": "q22", "query": "Face ID login", "source": "search"}
{"id": "q23", "query": "csv export", "source": "search"}
{"id": "q24", "query": "reset link expired", "source": "search"}
{"id": "q25", "query": "change payment method", "source": "search"}
{"id": "q26", "query": "billed twice by Google Play", "source": "ticket"}
{"id": "q27", "query": "phone app stopped sending alerts", "source": "ticket"}
{"id": "q28", "query": "report too big to export", "source": "ticket"}
{"id": "q29", "query": "Apple charged me, who refunds it", "source": "chat"}
{"id": "q30", "query": "413 error", "source": "search"}
{"id": "q31", "query": "how many rows can I export", "source": "chat"}
{"id": "q32", "query": "sign in with face recognition on Android", "source": "chat"}
{"id": "q33", "query": "update payment card for my plan", "source": "chat"}
{"id": "q34", "query": "refund duplicate payment Android", "source": "search"}
{"id": "q35", "query": "cancel a plan bought through the App Store", "source": "chat"}
{"id": "q36", "query": "which iPhone version does the app need", "source": "chat"}
{"id": "q37", "query": "exports endpoint row limit", "source": "search"}
{"id": "q38", "query": "too many failed sign-in attempts", "source": "ticket"}
{"id": "q39", "query": "notifications not showing on Android", "source": "ticket"}
{"id": "q40", "query": "paid twice, when do I get the money back", "source": "chat"}python -c "import json; print(len([json.loads(l) for l in open('data/queries.jsonl')]))"4003. Step 2: label relevance with grades
A binary label, relevant or not, is enough for precision@k and recall@k, but it loses a distinction you will want later: an article that answers the question is worth more than one that only helps. Graded labels keep it, and a threshold turns them into binary labels whenever a metric needs that. Define the grades in a guidelines file so every annotator applies the same rules, and save it as data/GUIDELINES.md.
# Relevance guidelines, v1
Judge every query against all 14 articles, as written; do not guess intent.
An article missing from a query's labels was judged 0.
- 2: answers the query; a user could act on this article alone.
- 1: partly relevant: the same problem on another platform, or needed background.
- 0: anything else, including articles on the topic that would not help.
A query with no grade-2 article goes to unanswerable.jsonl, not to this set.With 14 articles, every query can be judged against every article (exhaustive judging), so an article missing from a query's labels is a genuine 0. Large corpora use pooling instead: judge the union of the top results from several retrievers plus your own searches. A missing document then means not judged rather than not relevant, a difference lesson 5 returns to.
Labels live in their own file, keyed by query id, so a second annotator can label the same queries separately and labels can be revised without touching the queries. Only grades 1 and 2 are stored. Save the file below as data/labels.jsonl exactly as shown, including one deliberate mistake for the validator to find.
{"id": "q01", "relevant": {"d01": 2, "d13": 1}}
{"id": "q02", "relevant": {"d01": 2, "d13": 1}}
{"id": "q03", "relevant": {"d02": 2}}
{"id": "q04", "relevant": {"d03": 2}}
{"id": "q05", "relevant": {"d04": 2}}
{"id": "q06", "relevant": {"d04": 2}}
{"id": "q07", "relevant": {"d05": 2}}
{"id": "q08", "relevant": {"d06": 2}}
{"id": "q09", "relevant": {"d07": 2}}
{"id": "q10", "relevant": {"d08": 2}}
{"id": "q11", "relevant": {"d08": 2, "d09": 1}}
{"id": "q12", "relevant": {"d09": 2, "d08": 1}}
{"id": "q13", "relevant": {"d10": 2}}
{"id": "q14", "relevant": {"d11": 2}}
{"id": "q15", "relevant": {"d12": 2}}
{"id": "q16", "relevant": {"d13": 2, "d01": 1}}
{"id": "q17", "relevant": {"d14": 2}}
{"id": "q18", "relevant": {"d12": 2}}
{"id": "q19", "relevant": {"d11": 2}}
{"id": "q20", "relevant": {"d03": 2}}
{"id": "q21", "relevant": {"d05": 2}}
{"id": "q22", "relevant": {"d06": 2}}
{"id": "q23", "relevant": {"d07": 2}}
{"id": "q24", "relevant": {"d04": 2}}
{"id": "q25", "relevant": {"d02": 2}}
{"id": "q26", "relevant": {"d13": 2, "d01": 1}}
{"id": "q27", "relevant": {"d10": 2}}
{"id": "q28", "relevant": {"d08": 2, "d09": 1}}
{"id": "q29", "relevant": {"d21": 2}}
{"id": "q30", "relevant": {"d09": 2, "d08": 1}}
{"id": "q31", "relevant": {"d08": 2, "d09": 1}}
{"id": "q32", "relevant": {"d06": 2}}
{"id": "q33", "relevant": {"d02": 2}}
{"id": "q34", "relevant": {"d13": 2, "d01": 1}}
{"id": "q35", "relevant": {"d14": 2, "d12": 1}}
{"id": "q36", "relevant": {"d11": 2}}
{"id": "q37", "relevant": {"d09": 2, "d08": 1}}
{"id": "q38", "relevant": {"d05": 2}}
{"id": "q39", "relevant": {"d10": 2}}
{"id": "q40", "relevant": {"d01": 2, "d13": 1}}python -c "import json; print(len([json.loads(l) for l in open('data/labels.jsonl')]))"40This skill counts grades 1 and 2 as relevant whenever a metric needs a binary label (grade >= 1). Counting only grade 2 is just as defensible and gives different numbers, as a stretch task in lesson 4 shows. Whichever you choose, report it with the results.
04. Step 3: validate before you measure
A typo in a label never raises an error in a metric: an id that matches no document just never counts as a hit, and recall drops for no visible reason. validate.py checks the structure first (unique ids and texts, labels for every query, known document ids, valid grades, at least one answering article per query), prints a profile of the set, and exits with status 1 on any problem, so it can also guard a CI job.
"""Check the labelled query set before any metric is computed from it."""
import json
from collections import Counter
from corpus import IDS
GRADES = {1, 2} # 2 = answers the query, 1 = partly relevant; grade 0 is not stored
def read_jsonl(path: str) -> list[dict]:
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def problems(queries: list[dict], labels: list[dict]) -> list[str]:
found = []
query_ids = [q["id"] for q in queries]
texts = Counter(q["query"].strip().lower() for q in queries)
found += [f"duplicate query id {i}" for i, n in Counter(query_ids).items() if n > 1]
found += [f"duplicate query text {t!r}" for t, n in texts.items() if n > 1]
labelled = Counter(row["id"] for row in labels)
found += [f"{i}: labelled {n} times" for i, n in labelled.items() if n > 1]
found += [f"{i}: labels but no query" for i in labelled if i not in query_ids]
found += [f"{i}: no labels" for i in query_ids if i not in labelled]
for row in labels:
for doc_id, grade in row["relevant"].items():
if doc_id not in IDS:
found.append(f"{row['id']}: unknown document {doc_id}")
if grade not in GRADES:
found.append(f"{row['id']}: grade {grade!r} for {doc_id}")
if 2 not in row["relevant"].values():
found.append(f"{row['id']}: no document answers it (no grade 2)")
return found
if __name__ == "__main__":
queries = read_jsonl("data/queries.jsonl")
labels = read_jsonl("data/labels.jsonl")
found = problems(queries, labels)
for problem in found:
print("PROBLEM:", problem)
sources = Counter(q["source"] for q in queries)
sizes = Counter(len(row["relevant"]) for row in labels)
covered = {doc_id for row in labels for doc_id in row["relevant"]}
print(f"{len(queries)} queries by source:", dict(sources))
print("relevant documents per query:", dict(sorted(sizes.items())))
print("documents no query points to:", sorted(set(IDS) - covered) or "none")
raise SystemExit(1 if found else 0) # a non-zero exit fails a CI jobpython validate.py; echo "exit status: $?" # PowerShell: $LASTEXITCODEPROBLEM: q29: unknown document d21
40 queries by source: {'ticket': 12, 'chat': 16, 'search': 12}
relevant documents per query: {1: 27, 2: 13}
documents no query points to: none
exit status: 1The validator found the planted mistake: q29 points at d21, which does not exist. The query asks who refunds an Apple charge, so the intended article is d12. Change that line in data/labels.jsonl to {"id": "q29", "relevant": {"d12": 2}} and run the same command again.
40 queries by source: {'ticket': 12, 'chat': 16, 'search': 12}
relevant documents per query: {1: 27, 2: 13}
documents no query points to: none
exit status: 0Read the profile too: all three sources are well represented, 13 queries have two relevant articles (one graded 2 that answers them and one graded 1 that partly helps), and every article is needed by at least one query, so no part of the corpus goes untested. No query here needs two articles together to be answered; a real set should add some, as step 1 advises.
05. Step 4: split off a held-out test set
Each time you look at scores and adjust a setting, the configuration fits these particular queries a little more, and the scores say less about new ones. The defence is a held-out split: develop against dev, and score test only to compare finished configurations, ideally once.
split.py assigns each query by hashing its id rather than shuffling the list. A shuffle reassigns old queries whenever you add new ones; a hash depends only on the id, so each query keeps its split for good and anyone who reruns the script gets the same files.
"""Assign every query to dev or test by a hash of its id; write one file per split."""
import hashlib
import json
from validate import read_jsonl
def split_of(query_id: str) -> str:
"""Stable: depends only on the id, so adding queries never moves old ones."""
number = int(hashlib.sha256(query_id.encode("utf-8")).hexdigest(), 16)
return "dev" if number % 3 == 0 else "test"
queries = read_jsonl("data/queries.jsonl")
labels = {row["id"]: row["relevant"] for row in read_jsonl("data/labels.jsonl")}
splits: dict[str, list[dict]] = {"dev": [], "test": []}
for query in queries:
record = {**query, "relevant": labels[query["id"]]}
splits[split_of(query["id"])].append(record)
for name, records in splits.items():
with open(f"data/{name}.jsonl", "w", encoding="utf-8", newline="\n") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
print(f"{name}: {len(records)} queries")
print("dev ids:", " ".join(r["id"] for r in splits["dev"]))python split.pydev: 16 queries
test: 24 queries
dev ids: q01 q05 q06 q07 q08 q10 q11 q14 q15 q18 q25 q28 q29 q38 q39 q40Hashing sends roughly a third of the queries to dev: here 16 against 24. Each output line carries the query, its source and its graded labels. If several queries come from one ticket or rephrase one problem, hash a shared group key instead of the id, so near-duplicates cannot sit on both sides and leak information from dev into test.
06. Step 5: check agreement on a sample
Your labels are one person's judgement. To find out whether the guidelines are clear enough for someone else to reach the same labels, ask a second annotator to label a random sample without seeing yours, then compare. A fixed seed makes the sample reproducible, and sampling at random stops you from choosing the queries you feel sure about.
import random
from validate import read_jsonl
ids = [q["id"] for q in read_jsonl("data/queries.jsonl")]
print(sorted(random.Random(42).sample(ids, 8))) # fixed seed: the same sample every run['q02', 'q06', 'q07', 'q08', 'q09', 'q15', 'q16', 'q18']The second annotator's labels for those eight queries go in data/labels_b.jsonl, in the same format.
{"id": "q02", "relevant": {"d01": 2}}
{"id": "q06", "relevant": {"d04": 2}}
{"id": "q07", "relevant": {"d05": 2, "d04": 1}}
{"id": "q08", "relevant": {"d06": 2}}
{"id": "q09", "relevant": {"d07": 2}}
{"id": "q15", "relevant": {"d12": 2}}
{"id": "q16", "relevant": {"d13": 2}}
{"id": "q18", "relevant": {"d12": 1}}agreement.py compares the two annotators over every query–document pair in the sample, treating grades 1 and 2 as relevant, and reports Cohen's kappa, which corrects raw agreement for the agreement two annotators would reach by chance.
"""Compare two annotators over every (query, document) pair of the shared sample."""
from corpus import IDS
from validate import read_jsonl
a = {row["id"]: row["relevant"] for row in read_jsonl("data/labels.jsonl")}
b = {row["id"]: row["relevant"] for row in read_jsonl("data/labels_b.jsonl")}
pairs = [(q, d) for q in sorted(b) for d in IDS] # unstored pairs are grade 0
yes_a = [d in a[q] for q, d in pairs] # binary: grade 1 or 2 is relevant
yes_b = [d in b[q] for q, d in pairs]
n = len(pairs)
observed = sum(x == y for x, y in zip(yes_a, yes_b)) / n
p_a, p_b = sum(yes_a) / n, sum(yes_b) / n
chance = p_a * p_b + (1 - p_a) * (1 - p_b) # agreement expected by chance
kappa = (observed - chance) / (1 - chance)
print(f"{len(b)} queries x {len(IDS)} documents = {n} pairs")
print(f"marked relevant: A {sum(yes_a)}, B {sum(yes_b)}")
print(f"raw agreement {observed:.3f} (an annotator marking nothing: {1 - p_a:.3f})")
print(f"Cohen's kappa {kappa:.2f}")
for q, d in pairs:
grade_a, grade_b = a[q].get(d, 0), b[q].get(d, 0)
if grade_a != grade_b:
print(f" {q} {d}: A={grade_a} B={grade_b}")8 queries x 14 documents = 112 pairs
marked relevant: A 10, B 9
raw agreement 0.973 (an annotator marking nothing: 0.911)
Cohen's kappa 0.83
q02 d13: A=1 B=0
q07 d04: A=0 B=1
q16 d01: A=1 B=0
q18 d12: A=2 B=1Raw agreement of 97% sounds excellent, but an annotator who marked nothing relevant would still score 91%, because most pairs are obvious zeros. Kappa, (observed - chance) / (1 - chance), measures how much of the remaining room the two annotators share, where chance agreement comes from how often each says relevant. Here it is 0.83. (This is Cohen's version, with each annotator's own rate, as in scikit-learn's cohen_kappa_score; Introduction to Information Retrieval pools the two rates, a slightly more conservative variant.) That book reads values above 0.8 as good, 0.67 to 0.8 as fair and lower as a dubious basis for evaluation, and notes that TREC judges usually land in the fair range.
The disagreements matter more than the number. Two of the three binary ones share a cause, the article for the same problem on the other platform: annotator B gave it 0 both when the query named no platform (q02) and when it named one (q16), so the rule for grade 1 was not clear enough. The other two are judgement calls. Settle each with the second annotator and record the decisions: append these lines to data/GUIDELINES.md, after a blank line.
Decisions after the spot check (v1):
- The other platform's article for the same problem is a 1, whether or not
the query names a platform (q02, q16).
- Resetting a password does not unlock an account: d04 is 0 for lockouts (q07).
- Saying who issues a refund, and where to ask, answers a refund query: 2 (q18).Here the decisions confirm the first annotator's labels, so nothing else changes. When a decision does change labels, edit data/labels.jsonl, then rerun validate.py and split.py.
07. Step 6: freeze and version the set
A comparison only means something if both sides were scored against the same set, and a result is only reproducible if you can say which set that was. freeze.py writes a manifest: the version, a hash of the corpus the set was labelled against, the label rules, the counts and a hash of every file.
"""Record what this version of the set is: counts, label rules and file hashes."""
import hashlib
import json
from pathlib import Path
from corpus import DOCS
from validate import read_jsonl
VERSION = "1.0.0"
COUNTED = ("queries", "dev", "test")
FILES = ["data/queries.jsonl", "data/labels.jsonl", "data/dev.jsonl",
"data/test.jsonl", "data/labels_b.jsonl", "data/GUIDELINES.md"]
def short_hash(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()[:16] # 16 hex digits identify a file
corpus_bytes = json.dumps(DOCS, ensure_ascii=False).encode("utf-8")
manifest = {
"name": "helpcentre-retrieval",
"version": VERSION,
"corpus_sha256": short_hash(corpus_bytes),
"grades": {"2": "answers the query", "1": "partly relevant"},
"binary_relevant": "grade >= 1",
"counts": {name: len(read_jsonl(f"data/{name}.jsonl")) for name in COUNTED},
"files": {path: short_hash(Path(path).read_bytes()) for path in FILES},
}
text = json.dumps(manifest, indent=2) + "\n"
Path("data/MANIFEST.json").write_text(text, encoding="utf-8", newline="\n")
print(text, end="")python freeze.py{
"name": "helpcentre-retrieval",
"version": "1.0.0",
"corpus_sha256": "3d7f9b9f8115d99d",
"grades": {
"2": "answers the query",
"1": "partly relevant"
},
"binary_relevant": "grade >= 1",
"counts": {
"queries": 40,
"dev": 16,
"test": 24
},
"files": {
"data/queries.jsonl": "71cd34f7675fe909",
"data/labels.jsonl": "3cac6605634da7f4",
"data/dev.jsonl": "050adcd396d49a67",
"data/test.jsonl": "401973998ea87c95",
"data/labels_b.jsonl": "6fda922ae25edbbc",
"data/GUIDELINES.md": "6cb303818226a20a"
}
}Commit the set with the scripts that built it, and tag the version:
git init -b main
git add data *.py
git commit -m "Query set v1.0.0: 40 queries, graded labels, dev/test split"
git tag qset-v1.0.0
git tag --listqset-v1.0.0Treat a released version as read-only: adding queries makes 1.1.0, changing labels or grade meanings makes 2.0.0, and scores are comparable only within one version, so report the version and the corpus hash with every metric. After a corpus change, validate.py catches labels that point at deleted articles, but not edited articles whose labels are no longer true; lesson 5 covers that drift.
08. Check your understanding
09. Apply it: stretch tasks
Build the set for your practice project from your own corpus and the queries you collected in lesson 1:
- Write
GUIDELINES.mdfor your domain, with an example query for each grade. - Label every query. If your corpus is too large to judge every document, pool the top 10 of two different retrievers plus your own searches, and store the documents you judged irrelevant as grade 0 so that not judged stays distinct from not relevant; extend
validate.pyto accept grade 0, and check that every script that reads labels still counts only grades 1 and 2 as relevant. - Validate and split, then ask a colleague to label three queries blind. Compute kappa and write down every decision.
- Freeze version 1.0.0 with its manifest and tag it.
Stretch: add a doc_sha256 map with one hash per document to the manifest, so that after a corpus update you can list exactly which labels need another look (lesson 5's drift check).
10. Review prompt
Without looking back:
- List the six steps of this lab in order, with the file each one produces.
- Why should queries come from logs or tickets rather than from reading the documents?
- What does a graded label keep that a binary one loses, and what must you report when you turn grades into binary relevance?
- Why split by hashing ids, and what should you hash when several queries come from one ticket?
- What does kappa correct for, and why is the list of disagreements more useful than the kappa value?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 12 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.