SkillNavora
AI Master Course › Week 2 › New lesson 1 of 7
Week 2 · extends Subject 6

Chunking: how to split documents for RAG

Chunking decides what the model can see. Split a document badly and the right answer is never retrieved, however good the model is.

In plain words. Think of a textbook cut into index cards. Cards that are too small lose the context ("it" with no subject). Cards that are too big hold five topics, so a search for one topic returns a card full of noise. Good cards hold one idea each, with the chapter title written at the top.

1. Why it matters

  • Retrieval works on chunks, not documents. The model only sees the chunks you retrieve.
  • Most RAG quality problems are retrieval problems, and most retrieval problems start with chunking.
  • Chunk size also sets cost: three chunks of 800 words cost about ten times more input tokens than three chunks of 80 words.

2. Key ideas

ChunkA piece of a document that is embedded and stored as one unit in the vector store.
Fixed-size chunkingCut every N words (or tokens). Simple and predictable, but it cuts sentences and topics in half.
OverlapRepeat the last few words of one chunk at the start of the next, so a fact that sits on a boundary appears whole in at least one chunk. Typical overlap: 10 to 20 percent.
Recursive chunkingSplit by the largest natural unit first (sections, then paragraphs, then sentences) and only go smaller when a piece is still too big. The default in most frameworks.
Structure-aware chunkingUse the document's own structure: headings, list items, table rows, pages. Each chunk keeps its heading as metadata.
MetadataFacts stored with each chunk: file name, page, section, date, owner, access level. Used for citations and for filters such as 'only HR documents'.
Recall@kOut of a set of test questions, how often the chunk that holds the answer is in the top k results. The main number for comparing chunking strategies.

3. How it works, step by step

  1. Collect 20 to 50 real questions and, for each, the sentence in the document that answers it. This is your retrieval test set.
  2. Start with recursive chunking at 200 to 400 tokens (about 150 to 300 words) and 10 to 15 percent overlap.
  3. Store file, page and section with every chunk so you can cite sources and filter.
  4. Measure recall@3 and recall@5 on your test set.
  5. Try two or three alternatives (smaller chunks, heading-based chunks, more overlap) and keep the one with the best recall at an acceptable token cost.
  6. Inspect failures by hand: print the question, the expected sentence and the chunks that were retrieved instead.
  7. Re-run the test whenever the documents, the chunker or the embedding model change.

4. Code you can run

Run it from the starter project folder: python examples/l1_chunking.py. It runs offline for free; add an API key in .env to use Claude.

examples/l1_chunking.py (in the starter project)
"""Lesson 1: compare chunking strategies on the sample PDF by retrieval recall at 3.
Run: python examples/l1_chunking.py"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from starter.chunking import by_heading, fixed_size, recursive
from starter.pdf_loader import load_pdf
from starter.store import VectorStore

PDF = os.path.join(os.path.dirname(__file__), "..", "data", "sample_policy.pdf")
GOLDEN = [  # question, a phrase that must be inside a retrieved chunk
    ("How many days of paid leave do I get each year?", "20 days of paid leave"),
    ("How much unused leave can I carry forward?", "carried forward up to 5 days"),
    ("When must expense claims be submitted?", "within 30 days"),
    ("What is the daily meal limit when travelling?", "1,500 rupees per day"),
    ("How many days a week can I work remotely?", "up to 3 days a week"),
    ("How long must a laptop password be?", "at least 14 characters"),
    ("What is the yearly learning budget?", "40,000 rupees"),
    ("When do I need a doctor's note for sick leave?", "longer than 2 days"),
]

text = "\n\n".join(p["text"] for p in load_pdf(PDF))
strategies = {
    "fixed 40 words, overlap 0": fixed_size(text, 40, 0),
    "fixed 40 words, overlap 10": fixed_size(text, 40, 10),
    "recursive, max 60 words": recursive(text, 60),
    "by heading": by_heading(text),
}

for name, chunks in strategies.items():
    store = VectorStore(); store.add(chunks)
    found = sum(any(phrase in hit["text"].replace("\n", " ") for hit in store.search(q, k=3)) for q, phrase in GOLDEN)
    avg = sum(len(c.text.split()) for c in chunks) / len(chunks)
    print(f"{name:<28} chunks={len(chunks):>3}  avg words={avg:5.1f}  recall@3={found}/{len(GOLDEN)}")

print("\nExample chunk with metadata (by heading):")
c = strategies["by heading"][2]
print(c.meta, "|", c.text[:90] + "...")
Real output (offline mode, captured when this page was built)
fixed 40 words, overlap 0    chunks=  9  avg words= 36.1  recall@3=7/8
fixed 40 words, overlap 10   chunks= 11  avg words= 38.6  recall@3=7/8
recursive, max 60 words      chunks=  6  avg words= 54.2  recall@3=7/8
by heading                   chunks=  8  avg words= 38.6  recall@3=7/8

Example chunk with metadata (by heading):
{'section': 'Sick Leave'} | Employees get 10 days of sick leave each year, separate from paid leave. A doctor's note i...

5. What the code does

  • load_pdf returns one item per page; the text of all pages is joined for the comparison.
  • Each strategy produces a list of Chunk objects (id, text, meta). by_heading keeps the section title as metadata.
  • GOLDEN pairs a question with a phrase that must appear in a retrieved chunk. That is a retrieval test, separate from the answer test.
  • recall@3 counts how many questions have the answer phrase inside one of the top three chunks.
  • On this small, well-structured document all four strategies find 7 of 8. On long, messy documents the differences are much larger, which is why you measure instead of guessing.

6. Common mistakes and fixes

ProblemFix
Chunks are huge (whole pages)Retrieval returns mostly irrelevant text and costs rise. Split pages into paragraphs or sections.
Chunks are tiny (one line)Answers lose their subject: "It must be approved within 7 days." Use bigger chunks or add the heading to each chunk.
Tables are flattened into one long lineKeep a table row with its header, or convert each row to a sentence such as "Plan: Gold. Price: 499."
No page or section storedYou cannot cite or filter. Add metadata at chunking time; it is hard to add later.
Scanned PDF returns empty textThe PDF is an image. Run OCR first, then chunk.
Chunker changed but nothing was re-testedTreat chunking as code: version it and re-run the retrieval test set.

7. Product manager view

  • Ask the team for recall@k on a real question set, not a demo. If recall is low, no prompt change will fix the answers.
  • Chunk size is a cost lever: smaller chunks mean fewer input tokens per answer.
  • Metadata decides what features are possible: citations, 'search only my department', 'only documents updated this year'.

8. Assignment

Take a 10 to 30 page PDF you know well. Write 15 questions with the exact answer phrase. Compare fixed-size (with and without overlap), recursive and heading-based chunking on recall@3. Write a half-page note: which strategy you chose, the recall and the average chunk size.

Check your work against the model answer for Subject 6.

9. Interview questions

How do you choose a chunk size?

Start from the content and the questions: one idea per chunk, usually 200 to 400 tokens with 10 to 15 percent overlap. Then measure recall@k on real questions and pick the smallest size that keeps recall high, because smaller chunks also cut cost.

Why use overlap?

So a fact that falls on a chunk boundary still appears whole in at least one chunk. Too much overlap wastes storage and returns near-duplicate chunks.

What metadata would you store with each chunk and why?

Source file, page, section, date and access level: for citations, filtering, freshness and permission checks.

Retrieval misses answers in tables. What do you do?

Chunk tables row by row with the header repeated, or turn each row into a sentence, then re-measure recall on table questions.

Refer & earn