+91 99301 12627
RAG & AI Applications

How to Build a PDF Chatbot Using RAG (Step-by-Step with Python)

By Mehul Prajapati

Stacks of documents that a RAG-based PDF chatbot can search and answer questions from
On this page

Short answer: To build a PDF chatbot using RAG: (1) extract text from your PDFs page by page, (2) split it into overlapping chunks, (3) convert each chunk into an embedding, (4) store the embeddings with page metadata in a vector database such as ChromaDB, (5) for each question, retrieve the most similar chunks, (6) send them to an LLM with instructions to answer only from that context and cite pages, and (7) evaluate answers on a test set. The whole pipeline fits in about 100 lines of Python.

Key takeaways

  • A PDF chatbot is a classic RAG (Retrieval-Augmented Generation) application.
  • Chunking and retrieval quality decide answer quality more than the choice of LLM.
  • Store page numbers and file names as metadata so answers can cite sources.
  • Tell the model to say “I don’t know” when the answer isn’t in the context.
  • Always build a small evaluation set to measure accuracy.

New to the concept? Read What Is RAG? and What Is a Vector Database? first.

Architecture of a PDF chatbot

  1. Ingestion (once): PDF → text per page → chunks → embeddings → vector database
  2. Query (every question): question → embedding → top-k similar chunks → prompt with context → LLM answer with page citations

Tools used in this tutorial

Step Tool
PDF text extraction pypdf
Embeddings Sentence-Transformers (open-source model, runs locally)
Vector database ChromaDB
Answer generation Any LLM API or local model
User interface Streamlit
pip install pypdf sentence-transformers chromadb streamlit

Library APIs evolve, so check each library’s documentation if a function signature has changed.

Step 1: Extract text from PDFs page by page

from pypdf import PdfReader

def load_pdf(path):
    reader = PdfReader(path)
    pages = []
    for i, page in enumerate(reader.pages, start=1):
        text = page.extract_text() or ''
        if text.strip():
            pages.append({'text': text, 'page': i, 'source': path})
    return pages

Note: scanned PDFs contain images, not text, and need OCR before this step.

Step 2: Chunk the text with overlap

def chunk_pages(pages, chunk_size=800, overlap=150):
    chunks = []
    for p in pages:
        text = p['text']
        start = 0
        while start < len(text):
            end = start + chunk_size
            chunks.append({'text': text[start:end], 'page': p['page'], 'source': p['source']})
            start = end - overlap
    return chunks

Character-based chunking keeps this example simple. Splitting on paragraphs or sentences usually gives cleaner chunks. Overlap prevents important sentences from being cut off between chunks.

Step 3: Create embeddings and store them in ChromaDB

import chromadb
from sentence_transformers import SentenceTransformer

embedder = SentenceTransformer('all-MiniLM-L6-v2')
client = chromadb.PersistentClient(path='./pdf_db')
collection = client.get_or_create_collection('pdf_chunks')

def index_pdf(path):
    chunks = chunk_pages(load_pdf(path))
    texts = [c['text'] for c in chunks]
    embeddings = embedder.encode(texts).tolist()
    collection.add(
        ids=[f"{path}-{i}" for i in range(len(chunks))],
        documents=texts,
        embeddings=embeddings,
        metadatas=[{'page': c['page'], 'source': c['source']} for c in chunks],
    )

Step 4: Retrieve the most relevant chunks

def retrieve(question, k=4):
    q_emb = embedder.encode([question]).tolist()
    res = collection.query(query_embeddings=q_emb, n_results=k)
    return list(zip(res['documents'][0], res['metadatas'][0]))

Step 5: Build the prompt and generate an answer

def build_prompt(question, contexts):
    context_text = '\n\n'.join(
        f"[{m['source']} p.{m['page']}] {doc}" for doc, m in contexts)
    return (
        'Answer the question using ONLY the context below. '
        'Cite the source and page in brackets for each fact. '
        "If the answer is not in the context, say 'I could not find this in the documents.'\n\n"
        f'Context:\n{context_text}\n\nQuestion: {question}\nAnswer:'
    )

def answer(question):
    contexts = retrieve(question)
    prompt = build_prompt(question, contexts)
    return call_llm(prompt), contexts  # call_llm wraps your chosen LLM API

call_llm is a small function that sends the prompt to your chosen model, through a hosted API or a local open-source model. Keep API keys in environment variables, never in code.

Step 6: Add a simple Streamlit interface

import streamlit as st

st.title('Ask your PDFs')
q = st.text_input('Your question')
if q:
    reply, sources = answer(q)
    st.write(reply)
    with st.expander('Sources'):
        for doc, m in sources:
            st.markdown(f"**{m['source']} – page {m['page']}**: {doc[:300]}...")

Step 7: Evaluate your chatbot

This is the step most tutorials skip, and the one that impresses interviewers.

  1. Write 20–30 questions with known answers and the page where each answer appears.
  2. Retrieval check: does the correct page appear in the top-k results?
  3. Answer check: is the answer correct, and is it supported by the cited context?
  4. Refusal check: for questions not covered by the PDFs, does it correctly say it can’t find the answer?
  5. Change one thing at a time (chunk size, k, embedding model) and compare scores.

How to improve your PDF chatbot

  • Better chunking: split on headings and paragraphs instead of fixed character counts
  • Hybrid search: combine keyword search with vector search for names, codes and numbers
  • Re-ranking: use a cross-encoder to reorder retrieved chunks
  • Tables: extract tables separately; plain text extraction often scrambles them
  • Conversation memory: rewrite follow-up questions into standalone questions before retrieval
  • Access control: filter documents by user permissions using metadata

When should you fine-tune instead? Usually not for this use case. See RAG vs Fine-Tuning.

Common problems and fixes

Problem Likely cause Fix
Empty or garbled text Scanned PDF or complex layout Use OCR or a layout-aware parser
Right page not retrieved Chunks too large/small, weak embeddings Tune chunk size, try hybrid search or re-ranking
Made-up answers Weak prompt instructions Strict “context only” instructions and refusal rule
Slow responses Too many/large chunks in the prompt Reduce k, shorten chunks, cache embeddings

Frequently asked questions

Can I build a PDF chatbot without paid APIs?

Yes. Open-source embedding models and locally run open-source LLMs can power the whole pipeline, though answer quality and speed depend on the model and your hardware.

Do I need LangChain?

No. This tutorial uses plain Python so you understand every step. LangChain or LlamaIndex can speed up larger projects.

How many PDFs can this handle?

This setup is fine for learning and small collections. Large collections need batching, better parsing and a production-grade vector database.

Is this a good portfolio project?

Yes, especially with an evaluation report and a short write-up of what you improved. It’s one of our recommended data science projects for beginners.

Conclusion

A PDF chatbot is the best first RAG project: extract, chunk, embed, store, retrieve, prompt and evaluate. Build the simple version, measure it, then improve chunking and retrieval step by step.

Build production-style RAG apps in our Generative AI App Developer course, or see our Enterprise RAG Chatbot project.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.