Build a RAG app

Chapter 3 of 1125 min

Load the documents

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

In this chapter you will:

  • read every handbook file into your program
  • store each document as a dictionary that remembers which file it came from
  • split your code into two files: the parts, and the program that uses them

What "loading" means

Right now the handbook is five files on your disk. Your program can't search files; it can search Python data. So the first part of every RAG app turns files into data.

Each document becomes a dictionary with two keys:

{"source": "leave.txt", "text": "Everyone at Brightpath Studio gets 24 days..."}

Why keep source? Because at the end your app will say where each answer came from. A RAG app that can't show its source is hard to trust.

Write load_documents

Create a new file called rag.py. It will hold every part of your RAG app, one function per part.

rag.py
import os
 
 
# Chapter 3: read every .txt file in a folder
def load_documents(folder):
    documents = []
    for name in sorted(os.listdir(folder)):
        if name.endswith(".txt"):
            path = os.path.join(folder, name)
            with open(path, encoding="utf-8") as file:
                text = file.read()
            documents.append({"source": name, "text": text})
    return documents

Line by line:

  • os.listdir(folder) gives the names of the files in the folder. sorted puts them in alphabetical order, so the output is the same every time.
  • name.endswith(".txt") skips anything that isn't a text file.
  • os.path.join(folder, name) builds the path, like data/leave.txt, with the right slash for your computer.
  • with open(...) as file opens the file and closes it again when the block ends. encoding="utf-8" makes characters like ₹ or é read correctly on every computer.

Use it

Replace everything in main.py with this. main.py is the program you run; rag.py holds the parts it uses.

main.py
from rag import load_documents
 
documents = load_documents("data")
print("Loaded", len(documents), "documents")
for document in documents:
    print("-", document["source"], len(document["text"]), "characters")

Predict, then check

There are five files in data/. Before you run it: in what order will they be printed?

Show answer

Alphabetical order, because of sorted: expenses.txt, first-week.txt, it-security.txt, leave.txt, remote-work.txt. Without sorted, the order depends on your operating system.

python main.py

You should see

Loaded 5 documents
- expenses.txt 885 characters
- first-week.txt 813 characters
- it-security.txt 883 characters
- leave.txt 929 characters
- remote-work.txt 813 characters

Practice

Change main.py so that, under each file name, it also prints the first 80 characters of that document.

Show a solution
main.py
from rag import load_documents
 
documents = load_documents("data")
print("Loaded", len(documents), "documents")
for document in documents:
    print("-", document["source"], len(document["text"]), "characters")
    print("  ", document["text"][:80])

text[:80] is a slice: the characters from the start up to (not including) number 80.

Save your progress

git add .
git commit -m "Chapter 3: load the documents"

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