AI ENGINEER · RAG GUIDE
RAG With Python: Build a PDF Question-Answering Pipeline and Measure It
In this guide
RAG, retrieval-augmented generation, answers a question by first finding the most relevant passages in your own documents and then asking a language model to answer from them. To build and measure it over a PDF in Python, read the PDF with pypdf, split it into chunks, index the chunks, retrieve the best matches for each question, and score retrieval with a small set of questions whose correct passage you already know. In the test run for this guide, a word-based index found the right passage first for 9 of 10 questions, and a character-based index found it for 10 of 10. The set is tiny, so treat that as a method to copy, not a benchmark to quote.
Many RAG tutorials stop when the demo answers one question correctly. That proves very little. A demo that works on the question you tried says nothing about the next fifty, and the failure is rarely in the language model. It is usually in retrieval: the right passage was never shown to the model, so the model either guessed or said it did not know.
This guide builds the retrieval half of a RAG pipeline over a PDF and, more importantly, shows how to measure it. The measuring habit is what separates a prototype from something you can trust and improve. If you are following a wider learning plan, the AI Engineer roadmap shows where retrieval and evaluation fit.
What RAG does and why it exists
A language model knows what it learned in training. It does not know your company’s leave policy, last week’s price list or a contract signed yesterday. RAG solves this by adding a step before the model answers. The system searches your documents, picks the most relevant passages and places them in the prompt, so the model answers from your material.
The pipeline has two halves. Retrieval finds the passages. Generation turns them into an answer. This guide focuses on retrieval because that is where most real problems start, and because you can measure it without paying for a model or sharing documents with anyone.
The test document
To keep every result reproducible, we created a three-page PDF for a made-up company policy. Page one covers leave, page two covers travel and expenses, and page three covers remote work. Each page has a heading and four plain sentences, for example “Employees get 18 days of paid annual leave each year.” and “Expense claims must be submitted within 30 days of the trip.” The content is invented for the exercise and does not describe any real organisation.
Using your own PDF works the same way. The important point is that you must know, for each test question, which passage contains the answer. That knowledge is what lets you score the system.
Step 1: read the PDF and split it into chunks
A model cannot search a file. It needs text split into pieces small enough to match against a question. Each piece is a chunk. Keep the page number with each chunk so your answers can cite where they came from.
from pypdf import PdfReader
def load_chunks(path):
chunks = []
for page_no, page in enumerate(PdfReader(path).pages, start=1):
text = page.extract_text() or ""
# one chunk per line here; keep the page number for citations
for line in [l.strip() for l in text.splitlines() if l.strip()]:
chunks.append({"page": page_no, "text": line})
return chunks
On our test PDF this produced 15 chunks from 3 pages. Chunking is a design choice. One line per chunk suits short policy sentences. For long prose you would use overlapping windows of a few sentences so an answer is not cut in half. Whatever you choose, change it only while measuring, which is the point of this guide.
Step 2: build an index
An index turns text into numbers so the computer can compare a question with every chunk. The simplest useful method is TF-IDF, which scores how well the words in a question match the words in a chunk, giving more weight to rarer words. It needs no model and no account, and it runs in milliseconds.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
chunks = load_chunks("policy.pdf")
vec = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
matrix = vec.fit_transform([c["text"] for c in chunks])
def retrieve(question, k=3):
scores = cosine_similarity(vec.transform([question]), matrix)[0]
order = scores.argsort()[::-1][:k]
return [(int(i), float(scores[i])) for i in order]
The function returns the positions of the top k chunks with their scores. In a full RAG system you would pass those chunks to a language model along with the question. Embedding models, covered in later guides, replace TF-IDF with meaning-based vectors, but the measuring method below stays identical, which is why learning it first is worthwhile.
Step 3: write the test set before you tune anything
This is the step most tutorials skip. Write down questions and, for each, a piece of text that the correct chunk must contain. Ten questions took a few minutes:
EVAL = [
("How many days of annual leave do I get?", "18 days of paid annual leave"),
("Can I carry forward unused leave?", "carried forward"),
("Who approves leave longer than 5 days?", "department head"),
("When do I need a medical note?", "medical note"),
("How early must I book a domestic flight?", "at least 7 days"),
("What is the hotel limit in metro cities?", "6,000 rupees"),
("What is the deadline for expense claims?", "within 30 days"),
("How many days can I work from home?", "up to 2 days"),
("Do I need to use a VPN on my laptop?", "VPN"),
("How much is the internet allowance?", "1,000 rupees per month"),
]
Notice that the questions are phrased the way a person would ask, not copied from the document. If your test questions reuse the document’s exact words, any method will look perfect and you will learn nothing.
The two numbers to report
Two simple measures cover most needs.
| Measure | What it asks | How to read it |
|---|---|---|
| Hit rate at k (hit@k) | Is a correct chunk anywhere in the top k results? | Of ten questions, “9/10 at 3” means nine had the answer in the top three. |
| Mean reciprocal rank (MRR) | How high up is the first correct chunk? | Rank 1 scores 1, rank 2 scores 0.5, rank 3 scores 0.33; a miss scores 0. The average is the MRR. |
Hit rate tells you whether the model could possibly see the answer. MRR tells you how near the top it sits, which matters when you can only afford to send a few chunks to the model.
def evaluate(k_list=(1, 3)):
hits = {k: 0 for k in k_list}; rr = 0.0
for q, needle in EVAL:
ranked = retrieve(q, max(k_list))
pos = next((r for r, (i, _) in enumerate(ranked, 1)
if needle in chunks[i]["text"]), None)
for k in k_list:
if pos and pos <= k: hits[k] += 1
rr += 1 / pos if pos else 0
print(("OK " if pos == 1 else "MISS" if not pos else f"@{pos} "), q)
n = len(EVAL)
print({f"hit@{k}": f"{hits[k]}/{n}" for k in k_list}, "MRR", round(rr / n, 3))
What the first run showed
The word-based index found the right chunk first for nine of the ten questions. The output summary was hit@1 9/10, hit@3 9/10, MRR 0.9. The single miss was “Who approves leave longer than 5 days?”, where the correct sentence reads “Leave of more than 5 days in a row needs approval from the department head.”
The reason is easy to see once you look. The question says “approves” and “longer”, while the document says “approval” and “more”. A word-matching index treats “approves” and “approval” as different words, so little overlaps. A person would call these the same idea. This is the typical retrieval failure: the answer is present, but the wording differs.
Without a measurement you would never have found this. The demo question you tried first probably used the document’s own words and looked fine.
Trying a fix, and testing it
One cheap change is to compare small pieces of words instead of whole words. A character n-gram index splits each word into overlapping fragments of three to five letters, so “approves” and “approval” share fragments such as “appro”. Only one line changes:
vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5))
On the same ten questions this scored hit@1 10/10, hit@3 10/10, MRR 1.0, and the earlier miss now ranked first. That is the whole method in practice: measure, see a failure, change one thing, measure again.
Be careful about what this proves. Ten questions on a 15-chunk document is a small, easy test, and we chose the fix after seeing the failure. The honest conclusion is that character fragments helped on this example, not that they are better in general. To trust a change, test it on questions you did not use while tuning, and on a document of realistic size.
Measuring the rest of the pipeline
Retrieval is the first gate. Once it is dependable, measure generation too. Three checks are common. Is the answer supported by the retrieved text, or did the model add facts? Does the answer actually address the question? And when the document does not contain the answer, does the system say so instead of inventing one? That last case deserves its own questions in your test set, because a system that always answers confidently is the most dangerous kind.
Scoring generated answers needs either human review or a second model acting as a judge. Both have limits, so start with a small set that a person checks. The AI Engineer course builds a retrieval evaluation into its knowledge-assistant project for this reason.
When retrieval is good but the answer is still wrong
Sometimes the right passage is in the top results and the final answer is still wrong. Read the failing case and ask three questions. Did the prompt tell the model to answer only from the supplied passages? Were so many passages included that the useful one was buried? Did two passages disagree, such as an old policy and a new one? Each cause has a different fix: a stricter instruction, fewer and better passages, or cleaning the documents so only the current version is indexed. Writing the cause next to each failing question turns a vague feeling that the system is unreliable into a short list of jobs you can finish.
Mistakes that make RAG look better than it is
- Testing with the document’s own wording. It hides vocabulary mismatches like the one above.
- Judging by one or two examples. Use at least ten, and grow the set whenever a real user finds a failure.
- Changing several things at once. Change chunking, the index or the number of results one at a time so you know what helped.
- Ignoring “not in the document” questions. Include some, and check that the system declines to answer them.
- Dropping page numbers. Without them you cannot cite sources or check answers.
Do not forget permissions
A company assistant built on internal documents must respect who is allowed to read what. If a junior employee’s question retrieves a passage from a confidential file, the model will happily quote it. Store access information with each chunk and filter the results before they reach the model, not after. This is far easier to design at the start than to add later.
Frequently asked questions about RAG with Python
What does RAG stand for?
RAG stands for retrieval-augmented generation. The system retrieves relevant passages from your documents and gives them to a language model so the answer is based on your material.
Do I need a vector database to start?
No. For a few hundred chunks, an in-memory index like the one above is enough, and it is easier to debug. Move to a vector database when the number of chunks, the speed you need or the sharing between users outgrows memory.
Which Python libraries did you use?
The test used pypdf version 6.21.4 to read the PDF and scikit-learn version 1.9.1 for the index and similarity, on Python 3.12. Neither needs an account or an API key.
Why measure retrieval separately from the final answer?
If retrieval misses the right passage, no model can answer well, and fixing the prompt will not help. Measuring retrieval first tells you whether to work on search or on generation.
Is 10 test questions enough?
It is enough to learn the method and to catch obvious failures, as it did here. It is not enough to claim a general accuracy figure. Grow the set with real user questions, and keep a separate set you never tune on.
Where can I learn to build and evaluate RAG with mentor feedback?
The BuildAI Careers AI Engineer course is 2 months at ₹34,999 including taxes, and includes a permission-aware runbook assistant with a retrieval evaluation among its pieces of work. Check the course page for current batches and terms.
Build and evaluate a RAG project with a mentor
You can follow this guide alone and learn the method. Having a mentor review your test questions, your chunking choices and your failure cases is what speeds up real skill. See the AI Engineer course for the full path through retrieval, agents and deployment. New Batch every 2 weeks. Enquire now.
Sources and review date
Reviewed on 8 November 2026. The PDF, questions and scores above were created and run for this guide on Python 3.12 with pypdf 6.21.4 and scikit-learn 1.9.1. The test set is small by design. The code is original learning material.