Sunday , November 29 2026
Advanced project: build a PDF Q&A assistant with pypdf, ChromaDB, an LLM and Streamlit, with page citations.

PDF Question Answering Assistant with RAG (Advanced AI Project)

Updated: 28 November 2026Level: AdvancedReading time: about 15 minutespypdf · chromadb · openai · streamlit

Build an AI assistant that answers questions from your PDFs – college notes, policy documents, product manuals – and shows which page each answer came from. This is a real-world RAG application with a web interface.

What You Will Learn

  • Extract and chunk PDF text with page numbers
  • Store embeddings in ChromaDB
  • Retrieve relevant chunks and build a grounded prompt
  • Generate answers with citations
  • Add a Streamlit chat interface

Prerequisites

RAG, Vector Databases and OpenAI API.

Architecture

  1. PDF → text per page (pypdf)
  2. Text → overlapping chunks
  3. Chunks → embeddings → ChromaDB (with file and page metadata)
  4. Question → top-k similar chunks
  5. Prompt = rules + chunks + question → LLM
  6. Answer + sources shown in Streamlit
Install
pip install pypdf chromadb openai streamlit

Step 1: Load and Chunk

ingest.py
from pypdf import PdfReader

def load_chunks(path, size=800, overlap=150):
    chunks = []
    for page_no, page in enumerate(PdfReader(path).pages, start=1):
        text = " ".join((page.extract_text() or "").split())
        for start in range(0, len(text), size - overlap):
            piece = text[start:start + size]
            if len(piece) > 50:
                chunks.append({"text": piece, "page": page_no, "file": path})
    return chunks

Explanation: Each chunk keeps its page number for citations. Overlap stops sentences being cut between chunks. Scanned PDFs have no text layer – use OCR (Tesseract) or a multimodal model for those.

Step 2: Index in ChromaDB

Example
import chromadb
client = chromadb.PersistentClient(path="db")
col = client.get_or_create_collection("docs")

def index_pdf(path):
    chunks = load_chunks(path)
    col.upsert(ids=[f"{path}-{i}" for i in range(len(chunks))],
               documents=[c["text"] for c in chunks],
               metadatas=[{"page": c["page"], "file": c["file"]} for c in chunks])
    return len(chunks)

Step 3: Retrieve and Answer

rag.py
from openai import OpenAI
llm = OpenAI()
MODEL = "gpt-4o-mini"     # or any current model

def answer(question, k=4):
    res = col.query(query_texts=[question], n_results=k)
    docs, metas = res["documents"][0], res["metadatas"][0]
    context = "\n\n".join(f"[{m['file']} p.{m['page']}] {d}" for d, m in zip(docs, metas))
    prompt = f"""Answer the question using ONLY the context below.
Cite sources like [file p.N]. If the answer is not in the context, say "Not found in the documents."

Context:
{context}

Question: {question}"""
    reply = llm.chat.completions.create(model=MODEL, temperature=0,
                                        messages=[{"role": "user", "content": prompt}])
    return reply.choices[0].message.content, metas

Explanation: Temperature 0 keeps answers factual. The strict rules and the “Not found” instruction reduce hallucinations; citations let users verify.

Step 4: Streamlit Interface

app.py
import streamlit as st
from rag import index_pdf, answer

st.title("Ask your PDFs")
up = st.file_uploader("Upload a PDF", type="pdf")
if up:
    with open(up.name, "wb") as f:
        f.write(up.getbuffer())
    st.success(f"Indexed {index_pdf(up.name)} chunks")

q = st.chat_input("Ask a question")
if q:
    st.chat_message("user").write(q)
    text, sources = answer(q)
    st.chat_message("assistant").write(text)
    st.caption("Sources: " + ", ".join(sorted({f"p.{s['page']}" for s in sources})))
Example
streamlit run app.py

Make It Production-Ready

  • Evaluate with a question set (LLM Evaluation).
  • Add hybrid search and a re-ranker for better retrieval.
  • Handle many users: per-user collections and authentication.
  • Do not upload confidential files to services your organisation has not approved.
  • Deploy with Docker on Cloud Run or a VM.

All Projects

Projects: Beginner: House Price Prediction · Intermediate: Customer Segmentation · Advanced: PDF Question-Answering Assistant · End-to-End: Churn Prediction App · Industry Project Ideas · GitHub Portfolio Guide

Interview Questions

Q: How do you reduce hallucinations in RAG?
Strict “answer only from context” instructions, a “not found” option, good retrieval, temperature 0 and citations.

Q: Why store page numbers?
To cite sources so users can verify answers.

Practice Exercises

  1. Index three PDFs and ask questions that need information from two of them.
  2. Show the retrieved chunks in an expandable section.
  3. Swap OpenAI for Gemini or Claude.

Summary

You built a PDF question-answering assistant: chunk with page numbers, index in Chroma, retrieve top chunks, answer with a grounded prompt and citations, and serve it with Streamlit.

Next: End-to-End Churn Project

About Machine Learning

Check Also

House Price Prediction Project with Python (Beginner ML Project)

Beginner machine learning project: predict house prices with pandas and scikit-learn, compare Linear Regression and Random Forest, explain and predict.