Parsing and chunking are the first model you ship
Before embeddings and prompts, a RAG system is a document pipeline. How to parse real PDFs, chunk by structure instead of by token count, and measure the result with retrieval recall.
Many RAG failures are not retrieval failures and not model failures. They are parsing failures wearing a retrieval costume: the right passage existed in the corpus, it just never made it into the index in a form anyone could find. The demo hides this because the demo runs on five clean PDFs. Production runs on everything else.
So the first model you ship is not the embedding model and not the LLM. It is the pipeline that turns documents into chunks. It deserves the same discipline: a spec, a test set, a number that goes up or down when you change it.
1. Your documents are not text, they are layouts
A real corpus is scanned contracts, two-column papers, spreadsheets exported to PDF, tables that span three pages, slide decks, and email threads quoting each other. Flatten any of these with a plain text extractor and you get sentences from two columns interleaved, tables turned into word soup, and a running header stamped into the middle of every page.
The chunk is “correct” in the sense that the text is there. It is useless in the sense that no question will ever retrieve it.
A few rules that have held up:
- Use a layout-aware parser that gives you blocks with a type: heading, paragraph, table, figure, caption. Which library matters less than having the types at all. Two open-source options: Docling, which pairs a layout model trained on DocLayNet with TableFormer for table structure (technical report), and Unstructured, which returns typed elements such as
TitleandTable. - Keep tables as tables. Markdown or HTML, never flattened. A table is the one place where a model needs the column headers next to the values.
- Strip running headers and footers. Docling already labels them
page_headerandpage_footer. As a backstop, anything that repeats on more than half of the pages is page furniture, not content. - OCR the scans, keep the confidence. A chunk built from 60 % confidence OCR should carry that number so the answer can say so. Docling, for example, reports per-page layout and OCR scores with a grade from poor to excellent.
- Keep the page number and the heading path on every block. You will need both for citations.
from dataclasses import dataclass, field
@dataclass
class Block:
kind: str # "heading" | "paragraph" | "table" | "figure" | "caption"
text: str
page: int
heading_path: list[str] = field(default_factory=list) # ["3. Pricing", "3.2 Discounts"]
ocr_confidence: float | None = None
2. Chunk by structure, not by token count
The tutorial chunker is a fixed window, say 512 tokens with 50 tokens of overlap. It cuts sentences in half, splits a table from its header row, and produces chunks that start with “of the above-mentioned conditions” with no way to know what conditions.
Structure-aware chunking uses the blocks from step one:
- Walk the blocks in order, grouping paragraphs under their heading path.
- Close a chunk when it reaches a size budget or when the heading path changes. I start at 300 to 500 tokens. Chroma’s chunking evaluation found recall nearly flat between 200 and 400 tokens and lowest at 800, on its own benchmark, so treat the budget as a parameter to measure, not a constant.
- Never split a table in the middle of a row. If a table is bigger than the budget, split at row boundaries and repeat the header row in every piece.
- Prepend a context header to the text that gets embedded: document title, heading path, maybe the date. The chunk “Discounts apply above 10,000 units” becomes “Supplier contract 2025 › 3. Pricing › 3.2 Discounts: Discounts apply above 10,000 units”.
You may not need to write this yourself. Docling’s HybridChunker splits oversized elements, merges small neighbours that share the same headings, and repeats table headers by default. Unstructured’s by_title strategy guarantees that “a single chunk will never contain text that occurred in two different sections”. If you do write it, it looks like this:
# token_count() and split_table_rows() are small helpers you supply,
# using the tokenizer of your embedding model.
def chunk_blocks(blocks: list[Block], doc_title: str, budget: int = 400) -> list[str]:
chunks, current, current_path = [], [], None
def flush():
if current:
header = " › ".join([doc_title, *current_path])
chunks.append(f"{header}: " + "\n".join(current))
current.clear()
for b in blocks:
if b.heading_path != current_path or token_count(current) + token_count([b.text]) > budget:
flush()
current_path = b.heading_path
if b.kind == "table" and token_count([b.text]) > budget:
flush()
chunks.extend(split_table_rows(b.text, budget, header=" › ".join([doc_title, *b.heading_path])))
continue
current.append(b.text)
flush()
return chunks
The context header is the cheapest improvement I know of. It costs a few tokens per chunk and it fixes the “this chunk makes no sense on its own” problem for both the embedding model and the reranker. Anthropic measured a richer version, an LLM-written context of 50 to 100 tokens per chunk, in its contextual retrieval write-up: the top-20 retrieval failure rate fell from 5.7 % to 3.7 %, a 35 % reduction, and to 2.9 % when combined with contextual BM25. These are vendor numbers on vendor datasets, but the direction matches the intuition.
3. Deduplicate, then version
Enterprise corpora are full of the same document four times: the draft, the signed version, the scanned copy of the signed version, and the one someone re-uploaded last week. Without deduplication, a good question retrieves the same paragraph four times and the other six slots in the context go to noise.
- Exact duplicates: hash the normalised text of every chunk and keep one.
- Near duplicates: MinHash, which estimates the overlap of two documents’ shingle sets (Broder, 1997), or a cheap embedding similarity threshold, applied per document family rather than across the whole corpus so you do not merge things that merely sound alike.
- Versions are not a similarity problem, they are a metadata problem. Store
document_version,effective_dateandsuperseded_bywith every chunk, and filter at query time. “Which policy applies today” should be answered by a filter, never by hoping the newest text embeds closest.
4. Measure chunking with retrieval recall
There is one metric that matters most for this stage: does the passage that answers the question make it into the top-k? Build the evaluation set at the passage level, fifty questions each pointing at the source passage, and compare chunkers on the same retriever.
| Change | What usually moves |
|---|---|
| Layout-aware parsing instead of plain text | Recall on tables and multi-column pages |
| Structure-aware chunking with context headers | Recall on “which section” questions, reranker quality |
| Deduplication | Precision of the context, answer length |
| Version metadata and filters | Correctness on “current” questions |
I do not quote my own numbers here because they depend entirely on the corpus. My expectation, which a passage-level test set will confirm or refute for yours: this stage moves recall more than switching embedding models does, and it is the stage teams skip because it is not interesting.
What this looks like in practice
- One parser that emits typed blocks, with tables kept whole and page furniture removed.
- Chunks that follow headings, with a context header, a measured token budget (start at 300 to 500).
- Exact and near-duplicate removal, version metadata on every chunk.
- A passage-level evaluation set, and recall@k on the dashboard next to the model’s metrics.
The embedding model gets the credit. The chunker does the work.
Sources
- Docling Project, Docling documentation, October 2026.
- C. Auer et al., Docling Technical Report, August 2024.
- Docling Project, Chunking, October 2026.
- Docling Project, Confidence scores, October 2026.
- Unstructured, Chunking, October 2026.
- B. Smith and A. Troynikov (Chroma), Evaluating Chunking Strategies for Retrieval, July 2024.
- Anthropic, Introducing Contextual Retrieval, September 2024.
- A. Z. Broder, On the resemblance and containment of documents, June 1997.