TExcelTAD
Home › Generative AI & LLMs › AI Mini Project: Toy RAG

AI Mini Project: Toy RAG

In this project you'll build a complete retrieval-augmented question-answering pipeline for a fictional public library, step by step. It brings together much of the course: chunking, TF-IDF retrieval built from scratch, similarity thresholds, prompt templates, a "generation" step, citations and evaluation.

There is one honest simplification: the site can't call a real LLM, so the generation step is a deterministic fake LLM — a small function that answers by picking the best-supported sentence from the retrieved sources and citing it. The final step shows the few lines you would change to plug in a real model API.

text
documents ──► chunks ──► TF-IDF index
question  ──► retrieve top-k (with threshold) ──► prompt ──► fake LLM ──► answer + citation
                                                                     └──► evaluation

Step 1: The knowledge base and chunks

The library's information lives in a few short documents. We split each into sentence-sized chunks and keep the document id as metadata, so answers can cite their source.

python · try it yourself
import re

DOCS = {
    "hours": "Riverside Library is open Tuesday to Saturday from 10:00 to 19:00. "
             "It is closed on Sundays, Mondays and public holidays.",
    "membership": "Membership is free for residents of the city. "
                  "To register, bring a photo ID and a proof of address. "
                  "Visitors from outside the city can buy a guest card for 5 euros per year.",
    "loans": "Members can borrow up to 12 items at a time. "
             "Books are loaned for three weeks and films for one week. "
             "Loans can be renewed twice online if nobody has reserved the item.",
    "late": "Late returns cost 20 cents per item per day. Children's books have no late fees.",
    "rooms": "Study rooms on the second floor can be booked for up to three hours per day. "
             "Bookings open seven days in advance at the front desk or online.",
    "wifi": "Free Wi-Fi is available throughout the building. "
            "The network is called RiversideGuest and needs no password.",
}

def make_chunks(docs):
    chunks = []
    for doc_id, text in docs.items():
        for n, sentence in enumerate(re.split(r"(?<=\.)\s+", text.strip())):
            chunks.append({"id": f"{doc_id}-{n}", "doc": doc_id, "text": sentence})
    return chunks

chunks = make_chunks(DOCS)
print(len(DOCS), "documents ->", len(chunks), "chunks")
for c in chunks[:4]:
    print(f"{c['id']:<13} {c['text']}")
6 documents -> 14 chunks
hours-0       Riverside Library is open Tuesday to Saturday from 10:00 to 19:00.
hours-1       It is closed on Sundays, Mondays and public holidays.
membership-0  Membership is free for residents of the city.
membership-1  To register, bring a photo ID and a proof of address.

Sentence chunks are tiny, which suits these short, fact-dense documents. For longer documents you would use paragraphs or sections (see Chunking Documents).

Step 2: Retrieval with a threshold

We index the chunks with TF-IDF — built by hand with NumPy so every step is visible — and return the top-k chunks for a question — but only those whose similarity passes a threshold. If nothing passes, the pipeline will say it doesn't know instead of guessing.

python · try it yourself
import re
import numpy as np

DOCS = {
    "hours": "Riverside Library is open Tuesday to Saturday from 10:00 to 19:00. It is closed on Sundays, Mondays and public holidays.",
    "membership": "Membership is free for residents of the city. To register, bring a photo ID and a proof of address. Visitors from outside the city can buy a guest card for 5 euros per year.",
    "loans": "Members can borrow up to 12 items at a time. Books are loaned for three weeks and films for one week. Loans can be renewed twice online if nobody has reserved the item.",
    "late": "Late returns cost 20 cents per item per day. Children's books have no late fees.",
    "rooms": "Study rooms on the second floor can be booked for up to three hours per day. Bookings open seven days in advance at the front desk or online.",
    "wifi": "Free Wi-Fi is available throughout the building. The network is called RiversideGuest and needs no password.",
}
chunks = [{"id": f"{d}-{n}", "doc": d, "text": s}
          for d, t in DOCS.items() for n, s in enumerate(re.split(r"(?<=\.)\s+", t))]

STOP = {"the", "a", "an", "is", "are", "can", "i", "do", "you", "how", "what", "for", "to", "of", "on",
        "my", "and", "in", "it", "at", "there", "does", "be", "from", "or", "if", "no", "when", "per", "have",
        "library", "riverside"}          # words that appear everywhere or carry no meaning here

def terms(text):
    """Lower-case words without stop words, with a crude plural rule (films -> film)."""
    out = []
    for w in re.findall(r"[a-z0-9:-]+", text.lower()):
        if w in STOP:
            continue
        if len(w) > 3 and w.endswith("s") and not w.endswith("ss"):
            w = w[:-1]
        out.append(w)
    return out

# --- TF-IDF index, built by hand ---------------------------------------
vocab = sorted({w for c in chunks for w in terms(c["text"])})
col = {w: i for i, w in enumerate(vocab)}
doc_freq = np.zeros(len(vocab))
for c in chunks:
    for w in set(terms(c["text"])):
        doc_freq[col[w]] += 1
idf = np.log((1 + len(chunks)) / (1 + doc_freq)) + 1      # rare words weigh more

def tfidf(text):
    v = np.zeros(len(vocab))
    for w in terms(text):
        if w in col:
            v[col[w]] += 1
    v *= idf
    norm = np.linalg.norm(v)
    return v / norm if norm else v

matrix = np.array([tfidf(c["text"]) for c in chunks])

def retrieve(question, k=2, threshold=0.2):
    scores = matrix @ tfidf(question)                      # cosine similarity
    ranked = np.argsort(-scores, kind="stable")[:k]
    return [(chunks[i], round(float(scores[i]), 3)) for i in ranked if scores[i] >= threshold]

print("vocabulary size:", len(vocab))
for q in ["How long can I keep a film?", "Is the library open on Monday?", "Do you have a cafe?"]:
    print(q)
    hits = retrieve(q)
    for chunk, score in hits:
        print(f"   {score:.3f} [{chunk['id']}] {chunk['text']}")
    if not hits:
        print("   (nothing above the threshold)")
vocabulary size: 76
How long can I keep a film?
   0.343 [loans-1] Books are loaned for three weeks and films for one week.
Is the library open on Monday?
   0.338 [hours-1] It is closed on Sundays, Mondays and public holidays.
   0.260 [hours-0] Riverside Library is open Tuesday to Saturday from 10:00 to 19:00.
Do you have a cafe?
   (nothing above the threshold)

Three details matter here. The plural rule lets film match films (real systems use proper stemming or embeddings). The domain stop words library and riverside are removed, because nearly every question mentions the library, and without this "Is there a cafe in the library?" would match the opening-hours sentence. And "Do you have a cafe?" retrieves nothing — the documents don't mention one, and the threshold stops weak matches from being passed on as if they were relevant.

Step 3: The prompt and the fake LLM

Now we build the prompt a real model would receive, and a fake model that "answers" it. The fake model reads the sources and the question from the prompt text itself, like a real one would, picks the source sentence that shares the most terms with the question, and cites it. If there are no sources, it replies with the agreed fallback.

python · try it yourself
import re

PROMPT_TEMPLATE = """Answer the question using only the sources.
Cite the source id in square brackets. If the sources don't answer it, reply: I don't know.

{sources}

Question: {question}"""

def build_prompt(question, hits):
    sources = "\n".join(f'<source id="{c["id"]}">{c["text"]}</source>' for c, _ in hits)
    return PROMPT_TEMPLATE.format(sources=sources or "(no sources)", question=question)

STOP = {"the", "a", "an", "is", "are", "can", "i", "do", "you", "how", "what", "for", "to", "of", "on",
        "my", "and", "in", "it", "at", "there", "does", "be", "from", "or", "if", "no", "when", "per", "have",
        "library", "riverside"}          # words that appear everywhere or carry no meaning here

def terms(text):
    """Lower-case words without stop words, with a crude plural rule (films -> film)."""
    out = []
    for w in re.findall(r"[a-z0-9:-]+", text.lower()):
        if w in STOP:
            continue
        if len(w) > 3 and w.endswith("s") and not w.endswith("ss"):
            w = w[:-1]
        out.append(w)
    return out

def fake_llm(prompt):
    """Deterministic stand-in for a model call: extractive answer + citation."""
    sources = re.findall(r'<source id="([^"]+)">(.*?)</source>', prompt)
    question = prompt.rsplit("Question:", 1)[1].strip()
    if not sources:
        return "I don't know."
    q = set(terms(question))
    best_id, best_text = max(sources, key=lambda s: len(q & set(terms(s[1]))))
    return f"{best_text} [{best_id}]"

hits = [({"id": "loans-1", "text": "Books are loaned for three weeks and films for one week."}, 0.52),
        ({"id": "loans-0", "text": "Members can borrow up to 12 items at a time."}, 0.31)]
prompt = build_prompt("How long can I keep a film?", hits)
print(prompt)
print("---")
print("answer:", fake_llm(prompt))
print("answer:", fake_llm(build_prompt("Do you have a cafe?", [])))
Answer the question using only the sources.
Cite the source id in square brackets. If the sources don't answer it, reply: I don't know.

<source id="loans-1">Books are loaned for three weeks and films for one week.</source>
<source id="loans-0">Members can borrow up to 12 items at a time.</source>

Question: How long can I keep a film?
---
answer: Books are loaned for three weeks and films for one week. [loans-1]
answer: I don't know.

The fake model is extractive: it can only repeat a source sentence. A real LLM would write a natural, focused answer ("Films can be borrowed for one week [loans-1].") — and could also make mistakes the fake can't, which is why the next step evaluates the pipeline.

Step 4: The complete pipeline with evaluation

Finally, everything goes into one class, and a small test set checks two things separately: did retrieval find the right document, and does the answer contain the expected fact?

python · try it yourself
import re
import numpy as np

DOCS = {
    "hours": "Riverside Library is open Tuesday to Saturday from 10:00 to 19:00. It is closed on Sundays, Mondays and public holidays.",
    "membership": "Membership is free for residents of the city. To register, bring a photo ID and a proof of address. Visitors from outside the city can buy a guest card for 5 euros per year.",
    "loans": "Members can borrow up to 12 items at a time. Books are loaned for three weeks and films for one week. Loans can be renewed twice online if nobody has reserved the item.",
    "late": "Late returns cost 20 cents per item per day. Children's books have no late fees.",
    "rooms": "Study rooms on the second floor can be booked for up to three hours per day. Bookings open seven days in advance at the front desk or online.",
    "wifi": "Free Wi-Fi is available throughout the building. The network is called RiversideGuest and needs no password.",
}
STOP = {"the", "a", "an", "is", "are", "can", "i", "do", "you", "how", "what", "for", "to", "of", "on",
        "my", "and", "in", "it", "at", "there", "does", "be", "from", "or", "if", "no", "when", "per", "have",
        "library", "riverside"}          # words that appear everywhere or carry no meaning here

def terms(text):
    """Lower-case words without stop words, with a crude plural rule (films -> film)."""
    out = []
    for w in re.findall(r"[a-z0-9:-]+", text.lower()):
        if w in STOP:
            continue
        if len(w) > 3 and w.endswith("s") and not w.endswith("ss"):
            w = w[:-1]
        out.append(w)
    return out

def fake_llm(prompt):
    """Deterministic stand-in for a model call: extractive answer + citation."""
    sources = re.findall(r'<source id="([^"]+)">(.*?)</source>', prompt)
    if not sources:
        return "I don't know."
    q = set(terms(prompt.rsplit("Question:", 1)[1]))
    best_id, best_text = max(sources, key=lambda s: len(q & set(terms(s[1]))))
    return f"{best_text} [{best_id}]"

class LibraryQA:
    def __init__(self, docs, k=2, threshold=0.2, llm=fake_llm):
        self.chunks = [{"id": f"{d}-{n}", "doc": d, "text": s}
                       for d, t in docs.items() for n, s in enumerate(re.split(r"(?<=\.)\s+", t))]
        self.vocab = sorted({w for c in self.chunks for w in terms(c["text"])})
        self.col = {w: i for i, w in enumerate(self.vocab)}
        df = np.zeros(len(self.vocab))
        for c in self.chunks:
            for w in set(terms(c["text"])):
                df[self.col[w]] += 1
        self.idf = np.log((1 + len(self.chunks)) / (1 + df)) + 1
        self.matrix = np.array([self.tfidf(c["text"]) for c in self.chunks])
        self.k, self.threshold, self.llm = k, threshold, llm

    def tfidf(self, text):
        v = np.zeros(len(self.vocab))
        for w in terms(text):
            if w in self.col:
                v[self.col[w]] += 1
        v *= self.idf
        norm = np.linalg.norm(v)
        return v / norm if norm else v

    def retrieve(self, question):
        scores = self.matrix @ self.tfidf(question)
        ranked = np.argsort(-scores, kind="stable")[: self.k]
        return [self.chunks[i] for i in ranked if scores[i] >= self.threshold]

    def ask(self, question):
        hits = self.retrieve(question)
        sources = "\n".join(f'<source id="{c["id"]}">{c["text"]}</source>' for c in hits)
        prompt = ("Answer the question using only the sources. Cite the source id in square brackets. "
                  f"If the sources don't answer it, reply: I don't know.\n\n{sources}\n\nQuestion: {question}")
        return self.llm(prompt), [c["doc"] for c in hits]

TESTS = [
    ("When does the library open on Saturday?", "hours", "10:00"),
    ("How many items can I borrow?", "loans", "12 items"),
    ("How long can I keep a film?", "loans", "one week"),
    ("What does a guest card cost?", "membership", "5 euros"),
    ("How much do late returns cost?", "late", "20 cents"),
    ("What is the Wi-Fi network called?", "wifi", "RiversideGuest"),
    ("How many days in advance can I book a study room?", "rooms", "seven days"),
    ("Is there a cafe in the library?", None, "I don't know"),
]

qa = LibraryQA(DOCS)
retrieval_ok = answer_ok = 0
for question, expected_doc, expected_text in TESTS:
    answer, docs = qa.ask(question)
    r_ok = (expected_doc in docs) if expected_doc else not docs
    a_ok = expected_text.lower() in answer.lower()
    retrieval_ok += r_ok
    answer_ok += a_ok
    print(f"{'ok ' if r_ok and a_ok else 'BAD'} Q: {question}")
    print(f"    A: {answer}")
print(f"retrieval: {retrieval_ok}/{len(TESTS)}   answers: {answer_ok}/{len(TESTS)}")
ok  Q: When does the library open on Saturday?
    A: Riverside Library is open Tuesday to Saturday from 10:00 to 19:00. [hours-0]
ok  Q: How many items can I borrow?
    A: Members can borrow up to 12 items at a time. [loans-0]
ok  Q: How long can I keep a film?
    A: Books are loaned for three weeks and films for one week. [loans-1]
ok  Q: What does a guest card cost?
    A: Visitors from outside the city can buy a guest card for 5 euros per year. [membership-2]
ok  Q: How much do late returns cost?
    A: Late returns cost 20 cents per item per day. [late-0]
ok  Q: What is the Wi-Fi network called?
    A: The network is called RiversideGuest and needs no password. [wifi-1]
BAD Q: How many days in advance can I book a study room?
    A: Study rooms on the second floor can be booked for up to three hours per day. [rooms-0]
ok  Q: Is there a cafe in the library?
    A: I don't know.
retrieval: 8/8   answers: 7/8

Retrieval is perfect, but one answer is wrong — and the split evaluation tells you exactly where to look. For the study-room question both rooms chunks were retrieved, but the fake LLM picked the sentence sharing more words with the question (study, room, day — three terms) instead of the one that answers it (days, advance — only two, because Bookings doesn't match book). Word overlap is a poor model of "answers the question"; a real LLM would very likely pick the right sentence here. In general: a BAD line with correct retrieval points at the generation step; a BAD line with wrong retrieval points at chunking, the threshold or the query wording.

Swapping in a real model

The pipeline only touches the model through llm(prompt) -> str, so a real API is a drop-in replacement (reference code — needs an API key):

python
import anthropic

client = anthropic.Anthropic()

def claude_llm(prompt):
    response = client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=200,
        temperature=0,
        system="You answer questions about Riverside Library. Be brief and always cite sources.",
        messages=[{"role": "user", "content": prompt}],
    )
    return response.content[0].text

qa = LibraryQA(DOCS, llm=claude_llm)

Any provider's chat API works the same way. Run the same TESTS against the real model: you will typically get more natural answers, and the evaluation tells you whether accuracy held up.

Make it your own

  1. Add documents — e.g. an "events" document — and test questions for them. Does the threshold still work?
  2. Tune k and the threshold — print the scores for every test question and pick values that separate relevant from irrelevant matches.
  3. Better retrieval — improve the crude plural rule (try bookings vs book), or replace TF-IDF with toy embeddings and cosine similarity from the Vector Search lesson.
  4. Citation check — verify that every [id] in an answer is one of the retrieved chunk ids (see Retrieval-Augmented Generation).
  5. Conversation — keep a short history so follow-up questions like "and on Sunday?" can be rewritten into standalone questions before retrieval.

Test yourself

Why does the pipeline use a similarity threshold in retrieval?

  1. To make retrieval slower
  2. So weak, irrelevant matches aren't passed to the model as if they were relevant, enabling 'I don't know'
  3. To increase the number of chunks
  4. The TF-IDF vectorizer requires it

Why evaluate retrieval and answers separately?

  1. It's required by scikit-learn
  2. To tell whether a failure comes from finding the wrong sources or from generating a wrong answer
  3. To double the score
  4. Answers don't need evaluation

What makes it easy to swap the fake LLM for a real API?

  1. The pipeline only depends on a function llm(prompt) -> str
  2. TF-IDF works with any model
  3. The fake LLM is written in NumPy
  4. Real models ignore prompts