- Capstones
- Capstone 2
Hybrid-search PDF RAG with page citations
The finished service answers questions about technical manuals with two-column pages and tables: it parses pages by layout, searches with keywords and vectors merged by rank fusion, reranks, cites the page behind every sentence and says "Not in the documents." when retrieval is weak. You build it from the page up: layout and chunking, a filtered vector store, hybrid retrieval, cited answers with a refusal gate, a 50-question golden set with a calibrated judge, and finally tests that measure each acceptance target.
A question-answering service over technical PDFs with multi-column layouts and tables. It parses by layout, stores vectors with metadata, combines keyword and vector search, reranks, and cites the page behind every claim.
Try each milestone yourself first. Hints and the solution for each step are folded away until you open them. Everything runs offline with a built-in fake model, so you need no API key and spend no credits.
Architecture
Hybrid-search PDF RAG with page citations
Swipe to change step
Step 1 of 8. Manuals arrive as pages with two columns, tables and running headers. A layout-aware parser reads each page the way a person would, keeps every table whole and stamps each chunk with its document, page and section. Manual pages (two columns, tables). Layout parser (reading order, tables whole). Vector store (chunks + doc, page, section). arrow from Manual pages to Layout parser. arrow from Layout parser to Vector store, labelled chunks. a pages moving along e1, then chunks.
Set up
Clone the capstones repository to run the reference solution, or start an empty folder with the same layout to build it yourself. You need Python 3.11 or later and uv.
git clone https://github.com/gauthamboppana/agentic-ai-wiki-capstones.git
cd agentic-ai-wiki-capstones/pdf-raguv sync
uv run pytest -q
uv run python -m pdfrag.cli demoLessons to finish first (12)
- 4.9 Sparse vectors: TF-IDF, BM25 and SPLADE
- 21.1 The four steps: chunk, embed, retrieve, generate
- 22.4 Filtering, hybrid search and metadata
- 23.1 Chunking strategies
- 23.2 Hybrid search: BM25 plus embeddings
- 23.3 Reranking
- 23.7 Reciprocal rank fusion step by step
- 26.4 Ranking metrics: MRR and nDCG
- 26.5 Context precision and context recall
- 26.6 Synthetic test sets
- 27.2 Layout-aware parsing tools
- 27.3 Tables, charts and figures
Milestone 1 of 6
Parse pages by layout and chunk with page numbers
Every manual becomes chunks in reading order, each carrying its document, page, section and kind, with tables kept whole.
Steps
- Model a page as positioned blocks: heading, text or table, each with a bounding box.
- Drop running headers and footers: blocks in the top or bottom few per cent of the page.
- Write reading_order(): full-width blocks split the page into bands; inside a band read the left column top to bottom, then the right.
- Chunk in that order, starting a new chunk at every heading and every page break, and never splitting a table.
- Render each table row as one line with labelled cells, such as "Code: E12; Meaning: Pressure sensor fault", so a row can be quoted and cited alone.
Hint 1
The bundled manuals store blocks in drawing order on purpose. Print a page in stored order first and see how wrong it reads.
Hint 2
A block wider than about 60% of the page is full width: a title, an intro paragraph or a wide table.
Hint 3
Keep the last heading in a variable as you walk the blocks: that is the chunk's section, and it gives short chunks the context they lack.
Hint 4 (strongest)
Emit the buffer before every heading, before every table and at the end of every page. That one rule gives you all three guarantees.
Checkpoint
uv run pytest -q tests/test_layout.py4 tests pass: the two-column page reads in order, running headers are gone, no chunk crosses a page and tables stay whole.
Show solution src/pdfrag/layout.py
def is_running_text(block: Block, page: Page, margin: float = 0.04) -> bool:
"""Running headers and footers sit in the top or bottom margin and repeat on every page."""
return block.y0 < page.height * margin or block.y0 > page.height * (1 - margin)
def reading_order(page: Page) -> list[Block]:
"""Full-width blocks split the page into bands; inside a band read the left column, then the right."""
body = [b for b in page.blocks if not is_running_text(b, page)]
full = sorted((b for b in body if b.width > page.width * 0.6), key=lambda b: b.y0)
columns = [b for b in body if b.width <= page.width * 0.6]
ordered: list[Block] = []
top = float("-inf")
for separator in [*full, None]:
bottom = separator.y0 if separator else float("inf")
band = [b for b in columns if top <= b.y0 < bottom]
left = sorted((b for b in band if b.x0 < page.width / 2), key=lambda b: b.y0)
right = sorted((b for b in band if b.x0 >= page.width / 2), key=lambda b: b.y0)
ordered += left + right
if separator:
ordered.append(separator)
top = separator.y0
return ordered
Sorting by bands, then columns, handles the common manual layout without a layout model. A real PDF loader (pdf.py) produces the same Page objects, so nothing downstream changes.
Milestone 2 of 6
Store vectors with metadata filters
Chunks and their embeddings live in a store you can search with filters on document, page, kind and section.
Steps
- Define a small VectorStore interface: add, search(vector, k, where) and chunks(where).
- Write matches(): a where dict of equality tests, where a list value means any of.
- Build an in-memory store, then a SQLite store that runs the filters in SQL.
- Add a deterministic embedder that hashes character n-grams, so near matches score well without a download.
- Check that both stores return the same ranking for the same query.
Hint 1
Normalise vectors once when you embed them; cosine similarity is then a plain dot product.
Hint 2
Whitelist the filter fields in the SQLite store: never paste a key from the caller into SQL.
Hint 3 (strongest)
Qdrant, pgvector and Chroma all map onto the same three methods, so the pipeline never needs to know which one it has.
Checkpoint
uv run pytest -q tests/test_store.py8 tests pass for both stores: filters by document, kind and page lists, filtered search and matching rankings.
Show solution src/pdfrag/store.py
def matches(chunk: Chunk, where: dict | None) -> bool:
if not where:
return True
for key, want in where.items():
have = chunk.meta[key]
if isinstance(want, (list, tuple, set)):
if have not in want:
return False
elif have != want:
return False
return True
class VectorStore(Protocol):
def add(self, chunks: list[Chunk], vectors: list[list[float]]) -> None: ...
def search(self, vector: list[float], k: int = 10, where: dict | None = None) -> list[tuple[Chunk, float]]: ...
def chunks(self, where: dict | None = None) -> list[Chunk]: ...
class InMemoryStore:
def __init__(self) -> None:
self._rows: list[tuple[Chunk, list[float]]] = []
def add(self, chunks: list[Chunk], vectors: list[list[float]]) -> None:
self._rows.extend(zip(chunks, vectors))
def search(self, vector, k=10, where=None):
scored = [(c, cosine(vector, v)) for c, v in self._rows if matches(c, where)]
return sorted(scored, key=lambda cs: (-cs[1], cs[0].chunk_id))[:k]
def chunks(self, where=None):
return [c for c, _ in self._rows if matches(c, where)]
The filter rule is written once and shared, so the local stores and a real vector database agree on what a filter means.
Milestone 3 of 6
Combine BM25 and dense search with RRF, then rerank
A question returns the five best chunks from keyword and vector search together, reranked, with a top score you can trust.
Steps
- Write BM25 over each chunk's title, section and text, with tokens that keep codes such as E12 and 192.168.10.40 whole.
- Merge the BM25 and dense rankings with reciprocal rank fusion: score 1 / (60 + rank) in each list and add them up.
- Route by product: if the question names exactly one manual, filter both searches to that doc_id.
- Rerank the fused top 20 by how much of the question's weighted terms each chunk contains, and keep the top 5.
- Print the top score for answerable and unanswerable questions and see how far apart they sit.
Hint 1
Fusion uses ranks, not scores, so BM25 scores and cosine scores never need rescaling.
Hint 2
Exact codes are where keyword search beats vectors; paraphrases are where vectors help.
Hint 3
Leave the product name out of the rerank score: naming the product is not evidence that a chunk answers the question.
Hint 4 (strongest)
A reranker score between 0 and about 1 doubles as an "is the answer here at all" signal for the next milestone.
Checkpoint
uv run pytest -q tests/test_retrieval.py4 tests pass: BM25 finds exact codes, RRF rewards agreement, routing filters to one manual and the right chunk ranks first.
Show solution src/pdfrag/pipeline.py
@staticmethod
def route(question: str) -> dict | None:
"""If the question names exactly one product, search only that manual (a metadata filter)."""
docs = {ALIASES[t] for t in tokens(question) if t in ALIASES}
return {"doc_id": docs.pop()} if len(docs) == 1 else None
def retrieve(self, question: str, where: dict | None = None) -> Retrieval:
vector = self.embedder.embed([question])[0]
if self.mode == "naive":
dense = self.store.search(vector, self.top_n, where)
return Retrieval(question, where, [c for c, _ in dense], dense)
where = where if where is not None else self.route(question)
keyword = [c for c, _ in self.bm25.search(question, self.k, keep=lambda c: matches(c, where))]
dense = [c for c, _ in self.store.search(vector, self.k, where)]
fused = [c for c, _ in rrf([keyword, dense])][: self.k]
return Retrieval(question, where, fused, self.reranker.rerank(question, fused, self.top_n))
The naive mode is kept in the same method so the eval can compare the two pipelines on the same questions.
Milestone 4 of 6
Answer with citations, or refuse
Every answer sentence ends with a [doc p.N] citation to a page in its context, and weak retrieval gives "Not in the documents."
Steps
- Label each context block with its citation, for example ### [h200 p.4] 6 Fault codes, and tell the model to copy one onto every sentence.
- Gate on the reranker: if the top score is below the threshold, return "Not in the documents." without calling the model.
- After the model replies, check every sentence has a citation and that each cited page was in the context.
- On a failed check, ask once more with the problem named; if it fails again, refuse rather than show an unsupported answer.
- Keep the provider behind one complete(system, user) method: a fake by default, an OpenAI-compatible adapter by environment variable.
Hint 1
Refusing before the model call is cheaper and more reliable than asking the model to notice there is no answer.
Hint 2
Check citations against the context pages, not just the corpus: a real page that was never retrieved is still an invented citation.
Hint 3 (strongest)
Read the key from the environment inside the adapter and leave it out of repr, so it never lands in a log.
Checkpoint
uv run pytest -q tests/test_models.py4 tests pass: the fake model is the default, the key never shows, an unknown provider fails clearly and an uncited answer is repaired once, then refused.
Show solution src/pdfrag/pipeline.py
def answer(self, question: str, where: dict | None = None) -> Answer:
r = self.retrieve(question, where)
if self.mode != "naive" and r.top_score < self.threshold:
return Answer(question, NOT_FOUND, True, r, reason=f"weak retrieval (top score {r.top_score:.2f})")
prompt = build_prompt(question, r.chunks)
text = self.model.complete(SYSTEM_PROMPT, prompt)
problem = "" if text.startswith(NOT_FOUND) else check_citations(text, r.chunks)
if problem: # one repair attempt, then refuse rather than show an unsupported answer
text = self.model.complete(SYSTEM_PROMPT, prompt + f"\nYour last answer was rejected: {problem}. Fix it.")
problem = "" if text.startswith(NOT_FOUND) else check_citations(text, r.chunks)
if problem:
return Answer(question, NOT_FOUND, True, r, reason=problem)
if text.startswith(NOT_FOUND):
return Answer(question, NOT_FOUND, True, r, reason="model found no answer in the context")
return Answer(question, text, False, r, citations=list(dict.fromkeys(citations(text))))
Every exit path is either a checked, cited answer or the fixed refusal string, which makes both easy to test.
Milestone 5 of 6
Build the golden set and a calibrated judge
A 50-question golden set with evidence quotes, and a claim-support judge whose agreement with hand labels is known.
Steps
- Generate synthetic questions from table rows with a seeded script, one per sampled row, asking for one cell.
- Hand-write the rest: prose questions, paraphrases, one that needs two manuals and at least five that no manual answers.
- Give each answerable item its evidence as doc, page and a short quote, and test that every quote exists on its page.
- Write the judge: split an answer into sentence claims and check each only against the chunks on the pages it cites.
- Hand-label a calibration set of supported and unsupported claims, then measure agreement and both error kinds.
Hint 1
Synthetic questions are cheap but stiff. The hand-written ones are where real users' wording and the unanswerable cases come from.
Hint 2
Make the judge strict on numbers: a claim with a number the evidence lacks is unsupported, whatever else matches.
Hint 3
Expect the lexical judge to miss negation and swapped numbers. Write those cases into the calibration set so the misses are visible, not hidden.
Hint 4 (strongest)
For a model judge, ask for one word, parse strictly and count anything unclear as unsupported.
Checkpoint
uv run pytest -q tests/test_golden.py tests/test_judge.py6 tests pass: 50 mixed questions, the synthetic file matches the generator, every quote resolves, and the judge's agreement and known misses are as recorded.
Show solution src/pdfrag/judge.py
class ClaimSupportJudge:
def __init__(self, min_coverage: float = 0.8):
self.min_coverage = min_coverage
def supports(self, claim: str, evidence: str) -> tuple[bool, str]:
have_tokens, have_terms = set(tokens(evidence)), set(terms(evidence))
numbers = [t for t in tokens(claim) if any(ch.isdigit() for ch in t)]
missing = [n for n in numbers if n not in have_tokens]
if missing:
return False, f"number not in the cited text: {missing[0]}"
claim_terms = set(terms(claim))
if not claim_terms:
return False, "no content to check"
coverage = len(claim_terms & have_terms) / len(claim_terms)
if coverage < self.min_coverage:
return False, f"only {coverage:.0%} of the claim's terms are in the cited text"
return True, ""
Two cheap rules catch the most common faithfulness failure in manuals: a wrong number or an added step. Calibration tells you what they miss.
Milestone 6 of 6
Measure the acceptance targets
One command reports context recall, faithfulness, citations and refusals on the golden set, for the hybrid pipeline and a naive baseline.
Steps
- Context recall: the share of each item's evidence quotes found in a top-5 chunk on the right page, averaged over answerable items.
- Faithfulness: supported claims over all claims, using the judge from the last milestone.
- Citations: fail any answer without a page reference, with a sentence that cites nothing, or citing a page that does not exist.
- Refusals: every unanswerable item must get exactly "Not in the documents." while answerable ones still get answers.
- Run the demo and compare hybrid with naive retrieval on the same 50 questions.
Hint 1
Score retrieval and generation separately: recall can be perfect while the answer quotes the wrong sentence.
Hint 2
Keep one test module per target, so a failing build says which target slipped.
Hint 3 (strongest)
On a corpus this small naive dense search can match recall. Look at what it does with unanswerable questions instead.
Checkpoint
uv run pytest -q tests/test_accept_*.py8 tests pass: recall, faithfulness and citations meet their targets, unanswerable questions are refused and the naive baseline is shown to fail that.
Show solution src/pdfrag/evaluate.py
def context_recall(item: dict, retrieved: list[Chunk]) -> float:
"""Share of the item's evidence quotes found in a retrieved chunk on the right page."""
found = 0
for ev in item["evidence"]:
found += any(c.doc_id == ev["doc"] and c.page == ev["page"] and ev["quote"].lower() in c.text.lower() for c in retrieved)
return found / len(item["evidence"])
def citation_problem(answer: Answer, pages: set[tuple[str, int]]) -> str:
"""Empty if the answer cites at least one page and every sentence cites pages that exist."""
if answer.abstained:
return ""
if not citations(answer.text):
return "no page cited"
for s in sentences(answer.text):
cited = citations(s)
if not cited:
return f"sentence without a citation: {s!r}"
missing = [c for c in cited if c not in pages]
if missing:
return f"{missing[0][0]} p.{missing[0][1]} does not exist"
return ""
Both checks work on plain data (evidence quotes and a page index), so they run the same with the fake model or a real one.
Acceptance targets
- Context recall
- at least 0.85Score retrieval on the 50-question golden set.
- Faithfulness
- at least 0.90Check each answer's claims against its cited chunks with a calibrated judge.
- Citations
- every answer cites a pageFail any answer without a page reference that resolves.
Stretch: Compare naive RAG and your hybrid pipeline on the same set and write up the difference.