Build a RAG app

Chapter 4 of 1120 min

Split them into chunks

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

In this chapter you will:

  • learn why RAG apps cut documents into small pieces
  • split every document into one chunk per paragraph
  • keep track of which file each chunk came from

Why chunks?

Ask "How long must a work password be?" The answer is one sentence in it-security.txt. The rest of that file, about laptops and suspicious emails, doesn't help, and the other four files don't help at all.

So instead of searching whole files, a RAG app cuts every document into chunks, small passages, and searches those. This has two big benefits:

  • Search gets more precise. It can point at the exact paragraph, not just "somewhere in this file".
  • The AI gets less to read. In chapter 8 you'll send it only the best three chunks, not whole files. Language models have a limit on how much text they take in, and every word you send costs time (and, on paid plans, money).

How big should a chunk be?

There are many ways to cut text: every 200 words, every sentence, every paragraph. Real projects choose based on their documents.

Our handbook is written in paragraphs, and each paragraph is about one thing: booking leave, sick days, core hours. So one chunk per paragraph is both the simplest choice and a good one.

Write split_into_chunks

In the text files, paragraphs are separated by an empty line. In Python that's two newline characters in a row: "\n\n".

Predict, then check

What does this print?

print("one\n\ntwo\n\nthree".split("\n\n"))
Show answer

['one', 'two', 'three']: split cuts the text wherever it finds "\n\n", and returns the pieces as a list. That's all chunking by paragraph is.

Add this function to the end of rag.py:

rag.py
# Chapter 4: one chunk per paragraph
def split_into_chunks(documents):
    chunks = []
    for document in documents:
        for paragraph in document["text"].split("\n\n"):
            paragraph = paragraph.strip()
            if paragraph != "":
                chunks.append({"source": document["source"], "text": paragraph})
    return chunks
  • The outer loop goes through the documents; the inner loop goes through the paragraphs of one document.
  • strip() removes spaces and newlines from both ends of the paragraph.
  • if paragraph != "" skips empty pieces, which appear if a file has extra blank lines.
  • Every chunk keeps the source of its document. That's how the app will cite its answers.

Use it

Replace main.py:

main.py
from rag import load_documents, split_into_chunks
 
documents = load_documents("data")
chunks = split_into_chunks(documents)
print("Loaded", len(documents), "documents and made", len(chunks), "chunks")
 
for chunk in chunks[:3]:
    print()
    print("From", chunk["source"])
    print(chunk["text"])

chunks[:3] is the first three chunks, so the screen doesn't fill up.

python main.py

You should see

Loaded 5 documents and made 26 chunks
 
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.
 
From expenses.txt
Book work trains and flights through the travel desk, so the company pays directly. Fly economy class for flights under six hours. For a taxi to the airport or to a client, keep the taxi app's receipt and claim it.
 
From expenses.txt
When you travel for work, the company pays for meals up to 1,500 rupees a day. Alcohol is never paid for. A team lunch needs your team lead's approval before the lunch, not after.

Practice

Print how many chunks each file has. (Hint: a loop over documents, and inside it a loop over chunks that counts the ones with the same source.)

Show a solution
for document in documents:
    count = 0
    for chunk in chunks:
        if chunk["source"] == document["source"]:
            count = count + 1
    print(document["source"], count)

it-security.txt has 6 chunks; the other four files have 5 each.

Save your progress

git add .
git commit -m "Chapter 4: split into chunks"

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