Lesson 15 of 16 · Projects
Project: PDF Question Answering
Build a PDF question-answering app with RAG: extract pages, chunk with page numbers, store in Chroma, retrieve with a distance limit and cite pages in answers.
- 7 min read
- Intermediate
- Reviewed
- Build an end-to-end RAG app that answers questions about a PDF
- Keep page numbers through every stage so answers can cite them
- Combine pypdf, an embedding model, Chroma and an LLM in one script
- Test and improve the app with a few targeted checks
What you'll build
A command-line app: point it at a PDF (a handbook, a manual, a contract), then ask questions and get answers that cite the pages they came from. Every stage from this course appears:
| Stage | In this project |
|---|---|
| Load | pypdf, one text per page |
| Chunk | Word windows with overlap, each tagged with its page |
| Embed and store | An embedding API and a Chroma collection |
| Retrieve | Top 4 chunks, dropping weak matches |
| Generate | An LLM with a grounded prompt that cites pages |
Try the logic here first
This version runs in your browser. It treats each handbook page as text (as if already extracted from the PDF), keeps the page number with every chunk, and builds the prompt the LLM would receive:
import math, re
# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
"leave": "leave holiday holidays vacation annual time-off carried",
"sick": "sick ill illness unwell doctor self-certify",
"remote": "remote home hybrid office hours",
"expenses": "expenses expense claim reimbursed receipt receipts meals",
"equipment": "laptop laptops monitor headset equipment lost stolen",
"security": "password passwords 2fa two-factor login phishing security",
"parental": "parental maternity paternity baby birth adoption adoptive",
"training": "training course courses learning books conferences",
"travel": "travel trip trips flight flights train trains journeys",
"pay": "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}
def words(text):
return re.findall(r"[a-z0-9'-]+", text.lower())
def embed(text):
v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
length = math.sqrt(sum(x * x for x in v))
return [x / length for x in v] if length else v
def cosine(a, b):
return sum(x * y for x, y in zip(a, b)) # vectors are unit length
# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
"Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
"Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
"Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
"Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
"Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
"Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
"Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
"Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
"Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}
# ---- 1. Load: one string per PDF page (here we build them from the handbook) ----
layout = {3: ["Annual leave", "Sick leave"], 4: ["Parental leave", "Remote work"],
5: ["Expenses", "Business travel"], 6: ["Equipment", "Security", "Training"]}
pages = {n: "\n".join(f"{t}\n{HANDBOOK[t]}" for t in titles) for n, titles in layout.items()}
# ---- 2. Chunk: split each page into paragraphs, keeping the page number ----
chunks = []
for page_number, text in pages.items():
lines = text.split("\n")
for heading, body in zip(lines[0::2], lines[1::2]):
chunks.append({"page": page_number, "heading": heading, "text": body})
# ---- 3. Index ----
for c in chunks:
c["vector"] = embed(c["heading"] + ". " + c["text"])
# ---- 4. Ask ----
def ask(question, k=2, min_score=0.3):
q = embed(question)
ranked = sorted(chunks, key=lambda c: cosine(q, c["vector"]), reverse=True)[:k]
found = [c for c in ranked if cosine(q, c["vector"]) >= min_score]
if not found:
return "I couldn't find that in the handbook."
sources = "\n".join(f"[page {c['page']}] {c['heading']}: {c['text']}" for c in found)
return ("Answer using only these extracts from handbook.pdf. "
"Cite pages like (page 4). If the answer isn't there, say so.\n"
f"{sources}\nQuestion: {question}")
print(f"{len(pages)} pages -> {len(chunks)} chunks\n")
print(ask("How many weeks of leave do partners get when a baby arrives?"))
print()
print(ask("What's the dress code?"))Page numbers travel with every chunk from loading to the prompt, so the model can cite them and the app can link to them. The dress-code question finds nothing above the minimum score and gets the honest reply without calling the model.
The full app
On your own computer, install the packages and set your API keys as environment variables (see the Working with AI APIs course). This version uses OpenAI for embeddings and Claude for answers; you can swap either for another provider by changing one function.
pip install pypdf chromadb openai anthropic# pdf_qa.py: ask questions about a PDF. pip install pypdf chromadb openai anthropic
import sys
import anthropic
import chromadb
from openai import OpenAI
from pypdf import PdfReader
openai_client = OpenAI() # reads OPENAI_API_KEY
claude = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
EMBEDDING_MODEL = "EMBEDDING_MODEL" # copy current model names from the docs
CHAT_MODEL = "MODEL_NAME"
def embed(texts):
response = openai_client.embeddings.create(model=EMBEDDING_MODEL, input=texts)
return [item.embedding for item in response.data]
def load_chunks(path, max_words=200, overlap=40):
chunks = []
for page_number, page in enumerate(PdfReader(path).pages, start=1):
words = (page.extract_text() or "").split()
for start in range(0, len(words), max_words - overlap):
text = " ".join(words[start:start + max_words])
if text:
chunks.append({"id": f"p{page_number}-{start}", "page": page_number, "text": text})
if start + max_words >= len(words):
break
return chunks
def build_index(path):
db = chromadb.PersistentClient(path="./pdf_index")
collection = db.get_or_create_collection("pdf_chunks", configuration={"hnsw": {"space": "cosine"}})
chunks = load_chunks(path)
for start in range(0, len(chunks), 100): # embed in batches
batch = chunks[start:start + 100]
collection.upsert(
ids=[c["id"] for c in batch],
embeddings=embed([c["text"] for c in batch]),
documents=[c["text"] for c in batch],
metadatas=[{"page": c["page"]} for c in batch],
)
return collection
def ask(collection, question, k=4, max_distance=0.6):
results = collection.query(query_embeddings=embed([question]), n_results=k)
found = [
(doc, meta["page"])
for doc, meta, dist in zip(results["documents"][0], results["metadatas"][0], results["distances"][0])
if dist <= max_distance
]
if not found:
return "I couldn't find that in the document."
sources = "\n\n".join(f"[page {page}]\n{doc}" for doc, page in found)
message = claude.messages.create(
model=CHAT_MODEL,
max_tokens=500,
system=("Answer using only the document extracts provided. Cite pages like (page 4). "
"If the extracts don't contain the answer, say you couldn't find it."),
messages=[{"role": "user", "content": f"{sources}\n\nQuestion: {question}"}],
)
return message.content[0].text
if __name__ == "__main__":
collection = build_index(sys.argv[1])
while True:
question = input("\nQuestion (or press Enter to quit): ").strip()
if not question:
break
print(ask(collection, question))Run it with python pdf_qa.py handbook.pdf. A session looks like this:
Question (or press Enter to quit): How many weeks of leave do partners get? Partners get 4 weeks of paid parental leave (page 4). Question (or press Enter to quit): What's the dress code? I couldn't find that in the document.
How the parts fit:
load_chunksreads each page and cuts it into 200-word windows with 40 words of overlap, tagging each chunk with its page.build_indexembeds chunks in batches of 100 and upserts them, so running the app again on the same PDF doesn't create duplicates.askembeds the question, queries Chroma, drops chunks with a cosine distance above 0.6 (a similarity below 0.4), and asks the model to answer from the remaining extracts with page citations.
Make it better
Ideas, roughly in order of value:
- Check extraction: print a few pages of
load_chunksoutput before anything else. Scanned PDFs need OCR. - Write 20 test questions with their page numbers, and measure hit rate@4 using
collection.queryalone. - Chunk by headings if the PDF has a clear structure, adding the heading to each chunk.
- Add reranking (retrieve 20, rerank to 4) if the right page is retrieved but not near the top.
- Skip unchanged files by storing a hash of the PDF and re-indexing only when it changes.
Common mistakes
Show readers where an answer came from: list the PDF pages used, without repeats.
file_name = "handbook.pdf" pages_used = [5, 3, 5] # pages of the chunks that were sent to the LLM # Print a citation line with each page once, in order, like: # (handbook.pdf, pages 3, 5)
Why does the app store a page number with every chunk?
Summary
- The PDF Q&A app runs the full RAG pipeline: load, chunk, embed and store, retrieve, generate.
- Page numbers travel with each chunk, so answers cite pages.
- Upserts with stable IDs, batching, a distance limit and an exact fallback make it dependable.
- Improve it with extraction checks, a test set, heading-aware chunks and reranking.
Next: the final project, a knowledge base for a whole organisation.
Finished reading? Tick it off to track your progress.