What it does
You upload a PDF, ask questions about it in plain English, and get answers drawn from that document, all on your own computer. No text is sent to OpenAI or any other cloud service: the language model runs locally through Ollama, and the interface is a small Gradio web app with two tabs: Process PDF and Ask Questions. The whole application is one Python file of about 160 lines, which makes it a good way to see every step of retrieval-augmented generation (RAG) without a framework hiding them.
How it works, step by step
1. Extract the text
PyPDF2 reads each page and concatenates page.extract_text(). This only works for PDFs that contain real text. A scanned document is just images of pages, so it comes out empty and would need OCR first.
2. Split it into chunks
A language model can only read so much at once, and a question is usually answered by one or two paragraphs, not the whole document. So the text is cut into chunks of about 500 characters. Instead of cutting at exactly 500, the code splits on sentence endings and keeps adding whole sentences until the next one would push the chunk past 500:
for sentence in re.split(r'(?<=[.!?])\s+', text):
if len(current_chunk) + len(sentence) > 500:
chunks.append(current_chunk.strip())
current_chunk = sentence
else:
current_chunk += " " + sentence
Keeping sentences whole matters: a chunk that ends mid-sentence often loses the part that answers the question. Thirty copies of a 41-character sentence come out as chunks of 491, 491 and 245 characters.
3. Turn each chunk into an embedding
Each chunk is passed to ollama.embeddings(model="llama3.2", ...), which returns a long list of numbers: a vector that represents what the text is about. Chunks about similar things end up with vectors pointing in similar directions. The chunks and their vectors are saved to embeddings_storage.json, so the slow embedding step doesn't have to run again the next time the app starts.
4. Find the chunks that match the question
When you ask a question, it gets embedded the same way. The app then compares the question's vector with every stored chunk using cosine similarity (the angle between two vectors: 1 means the same direction, 0 means unrelated), sorts the scores and keeps the top five chunks.
5. Ask the model, with guard rails
The five chunks are pasted into a prompt for Llama 3.2 along with the question. The most important line in the prompt is the instruction for what to do when the answer isn't there:
If the answer is not in the provided information, say
"I don't have enough information to answer this question."
Without it, a model will happily answer from its general knowledge, and you can no longer tell which answers came from your document. The Ask tab also has sliders for temperature (0.1–1.0; lower gives more literal, repeatable answers, which suits document Q&A) and max tokens (50–500, default 100). If answers stop mid-sentence, raise max tokens: 100 tokens is only around 75 words.
Things I'd fix in a second version
Reading the code again with fresh eyes, there are three limitations worth knowing about if you build on it:
- The embeddings cache isn't tied to the PDF. The cache file name is always
embeddings_storage.json, and if it exists it is loaded without checking which document it came from. Process a second PDF and the app will quietly keep answering from the first one. The fix is to name the cache after a hash of the file's contents, so each document gets its own cache and a changed file gets a new one. - A very long first sentence creates an empty chunk. If the first sentence is longer than 500 characters, the loop appends the still-empty
current_chunkbefore starting a new one. Running the function on a 601-character sentence followed by two short ones gives chunk lengths of[0, 601, 19]. That empty chunk gets embedded and can be "retrieved" as context. Oneif current_chunk:check before appending fixes it. - A chat model is doing an embedding model's job. Llama 3.2 can produce embeddings, but models trained specifically for embeddings, such as
nomic-embed-text(also available through Ollama), are smaller, faster, and usually retrieve more relevant chunks. Swapping it in is a one-line change, as long as you delete the old cache, because vectors from different models can't be compared.
For a document of a few hundred pages, comparing the question against every chunk one at a time is fast enough. For thousands of documents you would compute all similarities in one NumPy operation or move to a vector database such as Chroma or FAISS.
Running it
ollama pull llama3.2
pip install gradio ollama numpy scikit-learn PyPDF2 tqdm
python rag_gradio_app.py
Gradio prints a local URL (normally http://127.0.0.1:7860). Upload a PDF on the first tab, press Process PDF, then switch to Ask Questions. Embedding is the slow part, because every chunk is a separate call to the model, and a progress bar shows it in the terminal. That one-off cost is why the cache exists.
Where this is useful
Local RAG makes sense when the documents can't leave your machine, such as contracts, internal policies, medical or financial reports, or when you want to learn how RAG works before reaching for LangChain or LlamaIndex. Every step those frameworks automate is visible here in a few lines of plain Python.