Goal

You are given a small question-answering system over a (fictional) company handbook. It finds the relevant passages and gives them to a model (RAG). Your job is to measure how well it finds the right passage, find out why it sometimes does not, and improve both the search and the prompt. Retrieval can be scored without calling a model at all, so you can run many experiments quickly and for free.

Working style: In-person lab, individual · Total time: ~60 minutes

Retrieval scores are deterministic: the same command gives the same result every time. If answer generation does not fail for you, that is a valid result; Part 3 says what to report.

What You Submit (read this first)

WhoIndividual. Each student submits their own file
WhatOne PDF document with the contents listed below
WhereE3, under “Week 9 Lab”
WhenBy the end of Wednesday, November 4 (23:59)
File nameWeek9_Lab_<your student ID>.pdf
GradingGraded on completion, like the earlier labs. Be specific

Your PDF should contain, in this order:

  1. Header: your name, student ID, team number, and the model you used
  2. Part 1: the with/without retrieval comparison, with your predictions
  3. Part 2: retrieval results: the chunking table, your two diagnosed misses, and your chunk_by_heading code
  4. Part 3: your build_prompt, before/after answer scores, a faithfulness spot-check of three answers, and three classified failures (or the “did not fail” report)
  5. Part 4: your written responses to Question 1 and Question 2

A fillable copy is in week9_lab_submission_template.md, available with the required files on E3. Write in any tool and save as PDF before uploading. Please do NOT include your API key.

Time Plan

PartWhatMinutes
Setupfiles, packages, smoke test5
Part 1RAG vs. no RAG on four questions10
Part 2measure and diagnose retrieval; write a second chunker20
Part 3measure the answers; write a better prompt15
Part 4written responses10

Setup (5 minutes)

You need Python 3.9 or newer.

  1. Put week9_lab_starter.py, eval_questions.json and the corpus/ folder in the same folder. Download them from the required lab files on E3
  2. Install the packages: pip install chromadb anthropic
  3. Run python week9_setup_check.py. The first run downloads a small embedding model
  4. API key (needed in Parts 1 and 3 only): your team's API key is in the same required lab files folder on E3. Set it in your terminal and never in a file:
    • macOS / Linux: export ANTHROPIC_API_KEY=your-key-here
    • Windows: setx ANTHROPIC_API_KEY your-key-here, then open a new terminal
  5. Smoke test (free, no key needed): python week9_lab_starter.py eval. You should see a list of questions with ok or MISS
Protect your key. Never post it on E3, Discord, in email, in a screenshot, or in your team's repository. The class shares a budget: keep --repeat at 5 or below.

What the Starter File Gives You

You write three things: chunk_by_heading (Part 2), build_prompt (Part 3), and optionally HybridIndex.search (Part 4).

Commands you will use

python week9_lab_starter.py eval --retriever bm25 --chunk fixed:200:0 --k 3
python week9_lab_starter.py grid --retrievers bm25,dense --k 3
python week9_lab_starter.py ask "question"            # add --no-rag, --retriever dense, --k 5
python week9_lab_starter.py run-all --prompt v0       # all 21 questions with the basic prompt
python week9_lab_starter.py run-all                   # all 21 questions with YOUR prompt

--chunk fixed:200:0 means chunks of 200 words with 0 words of overlap. fixed:200:50 means 50 words are shared between neighbouring chunks.

Part 1 — Does Retrieval Help? (10 minutes)

Predict first. For each question below, write whether you expect the model to answer correctly without retrieval, and why. The company is fictional, so think about what a model could possibly know.

#Question
aWhich port does the search service listen on?
bHow many approvals does a change to the billing code need?
cWhat uptime SLA do Team plan customers get?
dWhat is the maximum size of a pull request?

Run each question twice:

python week9_lab_starter.py ask "Which port does the search service listen on?" --no-rag
python week9_lab_starter.py ask "Which port does the search service listen on?" --prompt v0

Record, for each: the answer, the chunk ids retrieved (RAG only), and whether it is correct. Look at the ideal answers by reading the retrieved chunks yourself.

Look for: what did the model do when it did not know? Did it say so, or invent something? Which question is unanswerable from the documents, and what did RAG do with it? Were b and d answered correctly with the basic prompt? Check the retrieved chunks: is there more than one version of the relevant policy?

Part 2 — Measure and Diagnose Retrieval (20 minutes)

All commands in this part are free: no API calls.

Step 1: Predict (3 minutes)

The questions have these types: factual, paraphrase (the question uses different words from the document), exact term (an acronym or command), conflict, multi chunk (the evidence is in two places far apart), multi hop (needs two documents), number confusion. Write down which two types you expect keyword search (BM25) to find hardest, and why. Then which types you expect semantic search (dense) to handle better, and which worse.

Step 2: Run (4 minutes)

python week9_lab_starter.py eval --retriever bm25 --chunk fixed:200:0 --k 3
python week9_lab_starter.py eval --retriever dense --chunk fixed:200:0 --k 3

Record hit@3, MRR, and the list of questions marked MISS for each retriever. Compare with your prediction.

Step 3: The Chunking Table (6 minutes)

python week9_lab_starter.py grid --retrievers bm25,dense --k 3

Each cell shows hit@k / MRR / average context words. Copy at least four rows into your PDF. Then answer:

Step 4: Write a Second Chunker (5 minutes)

Implement chunk_by_heading(doc, max_words) in the starter. Documents are split into sections that begin with ## . Pack consecutive sections into one chunk until adding the next section would make the chunk longer than max_words; cut any single section that is longer than max_words. Then compare:

python week9_lab_starter.py grid --retrievers bm25,dense --k 3 --heading

Is heading:250 better, worse, or the same as your best fixed setting? Offer one reason, and say whether you think the difference would survive on a bigger corpus.

Step 5: Diagnose Two Misses (2 minutes)

Choose two questions that missed with your best setting (different retrievers or different types if possible). For each, run eval and look at the chunk ids it retrieved. Use the printed top: list and open the files if you need to. Write: the question; what was retrieved; the most likely reason it missed (vocabulary mismatch, evidence split across two chunks, a different chunk with the same words, a chunk too small, k too small, or something else); and one change that might fix it.

Part 3 — Measure the Answers and Improve the Prompt (15 minutes)

Use the best retrieval setting you found. These commands call the model: about 21 calls per run.

Step 1: Baseline With the Basic Prompt (3 minutes)

python week9_lab_starter.py run-all --prompt v0 --retriever dense --chunk fixed:200:0 --k 3

(Use your own best retriever and chunk setting.) It prints a pass/fail line for each question and saves all answers to a results_*.json file. The automatic check is a rough heuristic, so open the results file and read the answers, especially the failures and these three types: conflict, unanswerable and injection.

Step 2: Write a Better Prompt (6 minutes)

Edit build_prompt in the starter. Think about:

Run python week9_lab_starter.py run-all --retriever ... --chunk ... --k ... again (without --prompt v0). Compare the number of questions passed with the basic prompt and with yours.

Step 3: Faithfulness Spot-Check (3 minutes)

The automatic check does not tell you whether an answer is grounded. Pick three answers from your improved prompt (include one conflict or unanswerable question). For each, list the claims the answer makes and mark whether a retrieved chunk supports each claim (faithful: yes or no), and whether the answer addresses the question that was asked (relevant: yes or no). Note any claim you cannot point to a passage for.

Step 4: Classify Three Failures (3 minutes)

Pick three questions that failed with either prompt (or that you consider wrong after reading). For each, say which of these it is, and what the first fix would be:

FailureWhat it looks likeFirst fix to try
Retrieval missthe needed chunk was not retrievedchange the chunk size, k, or retriever (Part 2)
Context ignored or misreadthe chunk was retrieved but the answer is wrongprompt: ask for quotes or citations, reduce noise
Conflicting sourcesan outdated document was usedshow status and date; tell the model which to prefer
Invented answerthe answer is not in the documents, but the model gave oneprompt: allow “I could not find this”
Injection followedthe model obeyed an instruction inside a documentprompt: treat documents as data; filter or review the corpus
Other

If Generation Did Not Fail

Because the model is strong, some generation problems may not show up for you. That is a valid result and earns the same credit. If the basic prompt already passes the conflict, unanswerable and injection questions, do all of these:

  1. Evidence. Run run-all --prompt v0 --repeat 3 and report, for those questions, how many of 3 runs passed
  2. Try to break it. Write two questions of your own that you predict could trip the basic prompt (for example, ask about a topic the documents only touch on, ask in Chinese, or ask something an outdated document would answer differently). Write your prediction first, then report the result
  3. Reflect (4–5 sentences): why do you think it held up? What would make it fail in a real project (a bigger corpus, more conflicting versions, a user-editable corpus, a different model)? What would you log or test to notice? Why is “it passed today” not enough?

Part 4 — Written Responses (10 minutes)

Question 1 (3–5 sentences). Think of your team's project. What would a knowledge base for it contain, and would you use RAG? Consider the size of the knowledge base (could it simply be placed in the prompt?), how often it changes, and what you learned about which retriever and chunk size worked. If you would not use RAG, say why.

Question 2 (2–4 sentences). One document in the corpus contains an instruction aimed at AI assistants. Who can write to your project's knowledge base, and what could go wrong if a document there were malicious or simply wrong? Name two controls you would use (for example: restrict who can add documents, review additions, show sources to the user, tell the model that retrieved text is data and not instructions, test with known-bad documents).

Optional extension (not required). Implement HybridIndex.search (reciprocal rank fusion of BM25 and dense) and run grid --retrievers bm25,dense,hybrid. Does combining the two help? Which questions does each retriever get right that the other gets wrong?

Submission Checklist

Upload it on E3 under “Week 9 Lab” by Wednesday, November 4 (23:59).

If Things Go Wrong

ProblemWhat to do
Semantic search needs chromadbRun pip install chromadb
The embedding model will not downloadCheck your network and free disk space; a VPN or proxy can block it. Use --retriever bm25 meanwhile and tell a TA
ModuleNotFoundError: anthropicRun pip install anthropic (only needed for Parts 1 and 3)
An authentication errorThe key is missing or wrong. Reset it, open a new terminal if you used setx, and rerun
“Your credit balance is too low”Tell a TA. Do not keep retrying
Rate limit or “overloaded”Wait 30 seconds, then retry with a smaller --repeat
NotImplementedError: TODOThat function is yours to write: chunk_by_heading in Part 2, HybridIndex.search in Part 4
FileNotFoundError for corpus or questionsKeep the script, corpus/ and eval_questions.json in one folder, and run from that folder
The first dense run is slowIt embeds every chunk once. Results are cached while the program runs
Scores differ slightly from a neighbour'sDifferent chunk or k settings. Compare your commands

← Back to Calendar