Module 3 of 6 · 45 minutes

Preparing documents: chunking and metadata

Most RAG quality problems start before a single question is asked — in how documents are cleaned, split and labelled.

By · Last updated

Learning objectives

  • Clean and de-duplicate source documents
  • Explain why chunking matters
  • Compare chunking strategies and implement one
  • Design useful chunk metadata
  • Plan index updates
  • Detect new, changed and removed documents with fingerprints
  • Add title context to chunks and explain why it helps
Setup: the documents and helper functions from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
from openai import OpenAI

embed_client = OpenAI()                      # the real SDK reads OPENAI_API_KEY from the environment
EMBED_MODEL = "YOUR-EMBEDDING-MODEL"         # copy a current model name from the provider's docs

def embed(texts):
    resp = embed_client.embeddings.create(model=EMBED_MODEL, input=list(texts))
    return np.array([d.embedding for d in resp.data])

documents = {
    "Returns Policy v7": """Damaged items can be returned within 30 days for a full refund. Send a photo of the damage to support before returning the item.

Unwanted items in their original packaging can be returned within 14 days. The customer pays the return postage for unwanted items.

Refunds are paid to the original payment method within 7 days of the return arriving.""",
    "Delivery FAQ": """Standard UK delivery takes 3 to 5 working days and costs £3.95. Orders over £40 are delivered free.

Express delivery arrives the next working day if ordered before 2pm and costs £7.95.

Delivery to Ireland takes 5 to 7 working days.""",
    "Care Guide": """Hand-wash bamboo boards in warm soapy water and dry them upright. Never put a bamboo board in the dishwasher.

Oil the board once a month with food-safe mineral oil to stop it cracking.

Product code BB-204 is the large bamboo board, 45 cm by 30 cm. Product code BB-110 is the small bamboo board.""",
    "Gift Cards": """Gift cards are valid for 12 months from the date of purchase. They can be used online only.

A gift card cannot be exchanged for cash.""",
}

3.1 Loading and cleaning

Real documents are messy: PDFs with headers and footers on every page, tables, scanned images, HTML menus, duplicate versions. Garbage in the index means garbage in the answers.

  • Extract text with tools suited to each format (PDF parsers, OCR for scans, HTML-to-text)
  • Remove boilerplate: navigation, repeated headers, footers, cookie banners
  • Keep structure that carries meaning: headings, lists, table rows
  • De-duplicate and keep only the current version of each document
  • Respect access rights — record who is allowed to see each document

The course uses four short documents from an imaginary kitchenware shop, held in a dictionary called documents (see the setup cell at the top of this page). They are already clean. Yours won't be: Data Quality, Module 2 shows how to profile a document set for empty files, duplicates and out-of-date versions before indexing it.

3.2 Why chunk at all?

Embedding a whole 50-page document gives one vector that blurs every topic in it together. Retrieval works better when each vector represents one focused piece of content. Chunking splits documents into passages small enough to be specific, but large enough to make sense on their own.

3.3 Chunking strategies

StrategyHowPros / cons
Fixed sizeEvery N tokens or charactersSimple; may cut sentences and ideas in half
Fixed size with overlapEach chunk repeats the end of the previous oneReduces lost context at boundaries; more storage
Recursive / structure-awareSplit on headings, then paragraphs, then sentencesKeeps ideas together; a strong default
SemanticSplit where the topic changes (using embeddings)Coherent chunks; slower to build
Document-specificRows for tables, functions for code, Q&A pairs for FAQsBest quality for structured content

There's no universal best size. A few hundred tokens with some overlap is a common starting point — then test (Module 6).

Python · a simple paragraph-aware chunker with overlapdef chunk_text(text, max_words=180, overlap_words=40):
    paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
    chunks, current = [], []
    for para in paragraphs:
        words = para.split()
        if current and len(current) + len(words) > max_words:
            chunks.append(" ".join(current))
            current = current[-overlap_words:] if overlap_words else []   # carry some context forward
        current.extend(words)
    if current:
        chunks.append(" ".join(current))
    return chunks

for i, c in enumerate(chunk_text(documents["Returns Policy v7"], max_words=40, overlap_words=8)):
    print(f"--- chunk {i} ({len(c.split())} words)\n{c}\n")

Look at where the second and third chunks begin: each starts with the last eight words of the one before. That overlap is what stops a sentence that straddles a boundary from being lost to both sides.

Too smallfragments lose meaningToo largemany topics blurred togetherRight-sized + overlapone idea each, context keptoverlap
Chunk size is a trade-off. Tiny chunks lose context; huge chunks mix topics. Mid-sized chunks with a little overlap are a good default — then test.

3.4 Metadata: the secret weapon

Store metadata with every chunk: source document, title, section heading, date, version, author, product, region and access permissions. Metadata lets you:

  • filter retrieval (only current policies; only UK documents; only what this user may see);
  • cite sources precisely in answers;
  • add context to chunks — e.g. prefixing each chunk with its document title and heading.
{"id": "returns-policy-v7#3",
 "text": "Damaged items can be returned within 30 days ...",
 "source": "Returns Policy v7", "section": "Damaged goods",
 "updated": "2026-06-01", "region": "UK", "audience": ["staff", "customers"]}
Chunk text"Damaged items can be returnedwithin 30 days for a full refund…"sourceReturns Policy v7sectionDamaged goodsupdated2026-06-01regionUKaudiencestaff, customersFilteronly current, UK, allowedCite'Returns Policy v7'Contextualiseprefix title + heading
Each chunk travels with metadata. It powers filtering (including permissions), precise citations and added context.

3.5 Keeping the index fresh

Documents change. Plan for incremental updates: re-process changed documents, delete chunks from removed ones, and record the version indexed. Stale chunks are a common source of confidently wrong answers.

A simple way to spot what has changed is to store a fingerprint (a hash) of each document when you index it, and compare next time:

Python · which documents need re-indexing?import hashlib

def fingerprint(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]

indexed = {title: fingerprint(text) for title, text in documents.items()}      # saved at indexing time

# A week later: one document edited, one removed, one added
current = dict(documents)
current["Delivery FAQ"] = current["Delivery FAQ"].replace("£3.95", "£4.50")
del current["Gift Cards"]
current["Price Match Promise"] = "We match any UK retailer's price on the same item."

for title in sorted(set(indexed) | set(current)):
    if title not in current:
        print("REMOVED  (delete its chunks):   ", title)
    elif title not in indexed:
        print("NEW      (chunk and embed):     ", title)
    elif fingerprint(current[title]) != indexed[title]:
        print("CHANGED  (re-chunk and re-embed):", title)
    else:
        print("same     (nothing to do):       ", title)

Only the changed and new documents need embedding again, which keeps updates cheap. The step people forget is the first one: when a document is withdrawn, its chunks must be deleted, or the assistant will go on quoting it.

3.6 Chunk size is a trade-off you can see

Small chunks are precise but can separate a rule from its condition. Large chunks keep things together but blur several topics into one vector. Chunk the care guide three ways and look for the instruction about oiling:

Python · the same document at three chunk sizesguide = documents["Care Guide"]
for size in [12, 30, 200]:
    pieces = chunk_text(guide, max_words=size, overlap_words=0)
    lengths = [len(p.split()) for p in pieces]
    with_oil = [p for p in pieces if "Oil the board" in p][0]
    print(f"max_words={size:3}: {len(pieces)} chunks, sizes {lengths}")
    print(f"   chunk containing the oiling rule: {with_oil[:95]}...")

At the largest setting the whole guide is one chunk: a question about oiling retrieves the dishwasher warning and the product codes as well, and the model has to pick the answer out. At the smaller settings the oiling rule sits in a chunk of its own. This chunker never splits inside a paragraph, which is why the smallest setting gives the same result as the middle one; a fixed-size chunker would have cut the sentences in half.

3.7 Give every chunk its context

Read this chunk on its own: "Oil the board once a month with food-safe mineral oil to stop it cracking." Fine. Now this one, from a document about cast-iron pans: "Oil it after every wash." Oil what? Once a chunk is cut from its document, words like "it" and "this product" point at nothing. A cheap, effective fix is to put the document title (and section heading, if there is one) at the start of every chunk before embedding it.

Python · the same chunk with and without its titlebare = "It must be oiled once a month to stop it cracking."
with_context = "Care Guide for bamboo boards: " + bare
question = "How do I care for my bamboo board?"

q = embed([question])[0]
for label, text in [("bare chunk", bare), ("with title", with_context)]:
    print(f"{label:11} similarity {float(embed([text])[0] @ q):.2f}   {text}")

The words that connect the chunk to the question ("bamboo", "board", "care") are in the title, not the sentence, so the bare chunk scores poorly for a question it answers perfectly. Module 4 describes a more thorough version of this idea, in which an LLM writes a sentence of context for each chunk.

Exercise: a sentence-aware chunker

Write chunk_sentences(text, max_words=25) that splits text into sentences (a full stop followed by a space is good enough here), then groups whole sentences into chunks of at most max_words words. Run it on the delivery text in the starter code. No sentence should be cut in half.

Your turndelivery = ("Standard UK delivery takes 3 to 5 working days and costs £3.95. Orders over £40 are delivered free. "
            "Express delivery arrives the next working day if ordered before 2pm and costs £7.95. "
            "Delivery to Ireland takes 5 to 7 working days.")

# Write chunk_sentences(text, max_words=25), then press Run
Show a solution
delivery = ("Standard UK delivery takes 3 to 5 working days and costs £3.95. Orders over £40 are delivered free. "
            "Express delivery arrives the next working day if ordered before 2pm and costs £7.95. "
            "Delivery to Ireland takes 5 to 7 working days.")

import re

def chunk_sentences(text, max_words=25):
    sentences = re.split(r"(?<=[.!?])\s+", text.strip())
    chunks, current = [], []
    for s in sentences:
        if current and len(" ".join(current).split()) + len(s.split()) > max_words:
            chunks.append(" ".join(current))
            current = []
        current.append(s)
    if current:
        chunks.append(" ".join(current))
    return chunks

for c in chunk_sentences(delivery):
    print(len(c.split()), "words:", c)
Exercise: remove duplicate chunks

Document collections are full of repeated text: the same disclaimer on every page, or two copies of one policy. Write dedupe(chunks) that removes chunks whose text is the same once lowercased and stripped of extra spaces, keeping the first of each. How many of the five chunks in the starter code survive?

Your turnraw_chunks = [
    "Damaged items can be returned within 30 days.",
    "Prices include VAT. E&OE.",
    "damaged items can be returned  within 30 days.",
    "Standard UK delivery takes 3 to 5 working days.",
    "Prices include VAT. E&OE.",
]

# Write dedupe(chunk_list), then press Run
Show a solution
raw_chunks = [
    "Damaged items can be returned within 30 days.",
    "Prices include VAT. E&OE.",
    "damaged items can be returned  within 30 days.",
    "Standard UK delivery takes 3 to 5 working days.",
    "Prices include VAT. E&OE.",
]

def dedupe(chunk_list):
    seen, kept = set(), []
    for c in chunk_list:
        key = " ".join(c.lower().split())
        if key not in seen:
            seen.add(key)
            kept.append(c)
    return kept

result = dedupe(raw_chunks)
print(len(result), "of", len(raw_chunks), "kept")
for c in result:
    print("-", c)
# Duplicates waste storage and, worse, fill the top results with copies of one passage.

Key takeaways

  • Clean text, keep meaningful structure, de-duplicate and record permissions.
  • Chunks should be specific yet self-contained.
  • Structure-aware chunking with overlap is a strong default; test sizes.
  • Metadata enables filtering, citations and added context.
  • Stale chunks cause confident wrong answers — keep the index fresh.
  • When a document is withdrawn, delete its chunks or the assistant will keep quoting it.
  • Put the document title on every chunk: the words that link it to the question are often there.