Build a RAG app

Chapter 5 of 1130 min

Find the right chunk

  1. Load
  2. Chunk
  3. Embed
  4. Search
  5. Ask the AI
  6. App

In this chapter you will:

  • build your first search: find the chunk that shares the most words with a question
  • turn your program into one you can ask questions
  • find out exactly where word-matching fails, and why

This is the R in RAG, retrieval. Given a question, find the chunk most likely to answer it. Everything else depends on it: if search finds the wrong chunk, the AI answers from the wrong passage.

Start with the most obvious idea: the chunk that shares the most words with the question is probably the right one.

Add this to the end of rag.py:

rag.py
# Chapter 5: find the chunk that shares the most words with the question
def keyword_search(question, chunks):
    question_words = question.lower().replace("?", "").split()
    best_chunk = None
    best_score = 0
    for chunk in chunks:
        chunk_words = chunk["text"].lower().split()
        score = 0
        for word in question_words:
            if word in chunk_words:
                score = score + 1
        if score > best_score:
            best_score = score
            best_chunk = chunk
    return best_chunk
  • lower() makes "Leave" and "leave" the same word. replace("?", "") removes the question mark, and split() cuts the text into words at the spaces.
  • For each chunk, score counts how many of the question's words appear in it.
  • best_chunk and best_score remember the highest score seen so far. This "keep the best so far" loop is a pattern you'll use all the time.
  • If no chunk shares any word, the function returns None.

Ask it questions

Replace main.py. The while True loop keeps asking until you press Enter on an empty line:

main.py
from rag import load_documents, split_into_chunks, keyword_search
 
documents = load_documents("data")
chunks = split_into_chunks(documents)
print("Loaded", len(documents), "documents and made", len(chunks), "chunks")
 
while True:
    question = input("\nYour question (press Enter to stop): ")
    if question == "":
        break
    chunk = keyword_search(question, chunks)
    if chunk is None:
        print("No chunk shares a word with that question.")
    else:
        print("From", chunk["source"])
        print(chunk["text"])
python main.py

Ask: How many days of paid annual leave do I get?

You should see

From leave.txt
Everyone at Brightpath Studio gets 24 days of paid annual leave each calendar year. If you join partway through the year, you get two days of annual leave for every full month left in the year.

It works. Try Can I claim a taxi? and What if my laptop is stolen? too. Your first search engine, in fifteen lines.

Now break it

Predict, then check

Ask How many days off do I get a year? A person knows that means annual leave. Which chunk will your search find?

Show answer

The one about expense claims:

From expenses.txt
Claim work expenses in the finance app within 60 days of paying. Claims older than 60 days are not paid. Every claim needs a photo of the receipt; a bank statement alone is not enough.

The question's words are how, many, days, off, do, i, get, a, year. The expenses paragraph contains two of them, days and a (as in "a photo"). So does the paragraph that really answers it, which has days and get: "Everyone at Brightpath Studio gets 24 days of paid annual leave...". In fact seven chunks tie on 2, and the expenses one wins only because expenses.txt comes first alphabetically.

This is the core problem with word-matching: it matches words, not meaning. "Days off" and "annual leave" mean the same thing and share almost no words. The tie shows two more weaknesses:

  • Small words like a, do and I count as much as days, password or taxi.
  • "year." with a full stop doesn't match "year", so punctuation hides real matches.

You could patch each of these, and search engines did for decades. But the real fix is to search by meaning. That's next: in chapter 6 you'll turn text into numbers that capture what it means.

Practice

Find another question that a person would understand but your search gets wrong. Then write down why it failed: which words matched, and which were missing?

Save your progress

git add .
git commit -m "Chapter 5: keyword search"

Stuck, or want to compare? The finished code for this chapter is tagged ch05: run git diff ch05, or see it on GitHub.