Build a RAG System for PDF in Python (Up to 100 Pages)

Build a RAG system for PDF in Python - chat with a PDF up to 100 pages

You have a 60-page syllabus, a 90-page research paper or a long company policy PDF, and you need answers from it fast. Reading it again and again takes hours. A RAG system for PDF solves this: you upload the PDF once, then ask questions in plain English and get short answers with the page number they came from.

Quick answer: To build a RAG system that reads a PDF of up to 100 pages, read the text page by page with pypdf, split it into small overlapping chunks, store the chunks in ChromaDB (which turns them into embeddings), find the chunks closest to each question, and send only those chunks to a local LLM such as Llama 3.2 through Ollama. The whole project fits in about 80 lines of Python and runs free on your own laptop.

This guide is for BCA, MCA, B.Tech and M.Tech students who know basic Python and want a working AI project for their final year or mini project.

Read these first if you are new to RAG, or use them to compare ideas for your own project:

What Is a RAG System for PDF?

RAG stands for Retrieval-Augmented Generation. An LLM on its own only knows what it learned during training. It has never seen your PDF. A RAG system first retrieves the parts of your PDF that match the question, then gives them to the LLM so it can generate an answer from that text. Because the answer is built from your own document, it is more accurate and you can check the page yourself.

Project objectives

  • Read any text-based PDF of up to 100 pages.
  • Answer questions about the PDF in simple language.
  • Show the page numbers used for every answer.
  • Run fully offline and free, with no paid API key.

Key features

  • PDF upload: a Streamlit page where you drop the PDF in.
  • Page limit check: PDFs over 100 pages are rejected with a clear message.
  • Chunking with overlap: long pages are split into 800-character pieces so no sentence is lost at a border.
  • Semantic search: finds chunks by meaning, not just matching words.
  • Answers with page citations: every reply lists the pages it came from.
  • Saved index: ChromaDB stores the chunks on disk, so you do not re-read the PDF each time.

Technologies used

PartToolWhat it does
PDF readingpypdfExtracts text from each page
Embeddings and storageChromaDBTurns chunks into vectors (all-MiniLM-L6-v2 by default) and searches them
LLMOllama + Llama 3.2Writes the final answer on your own machine
InterfaceStreamlitUpload box, question box and answer display
LanguagePython 3.10+Coding
RAG system for PDF workflow: read PDF, chunk text, store in ChromaDB, retrieve top chunks, answer with Llama 3.2
The five steps of the PDF RAG system

Why limit it to 100 pages?

A 100-page PDF usually becomes a few hundred chunks. That is small enough to index in a short time on a normal student laptop and large enough for a full syllabus, thesis or manual. The limit also keeps your demo fast during the viva. You can raise MAX_PAGES later once you understand how indexing time grows.

Download the Complete Project (Code + Sample PDF)

The ZIP has everything used in this guide. We tested it on a Windows laptop by unzipping it into an empty folder and running it.

  • rag.py and app.py: the same code shown in the steps below.
  • requirements.txt: the exact library versions we tested.
  • sample-final-year-project-guide.pdf: a 14-page Final Year Project Guide (synopsis, report chapters, testing, viva questions) to practise with.
  • README.md: setup steps, practice questions and common errors.
  • screenshots folder: 9 real screenshots of the app you can use in your project report.

Try these questions with the sample PDF and check the page number in each answer:

QuestionAnswer is on
How many words should a synopsis abstract have?Page 5
What happens in weeks 9 to 12 of the project timeline?Page 4
What are the chapters of a final year project report?Page 8
Which Git command uploads commits to GitHub?Page 12
Who is the principal of the college?Not in the PDF, so it should say “I don’t know”

Requirements and Setup

1. Check Python. Install Python 3.10 or newer and check it with python --version.

2. Install Ollama from the official site, then download the model:

ollama pull llama3.2

3. Create a project folder and a virtual environment (on Linux or macOS activate it with source venv/bin/activate):

mkdir pdf-rag
cd pdf-rag
python -m venv venv
venv\Scripts\activate

4. Install the libraries:

pip install pypdf chromadb ollama streamlit

Step-by-Step: Build the RAG System for PDF

Step 1: Read the PDF page by page

  • Open the file with PdfReader.
  • Stop if it has more than 100 pages.
  • Keep the page number with each page’s text, so answers can cite it.
  • Skip empty pages.

Step 2: Split text into chunks

  • Cut each page into 800-character chunks.
  • Let each chunk share 150 characters with the next one (overlap), so an answer that falls across a cut is not lost.
PDF page text split into 800-character chunks with 150-character overlap and page number metadata
How chunking with overlap works

Step 3: Store chunks in ChromaDB

  • Give each chunk an id like p12-c0 (page 12, chunk 0).
  • Save the page number as metadata.
  • Use upsert so loading the same PDF twice does not create duplicates.
  • ChromaDB creates the embeddings itself. The first run downloads its small embedding model once.

Step 4: Retrieve and answer

  • Search ChromaDB for the 4 chunks closest to the question.
  • Put them in a prompt with their page numbers.
  • Tell the model to answer only from that context and to say “I don’t know” if the answer is missing. This cuts down made-up answers.

Save this as rag.py:

from pypdf import PdfReader
import chromadb
import ollama

MAX_PAGES = 100
CHUNK_SIZE = 800      # characters per chunk
OVERLAP = 150         # characters shared between two chunks

client = chromadb.PersistentClient(path="db")
collection = client.get_or_create_collection("pdf_chunks")


def read_pdf(path):
    reader = PdfReader(path)
    if len(reader.pages) > MAX_PAGES:
        raise ValueError(f"PDF has {len(reader.pages)} pages. Limit is {MAX_PAGES}.")
    pages = []
    for number, page in enumerate(reader.pages, start=1):
        text = page.extract_text() or ""
        if text.strip():
            pages.append((number, text))
    return pages


def split_text(text):
    chunks = []
    start = 0
    while start < len(text):
        chunks.append(text[start:start + CHUNK_SIZE])
        start += CHUNK_SIZE - OVERLAP
    return chunks


def index_pdf(path):
    pages = read_pdf(path)
    if not pages:
        raise ValueError("No text found. The PDF may be scanned images.")
    ids, docs, metas = [], [], []
    for page_no, text in pages:
        for i, chunk in enumerate(split_text(text)):
            ids.append(f"p{page_no}-c{i}")
            docs.append(chunk)
            metas.append({"page": page_no})
    collection.upsert(ids=ids, documents=docs, metadatas=metas)
    return len(pages), len(docs)


def ask(question, k=4):
    result = collection.query(query_texts=[question], n_results=k)
    chunks = result["documents"][0]
    pages = [m["page"] for m in result["metadatas"][0]]
    context = "\n\n".join(f"[Page {p}] {c}" for p, c in zip(pages, chunks))
    prompt = (
        "Answer the question using only the context below. "
        "Mention the page number. If the answer is not in the context, say you don't know.\n\n"
        f"Context:\n{context}\n\nQuestion: {question}"
    )
    reply = ollama.chat(model="llama3.2", messages=[{"role": "user", "content": prompt}])
    return reply["message"]["content"], sorted(set(pages))

Step 5: Add the Streamlit interface

Save this as app.py in the same folder:

import streamlit as st
from rag import index_pdf, ask

st.title("Chat with your PDF")

uploaded = st.file_uploader("Upload a PDF (up to 100 pages)", type="pdf")
if uploaded and st.button("Read PDF"):
    with open("uploaded.pdf", "wb") as f:
        f.write(uploaded.getbuffer())
    with st.spinner("Reading and indexing..."):
        try:
            pages, chunks = index_pdf("uploaded.pdf")
            st.success(f"Indexed {pages} pages into {chunks} chunks.")
        except ValueError as e:
            st.error(str(e))

question = st.text_input("Ask a question about the PDF")
if question:
    with st.spinner("Thinking..."):
        answer, pages = ask(question)
    st.write(answer)
    st.caption(f"Sources: pages {pages}")

Step 6: Run it

  • Make sure Ollama is running (it starts on its own after install on Windows and macOS).
  • Run streamlit run app.py.
  • Open the link it prints (usually http://localhost:8501), upload a PDF, click Read PDF, then ask a question.

Watch: Setup and Output in 2 Minutes

This short video shows the five setup steps and the real app answering questions from the sample PDF.

Setup and output of the RAG system for PDF

Expected Results and Limitations

We tested this exact code on a Windows laptop with a 100-page sample handbook PDF. One fact (“the library closes at 9:30 PM and the late fine is Rs 5 per day”) was placed only on page 73.

TestResult
Index 100 pages300 chunks in about 29 seconds (the very first run also downloads Chroma’s 79 MB embedding model once)
Question about the libraryCorrect answer with “(Page 73)” in about 12 to 23 seconds
Question not in the PDF“I don’t know. The provided context does not mention…”
101-page PDFRejected with “PDF has 101 pages. Limit is 100.”

Your timings will change with your laptop’s CPU, RAM and GPU.

Project Screenshots

Real screenshots of the app running with the sample PDF from the ZIP.

Limitations

  • Scanned PDFs: pypdf cannot read text inside images, so scanned pages return nothing without OCR.
  • Tables and multi-column pages: text can come out in a mixed order, which makes answers weaker.
  • One PDF at a time: all chunks go in one collection. Mixing PDFs needs extra metadata.
  • Small model: Llama 3.2 (3B) is fast but can miss answers that need reasoning across many pages.
  • Fixed-size chunks: splitting by characters can still cut a table or list in an odd place.

Common errors and fixes

ProblemWhy it happensFix
“No text found. The PDF may be scanned images.”The PDF is photos of pages, so there is no text layerRun OCR first (for example with Tesseract) or use a text PDF
Connection refused / failed to connect to OllamaOllama is not runningOpen the Ollama app or run ollama serve
model “llama3.2” not foundThe model was never downloadedRun ollama pull llama3.2
Answers from an old PDFThe db folder still holds the earlier PDFDelete the db folder, or use one collection per PDF
Very slow answersLow RAM or no GPUTry a smaller model like llama3.2:1b and close other apps
Wrong or missing answerThe right chunk was not in the top 4Increase k to 6, or reduce CHUNK_SIZE to 500

Ideas to Extend This Project

  • Multiple PDFs: store the file name in metadata and let the user pick which PDFs to search.
  • Chat history: keep past questions in st.session_state so follow-up questions work.
  • OCR support: add Tesseract so scanned notes and old question papers can be read.
  • Better chunking: split by paragraphs or headings instead of a fixed character count.
  • Login and history: add user accounts with Django or Flask and save each user’s PDFs.
  • Evaluation: write 20 test questions with known answers and measure how many the system gets right. This is great material for your project report.
  • Agentic RAG: let the system decide when to search the PDF and when to use another tool, like the Agentic RAG project.

FAQs

Can I build a RAG system for PDF without an OpenAI API key?

Yes. This project uses Ollama with Llama 3.2, which runs on your own computer for free. ChromaDB also creates embeddings locally. No paid key is needed.

Why does the RAG system read only 100 pages?

The limit keeps indexing quick on a student laptop and keeps your viva demo smooth. It is one setting, MAX_PAGES, so you can raise it once your system is working.

Does this work with scanned PDFs?

Not directly. pypdf reads the text layer, and scanned PDFs are only images. Add an OCR step, such as Tesseract, to turn the images into text first.

What is the difference between RAG and fine-tuning?

RAG gives the model the right text at question time, so you can swap PDFs anytime. Fine-tuning changes the model itself with training, which needs much more data, time and computing power.

Is a PDF RAG system good for a final year project?

Yes, if you go beyond the basic version. Add one or two extensions from the list above, measure accuracy with test questions, and explain chunking, embeddings and retrieval clearly in your viva.

Conclusion

A RAG system for PDF teaches you the full modern AI pipeline in one small project: reading documents, chunking, embeddings, vector search and prompting an LLM. Start with the code above, test it on a PDF you know well, then add one extension that matches your interest. If you want to understand the theory better, read the vector database guide next.

Sources and References

Written by Rishabh Saini Founder, UpdateGadh

Rishabh Saini is the founder of UpdateGadh. He has 5 years of experience building PHP, Python, Java, AI and ML projects, and works on projects with the latest and trending technologies. He has helped 2,000+ BCA, MCA and B.Tech students with final year projects. Every project on UpdateGadh is built and tested by him before it is published.

Leave a Reply

Your email address will not be published. Required fields are marked *