Parsing, chunking and metadata

Turning messy documents into retrievable units: parsing PDFs, chunk size and overlap, structure-aware splits and filters.

Intermediate about 5 h

The picture

  1. 01

    Parse

    PDF, HTML, Office

  2. 02

    Clean

    headers, boilerplate

  3. 03

    Chunk

    size, overlap, structure

  4. 04

    Enrich

    metadata, context

  5. 05

    Embed + index

    store

Ingestion is where most RAG quality is won or lost

If a table is flattened into nonsense or a heading is separated from its paragraph, no retriever or prompt can recover it. Spend time looking at your parsed text.

Parsing

import fitz                                  # PyMuPDF

def parse_pdf(path: str):
    pages = []
    for i, page in enumerate(fitz.open(path), start=1):
        pages.append({"page": i, "text": page.get_text("text")})
    return pages

For scanned documents you need OCR or a vision model; for layout-heavy documents (tables, multi-column) use a layout-aware parser and inspect the output. Strip repeated headers, footers and page numbers, which pollute embeddings.

Chunking

A chunk should be a self-contained unit of meaning, small enough to embed precisely and large enough to answer a question. Typical starting point: 200 to 500 tokens with 10 to 20 percent overlap. Then tune using your evaluation set.

import tiktoken
enc = tiktoken.get_encoding("cl100k_base")

def split_recursive(text, max_tokens=350, overlap=50, seps=("\n\n", "\n", ". ", " ")):
    if len(enc.encode(text)) <= max_tokens:
        return [text]
    for sep in seps:
        parts = text.split(sep)
        if len(parts) > 1:
            break
    chunks, cur = [], ""
    for p in parts:
        cand = f"{cur}{sep}{p}" if cur else p
        if len(enc.encode(cand)) <= max_tokens:
            cur = cand
        else:
            if cur:
                chunks.append(cur)
            cur = p
    if cur:
        chunks.append(cur)
    out = []
    for c in chunks:                                   # recurse on any still-too-long piece
        out += split_recursive(c, max_tokens, overlap, seps[1:] or (" ",)) if len(enc.encode(c)) > max_tokens else [c]
    if overlap:                                        # carry the tail of each chunk into the next
        out = [out[0]] + [enc.decode(enc.encode(a)[-overlap:]) + " " + b for a, b in zip(out, out[1:])]
    return out

Better still, split on structure first: headings, sections, list items, table rows. Keep a table together with its caption.

Metadata and context

Every chunk should carry where it came from, so you can cite it and filter by it.

chunk = {
    "id": "handbook.pdf#p14#c2",
    "text": "...",
    "source": "handbook.pdf",
    "page": 14,
    "section": "4.2 Leave policy",
    "updated": "2024-11-01",
    "acl": ["hr", "all-staff"],         # access control travels with the data
}

Contextual retrieval: prepend a one-sentence summary of the surrounding document to each chunk before embedding (for example "This chunk is from the leave policy section of the 2024 employee handbook."). It helps chunks that are ambiguous on their own.

Access control

If different users may see different documents, enforce that at retrieval time with metadata filters. Never retrieve everything and rely on the model to withhold it.

Common mistakes

  • Chunking by fixed characters and cutting sentences, tables and code in half.
  • Dropping the heading, so a chunk about "30 days" no longer says what it is 30 days of.
  • Forgetting to re-ingest when source documents change. Store a content hash and update incrementally.

Exercises

  1. Chunk the same document at 150, 350 and 800 tokens and measure recall@5 on a 30-question set.
  2. Add section headings as context to each chunk and measure the change.

You are done when you can…

  • Parse a PDF into text with page numbers and section headings preserved
  • Implement a recursive splitter and justify your chunk size with an experiment
  • Attach metadata that enables filtering and precise citations