Ravindra BagaleCourses & study guides Track your progress

Generative AI

How to Chunk Documents for RAG: Fixed Size vs Headings and Overlap

Generative AI course · Build with Gen AI (APIs, RAG) · Estimated reading time: 16 minutes

You built a RAG chatbot from a PDF, and the answers looked almost right, but one important exception was missing. Very often the problem is not the model and not the prompt. The problem is how the document was cut into pieces before it was stored. In this chapter we will learn what chunking is, why a fixed word window can split a fact across two chunks, when a little overlap helps, when heavy overlap hurts, and why splitting on headings often keeps a whole policy section together. You will run a complete offline Python exercise on a made-up tea shop FAQ, with no API key and no cost.

What you will learn in this chapter

  1. You will learn why RAG systems split documents into chunks before embedding them.
  2. You will learn how fixed-size chunking works, and how a cut at the wrong place can break a fact.
  3. You will learn what overlap is, when it rescues a boundary fact, and when it creates near-duplicate chunks.
  4. You will learn how heading-based chunking keeps a whole section together.
  5. You will learn how recursive splitting tries larger separators first, similar to common text splitters.
  6. You will learn why tables and bilingual lines need special care.
  7. You will run an offline Python exercise that compares five chunking strategies with tests.

Everything in this chapter is made up for learning

The company "Konkan Leaf Tea Co.", its FAQ, its price table, its bilingual note, its questions and every score on this page are fictional and SYNTHETIC. The FAQ text was typed by hand. No real AI model produced the document. No real customer data, personal data, API keys or live prices are used anywhere on this page.

1. Why we chunk documents for RAG

A RAG chatbot does not send your whole library with every question. Sending everything would be slow, costly, and often larger than the model's context window. Instead, during indexing, the system splits each document into smaller pieces called chunks, turns each chunk into an embedding, and stores those embeddings in a vector store. At question time, the system finds the most similar chunks and puts only those chunks into the prompt. The RAG chapter and the embeddings chapter explain that pipeline. This chapter focuses on the first step: how you cut the text.

If a chunk is too large, the embedding mixes many topics, so search becomes less precise. If a chunk is too small, a single fact can be cut in half, so the retriever may find only one half and the model never sees the full rule. Bad chunking is one of the most common reasons a RAG bot gives a weak answer even when the document is correct.

Table 1: What good chunking tries to achieve

GoalWhy it matters
Keep one idea togetherA return exception that needs three phrases in one place must not be cut across two chunks.
Keep chunks small enoughSmaller chunks usually match a question more precisely than a whole long chapter.
Keep useful metadataDocument name, section title and page help citations and permission filters later.
Avoid near-duplicatesHeavy overlap can make many chunks look almost the same, which wastes space and confuses ranking.

2. Suppose we index the FAQ of a small tea shop

Suppose we are building a help bot for Konkan Leaf Tea Co., a made-up tea shop in Pune. The bot will answer from one synthetic FAQ that has six Markdown sections: Returns, Shipping, Loyalty, Wholesale, a price table, and a bilingual storage note. Several golden questions need phrases that sit near a cut, so we can see which chunking strategy keeps the fact intact.

Table 2: Sections in the synthetic Konkan Leaf Tea Co. FAQ

SectionWhat a student should notice
ReturnsThe damaged-tin exception needs "Opened", "damaged" and "48 hours" together.
ShippingExpress same-day arrival depends on the "11 am" cutoff.
LoyaltyPoints expire after 12 months and cannot buy gift cards.
WholesaleWholesale starts at 20 sealed tins of the same flavour.
Price tableA Markdown table plus a rule that Family pack prices do not apply online.
Bilingual noteEnglish, Marathi and Hindi storage lines must stay readable and together.

3. Fixed-size chunking: simple, but it can cut a fact

Fixed-size chunking walks through the text and takes a window of a fixed number of tokens or words, then moves forward and takes the next window. Amazon Bedrock Knowledge Bases documents a fixed-size strategy where you set a maximum number of tokens per chunk and an overlap percentage between consecutive chunks. Bedrock's default chunking is about 300 tokens and honours sentence boundaries. In our exercise we use word windows instead of tokens, so students can run the code with the Python standard library only.

Follow these steps to see a boundary failure with a tiny window.

  1. Take the Returns section of the FAQ.
  2. Split it with a fixed window of 12 words and no overlap.
  3. Look for a chunk that contains "Opened", "damaged" and "48 hours" together.
  4. Notice that no single chunk holds all three phrases, so the damaged-tin exception is a split failure.
  5. Ask the golden question about a damaged opened tin, and see that retrieval can miss the full fact even when every word is somewhere in the index.

This is the classic fixed-size failure mode: the cut landed inside a rule that needed several phrases in one place.

Ravindra Bagale's Tip

When a RAG answer misses one half of a rule, print the retrieved chunks before you change the prompt. If the missing half is not in those chunks, fix chunking or retrieval first. No prompt can use a sentence the model never saw.

4. Overlap: when it helps and when it hurts

Overlap means the end of one chunk is repeated at the start of the next chunk. LangChain's recursive character splitter documents a chunk_overlap setting and notes that overlapping chunks helps reduce information loss when context is divided between chunks. Bedrock's fixed-size configuration uses an overlap percentage for the same reason.

Follow these steps to compare overlap with no overlap.

  1. Run the same 12-word window with overlap 0 and with overlap 4.
  2. Count how many golden answer cases keep their phrases intact in at least one chunk.
  3. Notice that a little overlap can raise the intact rate, because a fact that sat on the cut may now appear fully inside one window.
  4. Then try a heavy overlap, such as size 20 with overlap 18, and list near-duplicate pairs.
  5. Notice that heavy overlap creates many chunks that share most of their words, which raises storage and can make retrieval return near-copies instead of diverse context.

Table 3: Overlap tradeoffs in plain words

ChoiceWhat usually improvesWhat can go wrong
No overlapFewer chunks and no repeated textFacts that sit on the cut can be split
Small overlapBoundary facts are more often kept togetherA little extra storage and a few repeated sentences
Heavy overlapAlmost every boundary is coveredNear-duplicate chunks, higher cost, repetitive retrieval

5. Heading-based chunking: keep a whole section together

Heading-based chunking splits the document on Markdown headings such as ## Returns, so each section becomes one chunk. In our synthetic FAQ, the Returns section keeps the damaged-tin exception together, the price table stays with its online-order rule, and the bilingual note stays as one unit. On the golden set, the heading strategy reaches an intact rate of 1.00 and a hit rate of 1.00 in the offline exercise.

Heading chunking is not magic for every file. A section can still be too long for a precise embedding, and some PDFs have weak or missing headings. In those cases people often split by heading first, then apply a size limit inside each section, or they use a recursive splitter that prefers paragraph breaks before hard cuts.

6. Recursive splitting and what official tools offer

A recursive character splitter tries a list of separators from large to small. LangChain's documentation for RecursiveCharacterTextSplitter says the default separator list is ["\\n\\n", "\\n", " ", ""], so the splitter tries to keep paragraphs together, then lines, then words, before it cuts on characters. Size is measured by a length function, often character count, and chunk_overlap sets the target overlap. LlamaIndex documents node parsers such as SentenceSplitter with chunk_size and chunk_overlap, so the same ideas appear under different names.

Amazon Bedrock Knowledge Bases, checked on 6 November 2026, documents several strategies:

  1. Fixed-size: maximum tokens and overlap percentage.
  2. Default: about 300 tokens, honouring sentence boundaries.
  3. Hierarchical: child chunks for precise retrieval, replaced by broader parent chunks for context.
  4. Semantic: splits with attention to meaning, using maximum tokens, buffer size and a breakpoint threshold; it can add foundation-model cost during ingestion.
  5. No chunking: each file is one chunk, which is useful only when you already pre-split files yourself.

Our exercise includes a small recursive splitter and a naive character splitter so you can see mid-word cuts without calling any cloud API. The character splitter is intentionally weak: it can cut inside an English word and inside a Devanagari line, which is why we also keep a bilingual section in the FAQ.

Ravindra Bagale's Tip

In an interview, do not say "I used the default chunk size." Say "I compared fixed windows, overlap and heading splits on a golden set, and I chose the strategy that kept multi-phrase rules intact without creating near-duplicates." That answer shows you measured the tradeoff.

7. Tables, bilingual text and metadata

A Markdown table is easy for a person to read, but a fixed character cut can separate the header from a row, or separate a row from the rule under the table. In our FAQ, the Family pack rule says the shop price does not apply to online orders. Heading chunking keeps the whole Price table section together, so the golden question about online Family pack prices can still find the full fact.

Bilingual lines need the same care. If a character window cuts through a Marathi or Hindi sentence, the retrieved text can look broken even when the English line next to it is fine. Prefer splits that keep a language line whole, and store metadata such as source file and section title with every chunk so citations stay clear. Our exercise attaches a small metadata object with source, strategy and section after each strategy runs.

8. Worked example: compare five chunking strategies in plain Python

This exercise uses only Python's standard library. There is no AI call, no API key, no internet access and no cost. Word windows stand in for token windows. The retriever is a small stub that ranks chunks by shared words. The scores tell you which strategy keeps golden facts intact; they are not proof that a live cloud RAG bot is correct. The full source of both files is printed below, so you can copy it and run it yourself.

Steps to run it:

  1. Install Python 3.9 or newer on your computer.
  2. Create a new folder and save the two files below as chunking.py and test_chunking.py.
  3. Open a terminal in that folder.
  4. Run python3 chunking.py to compare the five strategies.
  5. Run python3 -m unittest -v test_chunking to run the 42 unit tests.

chunking.py

"""Offline RAG chunking tradeoffs exercise (Python standard library only).

Everything here is SYNTHETIC. "Konkan Leaf Tea Co." is a made-up tea shop in
Pune. The FAQ, table, bilingual lines, questions and scores are typed by hand.
No AI service, network, API key or real customer data is used.

Word windows stand in for token windows so students can run this without an
embedding model. Character and recursive splitters are included so you can see
tradeoffs the interview card does not cover. Checks are fail-closed on types.
"""
from __future__ import annotations

import re
from typing import Any

# ---------------------------------------------------------------------------
# 1. Synthetic FAQ: headings, a markdown table, and one bilingual note
# ---------------------------------------------------------------------------
DOCUMENT = """
## Returns
Unopened tea tins may be returned within 14 days of delivery for a full refund of the tea price.
Opened tins cannot be returned, except when the tin arrived damaged and a photo is shared within 48 hours.
Shipping charges are never refunded on returns.

## Shipping
Standard shipping inside Pune takes 2 working days.
Express shipping inside Pune arrives the same day if the order is placed before 11 am.
We do not ship liquids or loose tea leaves outside Maharashtra.

## Loyalty
Members earn 1 point for every 100 rupees spent on tea.
Points expire after 12 months of no purchase.
Points cannot be used to buy gift cards.

## Wholesale
Wholesale pricing starts at 20 sealed tins of the same flavour.
Wholesale orders need 5 working days of lead time.
Payment for wholesale must be completed before dispatch.

## Price table
| Pack | Size | Shop price |
| Mini | 50 g | 120 |
| Home | 250 g | 420 |
| Family | 500 g | 780 |
Table rule: Family pack prices apply only to sealed tins sold in the Pune shop, not to online orders.

## Bilingual note
English: Store sealed tins in a cool dry place away from sunlight.
Marathi: सीलबंद डबे थंड कोरड्या जागी ठेवा, सूर्यप्रकाशापासून दूर.
Hindi: सीलबंद डिब्बे ठंडी सूखी जगह पर रखें, धूप से दूर.
""".strip()

SECTION_HEADINGS = (
    "Returns", "Shipping", "Loyalty", "Wholesale", "Price table", "Bilingual note",
)

REFUSAL = "I could not find this in the FAQ."

# ---------------------------------------------------------------------------
# 2. Golden questions (several need phrases that sit near a cut)
# ---------------------------------------------------------------------------
EVAL_SET: list[dict[str, Any]] = [
    {
        "id": "q01",
        "kind": "answer",
        "question": "How many days do I have to return an unopened tea tin?",
        "facts": ["14 days"],
        "must_not": [],
        "needs_together": ["14 days", "Unopened"],
    },
    {
        "id": "q02",
        "kind": "answer",
        "question": "Can I return an opened tin if it arrived damaged?",
        "facts": ["48 hours"],
        "must_not": [],
        "needs_together": ["Opened", "damaged", "48 hours"],
    },
    {
        "id": "q03",
        "kind": "answer",
        "question": "Are shipping charges refunded when I return a tin?",
        "facts": ["never refunded"],
        "must_not": [],
        "needs_together": ["Shipping charges", "never refunded"],
    },
    {
        "id": "q04",
        "kind": "answer",
        "question": "Before what time must I place an express order for same day arrival in Pune?",
        "facts": ["11 am"],
        "must_not": [],
        "needs_together": ["Express", "11 am"],
    },
    {
        "id": "q05",
        "kind": "answer",
        "question": "Do you ship loose tea leaves outside Maharashtra?",
        "facts": ["do not ship"],
        "must_not": [],
        "needs_together": ["loose tea", "outside Maharashtra"],
    },
    {
        "id": "q06",
        "kind": "answer",
        "question": "When do loyalty points expire?",
        "facts": ["12 months"],
        "must_not": [],
        "needs_together": ["Points expire", "12 months"],
    },
    {
        "id": "q07",
        "kind": "answer",
        "question": "What is the minimum number of sealed tins for wholesale pricing?",
        "facts": ["20"],
        "must_not": [],
        "needs_together": ["Wholesale", "20"],
    },
    {
        "id": "q08",
        "kind": "refuse",
        "question": "Do you deliver tea to Singapore?",
        "facts": [],
        "must_not": ["singapore"],
        "needs_together": [],
    },
    {
        "id": "q09",
        "kind": "refuse",
        "question": "What discount do employees get?",
        "facts": [],
        "must_not": ["percent", "%"],
        "needs_together": [],
    },
    {
        "id": "q10",
        "kind": "answer",
        "question": "Can loyalty points buy a gift card?",
        "facts": ["cannot"],
        "must_not": [],
        "needs_together": ["Points cannot", "gift cards"],
    },
    {
        "id": "q11",
        "kind": "answer",
        "question": "Does the Family pack shop price apply to online orders?",
        "facts": ["not to online"],
        "must_not": [],
        # Table header + rule must stay with the Family row meaning.
        "needs_together": ["Family", "not to online orders"],
    },
    {
        "id": "q12",
        "kind": "answer",
        "question": "Where should sealed tins be stored according to the Marathi line?",
        "facts": ["थंड"],
        "must_not": [],
        "needs_together": ["सीलबंद डबे", "थंड कोरड्या"],
    },
]

STOP = {
    "a", "an", "the", "is", "are", "to", "for", "of", "if", "my", "i", "me", "do", "you",
    "your", "what", "when", "how", "can", "does", "any", "there", "this", "and", "it", "in",
    "with", "like", "must", "will", "get", "time", "before", "on", "at", "or", "be", "by",
}


def words(text: str) -> set[str]:
    """Lower-case Latin tokens without common filler words. Devanagari kept as tokens."""
    latin = {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP}
    dev = set(re.findall(r"[\u0900-\u097F]+", text))
    return latin | dev


def _require_positive_int(name: str, value: Any) -> int:
    if type(value) is not int or value <= 0:
        raise TypeError(f"{name} must be a positive int")
    return value


def _require_nonneg_int(name: str, value: Any) -> int:
    if type(value) is not int or value < 0:
        raise TypeError(f"{name} must be a non-negative int")
    return value


def attach_metadata(chunks: list[dict[str, Any]], source: str = "faq.txt") -> list[dict[str, Any]]:
    """Copy chunks and add source + section metadata. Fail closed on types."""
    if type(source) is not str or not source.strip():
        raise TypeError("source must be a non-empty str")
    chunks = validate_chunk_list(chunks)
    out: list[dict[str, Any]] = []
    for ch in chunks:
        meta = {
            "source": source,
            "strategy": ch.get("strategy", "unknown"),
            "section": ch.get("heading") or guess_section(ch["text"]),
        }
        item = dict(ch)
        item["metadata"] = meta
        out.append(item)
    return out


def guess_section(text: str) -> str:
    """Best-effort section label from leading ## heading or known title words."""
    if type(text) is not str:
        raise TypeError("text must be a str")
    m = re.match(r"##\s+([^\n]+)", text.strip())
    if m:
        return m.group(1).strip()
    low = text.lower()
    best = None
    best_pos = 10 ** 9
    for title in SECTION_HEADINGS:
        pos = low.find(title.lower())
        if 0 <= pos < best_pos:
            best_pos = pos
            best = title
    return best or "unknown"


# ---------------------------------------------------------------------------
# 3. Chunkers
# ---------------------------------------------------------------------------
def chunk_fixed_words(text: str, size: int, overlap: int = 0) -> list[dict[str, Any]]:
    """Split on a fixed word window. Overlap must be smaller than size."""
    size = _require_positive_int("size", size)
    overlap = _require_nonneg_int("overlap", overlap)
    if overlap >= size:
        raise ValueError("overlap must be smaller than size")
    if type(text) is not str:
        raise TypeError("text must be a str")
    tokens = text.split()
    if not tokens:
        return []
    step = size - overlap
    chunks: list[dict[str, Any]] = []
    start = 0
    index = 0
    while start < len(tokens):
        end = min(start + size, len(tokens))
        piece = " ".join(tokens[start:end])
        chunks.append({
            "id": f"fixed-w-{index}",
            "strategy": "fixed_words",
            "size": size,
            "overlap": overlap,
            "start_word": start,
            "end_word": end,
            "text": piece,
        })
        index += 1
        if end >= len(tokens):
            break
        start += step
    return chunks


def chunk_fixed_chars(text: str, size: int, overlap: int = 0) -> list[dict[str, Any]]:
    """Naive character windows. Can cut mid-word and mid-Devanagari cluster."""
    size = _require_positive_int("size", size)
    overlap = _require_nonneg_int("overlap", overlap)
    if overlap >= size:
        raise ValueError("overlap must be smaller than size")
    if type(text) is not str:
        raise TypeError("text must be a str")
    if not text:
        return []
    step = size - overlap
    chunks: list[dict[str, Any]] = []
    start = 0
    index = 0
    while start < len(text):
        end = min(start + size, len(text))
        piece = text[start:end]
        if piece.strip():
            chunks.append({
                "id": f"fixed-c-{index}",
                "strategy": "fixed_chars",
                "size": size,
                "overlap": overlap,
                "start_char": start,
                "end_char": end,
                "text": piece,
            })
            index += 1
        if end >= len(text):
            break
        start += step
    return chunks


def chunk_recursive(text: str, size: int, overlap: int = 0,
                    separators: list[str] | None = None) -> list[dict[str, Any]]:
    """Recursive split: try large separators first, then smaller ones.

    Inspired by the common recursive character splitter pattern (paragraphs,
    then lines, then sentences, then spaces). Size is measured in characters.
    """
    size = _require_positive_int("size", size)
    overlap = _require_nonneg_int("overlap", overlap)
    if overlap >= size:
        raise ValueError("overlap must be smaller than size")
    if type(text) is not str:
        raise TypeError("text must be a str")
    if separators is None:
        separators = ["\n\n", "\n", ". ", " ", ""]
    if type(separators) is not list or not separators:
        raise TypeError("separators must be a non-empty list")
    for sep in separators:
        if type(sep) is not str:
            raise TypeError("each separator must be a str")

    def split_part(part: str, seps: list[str]) -> list[str]:
        if len(part) <= size:
            return [part] if part else []
        if not seps:
            # Hard cut as last resort (same failure mode as fixed chars).
            out = []
            start = 0
            while start < len(part):
                out.append(part[start:start + size])
                start += max(size - overlap, 1)
            return [p for p in out if p]
        sep = seps[0]
        rest = seps[1:]
        if sep == "":
            return split_part(part, [])
        pieces = part.split(sep) if sep else list(part)
        rebuilt: list[str] = []
        buf = ""
        for i, piece in enumerate(pieces):
            addition = piece if sep == "" else (piece if buf == "" else buf and (sep + piece) or piece)
            # Rebuild carefully with separator between pieces.
            candidate = piece if buf == "" else buf + sep + piece
            if len(candidate) <= size:
                buf = candidate
            else:
                if buf:
                    rebuilt.extend(split_part(buf, rest) if len(buf) > size else [buf])
                if len(piece) > size:
                    rebuilt.extend(split_part(piece, rest))
                    buf = ""
                else:
                    buf = piece
        if buf:
            rebuilt.extend(split_part(buf, rest) if len(buf) > size else [buf])
        return [p for p in rebuilt if p]

    parts = split_part(text.strip(), separators)
    # Apply overlap by borrowing a tail from the previous chunk when needed.
    chunks: list[dict[str, Any]] = []
    prev_tail = ""
    for index, part in enumerate(parts):
        text_piece = part
        if overlap and prev_tail and not text_piece.startswith(prev_tail):
            # Prepend overlap only when it does not already start with it.
            text_piece = (prev_tail + " " + text_piece).strip()
            if len(text_piece) > size + overlap:
                text_piece = text_piece[-(size + overlap):]
        chunks.append({
            "id": f"recur-{index}",
            "strategy": "recursive",
            "size": size,
            "overlap": overlap,
            "text": text_piece,
        })
        prev_tail = part[-overlap:] if overlap and len(part) >= overlap else part
    return chunks


def chunk_by_heading(text: str) -> list[dict[str, Any]]:
    """Split on Markdown ## headings. Each section becomes one chunk."""
    if type(text) is not str:
        raise TypeError("text must be a str")
    parts = re.split(r"(?m)^##\s+", text.strip())
    chunks: list[dict[str, Any]] = []
    index = 0
    for part in parts:
        part = part.strip()
        if not part:
            continue
        title_line, _, body = part.partition("\n")
        title = title_line.strip()
        body = body.strip()
        chunk_text = f"## {title}\n{body}".strip() if body else f"## {title}"
        chunks.append({
            "id": f"heading-{index}",
            "strategy": "heading",
            "heading": title,
            "text": chunk_text,
        })
        index += 1
    return chunks


def validate_chunk_list(chunks: Any) -> list[dict[str, Any]]:
    """Fail closed: every chunk must be a dict with non-empty str id and text."""
    if type(chunks) is not list:
        raise TypeError("chunks must be a list")
    out: list[dict[str, Any]] = []
    seen: set[str] = set()
    for item in chunks:
        if type(item) is not dict:
            raise TypeError("each chunk must be a dict")
        cid = item.get("id")
        text = item.get("text")
        if type(cid) is not str or not cid.strip():
            raise TypeError("chunk id must be a non-empty str")
        if type(text) is not str or not text.strip():
            raise TypeError("chunk text must be a non-empty str")
        if cid in seen:
            raise ValueError(f"duplicate chunk id: {cid}")
        seen.add(cid)
        out.append(item)
    return out


# ---------------------------------------------------------------------------
# 4. Retrieval stub and integrity checks
# ---------------------------------------------------------------------------
def retrieve(question: str, chunks: list[dict[str, Any]], k: int = 2) -> list[str]:
    """Rank chunks by shared words. Real apps use embeddings."""
    k = _require_positive_int("k", k)
    if type(question) is not str:
        raise TypeError("question must be a str")
    chunks = validate_chunk_list(chunks)
    q = words(question)
    scored: list[tuple[int, str]] = []
    for ch in chunks:
        score = len(q & words(ch["text"]))
        if score > 0:
            scored.append((score, ch["id"]))
    scored.sort(key=lambda s: (-s[0], s[1]))
    return [cid for _, cid in scored[:k]]


def chunk_map(chunks: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
    chunks = validate_chunk_list(chunks)
    return {c["id"]: c for c in chunks}


def contains_all(text: str, phrases: list[str]) -> bool:
    if type(text) is not str:
        raise TypeError("text must be a str")
    if type(phrases) is not list or not phrases:
        raise TypeError("phrases must be a non-empty list")
    low = text.lower()
    for p in phrases:
        if type(p) is not str or not p:
            raise TypeError("each phrase must be a non-empty str")
        if p.lower() not in low:
            return False
    return True


def intact_fact_chunks(chunks: list[dict[str, Any]], phrases: list[str]) -> list[str]:
    chunks = validate_chunk_list(chunks)
    return [c["id"] for c in chunks if contains_all(c["text"], phrases)]


def split_failure(chunks: list[dict[str, Any]], phrases: list[str]) -> bool:
    return len(intact_fact_chunks(chunks, phrases)) == 0


def near_duplicate_pairs(chunks: list[dict[str, Any]], threshold: float = 0.8) -> list[tuple[str, str]]:
    if type(threshold) is not float and type(threshold) is not int:
        raise TypeError("threshold must be a number")
    threshold = float(threshold)
    if not 0.0 <= threshold <= 1.0:
        raise ValueError("threshold must be between 0 and 1")
    chunks = validate_chunk_list(chunks)
    pairs: list[tuple[str, str]] = []
    bags = [(c["id"], words(c["text"])) for c in chunks]
    for i in range(len(bags)):
        id_a, a = bags[i]
        for j in range(i + 1, len(bags)):
            id_b, b = bags[j]
            union = a | b
            if not union:
                continue
            sim = len(a & b) / len(union)
            if sim >= threshold:
                pairs.append((id_a, id_b))
    return pairs


def mid_word_cuts(chunks: list[dict[str, Any]]) -> list[str]:
    """Ids of chunks that start or end mid Latin word (naive char-cut signal)."""
    chunks = validate_chunk_list(chunks)
    bad: list[str] = []
    for ch in chunks:
        t = ch["text"]
        if not t:
            continue
        # Starts with lowercase letter continuing a word, or ends with letter
        # followed nowhere — heuristic: leading/trailing partial ASCII word.
        if re.match(r"^[a-z]", t) and (ch.get("start_char", 0) > 0):
            bad.append(ch["id"])
            continue
        if re.search(r"[A-Za-z]$", t) and not t.endswith((".", "!", "?", "\n")):
            # Only flag fixed_chars strategy to avoid false positives on headings.
            if ch.get("strategy") == "fixed_chars":
                bad.append(ch["id"])
    return bad


def hit(question: str, chunks: list[dict[str, Any]], phrases: list[str], k: int = 2) -> bool:
    ids = retrieve(question, chunks, k=k)
    cmap = chunk_map(chunks)
    for cid in ids:
        if contains_all(cmap[cid]["text"], phrases):
            return True
    return False


def evaluate_strategy(name: str, chunks: list[dict[str, Any]], k: int = 2) -> dict[str, Any]:
    if type(name) is not str or not name.strip():
        raise TypeError("name must be a non-empty str")
    chunks = validate_chunk_list(chunks)
    answer_cases = [c for c in EVAL_SET if c["kind"] == "answer"]
    refuse_cases = [c for c in EVAL_SET if c["kind"] == "refuse"]
    intact = 0
    hits = 0
    split_fails: list[str] = []
    miss_hits: list[str] = []
    for case in answer_cases:
        phrases = case["needs_together"]
        if intact_fact_chunks(chunks, phrases):
            intact += 1
        else:
            split_fails.append(case["id"])
        if hit(case["question"], chunks, phrases, k=k):
            hits += 1
        else:
            miss_hits.append(case["id"])
    refuse_safe = 0
    for case in refuse_cases:
        retrieved = retrieve(case["question"], chunks, k=k)
        cmap = chunk_map(chunks)
        bad = False
        for cid in retrieved:
            low = cmap[cid]["text"].lower()
            for banned in case["must_not"]:
                if banned.lower() in low and banned.lower() not in DOCUMENT.lower():
                    bad = True
        if not bad:
            refuse_safe += 1
    total_answer = len(answer_cases)
    return {
        "strategy": name,
        "chunk_count": len(chunks),
        "answer_cases": total_answer,
        "intact_rate": intact / total_answer if total_answer else 0.0,
        "hit_rate": hits / total_answer if total_answer else 0.0,
        "split_failures": split_fails,
        "missed_hits": miss_hits,
        "near_duplicates": near_duplicate_pairs(chunks),
        "mid_word_cuts": mid_word_cuts(chunks),
        "refuse_safe": refuse_safe,
        "refuse_cases": len(refuse_cases),
        "recall_loss_from_splits": [c for c in split_fails if c in miss_hits],
    }


def compare_strategies(reports: list[dict[str, Any]]) -> list[str]:
    if type(reports) is not list or not reports:
        raise TypeError("reports must be a non-empty list")
    cleaned: list[dict[str, Any]] = []
    for r in reports:
        if type(r) is not dict:
            raise TypeError("each report must be a dict")
        for key in ("strategy", "hit_rate", "intact_rate", "chunk_count"):
            if key not in r:
                raise TypeError(f"report missing {key}")
        cleaned.append(r)
    ranked = sorted(
        cleaned,
        key=lambda r: (-float(r["hit_rate"]), -float(r["intact_rate"]), int(r["chunk_count"]), str(r["strategy"])),
    )
    lines = []
    for i, r in enumerate(ranked, start=1):
        lines.append(
            f"{i}. {r['strategy']}: hit_rate={r['hit_rate']:.2f}, "
            f"intact_rate={r['intact_rate']:.2f}, chunks={r['chunk_count']}, "
            f"near_dupes={len(r.get('near_duplicates', []))}, "
            f"recall_loss={r.get('recall_loss_from_splits', [])}"
        )
    return lines


def build_default_strategies() -> dict[str, list[dict[str, Any]]]:
    """Strategies compared in the lesson (with metadata attached)."""
    raw = {
        "fixed_12_no_overlap": chunk_fixed_words(DOCUMENT, size=12, overlap=0),
        "fixed_12_overlap_4": chunk_fixed_words(DOCUMENT, size=12, overlap=4),
        "fixed_chars_80": chunk_fixed_chars(DOCUMENT, size=80, overlap=0),
        "recursive_180": chunk_recursive(DOCUMENT, size=180, overlap=40),
        "by_heading": chunk_by_heading(DOCUMENT),
    }
    return {name: attach_metadata(chunks) for name, chunks in raw.items()}


def main() -> None:
    strategies = build_default_strategies()
    reports = []
    for name, chunks in strategies.items():
        report = evaluate_strategy(name, chunks, k=2)
        reports.append(report)
        print(f"== {name} ==")
        print(
            f"chunks={report['chunk_count']} intact_rate={report['intact_rate']:.2f} "
            f"hit_rate={report['hit_rate']:.2f} split_failures={report['split_failures']} "
            f"recall_loss={report['recall_loss_from_splits']} "
            f"near_dupes={len(report['near_duplicates'])} "
            f"mid_word_cuts={len(report['mid_word_cuts'])}"
        )
    print("-- ranking --")
    for line in compare_strategies(reports):
        print(line)


if __name__ == "__main__":
    main()

test_chunking.py

import unittest

from chunking import (
    DOCUMENT,
    EVAL_SET,
    REFUSAL,
    SECTION_HEADINGS,
    attach_metadata,
    build_default_strategies,
    chunk_by_heading,
    chunk_fixed_chars,
    chunk_fixed_words,
    chunk_map,
    chunk_recursive,
    compare_strategies,
    contains_all,
    evaluate_strategy,
    guess_section,
    hit,
    intact_fact_chunks,
    mid_word_cuts,
    near_duplicate_pairs,
    retrieve,
    split_failure,
    validate_chunk_list,
    words,
)


CASES = {c["id"]: c for c in EVAL_SET}


class EvalSetShape(unittest.TestCase):
    def test_ids_are_unique(self):
        ids = [c["id"] for c in EVAL_SET]
        self.assertEqual(len(ids), len(set(ids)))

    def test_kinds_covered(self):
        self.assertEqual({c["kind"] for c in EVAL_SET}, {"answer", "refuse"})

    def test_answer_cases_need_together(self):
        for c in EVAL_SET:
            if c["kind"] == "answer":
                self.assertTrue(c["facts"])
                self.assertTrue(c["needs_together"])
                self.assertTrue(contains_all(DOCUMENT, c["needs_together"]))

    def test_refuse_cases_have_no_facts(self):
        for c in EVAL_SET:
            if c["kind"] == "refuse":
                self.assertEqual(c["facts"], [])
                self.assertEqual(c["needs_together"], [])

    def test_document_has_six_sections(self):
        self.assertEqual(DOCUMENT.count("## "), 6)
        self.assertEqual(len(SECTION_HEADINGS), 6)

    def test_document_has_table_and_bilingual(self):
        self.assertIn("| Family | 500 g | 780 |", DOCUMENT)
        self.assertIn("सीलबंद डबे", DOCUMENT)
        self.assertIn("सीलबंद डिब्बे", DOCUMENT)


class FixedWordChunker(unittest.TestCase):
    def test_rejects_bad_size_types(self):
        with self.assertRaises(TypeError):
            chunk_fixed_words(DOCUMENT, size=12.0, overlap=0)
        with self.assertRaises(TypeError):
            chunk_fixed_words(DOCUMENT, size="12", overlap=0)
        with self.assertRaises(TypeError):
            chunk_fixed_words(DOCUMENT, size=0, overlap=0)

    def test_rejects_overlap_too_large(self):
        with self.assertRaises(ValueError):
            chunk_fixed_words(DOCUMENT, size=12, overlap=12)
        with self.assertRaises(ValueError):
            chunk_fixed_words(DOCUMENT, size=12, overlap=13)

    def test_rejects_negative_overlap(self):
        with self.assertRaises(TypeError):
            chunk_fixed_words(DOCUMENT, size=12, overlap=-1)

    def test_no_overlap_covers_all_words(self):
        chunks = chunk_fixed_words(DOCUMENT, size=12, overlap=0)
        joined = " ".join(c["text"] for c in chunks)
        self.assertEqual(joined.split(), DOCUMENT.split())

    def test_overlap_advances_by_step(self):
        chunks = chunk_fixed_words(DOCUMENT, size=12, overlap=4)
        self.assertGreaterEqual(len(chunks), 2)
        self.assertEqual(chunks[1]["start_word"], 8)

    def test_empty_text(self):
        self.assertEqual(chunk_fixed_words("", size=12, overlap=0), [])


class FixedCharAndRecursive(unittest.TestCase):
    def test_fixed_chars_can_cut_mid_word(self):
        chunks = chunk_fixed_chars(DOCUMENT, size=80, overlap=0)
        self.assertTrue(mid_word_cuts(chunks))

    def test_fixed_chars_rejects_bad_overlap(self):
        with self.assertRaises(ValueError):
            chunk_fixed_chars(DOCUMENT, size=40, overlap=40)

    def test_recursive_keeps_paragraphs_when_small_enough(self):
        chunks = chunk_recursive(DOCUMENT, size=180, overlap=40)
        self.assertGreaterEqual(len(chunks), 4)
        # Heading strategy and recursive should both keep q02 intact.
        phrases = CASES["q02"]["needs_together"]
        self.assertFalse(split_failure(chunks, phrases))

    def test_recursive_rejects_bad_separators(self):
        with self.assertRaises(TypeError):
            chunk_recursive(DOCUMENT, size=100, overlap=10, separators="bad")
        with self.assertRaises(TypeError):
            chunk_recursive(DOCUMENT, size=100, overlap=10, separators=[1])


class HeadingChunker(unittest.TestCase):
    def test_six_heading_chunks(self):
        chunks = chunk_by_heading(DOCUMENT)
        self.assertEqual(len(chunks), 6)
        headings = [c["heading"] for c in chunks]
        self.assertEqual(list(headings), list(SECTION_HEADINGS))

    def test_each_heading_keeps_section_body(self):
        chunks = chunk_by_heading(DOCUMENT)
        returns = chunks[0]["text"]
        self.assertIn("14 days", returns)
        self.assertIn("48 hours", returns)
        self.assertNotIn("Express shipping", returns)
        price = chunks[4]["text"]
        self.assertIn("Family", price)
        self.assertIn("not to online orders", price)

    def test_rejects_non_str(self):
        with self.assertRaises(TypeError):
            chunk_by_heading(None)


class MetadataAndValidation(unittest.TestCase):
    def test_attach_metadata(self):
        chunks = attach_metadata(chunk_by_heading(DOCUMENT), source="faq.txt")
        self.assertEqual(chunks[0]["metadata"]["source"], "faq.txt")
        self.assertEqual(chunks[0]["metadata"]["section"], "Returns")

    def test_guess_section(self):
        self.assertEqual(guess_section("## Shipping\nHello"), "Shipping")
        with self.assertRaises(TypeError):
            guess_section(None)

    def test_validate_ok(self):
        chunks = [{"id": "a", "text": "hello"}]
        self.assertEqual(validate_chunk_list(chunks)[0]["id"], "a")

    def test_validate_rejects_bad_shapes(self):
        with self.assertRaises(TypeError):
            validate_chunk_list("nope")
        with self.assertRaises(TypeError):
            validate_chunk_list([{"id": 1, "text": "x"}])
        with self.assertRaises(TypeError):
            validate_chunk_list([{"id": "a", "text": "  "}])
        with self.assertRaises(ValueError):
            validate_chunk_list([{"id": "a", "text": "x"}, {"id": "a", "text": "y"}])


class RetrievalAndIntegrity(unittest.TestCase):
    def test_words_drops_stopwords_keeps_devanagari(self):
        self.assertNotIn("the", words("the tea tin"))
        self.assertIn("tea", words("the tea tin"))
        self.assertIn("थंड", words("थंड कोरड्या"))

    def test_contains_all_and_split_detection(self):
        phrases = CASES["q02"]["needs_together"]
        tiny = chunk_fixed_words(DOCUMENT, size=8, overlap=0)
        self.assertTrue(split_failure(tiny, phrases) or intact_fact_chunks(tiny, phrases) == [])
        headed = chunk_by_heading(DOCUMENT)
        self.assertFalse(split_failure(headed, phrases))
        self.assertTrue(intact_fact_chunks(headed, phrases))

    def test_fixed_no_overlap_splits_damaged_exception(self):
        phrases = CASES["q02"]["needs_together"]
        fixed = chunk_fixed_words(DOCUMENT, size=12, overlap=0)
        self.assertTrue(split_failure(fixed, phrases))

    def test_overlap_can_rescue_or_match_boundary_fact(self):
        phrases = CASES["q02"]["needs_together"]
        overlapped = chunk_fixed_words(DOCUMENT, size=12, overlap=6)
        no_ov = chunk_fixed_words(DOCUMENT, size=12, overlap=0)
        self.assertGreaterEqual(
            len(intact_fact_chunks(overlapped, phrases)),
            len(intact_fact_chunks(no_ov, phrases)),
        )

    def test_retrieve_respects_k_and_types(self):
        chunks = chunk_by_heading(DOCUMENT)
        self.assertLessEqual(len(retrieve("return unopened tin", chunks, k=1)), 1)
        with self.assertRaises(TypeError):
            retrieve("x", chunks, k=0)
        with self.assertRaises(TypeError):
            retrieve(None, chunks, k=2)

    def test_hit_on_heading_strategy(self):
        chunks = chunk_by_heading(DOCUMENT)
        case = CASES["q04"]
        self.assertTrue(hit(case["question"], chunks, case["needs_together"], k=2))

    def test_table_fact_intact_under_heading(self):
        chunks = chunk_by_heading(DOCUMENT)
        case = CASES["q11"]
        self.assertFalse(split_failure(chunks, case["needs_together"]))
        self.assertTrue(hit(case["question"], chunks, case["needs_together"], k=2))

    def test_bilingual_fact_intact_under_heading(self):
        chunks = chunk_by_heading(DOCUMENT)
        case = CASES["q12"]
        self.assertFalse(split_failure(chunks, case["needs_together"]))

    def test_near_duplicates_from_heavy_overlap(self):
        heavy = chunk_fixed_words(DOCUMENT, size=20, overlap=18)
        pairs = near_duplicate_pairs(heavy, threshold=0.7)
        self.assertTrue(pairs)

    def test_near_duplicate_threshold_bounds(self):
        chunks = chunk_by_heading(DOCUMENT)
        with self.assertRaises(ValueError):
            near_duplicate_pairs(chunks, threshold=1.5)
        with self.assertRaises(TypeError):
            near_duplicate_pairs(chunks, threshold="high")


class StrategyEval(unittest.TestCase):
    def test_heading_beats_tiny_fixed_on_intact(self):
        strategies = build_default_strategies()
        fixed = evaluate_strategy("fixed_12_no_overlap", strategies["fixed_12_no_overlap"])
        headed = evaluate_strategy("by_heading", strategies["by_heading"])
        self.assertGreater(headed["intact_rate"], fixed["intact_rate"])
        self.assertGreaterEqual(headed["hit_rate"], fixed["hit_rate"])

    def test_heading_has_no_split_failures_on_golden(self):
        headed = evaluate_strategy("by_heading", chunk_by_heading(DOCUMENT))
        self.assertEqual(headed["split_failures"], [])
        self.assertEqual(headed["intact_rate"], 1.0)

    def test_compare_strategies_orders_by_hit_then_intact(self):
        reports = [
            {"strategy": "a", "hit_rate": 0.5, "intact_rate": 1.0, "chunk_count": 4, "near_duplicates": []},
            {"strategy": "b", "hit_rate": 0.9, "intact_rate": 0.5, "chunk_count": 10, "near_duplicates": []},
            {"strategy": "c", "hit_rate": 0.9, "intact_rate": 1.0, "chunk_count": 4, "near_duplicates": []},
        ]
        lines = compare_strategies(reports)
        self.assertTrue(lines[0].startswith("1. c:"))
        self.assertTrue(lines[1].startswith("2. b:"))
        self.assertTrue(lines[2].startswith("3. a:"))

    def test_compare_rejects_bad_input(self):
        with self.assertRaises(TypeError):
            compare_strategies([])
        with self.assertRaises(TypeError):
            compare_strategies([{"strategy": "x"}])

    def test_default_strategies_keys(self):
        keys = set(build_default_strategies())
        self.assertEqual(
            keys,
            {"fixed_12_no_overlap", "fixed_12_overlap_4", "fixed_chars_80", "recursive_180", "by_heading"},
        )

    def test_chunk_map(self):
        chunks = chunk_by_heading(DOCUMENT)
        self.assertEqual(chunk_map(chunks)["heading-0"]["heading"], "Returns")

    def test_refusal_constant(self):
        self.assertTrue(REFUSAL.startswith("I could not find"))

    def test_recursive_ranks_with_heading(self):
        strategies = build_default_strategies()
        reports = [evaluate_strategy(n, ch) for n, ch in strategies.items()]
        lines = compare_strategies(reports)
        self.assertTrue(lines[0].startswith("1. by_heading:") or "recursive_180" in lines[0])


class EndToEndDemo(unittest.TestCase):
    def test_main_ranking_prefers_heading_or_recursive(self):
        strategies = build_default_strategies()
        reports = [evaluate_strategy(n, ch) for n, ch in strategies.items()]
        lines = compare_strategies(reports)
        top = lines[0]
        self.assertTrue("by_heading" in top or "recursive_180" in top)
        self.assertIn("hit_rate=1.00", top)


if __name__ == "__main__":
    unittest.main()

Output from an actual run of python3 chunking.py (synthetic FAQ only, no AI used):

== fixed_12_no_overlap ==
chunks=20 intact_rate=0.50 hit_rate=0.40 split_failures=['q02', 'q04', 'q10', 'q11', 'q12'] recall_loss=['q02', 'q04', 'q10', 'q11', 'q12'] near_dupes=0 mid_word_cuts=0
== fixed_12_overlap_4 ==
chunks=29 intact_rate=0.70 hit_rate=0.60 split_failures=['q02', 'q04', 'q11'] recall_loss=['q02', 'q04', 'q11'] near_dupes=0 mid_word_cuts=0
== fixed_chars_80 ==
chunks=16 intact_rate=0.50 hit_rate=0.40 split_failures=['q02', 'q03', 'q04', 'q06', 'q11'] recall_loss=['q02', 'q03', 'q04', 'q06', 'q11'] near_dupes=0 mid_word_cuts=14
== recursive_180 ==
chunks=11 intact_rate=1.00 hit_rate=1.00 split_failures=[] recall_loss=[] near_dupes=0 mid_word_cuts=0
== by_heading ==
chunks=6 intact_rate=1.00 hit_rate=1.00 split_failures=[] recall_loss=[] near_dupes=0 mid_word_cuts=0
-- ranking --
1. by_heading: hit_rate=1.00, intact_rate=1.00, chunks=6, near_dupes=0, recall_loss=[]
2. recursive_180: hit_rate=1.00, intact_rate=1.00, chunks=11, near_dupes=0, recall_loss=[]
3. fixed_12_overlap_4: hit_rate=0.60, intact_rate=0.70, chunks=29, near_dupes=0, recall_loss=['q02', 'q04', 'q11']
4. fixed_chars_80: hit_rate=0.40, intact_rate=0.50, chunks=16, near_dupes=0, recall_loss=['q02', 'q03', 'q04', 'q06', 'q11']
5. fixed_12_no_overlap: hit_rate=0.40, intact_rate=0.50, chunks=20, near_dupes=0, recall_loss=['q02', 'q04', 'q10', 'q11', 'q12']

Output from an actual run of the tests (last lines):

Ran 42 tests in 0.023s
OK

Read the report one result at a time:

  1. Fixed 12 words with no overlap splits several golden cases, including the damaged-tin exception.
  2. Fixed 12 words with overlap 4 improves intact rate and hit rate, but still misses some boundary cases.
  3. Fixed 80 characters shows mid-word cuts, which is a warning for naive character windows.
  4. Recursive size 180 with overlap 40 keeps the golden facts intact in this small FAQ.
  5. Heading chunking also keeps every golden fact intact, with fewer chunks than the recursive run.
  6. Heavy overlap in the tests produces near-duplicate pairs, which is why more overlap is not always better.

Ravindra Bagale's Tip

After you change chunk size, overlap or splitter type, re-run the same golden questions and compare case by case. The RAG evaluation chapter shows how to turn that habit into a small offline test suite.

9. Beginner mistakes and quick fixes

Table 4: Common chunking mistakes and how to fix them

MistakeQuick fix
The student uses one default size for every document.Compare at least fixed, overlap and heading or recursive splits on a golden set.
The student increases overlap until every boundary is covered.Stop when intact rate stops rising, and check near-duplicate pairs.
The student splits tables by character count.Keep the table with its header and nearby rule, or split by section first.
The student ignores Marathi or Hindi lines.Avoid mid-line character cuts; keep each language line whole when you can.
The student stores chunks without metadata.Save source, section and page with every chunk for citations and filters.
The student changes the prompt when retrieval missed half a rule.Print retrieved chunks first; fix chunking when the fact was never retrieved whole.

10. Try at home

  1. Run the exercise and the tests, and confirm that the tests end with "OK".
  2. Change the fixed word size from 12 to 20 with no overlap, and predict whether q02 stays split.
  3. Add a seventh FAQ section about gift wrapping, with one golden question, and update the tests.
  4. Write a check that fails any strategy whose near-duplicate count is greater than 3 at threshold 0.8.
  5. For your own PDF, split once by headings and once with a recursive splitter, then compare five hand-written questions.

Quick self-check quiz (5 questions)

This is browser-only practice. Your answers are not sent anywhere, are not saved, and do not count towards any course progress or certificate.

1. Why do RAG systems usually split documents into chunks before embedding them?
2. A fixed 12-word window with no overlap splits "Opened", "damaged" and "48 hours" across chunks. What failed?
3. Which statement about overlap is correct?
4. In the offline exercise, which strategy kept every golden fact intact with only six chunks?
5. Your bot misses half of a return rule. What should you check first?

Recap

  1. RAG indexes chunks, not whole libraries, so that retrieval stays affordable and precise.
  2. Fixed-size windows are simple, but a cut can split a multi-phrase rule across two chunks.
  3. A little overlap can rescue boundary facts; heavy overlap can create near-duplicates.
  4. Heading-based chunking often keeps a whole policy section, table or bilingual note together.
  5. Recursive splitters try large separators first, which matches common library defaults.
  6. Official Bedrock, LangChain and LlamaIndex docs describe the same tradeoffs with different names and settings.
  7. After any chunking change, re-run a golden set and compare case by case.

Further reading (official documentation, checked on 6 November 2026)

Related chapters: What Is RAG? Build a Chatbot from Your Own PDF · Embeddings Explained Simply · How to Test a RAG Chatbot · Vector Databases for Beginners · RAG on AWS: Bedrock Knowledge Bases with S3 · All Generative AI chapters


Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. Konkan Leaf Tea Co., its FAQ, table, bilingual note and questions on this page are made up for learning. Sources were checked on 6 Nov 2026.