Document QA
Prerequisites
- !How RAG pipelines retrieve and generate
- !Chunking and provenance in retrieval
- !The difference between OCR and layout analysis
What You'll Learn
- 1Diagnose why ordinary text chunking fails on real PDFs
- 2Choose a parsing tier from a cost-versus-fidelity ladder
- 3Assemble blocks into reading order with page and block provenance
- 4Verify that every answer span actually exists in the parsed document
PDFs are a rendering format, not a data format
A PDF records where glyphs were painted on a page. It does not record that these three lines form a paragraph, that this rectangle is a table cell, or that the text in the top margin is a running header to be ignored. Text extraction therefore gives you characters in an order that often does not match the order a human reads, and every downstream step inherits the damage.
The symptoms are recognisable. Answers that mix two unrelated columns because the extractor read left-to-right across both. Tables flattened into a single run-on line where "Q3 revenue 4,210" becomes unparseable soup. Headers, footers and page numbers retrieved as if they were content, so a question about the contract value returns "Page 4 of 12". Two-column academic papers and financial reports â precisely the documents people ask questions about â are the worst affected.
The fix is structural: parse with layout awareness, preserve page and block coordinates as provenance, and make retrieval return passages in reading order rather than arbitrary character windows. Everything else in document QA is downstream of that choice.
The parsing ladder
Each tier buys fidelity with compute and latency. Choose the lowest tier that answers your document types, and keep the ability to escalate per file rather than globally.
| Tier | Handles | Typical cost per page | Fails on |
|---|---|---|---|
| Raw text extraction | Reflowed digital PDFs | Milliseconds | Columns, tables, scans |
| Layout analysis | Reading order, headers, footers | Tens of ms | Complex table structure |
| Table structure model | Cells, spans, merged headers | Hundreds of ms | Handwriting, screenshots |
| OCR pass | Scanned pages, images | Hundreds of ms | Poor scan quality |
| Vision-language model | Any page as an image | Seconds | Precise numeric quoting |
Escalation logic pays for itself: run the cheap tier, detect trouble signals â low word count on a scanned-looking page, tables whose extracted rows have inconsistent column counts, pages where reading order produces implausible line breaks â and route only those pages to a higher tier. Most document sets are a mix: a handful of scanned exhibits inside a hundred pages of clean digital text, and paying vision-model prices for all of it is how document QA budgets explode.
Assembling blocks into reading order
Layout parsers emit blocks with bounding boxes; the reading order is a separate problem. Two columns, sidebars and floating figures all defeat naive top-to-bottom sorting, so a practical assembler combines vertical bands with horizontal position and block type.
from dataclasses import dataclass, field
@dataclass
class Block:
page: int
x0: float
y0: float
x1: float
y1: float
kind: str # "body" | "heading" | "table" | "header" | "footer"
text: str
col: int = 0
def reading_order(blocks: list[Block], page_width: float,
col_threshold: float = 0.45) -> list[Block]:
"""Split each page into columns, then sort inside each column."""
keep = [b for b in blocks if b.kind not in ("header", "footer")]
ordered = []
for page in sorted({b.page for b in keep}):
page_blocks = [b for b in keep if b.page == page]
centre = page_width * col_threshold * 2
left = [b for b in page_blocks if b.x0 < centre]
right = [b for b in page_blocks if b.x0 >= centre]
# A full-width block (title, wide table) separates the columns.
full_width = [b for b in page_blocks if (b.x1 - b.x0) > page_width * 0.8]
if len(left) + len(right) < len(page_blocks) * 1.5 and full_width:
ordered.extend(sorted(full_width, key=lambda b: b.y0))
continue
for column in (left, right):
if not column:
continue
column.sort(key=lambda b: b.y0)
ordered.extend(column)
return ordered
def to_passages(blocks: list[Block], max_chars: int = 1200) -> list[dict]:
"""Group ordered blocks into passages that keep page provenance."""
passages, buf, pages = [], "", set()
for b in reading_order(blocks, page_width=612):
if b.kind == "table" and buf:
passages.append({"text": buf, "pages": sorted(pages)})
buf, pages = "", set()
if len(buf) + len(b.text) > max_chars and buf:
passages.append({"text": buf, "pages": sorted(pages)})
buf, pages = "", set()
buf = (buf + "\n" + b.text).strip()
pages.add(b.page)
if b.kind == "table":
passages.append({"text": b.text, "pages": sorted(pages)})
buf, pages = "", set()
if buf:
passages.append({"text": buf, "pages": sorted(pages)})
return passages
Keep the coordinates and page numbers with every passage; the rest of the system needs them for citations, and they are unrecoverable once text is flattened into a string.
Tables, figures and the answers they hide
A large share of document questions are about numbers, and a large share of numbers live in tables. Retrieving a table as flattened text is the most common way document QA quietly answers wrongly: the model sees a row of digits with no column association and picks the one that looks most plausible.
Render tables to markdown with explicit headers before storing them, preserving the header row even when it is visually split across two lines. When a table spans pages, repeat the header into the second fragment so a passage retrieved from page 14 still names its columns. For figures, store the caption and any alt text, and be honest in the product about the limitation: a chart's underlying values are not in the caption, so questions about a figure either need the underlying data table or a vision model looking at the image itself.
Merged cells are the subtle killer. A cell spanning three rows applies to all three; naive extraction repeats it or drops it, and both errors change the answer. Detect spans in the table structure model, propagate the value downward, and record the fact so downstream consumers know the value was inherited rather than stated.
Multimodal or text pipeline
Two architectures compete. A text pipeline parses the page into blocks, chunks them, retrieves with embeddings and answers with a language model: fast, cheap, traceable, and only as good as the parser. A multimodal pipeline hands page images to a vision-language model, which handles arbitrary layout, charts and scans without a parser â at several seconds per page and with a harder time producing precise verbatim quotes.
The pragmatic answer is usually both, with routing. Send standard text pages through the pipeline; send scanned pages, complex tables and figures to the vision model; and for questions explicitly about a chart, answer from the image while citing the figure's page. Whichever path answers, the output contract stays the same: an answer, the quoted evidence, and the page numbers where it can be found.
âšī¸Verbatim quoting is the grounding test
Vision models paraphrase readily. Require a quoted span from the page and check it against the parsed text of that page; if the page was parsed at all, the check is a string search, and a paraphrase that cannot be matched is a claim a reviewer should see.
Grounding answers to page and block
Provenance turns "the document says" into a checkable assertion. Map each answer sentence to the passage that supported it and verify the quote exists in that passage's source text.
import re
def ground_answer(answer: str, passages: list[dict], top_k: int = 3):
"""Attach every answer sentence to a supporting passage, or flag it."""
sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", answer) if s.strip()]
results = []
for sent in sentences:
terms = set(re.findall(r"[a-z0-9']+", sent.lower()))
ranked = sorted(passages, key=lambda p: -len(
terms & set(re.findall(r"[a-z0-9']+", p["text"].lower()))
))[:top_k]
best = None
for p in ranked:
if _best_overlap(sent, p["text"]) >= 0.55:
best = p
break
results.append({
"sentence": sent,
"pages": best["pages"] if best else [],
"grounded": best is not None,
})
return results
def _best_overlap(sentence: str, passage: str) -> float:
"""Longest word-run of the sentence found inside the passage."""
words = re.findall(r"[a-z0-9']+", sentence.lower())
ptext = " " + " ".join(re.findall(r"[a-z0-9']+", passage.lower())) + " "
best = 0
for n in range(len(words), 3, -1):
if " ".join(words[:n]) + " " in ptext or " ".join(words[-n:]) + " " in ptext:
return n / len(words)
return best / max(1, len(words))
Anything ungrounded should be visibly marked in the interface â a badge, a colour, a collapsed section â rather than silently included. Users calibrate their trust to how often the system's citations check out, and a product that shows citations only when they pass trains people to distrust every number it prints.
Evaluating on your own documents
Public document-QA benchmarks describe someone else's PDFs. Build a slice from your own corpus: fifty to a hundred questions with gold answers and gold page numbers, sampled across the document types you actually receive. Score three things separately â answer correctness against the gold text, citation precision (do the cited pages really contain the support), and citation recall (did the supporting pages get cited at all).
Break results down by document type and parsing tier. It is common to find digital contracts at 0.92 and scanned exhibits at 0.4, a gap that a single aggregate hides and that routing decisions can address. Track regressions per parser version as well: swapping a layout model changes retrieval quality for reasons invisible in end-to-end numbers unless you keep the frozen slice. Finally, review the unanswerable questions â those where the document genuinely does not contain the answer â and measure abstain precision, because a document assistant that fabricates a clause number is worse than one that says the document does not address it.
Common Mistakes
Chunking PDF text at fixed character offsets
Fix: Parse with layout awareness, order blocks by column, and chunk on block boundaries with page provenance
Retrieving tables as flattened character streams
Fix: Render tables to markdown with headers, repeat headers across page breaks and propagate merged cells
Applying the most expensive parser to every page
Fix: Run a cheap tier first and escalate only pages that show trouble signals
Publishing answers without page citations
Fix: Ground every sentence to a passage, verify the quote, and surface ungrounded sentences as flagged
Best Practices
- Keep bounding boxes and page numbers with every passage â they are unrecoverable later
- Route by document type: text pipeline for clean pages, vision model for scans and figures
- Store caption and figure text so chart questions have something to retrieve
- Measure citation precision and recall separately from answer correctness
- Maintain a frozen evaluation slice per document type and per parser version
Key Takeaways
- PDFs encode glyph positions, not structure â reading order must be reconstructed, not extracted
- Parsing is a cost-versus-fidelity ladder; escalate per page using trouble signals rather than globally
- Tables are where document QA silently goes wrong: preserve headers, spans and page-break continuity
- Provenance is the product: page and block citations let every answer be checked in one click
- Evaluate on your own corpus, split by document type, and measure abstain precision on unanswerable questions