Build a RAG app

Chapter 11 of 1160 min

Make it yours

In this chapter you will:

  • point your app at your own documents, including PDFs
  • choose one improvement and build it without step-by-step instructions

Up to now you've followed instructions. This chapter is different: it gives you a starting point and some directions, and you decide the rest. Building something nobody told you exactly how to build is what turns a tutorial into your project.

Your own documents

Pick a set of documents you care about: your college notes, the rules of a game, a product manual, your company's policies (if you're allowed to share them), a set of recipes. Put the .txt files in data/ and remove the handbook.

Predict, then check

Before you run it: what will go wrong if your notes are one long paragraph, with no empty lines?

Show answer

The whole file becomes one chunk, because split_into_chunks cuts only at empty lines. Search can then only say "this file", never "this paragraph", and the AI gets a lot of text that doesn't help. Either add empty lines between topics, or change how you chunk (see the ideas below).

Read PDFs too

Most real documents are PDFs. Install the library that reads them:

pip install pypdf

Add from pypdf import PdfReader to the imports at the top of rag.py, then replace load_documents with this version:

rag.py
# Chapter 3: read every .txt file in a folder
# Chapter 11: and every .pdf file, one chunk per page
def load_documents(folder):
    documents = []
    for name in sorted(os.listdir(folder)):
        path = os.path.join(folder, name)
        if name.endswith(".txt"):
            with open(path, encoding="utf-8") as file:
                text = file.read()
        elif name.endswith(".pdf"):
            pages = []
            for page in PdfReader(path).pages:
                pages.append(page.extract_text())
            text = "\n\n".join(pages)
        else:
            continue
        documents.append({"source": name, "text": text})
    return documents

A PDF's text comes out page by page. Joining the pages with "\n\n" means your existing split_into_chunks makes one chunk per page, with no other change.

Add pypdf as a new last line of requirements.txt too, so your online app can read PDFs.

PDFs that are scanned images contain no text, so extract_text() returns nothing for them. Reading those needs OCR, a different tool.

Pick one improvement

Choose one. Each is a real feature of production RAG apps, and each is a good thing to talk about in an interview.

  • Show the sources. Under each answer, list the chunks the AI was given, so users can check it. (st.expander makes a neat "Sources" box.)
  • Keep the chat history. Store the messages in st.session_state so earlier questions stay on the page.
  • Better chunks. Long pages make poor chunks. Cut text into pieces of about 100 words instead, with a few words of overlap between neighbours so no sentence is lost at a cut.
  • Upload documents in the app. st.file_uploader lets visitors add their own file and ask about it.
  • Measure it. Write ten questions whose right file you know, and count how often search puts that file in the top three. Then change something (chunk size, top, the model) and measure again.

There's no solution to reveal for this chapter. Use what you've learned, the Streamlit docs, and your tutor if you have one.

You built a RAG app

You started with five text files and an empty folder. You now have an app that loads documents, chunks them, embeds them, searches them by meaning, asks a language model to answer from what it found, and runs online with its key kept secret. Every line of it is yours, and you can explain every line.

Save your progress

git add .
git commit -m "Chapter 11: my own documents"
git push

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