Say a team lead has a 60-page vendor contract and one question: how much notice do we have to give to cancel? Company policy says the contract cannot go into a hosted chatbot. Reading all 60 pages for one clause takes an afternoon. Searching for “notice” returns 40 matches.
You can answer questions about a PDF without the file leaving your computer. Run a model locally with Ollama, extract the text page by page with pypdf, split each page into chunks that remember their page number, find the chunks that match the question with BM25 keyword search, and send only those chunks to the model with an instruction to cite pages. This guide builds that as a command-line tool and a small Streamlit app in about 140 lines of Python, and shows how we tested each part.
Key Takeaways
- Chatting with a PDF is retrieval plus generation: find the few passages that matter, then ask the model to answer only from them.
- Keeping the page number on every chunk is what makes citations possible. Without it, you cannot check the answer.
- BM25 keyword search is enough for many documents and needs no extra model. Add embeddings when questions use different words than the document.
- Tell the model to cite pages and to say when the answer is not in the excerpts, and set the temperature to 0.
- With Ollama on your own machine, the document and the questions stay local. Pointing the client at a remote server changes that.
What You Need
Install Ollama from ollama.com/download and make sure it is running (the desktop app starts it; on a server, run ollama serve). Then pull a chat model. The examples in the official ollama-python README use gemma4; any chat model you have pulled will work, and you pass its name with --model.
ollama pull gemma4
python -m venv .venv && source .venv/bin/activate
pip install ollama pypdf rank-bm25 streamlit We wrote and tested the code with Python 3.13, ollama 0.6.3, pypdf 6.21.4, rank-bm25 0.2.2 and Streamlit 1.66.1.
How Chatting With a PDF Works
A language model can only read what you put in its prompt, and its context window has a limit. Even when a whole PDF fits, sending 60 pages for every question is slow on a laptop and buries the clause you need in text that does not matter. The usual pattern, called retrieval-augmented generation (RAG), works in four steps:
- Extract the text of each page and keep its page number.
- Chunk each page into pieces of a few hundred characters.
- Retrieve the chunks that best match the question.
- Generate an answer from those chunks only, with page citations.
Sending less text is also how you keep answers fast and cheap. Our guide to using fewer LLM tokens covers the same idea for hosted APIs.
Step 1: Extract Text With Page Numbers
pypdf reads the text layer of a PDF one page at a time. The function below returns a list of (page_number, text) pairs, numbered from 1 so they match what a reader sees, and collapses the extra spaces and line breaks that PDF extraction tends to produce. The pypdf documentation covers options for harder layouts.
def load_pages(path):
"""Return a list of (page_number, text), numbered from 1."""
reader = PdfReader(path)
pages = []
for number, page in enumerate(reader.pages, start=1):
text = page.extract_text() or ""
text = re.sub(r"\s+", " ", text).strip()
if text:
pages.append((number, text))
return pages One limit to know early: extract_text() only reads text that is stored as text. A scanned contract is a set of images, and it comes back empty. Those pages are skipped here, which is why a scanned PDF “loads” but never finds anything. You need an OCR step first for those files.
Step 2: Split Pages Into Chunks
A chunk is a short passage that can be scored and sent to the model on its own. Each chunk below carries the page it came from. Chunks break at a space so words stay whole, and neighboring chunks overlap by 150 characters, so a sentence that crosses a boundary still appears whole in at least one chunk.
def chunk_pages(pages, size=800, overlap=150):
"""Split each page into overlapping chunks that remember their page."""
chunks = []
for number, text in pages:
start = 0
while start < len(text):
end = min(start + size, len(text))
if end < len(text):
space = text.rfind(" ", start, end)
if space > start:
end = space
chunks.append({"page": number, "text": text[start:end].strip()})
if end == len(text):
break
start = max(end - overlap, start + 1)
return chunks About 800 characters is a reasonable start: long enough to hold a clause and its context, short enough that four of them fit easily in a prompt. If answers keep missing details that sit just before or after a match, raise the overlap. If retrieval keeps pulling in loosely related text, make the chunks smaller.
Step 3: Find the Right Chunks With BM25
BM25 is a keyword ranking method: a chunk scores higher when it contains the question’s words, especially words that are rare in the rest of the document. It needs no extra model and no GPU, and it is easy to debug, because you can see which words matched. Our article on BM25S for fast BM25 retrieval in Python explains the scoring in more detail.
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
class Index:
"""BM25 keyword search over the chunks."""
def __init__(self, chunks):
self.chunks = chunks
self.bm25 = BM25Okapi([tokenize(c["text"]) for c in chunks])
def search(self, question, k=4):
scores = self.bm25.get_scores(tokenize(question))
ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
return [self.chunks[i] for i in ranked[:k] if scores[i] > 0] The search drops chunks with a score of zero. If no chunk shares a word with the question, the tool says it found nothing instead of sending the model random text and hoping.
Keyword search has one weakness: it misses matches that use different words. A question about “cancelling” will not find a clause that only says “termination”. When that happens often, add vector search and combine the two scores. Our guide to hybrid search for RAG shows how, and the ollama Python package has an embed() method if you want to keep the embeddings local too.
Step 4: Ask the Local Model and Cite Pages
The prompt does three jobs. The system message tells the model to use only the excerpts, to cite a page after each claim, and to say so when the answer is not there. The user message labels each excerpt with its page, so the model has something to cite. The temperature is set to 0 so the same question gets the same answer, which matters when you are checking a contract.
SYSTEM = (
"Answer only from the excerpts below. After each claim, cite the page "
"in brackets, like [p. 3]. If the excerpts do not contain the answer, "
"say: \"I could not find that in the document.\""
)
def build_messages(question, hits):
excerpts = "\n\n".join(f"[p. {h['page']}] {h['text']}" for h in hits)
return [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Excerpts:\n{excerpts}\n\nQuestion: {question}"},
]
def ask(client, model, index, question, k=4):
"""Retrieve, then ask the model. Returns (answer, hits)."""
hits = index.search(question, k=k)
if not hits:
return "I could not find that in the document.", []
response = client.chat(
model=model,
messages=build_messages(question, hits),
options={"temperature": 0},
)
return response.message.content, hits ask() takes the client as an argument instead of creating it. That keeps the function easy to test, and the same function serves both the command line and the app. The call uses the official package’s chat() method, and the reply text is in response.message.content. If you later want the model to call tools as well as read documents, our guide to implementing AI agents in Python picks up from here.
The Full Command-Line Tool
Here is the whole file, pdfchat.py. It builds the index once, then answers questions in a loop until you press Enter on an empty line. The client connects to Ollama at http://127.0.0.1:11434 unless the OLLAMA_HOST environment variable points somewhere else.
"""Ask questions about a PDF with a local model served by Ollama."""
import argparse
import re
from pypdf import PdfReader
from rank_bm25 import BM25Okapi
SYSTEM = (
"Answer only from the excerpts below. After each claim, cite the page "
"in brackets, like [p. 3]. If the excerpts do not contain the answer, "
"say: \"I could not find that in the document.\""
)
def load_pages(path):
"""Return a list of (page_number, text), numbered from 1."""
reader = PdfReader(path)
pages = []
for number, page in enumerate(reader.pages, start=1):
text = page.extract_text() or ""
text = re.sub(r"\s+", " ", text).strip()
if text:
pages.append((number, text))
return pages
def chunk_pages(pages, size=800, overlap=150):
"""Split each page into overlapping chunks that remember their page."""
chunks = []
for number, text in pages:
start = 0
while start < len(text):
end = min(start + size, len(text))
if end < len(text):
space = text.rfind(" ", start, end)
if space > start:
end = space
chunks.append({"page": number, "text": text[start:end].strip()})
if end == len(text):
break
start = max(end - overlap, start + 1)
return chunks
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
class Index:
"""BM25 keyword search over the chunks."""
def __init__(self, chunks):
self.chunks = chunks
self.bm25 = BM25Okapi([tokenize(c["text"]) for c in chunks])
def search(self, question, k=4):
scores = self.bm25.get_scores(tokenize(question))
ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
return [self.chunks[i] for i in ranked[:k] if scores[i] > 0]
def build_messages(question, hits):
excerpts = "\n\n".join(f"[p. {h['page']}] {h['text']}" for h in hits)
return [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Excerpts:\n{excerpts}\n\nQuestion: {question}"},
]
def ask(client, model, index, question, k=4):
"""Retrieve, then ask the model. Returns (answer, hits)."""
hits = index.search(question, k=k)
if not hits:
return "I could not find that in the document.", []
response = client.chat(
model=model,
messages=build_messages(question, hits),
options={"temperature": 0},
)
return response.message.content, hits
def main():
import ollama
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("pdf")
parser.add_argument("--model", default="gemma4")
args = parser.parse_args()
index = Index(chunk_pages(load_pages(args.pdf)))
client = ollama.Client() # http://127.0.0.1:11434 unless OLLAMA_HOST is set
print(f"{len(index.chunks)} chunks loaded. Ask a question, or press Enter to quit.")
while True:
question = input("> ").strip()
if not question:
break
answer, hits = ask(client, args.model, index, question)
print(answer)
print("Sources: " + ", ".join(f"p. {h['page']}" for h in hits))
if __name__ == "__main__":
main() python pdfchat.py contract.pdf --model gemma4 Every answer is followed by the pages it was built from. That line is the most useful part of the tool: open those pages and check the answer before you rely on it.
A Small Streamlit App
For colleagues who do not use a terminal, the same functions fit into a Streamlit app with an upload button and a chat box. st.cache_resource keeps the index for a file in memory, so it is not rebuilt on every question, and st.session_state keeps the conversation on screen. The Streamlit documentation describes both. Save this as app.py next to pdfchat.py.
import tempfile
import ollama
import streamlit as st
from pdfchat import Index, ask, chunk_pages, load_pages
st.title("Ask Your PDF")
model = st.sidebar.text_input("Ollama model", "gemma4")
upload = st.file_uploader("PDF file", type="pdf")
@st.cache_resource
def build_index(data):
with tempfile.NamedTemporaryFile(suffix=".pdf") as f:
f.write(data)
f.flush()
return Index(chunk_pages(load_pages(f.name)))
if upload is None:
st.info("Upload a PDF to start.")
st.stop()
index = build_index(upload.getvalue())
st.caption(f"{len(index.chunks)} chunks indexed from {upload.name}")
if "history" not in st.session_state:
st.session_state.history = []
for role, text in st.session_state.history:
st.chat_message(role).write(text)
if question := st.chat_input("Ask about the document"):
st.chat_message("user").write(question)
answer, hits = ask(ollama.Client(), model, index, question)
sources = ", ".join(f"p. {h['page']}" for h in hits) or "none"
reply = f"{answer}\n\nSources: {sources}"
st.chat_message("assistant").write(reply)
st.session_state.history += [("user", question), ("assistant", reply)] streamlit run app.py The app shows the sources under each answer, just like the command line. If you want to show a table of retrieved chunks with their scores, our guide to styling Streamlit dataframes with pandas covers the display side.
How We Tested It
We had no Ollama model running in our test setup, so we tested everything around the model for real and replaced only the model call:
- We generated a three-page PDF (a short employee handbook with paid leave on page 2 and expense rules on page 3) and checked that extraction returned three pages, numbered 1 to 3, with the right text.
- We checked that chunks keep their page, are never empty, overlap with their neighbors, and that short pages stay whole at the default size.
- A question about paid leave ranked page 2 first, a question about expense approval ranked page 3 first, and an unrelated question (“quantum entanglement”) returned nothing.
- In place of the model, we used a stand-in client that checks every call against the real
ollama.Client.chat()signature and returns a fixed reply. It confirmed the model name, the messages and a temperature of 0, and that no call is made when nothing matches. - We ran the command-line loop and the Streamlit app (with Streamlit’s own test runner) to make sure both start without errors.
This is the real output of the command-line test, for the question “Who approves expense claims?”. The middle line is the stand-in’s fixed reply, not a model answer. The chunk count and the sources line come from the real code, and page 3 is where the expense rules are:
3 chunks loaded. Ask a question, or press Enter to quit.
(stand-in reply)
Sources: p. 3 With a real model, the answer line is where the model’s text goes. How good that text is depends on the model you pull, so test it on a document you already know well before you trust it on one you do not.
Limits and How to Handle Them
- Scanned PDFs have no text layer. Run OCR first, or the tool finds nothing.
- Tables and multi-column layouts can come out of extraction in a jumbled order. Check the extracted text for the pages that matter.
- Small local models sometimes ignore instructions, skip citations or cite the wrong page. The sources line lets you catch that. Try a larger model if it happens often.
- Different words between question and document defeat keyword search. Rephrase with the document’s terms, or add embeddings as described above.
- Privacy holds only while Ollama runs on your machine. If
OLLAMA_HOSTpoints to another server, the excerpts and questions go there.
Back to the Contract
The team lead from the opening does not need to read 60 pages or paste the contract into a hosted tool. With the tool above, the question “how much notice do we have to give to cancel?” becomes four excerpts, one local model call and an answer with page numbers to check. If the contract calls it “termination” instead, that is the next word to try. Either way, the file never leaves the laptop.
Frequently Asked Questions
Does My PDF Leave My Computer?
Not with this setup. pypdf and BM25 run in your Python process, and the ollama client talks to the Ollama server on your own machine by default. The data leaves only if you point OLLAMA_HOST at another server or swap in a hosted API.
Which Model Should I Use?
Start with the model your machine runs comfortably, then test it on a document you know well. Watch for two things: whether it cites pages, and whether it says “I could not find that” instead of guessing. A model that guesses is not safe for contracts, whatever its size.
Can It Read Scanned PDFs?
No. A scanned page is an image, and pypdf’s extract_text() returns nothing for it. Run the file through an OCR tool to add a text layer first, then load the result.
Why Use BM25 Instead of Embeddings?
BM25 needs no extra model, runs instantly on a laptop and is easy to inspect, which makes it a good first version. Embeddings find matches that use different words. Many teams end up combining both, which is the approach in our hybrid search guide.
How Large a PDF Can It Handle?
Extraction and BM25 indexing are fast for documents of a few hundred pages, because only the top four chunks go to the model, whatever the size of the file. For very large sets of documents, a dedicated search index or vector database is a better fit than rebuilding an index in memory each time.




