05.7 Advanced and Document-Specific Chunking

RetrievalLesson 7 of 1013,154 wordsDeep-dive9 parts
Module 05 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Lesson 05.6 gave you the flat splitters: fixed-size, sentence, paragraph, recursive, structure-aware, semantic and token-aware. Those answer one question — where do I cut the text? This lesson answers the three questions that decide whether retrieval actually works: what should be embedded (the indexing representation), what should be returned (the retrieval unit versus the context unit), and what shape should each document type produce (the recipe). Along the way you will build parent-child indexes, run contextual retrieval end to end, simulate late chunking and RAPTOR trees, decompose text into atomic propositions, and collect a splitter recipe for every document type your corpus will throw at you — contracts, API docs, papers, filings, source code, email threads, chat logs, subtitles, catalogues, tables, slides, forms and multilingual text.

What you'll learn

  • Why "the best chunk size" is really two different questions — the unit you match against and the unit you answer from — and the techniques that decouple them: parent-child chunking, sentence-window retrieval, auto-merging, and query-time expansion
  • Contextual retrieval (Anthropic's method): the exact prompt, what the published numbers do and don't say, what it costs with prompt caching, and a complete provider-agnostic implementation
  • Multi-vector representations: embedding a chunk's text, summary, hypothetical questions and keywords as separate vectors that all point back to the same chunk
  • Late chunking and which embedding models actually support it (Jina, Voyage), plus RAPTOR summary trees and proposition-level (atomic-fact) indexing, with the research behind each
  • A working splitter recipe for 17 document types, each with code, a worked example and its pitfalls
  • How dense, BM25, hybrid and long-context-stuffing retrieval each want different chunks — and how to evaluate which strategy wins on your question set
  • The chunk lifecycle: versioned chunking configs, stable IDs, re-embedding cost, and what changes when you switch strategies

What you don't need

  • The basics of splitting. Recursive splitting, token counting, overlap and the Chunk record are lesson 05.6; this lesson reuses them.
  • Embedding APIs, vector databases and indexes — that's Module 06. Retrieval pipelines and RAG assembly are Module 07. LLM request mechanics, prompt caching APIs and batch calls are Module 03; this lesson injects those calls so every sample runs without keys.
  • API keys. Every model call in this lesson is an injected function. The pure-Python parts run as-is; where a real model would be called, the output is labelled illustrative.

Setup

The samples need Python 3.11+ and almost nothing else — the techniques are taught with injected model calls so they run offline. The one real dependency is the ast module (standard library) for the code recipe; tree-sitter appears as an optional upgrade. If you already have the Module 05 project from 05.1, reuse it and skip the uv init line; otherwise start a fresh one:

bash
uv init data-pipelines --bare --python 3.13 && cd data-pipelines
uv add tree-sitter tree-sitter-python tiktoken
# or: pip install tree-sitter tree-sitter-python tiktoken

The samples were checked against the versions current as of November 2026 (tree-sitter 0.26.0, tree-sitter-python 0.25.0; see tree-sitter, tree-sitter-python, tiktoken). The library equivalents shown for comparison — langchain-text-splitters==1.1.3, chonkie==1.7.0, semchunk==4.1.1 — are also the versions current as of November 2026; add them only if you want to compare implementations. A plain install gives you the newest release, and a newer major version of tree-sitter or its grammars may change the Python API, so check the changelog if a sample does not match. No .env file is needed: nothing in this lesson calls a hosted API. If you wire the injected functions to real providers later, the .env conventions are in lesson 03.1.

Every Python block that opens with a filename comment is a complete file — save it under that name (s2_parent_child.py, blocks.py, recipes/legal.py, …) and run it with python3 <file> (the Part 5 recipes are modules that blocks.py supports; see the note at the start of Part 5). The short "Worked example — input" snippets are calls you add below a recipe. The Output: blocks that follow are real output produced by running that code on the toy input shown beside it.


What you must be able to do after this lesson#

  • Explain the difference between the unit you match and the unit you answer from
  • Build parent-child chunking
  • Add context to chunks before embedding
  • Pick a chunking strategy for a document type
  • Evaluate chunking quality on your own questions

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"We're on parent-document retrieval." 2.1 The idea: embed small, return big
"The chunk matches the query but can't answer it." 1.2 Two different questions
"Let's do contextual retrieval — it's a 49% win." 3.1 Contextual retrieval
"Why not just use a model with a bigger context window?" 4.1 Late chunking and Part 6
"One chunk per clause / per function / per slide." Part 5: the recipes
"BM25 wants different chunks than dense search." 6.2 Sparse and hybrid
"How do we know which chunker is better?" Part 7: evaluating chunking
"We changed the chunk size — do we re-embed everything?" Part 8: the chunk lifecycle
"Proposition-level indexing is state of the art." 4.3 Propositional and atomic-fact chunking

Part 1: The second half of chunking#

1.1 What flat chunking leaves undecided#

Lesson 05.6 treated chunking as a segmentation problem: pick boundaries, respect them, control size. That is necessary but not sufficient, because three separate decisions determine retrieval quality, and a flat splitter only makes the first:

flowchart LR
    subgraph ingest ["At ingestion time"]
        S["Segmentation<br/>where to cut"] --> R["Indexing representation<br/>what text/vector(s) represent the unit"]
    end
    subgraph query ["At query time"]
        Q["Query"] --> RET["Retrieval<br/>which units match"]
        RET --> X["Expansion<br/>what context the generator sees"]
        X --> G["Generator"]
    end
    R -.->|stored with each unit| RET
  • Segmentation — where the boundaries are. Owned by 05.6 and by the recipes in Part 5.
  • Indexing representation — what actually gets embedded and keyword-indexed. This is where contextual retrieval (3.1), multi-vector representations (3.2) and late chunking (4.1) live.
  • Expansion — what the generator receives after a unit matches: the unit itself, its parent, its neighbours, or a summary. This is where parent-child chunking (Part 2), sentence-window retrieval and query-time expansion live.

A technique in this lesson typically moves exactly one of these three dials — which is why they compose rather than compete.

1.2 Two different questions#

The deepest idea in this lesson is that the unit you retrieve and the unit you answer from are usually different sizes, and optimising for one can hurt the other:

  • A small chunk (a sentence, a clause, a function) embeds precisely: its vector points at exactly the meaning it contains, so similarity search finds it reliably.
  • But a small chunk often can't answer the question alone: "It costs $49 per month" is useless without knowing "it" is the Pro plan and "per month" is billed annually.
  • A large chunk (a section, a chapter) answers well but embeds diffusely: its vector averages many topics, so it loses to sharper competitors in top-k, and it wastes context-window budget on text the query didn't need.

LlamaIndex's documentation states the principle plainly: decouple the chunks used for retrieval from the chunks used for synthesis — this is the "small-to-big" pattern. Anthropic's contextual-retrieval post makes the same observation from the other side: prepend context so each small chunk carries its surroundings inside the indexed text.

flowchart TD
    subgraph small ["Small unit — precise match"]
        C1["'It costs $49 per month billed annually.'"]
    end
    subgraph big ["Big unit — enough context"]
        P1["## Pro plan<br/>The Pro plan is our mid-tier offering.<br/>It costs $49 per month billed annually.<br/>It includes unlimited projects."]
    end
    C1 -- "parent_id / neighbours / expansion" --> P1
    Q["query: 'pro plan price'"] --> C1
    C1 -->|"generator sees"| P1

The techniques in Part 2 and Part 4 are all variations on one move: retrieve small, synthesise big — or, equivalently, make the small unit carry the big unit's context inside its own representation.

1.3 The map of techniques#

Family What it changes Techniques Cost at index time Cost at query time
Hierarchy Return unit Parent-child, sentence-window, auto-merging Store parents alongside children One extra lookup
Expansion Return unit Chunk/window expansion, neighbour stitching Store offsets/IDs Assemble context per hit
Enrichment Indexed text Contextual retrieval, multi-vector, hypothetical questions 1 LLM call + N embeddings per chunk Same as flat
New granularity Segmentation unit Propositions, semantic units, per-type recipes Same or more chunks Same
New representation Embedding mechanics Late chunking, summary trees (RAPTOR) Long-context embedding pass; LLM summaries Same or tree walk
Model-side Nothing in your index Long-context stuffing None Whole corpus in prompt (only for small corpora)

Each family is covered below, then the per-document-type recipes that decide segmentation in practice.


Part 2: Hierarchical and parent-child chunking#

2.1 The idea: embed small, return big#

Parent-child chunking splits each document twice: into parents (sections, pages, or fixed windows of ~500–2,000 tokens) and into children (the retrieval units, ~100–400 tokens) nested inside them. Only the children go into the vector index. When a child matches, you return its parent — or the parent plus neighbouring context — to the generator.

sequenceDiagram
    participant I as Ingestion
    participant V as Vector index
    participant D as Docstore
    participant R as Retriever
    participant G as Generator
    I->>V: embed each CHILD chunk
    I->>D: store each PARENT text by id
    R->>V: search children for query
    V-->>R: top-k child hits (with parent_id)
    R->>D: fetch parent texts
    D-->>R: parent chunks (deduplicated)
    R->>G: parents as context

The named variants differ only in how "big" is defined and when expansion happens:

Variant Retrieval unit Returned unit Library equivalent Best when
Parent-child Child chunk Parent chunk (or whole doc) LangChain ParentDocumentRetriever; LlamaIndex HierarchicalNodeParser + docstore Documents have natural sections (handbook, policy, docs site)
Sentence-window Single sentence Window of N sentences around it LlamaIndex SentenceWindowNodeParser + MetadataReplacementNodePostProcessor Very large docs where even paragraphs are too coarse to embed well
Auto-merging Leaf chunks of a hierarchy Parent promoted when enough siblings hit LlamaIndex AutoMergingRetriever (default levels 2048/512/128 tokens) Queries that span several adjacent small chunks
Query-time expansion Any unit Unit + neighbours/parent fetched at query time Your own code (below) You already have neighbour pointers from 05.6

2.2 Building a parent-child index#

The pattern is simple enough to own outright — which you should, because every framework implements it slightly differently. This demo uses the running corpus's product handbook as three sections.

python
# s2_parent_child.py — embed small children, return big parents.
"""Parent-child chunking: small children are embedded and searched;
their larger parents are what the generator sees.

Toy corpus: three sections of a fictional product handbook.
Pure stdlib -> the printed output in the lesson is real.
"""

import hashlib
import re
from dataclasses import dataclass, field


# ---------- a minimal Chunk, shaped like the one 05.6 defines ----------

@dataclass
class Chunk:
    doc_id: str
    index: int                     # position in DOCUMENT order (parents+children share one counter)
    text: str
    strategy: str
    kind: str = "leaf"               # "parent" or "leaf"
    parent_id: str | None = None     # set on leaves
    char_start: int = 0
    char_end: int = 0
    section_path: str = ""
    token_count: int | None = None
    prev_id: str | None = None
    next_id: str | None = None
    meta: dict = field(default_factory=dict)

    @property
    def chunk_id(self) -> str:
        payload = "|".join([
            self.doc_id, self.strategy, str(self.index),
            str(self.char_start), str(self.char_end), self.text,
        ])
        return f"{self.doc_id}#{self.index:04d}-{hashlib.sha256(payload.encode()).hexdigest()[:12]}"

    def embed_input(self) -> str:
        """What the embedding model sees — 05.6's contract: breadcrumb + body.
        Children embed this (the heading is retrieval signal); parents live
        in the docstore and are never embedded."""
        return f"{self.section_path}\n\n{self.text}" if self.section_path else self.text


# ---------- toy document: (heading, paragraphs) ----------

HANDBOOK = [
    ("Warranty", [
        "Every Acme Drill carries a two-year limited warranty against defects in materials and workmanship.",
        "The warranty covers the motor, chuck and battery pack but excludes wear items such as drill bits and abrasives.",
        "To make a claim, register the tool within 30 days of purchase and keep your receipt.",
    ]),
    ("Returns", [
        "Unused tools may be returned within 45 days for a full refund.",
        "Opened power tools can only be returned if they are defective; contact support for a return authorisation number.",
        "Shipping costs on change-of-mind returns are paid by the customer.",
    ]),
    ("Battery care", [
        "Store battery packs at room temperature and charge them before first use.",
        "Do not leave packs on the charger for more than 24 hours; it shortens cell life.",
        "A pack that swells or smells must be removed from service and recycled at a certified facility.",
    ]),
]


def sentences(text: str) -> list[str]:
    return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]


def pack_sentences(paras: list[str], max_chars: int) -> list[str]:
    """Greedy sentence packing, same idea as 05.6's paragraph/sentence splitters.
    A single sentence longer than max_chars is hard-split — rare, but a silent
    overflow is worse than a mid-sentence cut (05.6's split_long does the same)."""
    out, buf = [], ""
    for para in paras:
        for sent in sentences(para):
            if len(sent) > max_chars:
                if buf:
                    out.append(buf)
                    buf = ""
                out.extend(sent[i:i + max_chars]
                           for i in range(0, len(sent), max_chars))
                continue
            if buf and len(buf) + len(sent) + 1 > max_chars:
                out.append(buf)
                buf = sent
            else:
                buf = f"{buf} {sent}".strip()
    if buf:
        out.append(buf)
    return out


def build_parent_child(doc_id: str, sections: list[tuple[str, list[str]]],
                       parent_chars: int = 900, child_chars: int = 260) -> tuple[list[Chunk], dict]:
    """One parent per section (or per group of sections under parent_chars),
    children packed inside each parent. `index` is one running counter in
    document order shared by parents and children — a parent's index is not
    its position among parents."""
    parents, children, docstore = [], [], {}
    n = 0
    for heading, paras in sections:
        body = "\n\n".join(paras)
        parent_text = f"{heading}\n\n{body}"
        if len(parent_text) > parent_chars:
            raise ValueError("section exceeds parent_chars; split the section first")
        p = Chunk(doc_id=doc_id, index=n, text=parent_text,
                  strategy="parent-child-v1", kind="parent", section_path=heading)
        n += 1
        parents.append(p)
        docstore[p.chunk_id] = p.text

        for child_text in pack_sentences(paras, child_chars):
            c = Chunk(doc_id=doc_id, index=n, text=child_text,
                      strategy="parent-child-v1", kind="leaf", parent_id=p.chunk_id,
                      section_path=heading)
            n += 1
            children.append(c)
            docstore[c.chunk_id] = c.text

    # deterministic ids first, then neighbour pointers — each kind's own
    # document-order chain (children chain across section boundaries, which
    # is what expansion wants; parents chain section-to-section)
    all_chunks = parents + children
    ids = {id(c): c.chunk_id for c in all_chunks}
    for seq in (parents, children):
        for i, c in enumerate(seq):
            c.prev_id = ids[id(seq[i - 1])] if i else None
            c.next_id = ids[id(seq[i + 1])] if i + 1 < len(seq) else None
    return parents + children, docstore


def retrieve_parents(query: str, children: list[Chunk], top_k: int = 3) -> list[str]:
    """Toy lexical search over children; return the PARENTS of the hits.
    In production the children go to the vector index and parents to a docstore."""
    q = set(re.findall(r"[a-z]+", query.lower()))
    scored = []
    for c in children:
        words = set(re.findall(r"[a-z]+", c.text.lower()))
        score = len(q & words) / max(len(q), 1)
        if score:
            scored.append((score, c))
    scored.sort(key=lambda t: -t[0])
    seen, out = set(), []
    for _, c in scored[:top_k]:
        if c.parent_id not in seen:
            seen.add(c.parent_id)
            out.append(c.parent_id)
    return out


if __name__ == "__main__":
    chunks, docstore = build_parent_child("handbook", HANDBOOK)
    children = [c for c in chunks if c.kind == "leaf"]
    parents = [c for c in chunks if c.kind == "parent"]

    print(f"{len(parents)} parents, {len(children)} children")
    for p in parents:
        kids = [c for c in children if c.parent_id == p.chunk_id]
        print(f"\nPARENT {p.chunk_id}  section={p.section_path!r}  ({len(kids)} children)")
        for k in kids:
            print(f"  LEAF {k.chunk_id}  {k.text[:70]!r}...")

    print("\n--- query: 'can I return a drill I already opened?' ---")
    for pid in retrieve_parents("can I return a drill I already opened", children):
        print(f"\nRETURNED PARENT {pid}:")
        print(docstore[pid])
Output31 lines
3 parents, 4 children

PARENT handbook#0000-b7531ac19e01  section='Warranty'  (2 children)
  LEAF handbook#0001-896a6e9f82f2  'Every Acme Drill carries a two-year limited warranty against defects i'...
  LEAF handbook#0002-53d7660cd8e8  'To make a claim, register the tool within 30 days of purchase and keep'...

PARENT handbook#0003-d9fb3767095f  section='Returns'  (1 children)
  LEAF handbook#0004-4aa77d148e52  'Unused tools may be returned within 45 days for a full refund. Opened '...

PARENT handbook#0005-818cbb936eab  section='Battery care'  (1 children)
  LEAF handbook#0006-cf99328b8d10  'Store battery packs at room temperature and charge them before first u'...

--- query: 'can I return a drill I already opened?' ---

RETURNED PARENT handbook#0003-d9fb3767095f:
Returns

Unused tools may be returned within 45 days for a full refund.

Opened power tools can only be returned if they are defective; contact support for a return authorisation number.

Shipping costs on change-of-mind returns are paid by the customer.

RETURNED PARENT handbook#0000-b7531ac19e01:
Warranty

Every Acme Drill carries a two-year limited warranty against defects in materials and workmanship.

The warranty covers the motor, chuck and battery pack but excludes wear items such as drill bits and abrasives.

To make a claim, register the tool within 30 days of purchase and keep your receipt.

Notice what just happened: the child that matched ("Opened power tools can only be returned if they are defective…") is a fragment — it never names the product or the policy — but the parent the generator received is a complete, self-contained answer. That is the whole trick.

2.3 Query-time expansion: window and neighbour expansion#

If your chunks already carry prev_id/next_id (05.6 gives them this), expansion is a lookup, not a re-chunk:

python
# s2_expand.py — query-time window/parent expansion over neighbour pointers.
"""Query-time expansion: a retrieval hit is expanded to its neighbours
(or its parent) before the generator sees it. Pure stdlib, real output.
"""

from dataclasses import dataclass


@dataclass
class Chunk:
    chunk_id: str
    text: str
    prev_id: str | None = None
    next_id: str | None = None
    parent_id: str | None = None


def window_expand(chunks: dict[str, Chunk], hit_id: str,
                  before: int = 1, after: int = 1,
                  mode: str = "siblings") -> list[Chunk]:
    """Return the hit plus `before`/`after` neighbours.
    mode="siblings": walk prev_id/next_id links (flat sequence).
    mode="parent":   return the parent chunk (hierarchy lives elsewhere).
    Dangling neighbour ids (the pointed-at chunk was deleted) are skipped,
    not an error — a half-updated index must not crash expansion."""
    if mode == "parent":
        hit = chunks[hit_id]
        return [chunks[hit.parent_id]] if hit.parent_id in chunks else [hit]

    out, seen, cur = [], set(), hit_id
    # walk backwards
    chain = []
    while cur is not None and len(chain) <= before:
        chain.append(cur)
        cur = chunks[cur].prev_id if cur in chunks else None
    for cid in reversed(chain):
        if cid in chunks and cid not in seen:
            seen.add(cid)
            out.append(chunks[cid])
    # walk forwards from the hit
    cur = chunks[hit_id].next_id
    n = 0
    while cur is not None and n < after:
        if cur in chunks and cur not in seen:
            seen.add(cur)
            out.append(chunks[cur])
            n += 1
        cur = chunks[cur].next_id if cur in chunks else None
    return out


if __name__ == "__main__":
    texts = [
        "Chapter 1. The Acme Drill has a two-year warranty.",
        "Chapter 1. Warranty claims need a receipt.",
        "Chapter 1. Wear items like bits are excluded.",
        "Chapter 2. Returns are accepted within 45 days.",
        "Chapter 2. Opened tools need a return authorisation.",
    ]
    chunks = {}
    for i, t in enumerate(texts):
        cid = f"c{i}"
        chunks[cid] = Chunk(cid, t,
                            prev_id=f"c{i-1}" if i else None,
                            next_id=f"c{i+1}" if i + 1 < len(texts) else None)

    print("Hit: 'Wear items like bits are excluded.' (c2), expand before=1 after=1\n")
    for c in window_expand(chunks, "c2", before=1, after=1):
        print(f"  [{c.chunk_id}] {c.text}")
Output5 lines
Hit: 'Wear items like bits are excluded.' (c2), expand before=1 after=1

  [c1] Chapter 1. Warranty claims need a receipt.
  [c2] Chapter 1. Wear items like bits are excluded.
  [c3] Chapter 2. Returns are accepted within 45 days.

Two honest caveats. First, neighbour expansion can pull in irrelevant neighbours — the hit above dragged in a Returns sentence that has nothing to do with warranties. That's why parent-child usually beats flat window expansion: the boundary is semantic (a section), not positional. Second, expansion multiplies context tokens per retrieved chunk; three hits × window of five can blow your prompt budget faster than you expect — cap total expanded tokens, not just hit count.

2.4 Sentence-window and auto-merging, concretely#

The two remaining variants are the same machinery with different leaf and return definitions — frameworks hide the delta, so here it is explicitly:

  • Sentence-window makes the leaf a single sentence and stores a ±N-sentence window in the leaf's metadata; there is no separate parent to fetch — expansion is a metadata read. LlamaIndex's SentenceWindowNodeParser plus MetadataReplacementNodePostProcessor is exactly this. You will see it working in Part 7's eval harness: sentence_index embeds each sentence (embed_text) but scores and returns the surrounding window (context_text) — the same decoupling, evaluated on questions.
  • Auto-merging keeps a real hierarchy (usually 2–3 levels) but changes the return rule: retrieve leaves as usual, then count how many retrieved leaves share each parent — a parent with ≥ threshold votes emits its full text once in place of its leaf hits. The parent text sits in the same docstore as the leaves, and it is fetched only for the parents that reach the threshold — the merge decision is made over the whole retrieved set, not hit by hit.
python
# s2_4_auto_merge.py — auto-merging retrieval, simplified.
"""LlamaIndex's AutoMergingRetriever in ~20 lines: retrieved leaves vote for
 their parent; a parent with >= threshold votes emits its text once."""
from collections import Counter

# toy index: each leaf knows its parent; parent text lives in the docstore
PARENTS = {
    "Warranty": ("Warranty\n\nEvery Acme Drill carries a two-year limited warranty "
                 "against defects. The warranty covers the motor and chuck but "
                 "excludes wear items such as drill bits."),
    "Returns": ("Returns\n\nUnused tools may be returned within 45 days for a full "
                "refund. Opened power tools can only be returned if defective."),
}
LEAVES = [
    {"id": "w1", "parent": "Warranty",
     "text": "The warranty covers the motor and chuck."},
    {"id": "r1", "parent": "Returns",
     "text": "Opened power tools need a return authorisation."},
    {"id": "w2", "parent": "Warranty",
     "text": "Wear items such as drill bits are excluded."},
]


def auto_merge(hits: list[dict], parents: dict, threshold: int = 2) -> list[str]:
    """hits: ranked leaf dicts. Returns context strings: promoted parent text
    where a parent reached the vote threshold, leaf text otherwise."""
    votes = Counter(h["parent"] for h in hits)
    out, emitted = [], set()
    for h in hits:
        if votes[h["parent"]] >= threshold:
            if h["parent"] not in emitted:
                emitted.add(h["parent"])
                out.append(parents[h["parent"]])
        else:
            out.append(h["text"])
    return out


if __name__ == "__main__":
    # ranked retrieval order: two Warranty leaves + one Returns leaf
    hits = [LEAVES[0], LEAVES[1], LEAVES[2]]
    for text in auto_merge(hits, PARENTS, threshold=2):
        print("---")
        print(text)
Output6 lines
---
Warranty

Every Acme Drill carries a two-year limited warranty against defects. The warranty covers the motor and chuck but excludes wear items such as drill bits.
---
Opened power tools need a return authorisation.

Two Warranty leaves voted their parent over the threshold, so the generator sees the whole Warranty section once instead of two fragments — while the lone Returns leaf stays small. Tune threshold on your eval: too low and you return big parents for weak evidence; too high and you never promote.


Part 3: Enriching what gets embedded#

Segmentation and expansion decide which text exists; enrichment decides what the index sees. Two techniques dominate this space, and they attack the same problem from different angles: contextual retrieval rewrites each chunk's indexed text with an LLM-generated context sentence, while multi-vector representations give each chunk several different embeddings (its own text, a summary, hypothetical questions, keywords) that all resolve back to the same chunk.

3.1 Contextual retrieval#

In September 2024 Anthropic published "Introducing Contextual Retrieval", a preprocessing method that became the reference implementation of chunk enrichment. The problem it solves is the one from 1.2: a chunk like "The company's revenue grew by 3% over the previous quarter" is unfindable and unusable without knowing it's from ACME Corp's Q2 2023 SEC filing.

The method has two halves, and you can adopt either independently:

  • Contextual Embeddings — prepend a short (typically 50–100 token) LLM-generated context sentence to each chunk before embedding.
  • Contextual BM25 — prepend the same context to the chunk before building the BM25 index, so keyword search also benefits (the context supplies the document's vocabulary — "ACME Corp", "SEC filing" — that the bare chunk lacks).

Anthropic's published prompt, verbatim:

text
<document>
{{WHOLE_DOCUMENT}}
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{{CHUNK_CONTENT}}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else.

Their reported results (top-20-chunk retrieval, averaged over codebases, fiction, arXiv and science papers, with Gemini embeddings as the strongest configuration): Contextual Embeddings alone cut the retrieval failure rate by 35% (5.7% → 3.7%); adding Contextual BM25 cut it by 49% (5.7% → 2.9%); adding a reranker on top reached 67% (5.7% → 1.9%). A working cookbook implementation is at platform.claude.com/cookbook/capabilities-contextual-embeddings-guide.

What is known since (as of November 2026). Independent evidence is still thin but growing. A community replication of Anthropic's cookbook on the one public dataset (9 codebases, 737 chunks, 248 queries; claude-cookbooks issue #650, May 2026) reproduced the directional gains — contextual embeddings the biggest single win — but found hybrid + reranking did not clearly beat dense + reranking at top-20 on that dataset, a reminder that the last-mile configuration is corpus-dependent. The underlying idea has also been productised: Voyage's contextualized chunk embeddings and Jina's late chunking (4.1) attack the same "chunk lacks document context" problem with different mechanics and commercial SLAs. Until more independent evals exist, treat Anthropic's percentages as a well-supported prior, not a promise — Part 7's harness is how you get your own number.

Cost: why prompt caching makes this affordable

The naive cost is one LLM call per chunk, each re-sending the whole document — prohibitive. Anthropic's trick is prompt caching (02.7, 03.7): the document is placed in the cached prefix once, and each chunk request reads it from cache at a fraction of the input price. With their stated assumptions — 800-token chunks, 8k-token documents, ~50 tokens of instructions and ~100 tokens of generated context per chunk — they put the one-time indexing cost at $1.02 per million document tokens (using Claude Haiku at the time). That is an indexing cost, paid once per chunking-config version; it does not recur at query time.

The trick is not Anthropic-specific. Any provider with prefix caching can serve it, as long as the document comes first in the prompt and the chunk last — caching matches on a shared prefix, so a chunk placed before the document would break it. Each provider has its own minimum prefix length, discount and expiry rules, which 03.7 owns; check them before budgeting, and recompute the estimate below with your provider's prices.

Here's the whole pipeline, provider-agnostic — the two model calls are injected so it runs without keys:

python
# s3_contextual.py — contextual retrieval pipeline (Anthropic's method).
"""Contextual retrieval (Anthropic, Sep 2024) as a provider-agnostic pipeline.

The two model calls are injected:
  - context_fn(document, chunk) -> a 50-100 token context sentence
  - embed_fn(text) -> vector          (your embedding API of choice)
BM25 scoring is implemented inline so the whole thing runs offline.
"""

import math
import re
from dataclasses import dataclass


# The prompt Anthropic published, verbatim (contextual-retrieval blog, Sep 2024).
CONTEXT_PROMPT = """<document>
{document}
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{chunk}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else."""


# ---------- a tiny BM25 (Okapi BM25, k1=1.2, b=0.75) ----------

def _tokens(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", text.lower())


def bm25_scores(query: str, docs: list[str]) -> list[float]:
    tokenized = [_tokens(d) for d in docs]
    q_terms = _tokens(query)
    n = len(docs)
    avgdl = sum(len(d) for d in tokenized) / max(n, 1)
    df: dict[str, int] = {}
    for d in tokenized:
        for t in set(d):
            df[t] = df.get(t, 0) + 1
    idf = {t: math.log(1 + (n - df[t] + 0.5) / (df[t] + 0.5)) for t in df}
    k1, b = 1.2, 0.75
    scores = []
    for d in tokenized:
        tf: dict[str, int] = {}
        for t in d:
            tf[t] = tf.get(t, 0) + 1
        dl = len(d) or 1
        s = 0.0
        for t in q_terms:
            f = tf.get(t, 0)
            if f:
                s += idf.get(t, 0.0) * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl))
        scores.append(s)
    return scores


# ---------- the pipeline ----------

@dataclass
class IndexedChunk:
    chunk_id: str
    text: str
    context: str
    embed_text: str     # what the embedding model sees
    bm25_text: str      # what BM25 indexes


def contextualize(document: str, chunks: list[str],
                  context_fn) -> list[IndexedChunk]:
    """One context_fn call per chunk. In production this is an LLM call with
    prompt caching on the document (see cost notes in the lesson)."""
    out = []
    for i, chunk in enumerate(chunks):
        ctx = context_fn(document, chunk).strip()
        out.append(IndexedChunk(
            chunk_id=f"c{i}", text=chunk, context=ctx,
            embed_text=f"{ctx}\n\n{chunk}",
            bm25_text=f"{ctx} {chunk}",
        ))
    return out


def indexing_cost(n_chunks: int, chunk_tokens: int, doc_tokens: int,
                  ctx_out_tokens: int, price_in: float, price_out: float,
                  price_cache_read: float, price_cache_write: float = 0.0) -> float:
    """Transparent version of Anthropic's $1.02/M-doc-tokens estimate.
    Prices are per million tokens. Assumes: the document is written to the
    prompt cache once (price_cache_write) and read back for every chunk
    (price_cache_read); ~50 instruction tokens + the chunk itself are fresh
    input per request; ~ctx_out_tokens of context are generated per chunk.
    n_docs = n_chunks * chunk_tokens / doc_tokens (the chunks tile the docs)."""
    n_docs = n_chunks * chunk_tokens / doc_tokens
    fresh_in = n_chunks * (50 + chunk_tokens)
    cached_in = n_chunks * doc_tokens
    out_tokens = n_chunks * ctx_out_tokens
    return (fresh_in * price_in + cached_in * price_cache_read
            + n_docs * doc_tokens * price_cache_write
            + out_tokens * price_out) / 1_000_000


# ---------- demo: a heuristic stand-in for the LLM context_fn ----------

def heuristic_context(document: str, chunk: str) -> str:
    """Free, keyless stand-in: 'This chunk is from <doc title>; it discusses <first words>'.
    Weaker than an LLM context sentence — use it to learn the pipeline, not the quality."""
    title = document.splitlines()[0].lstrip("# ").strip() or "the document"
    return f"This chunk is from {title!r}."


DOC = """# Acme Corp Q2 2025 Financial Summary

## Revenue

Acme Corp reported revenue of $4.2M in Q2 2025, up 8% year over year,
driven by the Enterprise tier.

## Margins

Gross margin held at 71%. Operating expenses rose 12% on hiring.

## Outlook

Management guided Q3 revenue to $4.5M-$4.7M."""

CHUNKS = [
    "Acme Corp reported revenue of $4.2M in Q2 2025, up 8% year over year, driven by the Enterprise tier.",
    "Gross margin held at 71%. Operating expenses rose 12% on hiring.",
    "Management guided Q3 revenue to $4.5M-$4.7M.",
]

if __name__ == "__main__":
    indexed = contextualize(DOC, CHUNKS, heuristic_context)
    for e in indexed:
        print(f"{e.chunk_id}: embed_text={e.embed_text!r}")

    q = "what was Acme's revenue in Q2 2025?"
    print("\nBM25 over contextualised text:")
    for score, e in sorted(zip(bm25_scores(q, [x.bm25_text for x in indexed]), indexed),
                           key=lambda t: -t[0]):
        print(f"  {score:.3f}  {e.text[:60]!r}")

Output (real — the BM25 math and the heuristic context run locally; an LLM context_fn would produce richer contexts):

text
c0: embed_text="This chunk is from 'Acme Corp Q2 2025 Financial Summary'.\n\nAcme Corp reported revenue of $4.2M in Q2 2025, up 8% year over year, driven by the Enterprise tier."
c1: embed_text="This chunk is from 'Acme Corp Q2 2025 Financial Summary'.\n\nGross margin held at 71%. Operating expenses rose 12% on hiring."
c2: embed_text="This chunk is from 'Acme Corp Q2 2025 Financial Summary'.\n\nManagement guided Q3 revenue to $4.5M-$4.7M."

BM25 over contextualised text:
  1.809  'Acme Corp reported revenue of $4.2M in Q2 2025, up 8% year o'
  0.942  'Management guided Q3 revenue to $4.5M-$4.7M.'
  0.418  'Gross margin held at 71%. Operating expenses rose 12% on hir'

In production, context_fn is an LLM call using CONTEXT_PROMPT with {{WHOLE_DOCUMENT}} and {{CHUNK_CONTENT}} substituted, sent through your provider of choice with the document in a cached prefix (03.7 covers the caching APIs; batch the calls per 03.9). Store context on the chunk record — you'll want it for debugging and for the "distinguish context from chunk" trick Anthropic recommends when generating answers.

3.2 Multi-vector representations#

Contextual retrieval produces one better vector per chunk. Multi-vector goes further: give each chunk several embeddings of different "views" of the same text, all pointing back to one chunk id. The classic views:

View What it is Why it helps
text The chunk itself Baseline
summary A 1–2 sentence summary Captures gist when the chunk is long or listy
question A hypothetical question the chunk answers Queries and chunks live in different "registers" — a question embedding matches a question-view better
keywords Important terms/entities extracted Cheap lexical-ish signal inside dense search

The research lineage is real: doc2query (arXiv:1904.08375, Nogueira et al. 2019) showed that appending model-predicted queries to documents improves retrieval; HyDE (arXiv:2212.10496, Gao et al. 2022, ACL 2023) showed the reverse direction — generating a hypothetical answer from the query and embedding that. Multi-vector indexing applies the same intuition symmetrically: generate the question side at index time so query-time embedding has something to match.

python
# s3_multivec.py — several embedding "views" per chunk.
"""Multi-vector representations: several 'views' of one chunk, each with
its own embedding, all pointing back to the same chunk.

Toy hashing embedder gives real cosine geometry offline; swap embed_fn for
your embedding API in production. Question/summary generators are injected.
"""

import hashlib
import math
import re
from dataclasses import dataclass

DIMS = 64


def toy_embed(text: str, dims: int = DIMS) -> list[float]:
    """Deterministic bag-of-words hashing embedder for offline demos.
    NOT a real embedding model — enough geometry to demonstrate the mechanics."""
    v = [0.0] * dims
    for tok in re.findall(r"[a-z0-9]+", text.lower()):
        h = int(hashlib.md5(tok.encode()).hexdigest(), 16)
        v[h % dims] += 1.0
        v[(h >> 8) % dims] += 0.5
    norm = math.sqrt(sum(x * x for x in v)) or 1.0
    return [x / norm for x in v]


def cosine(a: list[float], b: list[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


@dataclass
class VectorEntry:
    chunk_id: str
    view: str
    view_text: str
    vector: list[float]


def build_multivec_index(chunks: dict[str, str], views_fn, embed_fn=toy_embed) -> list[VectorEntry]:
    """views_fn(chunk_id, chunk_text) -> {view_name: view_text}.
    In production each non-'text' view is an LLM call (batch them — 03.9)."""
    index = []
    for cid, text in chunks.items():
        for view, view_text in views_fn(cid, text).items():
            index.append(VectorEntry(cid, view, view_text, embed_fn(view_text)))
    return index


def retrieve_multivec(query: str, index: list[VectorEntry], embed_fn=toy_embed,
                      top_k: int = 3) -> list[tuple[str, float, str]]:
    """Score every view vector against the query; keep the BEST view per chunk."""
    qv = embed_fn(query)
    best: dict[str, tuple[float, str]] = {}
    for e in index:
        s = cosine(qv, e.vector)
        if e.chunk_id not in best or s > best[e.chunk_id][0]:
            best[e.chunk_id] = (s, e.view)
    ranked = sorted(best.items(), key=lambda kv: -kv[1][0])[:top_k]
    return [(cid, score, view) for cid, (score, view) in ranked]


# ---------- demo data (running corpus: pricing page) ----------

CHUNKS = {
    "price-pro": "The Pro plan is $49 per month when billed annually, or $59 month-to-month. It includes unlimited projects and priority support.",
    "price-team": "The Team plan is $199 per seat per month and adds SSO and audit logs.",
    "features": "All plans include end-to-end encryption, SOC 2 Type II certification and a 99.9% uptime SLA.",
}

# Canned stand-ins for what an LLM would generate per chunk.
VIEWS = {
    "price-pro": {
        "text": CHUNKS["price-pro"],
        "question": "How much does the Pro plan cost per month?",
        "summary": "Pro plan pricing: $49/month billed annually, $59 month-to-month.",
        "keywords": "pro plan price monthly annual billing cost",
    },
    "price-team": {
        "text": CHUNKS["price-team"],
        "question": "What does the Team plan cost and what does it add?",
        "summary": "Team plan: $199/seat/month with SSO and audit logs.",
        "keywords": "team plan price seat sso audit logs",
    },
    "features": {
        "text": CHUNKS["features"],
        "question": "Which security and reliability features do all plans include?",
        "summary": "All plans: encryption, SOC 2 Type II, 99.9% uptime SLA.",
        "keywords": "encryption soc2 uptime sla security compliance",
    },
}


def canned_views(cid: str, text: str) -> dict[str, str]:
    return VIEWS[cid]


if __name__ == "__main__":
    index = build_multivec_index(CHUNKS, canned_views)
    print(f"{len(index)} vectors for {len(CHUNKS)} chunks "
          f"({len(index) // len(CHUNKS)} views each)\n")

    for q in ["how much is the pro plan?", "does the team plan include SSO?"]:
        print(f"query: {q!r}")
        for cid, score, view in retrieve_multivec(q, index):
            print(f"  {score:.3f}  {cid:<10} via {view} view")
        print()
Output · real — toy embedder, canned views11 lines
12 vectors for 3 chunks (4 views each)

query: 'how much is the pro plan?'
  0.601  price-pro  via question view
  0.336  price-team via text view
  0.079  features   via summary view

query: 'does the team plan include SSO?'
  0.545  price-team via question view
  0.400  features   via keywords view
  0.370  price-pro  via question view

Both queries were won by the question view — exactly the mechanism working: the query's phrasing matched the generated question better than the declarative chunk text. In production, views_fn calls an LLM per view per chunk (batched), embed_fn is your embedding API, and the "best view per chunk" step is a GROUP BY chunk_id / max-similarity in your vector store or a post-processing step. Hypothetical-question generation quality is the whole game — generic questions ("What is this about?") add noise; specific, answerable questions add recall.


Part 4: Late chunking, trees and propositions#

Deep-dive

Parts 2 and 3 all keep the same pipeline shape: segment → embed each chunk independently → optionally expand at query time. Part 4 changes the embedding step itself or the unit of indexing: late chunking lets the embedding model see the whole document before producing chunk vectors; RAPTOR builds a tree of LLM summaries you can retrieve at any level; propositions throw away the chunk and index atomic facts instead.

4.1 Late chunking#

Late chunking (Jina AI, arXiv:2409.04701, September 2024) exploits a property of long-context embedding models: their token-level representations are contextual — a token's vector already encodes the whole document around it. Naive chunking throws that away by embedding each chunk in isolation. Late chunking instead:

  1. Runs the transformer over the entire document (or the largest piece that fits the model's context), producing one vector per token.
  2. Applies mean pooling within each chunk's token span — so each chunk vector is the average of contextualised token vectors.

The chunking happens after the transformer ("late"), just before pooling. Chunk boundaries still matter — they define the pooling spans — but every token vector inside a span already "knows" the document, so pronouns, cross-references and implicit subjects resolve.

flowchart LR
    subgraph early ["Early/naive chunking"]
        E1["chunk text"] --> E2["embed chunk alone"] --> E3["vector per chunk"]
    end
    subgraph late ["Late chunking"]
        L1["whole document"] --> L2["transformer<br/>one vector per token"] --> L3["mean-pool each<br/>chunk's token span"] --> L4["vector per chunk"]
    end

Which models support it (as of November 2026):

Provider / model Mechanism Context Notes
Jina jina-embeddings-v3 late_chunking: true API parameter 8,192 tokens total per request Concatenates input sentences, embeds once, returns per-sentence vectors
Jina jina-embeddings-v4 late_chunking support + multi-vector output 32,768 tokens Released June 2025; 3.8B params; 2048-dim dense / 128-dim multi-vector; task LoRAs (retrieval, text-matching, code); Qwen Research License — non-commercial use only; Jina states no commercial licence is available
Jina jina-embeddings-v5-text-small / -nano Not documented as supporting late_chunking (as of November 2026) 32,768 / 8,192 tokens Released February 2026; 1024-dim default; weights under CC BY-NC 4.0 (commercial self-hosting needs a licence from Elastic, which now sells Jina On-Prem; the hosted API is covered by Jina's service terms). The long context makes the mechanism possible in principle, but check the current API reference before relying on it
Voyage voyage-context-3 Contextualized chunk embeddings endpoint (you pass each document's chunks as a list) 120K-token documents, 32K per-chunk context window Released July 2025; designed as a drop-in for standard embeddings
Voyage voyage-context-4 Same endpoint family; Voyage's docs recommend it over -3 32K tokens per request; the 120K limit applies only when you turn on auto-chunking (send whole documents, Voyage splits them) Dims 1024 (default)/256/512/2048; per-chunk window 32K
Hosted OpenAI / Google embedding APIs — — Return one vector per input — no per-token vectors, which late chunking requires; check each provider's current embedding docs before assuming

What late chunking is not. Jina's own explainer (Part II) is blunt about the limits, and they are worth keeping in mind: it is not a boundary-finding method (you still choose where to cut — it only makes the choice matter less for the vector); it needs token-level outputs, long-context support and mean pooling, so it does not apply to single-vector APIs, short-context models or CLS- or max-pooled models; and the gain depends on the embedding model — Jina reports no case where a weaker model with late chunking beat a stronger model without it. Those results are Jina's own benchmarks on a limited set of datasets. An independent comparison (Merola and Singh, arXiv:2504.19754, April 2025) found contextual retrieval kept semantic coherence better but cost more compute, while late chunking was more efficient but tended to lose some relevance and completeness. Read Part 6's section 6.5 for how to weigh this kind of evidence.

For documents longer than the model's context, Jina describes "long late chunking": split into overlapping macro-chunks that each fit the context window, embed each, then pool within the real chunk spans — boundaries get a small amount of duplicated context at macro-chunk edges.

The mechanism is easy to simulate offline. This demo fakes the contextualised token vectors (each token vector = its own hash + a share of the document centroid, standing in for what a transformer bakes in) and does the pooling and cosine maths for real:

python
# s4_late_chunk.py — late chunking mechanism, simulated with a toy embedder.
"""Late chunking, simulated with a toy embedder.

A real late-chunking embedder (jina-embeddings-v3/v4, voyage-context-3/4)
runs the transformer over the whole document ONCE, producing one vector per
token that already 'sees' the full context, then mean-pools the token
vectors inside each chunk's span.

We can't run a real embedding model here, so this demo fakes the mechanism:
each token vector = its own hash vector + a share of the whole document's
centroid (the 'context' the transformer would have baked in). The pooling
and cosine maths are real; the numbers are illustrative of the MECHANISM,
not of any model's quality.
"""

import hashlib
import math
import re

DIMS = 32
ALPHA = 0.4   # how much document context each token vector carries


def _hash_vec(text: str, dims: int = DIMS) -> list[float]:
    v = [0.0] * dims
    for tok in re.findall(r"[a-z0-9]+", text.lower()):
        h = int(hashlib.md5(tok.encode()).hexdigest(), 16)
        v[h % dims] += 1.0
        v[(h >> 8) % dims] += 0.5
    norm = math.sqrt(sum(x * x for x in v)) or 1.0
    return [x / norm for x in v]


def _add(a, b, w=1.0):
    return [x + w * y for x, y in zip(a, b)]


def _norm(v):
    n = math.sqrt(sum(x * x for x in v)) or 1.0
    return [x / n for x in v]


def doc_centroid(text: str) -> list[float]:
    """Mean of every token's base vector in the document — stands in for the
    contextual information a long-context transformer bakes into each token."""
    toks = re.findall(r"[a-z0-9]+", text.lower())
    acc = [0.0] * DIMS
    for t in toks:
        acc = _add(acc, _hash_vec(t))
    return _norm([x / len(toks) for x in acc])


def late_token_vectors(text: str, centroid: list[float]) -> list[list[float]]:
    """One vector per token, each already contextualised by the document."""
    return [_norm(_add(_hash_vec(t), centroid, ALPHA))
            for t in re.findall(r"[a-z0-9]+", text.lower())]


def mean_pool(vectors: list[list[float]]) -> list[float]:
    if not vectors:
        return [0.0] * DIMS
    acc = [sum(v[i] for v in vectors) / len(vectors) for i in range(DIMS)]
    return _norm(acc)


def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))


# ---------- the demo ----------

DOCUMENT = """# Pricing

## Pro plan
The Pro plan is our mid-tier offering for growing teams.
It costs $49 per month billed annually.

## Team plan
The Team plan is for larger groups with shared workspaces.
It costs $199 per seat per month."""

CHUNKS = [
    "The Pro plan is our mid-tier offering for growing teams.",
    "It costs $49 per month billed annually.",
    "It costs $199 per seat per month.",
]

QUERY = "how much does the pro plan cost?"

if __name__ == "__main__":
    centroid = doc_centroid(DOCUMENT)
    qv = _hash_vec(QUERY)

    print(f"query: {QUERY!r}\n")
    for i, chunk in enumerate(CHUNKS):
        early = _hash_vec(chunk)                                   # embed chunk alone
        span = late_token_vectors(chunk, centroid)
        late = mean_pool(span)                                     # pool contextual tokens
        print(f"chunk {i}: {chunk[:60]!r}")
        print(f"  cosine(early, query) = {cosine(early, qv):.3f}")
        print(f"  cosine(late,  query) = {cosine(late,  qv):.3f}\n")

Output (real computation on the toy embedder — read it as a mechanism illustration, not model quality):

text
query: 'how much does the pro plan cost?'

chunk 0: 'The Pro plan is our mid-tier offering for growing teams.'
  cosine(early, query) = 0.704
  cosine(late,  query) = 0.681

chunk 1: 'It costs $49 per month billed annually.'
  cosine(early, query) = 0.196
  cosine(late,  query) = 0.406

chunk 2: 'It costs $199 per seat per month.'
  cosine(early, query) = 0.204
  cosine(late,  query) = 0.418

Two things to take from this. The pronoun chunks ("It costs…") roughly doubled their query similarity under late chunking — document context flowed into the chunk vector. But note chunk 0 lost a little (0.704 → 0.681): document context also dilutes chunks that were already self-contained. And the toy embedder can't tell which "It" is Pro versus Team — both rose similarly; a real model resolves the anaphora properly. So late chunking is most likely to help when your embedder supports it and your documents have cross-chunk references, and neutral-to-slightly-negative when chunks are already self-contained. Even then, treat it as a hypothesis to test on your own questions (Part 7), not a free upgrade.

4.2 RAPTOR and summary trees#

RAPTOR (Sarthi et al., Stanford, ICLR 2024) takes the hierarchy idea to its logical end: instead of storing the document's own structure, it builds an abstraction tree with an LLM. Leaves are your normal chunks; each level clusters neighbouring chunks, asks an LLM to summarise each cluster, and treats the summaries as the next level's nodes. Repeat until one root remains. At query time you embed every node — leaves and summaries — and can retrieve a high-level summary for overview questions ("what are the main themes of this report?") or drill to leaves for detail.

flowchart TD
    subgraph L0 ["Level 0 — leaves (your chunks)"]
        a["c1: warranty covers motor…"] & b["c2: excludes wear items…"] & c["c3: register within 30 days…"]
        d["c4: 45-day returns…"] & e["c5: defective only…"] & f["c6: customer pays shipping…"]
    end
    subgraph L1 ["Level 1 — cluster summaries"]
        s1["Summary: warranty scope & claims process"] & s2["Summary: return policy & conditions"]
    end
    subgraph L2 ["Level 2 — root"]
        r["Summary: tool warranty & returns overview"]
    end
    a & b & c --> s1
    d & e & f --> s2
    s1 & s2 --> r

The paper reports strong gains on multi-step reasoning QA — coupling RAPTOR retrieval with GPT-4 improved the best QuALITY benchmark score by 20% absolute — but be honest about the costs: one LLM summarisation call per cluster per level (for N chunks and fan-out k, roughly N/k + N/k² + … calls), summary hallucination/drift at higher levels, and a corpus that must be re-summarised whenever chunks change. RAPTOR earns its keep on long documents that attract overview and synthesis questions; for factoid lookup over heterogeneous corpora it is usually overkill. Cluster with embeddings or a cheap algorithm (the paper uses Gaussian-mixture clustering); don't pay an LLM to cluster.

The build side is small enough to own. This demo clusters consecutive chunks (a stand-in for real clustering) and uses a first-sentence extractor as the summariser stand-in — the tree shape and bookkeeping are real, the summaries are illustrative:

python
# s4_raptor.py — RAPTOR-style summary tree, build side only.
"""RAPTOR-style summary tree, build side only.

Leaves are your normal chunks. Each level clusters neighbouring leaves and
replaces each cluster with an LLM-written summary; repeat until one root.
Retrieval embeds EVERY node (leaves + summaries) and can return a summary
for overview questions or leaves for detail questions.

summarize_fn is injected (LLM call in production). The demo stand-in just
joins first sentences — illustrative, not a real summary.
"""

from dataclasses import dataclass, field
import re


@dataclass
class Node:
    node_id: str
    text: str
    level: int                 # 0 = leaf chunks, higher = more abstract
    children: list[str] = field(default_factory=list)
    chunk_id: str | None = None  # set on leaves: the chunk this node came from


def build_raptor_tree(chunks: list, fanout: int, summarize_fn,
                      node_prefix: str = "n") -> tuple[list[Node], dict]:
    """chunks: objects with .chunk_id and .text. Returns all nodes + id->node."""
    nodes: list[Node] = []
    for i, c in enumerate(chunks):
        nodes.append(Node(f"{node_prefix}L{i}", c.text, 0,
                          children=[], chunk_id=c.chunk_id))

    level = 0
    frontier = list(range(len(nodes)))   # indices into `nodes` at current level
    while len(frontier) > 1:
        level += 1
        next_frontier = []
        for g in range(0, len(frontier), fanout):
            group = frontier[g:g + fanout]
            if len(group) == 1:
                next_frontier.extend(group)   # carry singletons up unchanged
                continue
            text = "\n".join(nodes[i].text for i in group)
            summary = summarize_fn(text).strip()
            nid = f"{node_prefix}{level}_{g // fanout}"
            nodes.append(Node(nid, summary, level,
                              children=[nodes[i].node_id for i in group]))
            next_frontier.append(len(nodes) - 1)
        frontier = next_frontier
    return nodes, {n.node_id: n for n in nodes}


def first_sentence_summary(text: str) -> str:
    """Stand-in for the LLM summariser: first sentence only — NOT a real summary.
    Node texts are newline-joined, so split on whitespace after terminal
    punctuation rather than the '. ' pair (which never appears across \n)."""
    first = re.split(r"(?<=[.!?])\s", text, maxsplit=1)[0].strip()
    return first if first.endswith((".", "!", "?")) else first + "."


# ---------- demo: the warranty/returns/battery handbook ----------

class FakeChunk:
    def __init__(self, cid, text):
        self.chunk_id, self.text = cid, text


LEAVES = [FakeChunk(f"h{i}", t) for i, t in enumerate([
    "Every Acme Drill carries a two-year limited warranty against defects in materials and workmanship.",
    "The warranty covers the motor, chuck and battery pack but excludes wear items such as drill bits.",
    "To make a claim, register the tool within 30 days of purchase and keep your receipt.",
    "Unused tools may be returned within 45 days for a full refund.",
    "Opened power tools can only be returned if defective; contact support for a return authorisation number.",
    "Shipping costs on change-of-mind returns are paid by the customer.",
])]

if __name__ == "__main__":
    nodes, by_id = build_raptor_tree(LEAVES, fanout=3, summarize_fn=first_sentence_summary)
    for n in nodes:
        kids = ", ".join(n.children) if n.children else "-"
        print(f"{n.node_id:<8} L{n.level}  children=[{kids}]")
        print(f"         {n.text[:80]!r}")

Output (real — the stand-in "summaries" are first sentences, labelled illustrative):

text
nL0      L0  children=[-]
         'Every Acme Drill carries a two-year limited warranty against defects in material'
nL1      L0  children=[-]
         'The warranty covers the motor, chuck and battery pack but excludes wear items su'
nL2      L0  children=[-]
         'To make a claim, register the tool within 30 days of purchase and keep your rece'
nL3      L0  children=[-]
         'Unused tools may be returned within 45 days for a full refund.'
nL4      L0  children=[-]
         'Opened power tools can only be returned if defective; contact support for a retu'
nL5      L0  children=[-]
         'Shipping costs on change-of-mind returns are paid by the customer.'
n1_0     L1  children=[nL0, nL1, nL2]
         'Every Acme Drill carries a two-year limited warranty against defects in material'
n1_1     L1  children=[nL3, nL4, nL5]
         'Unused tools may be returned within 45 days for a full refund.'
n2_0     L2  children=[n1_0, n1_1]
         'Every Acme Drill carries a two-year limited warranty against defects in material'

4.3 Propositional and atomic-fact chunking#

The finest granularity in the literature is the proposition: an atomic expression that encapsulates one distinct fact, self-contained enough to stand alone. Dense X Retrieval (Chen et al., EMNLP 2024) systematically compared retrieval units — document, passage, sentence, proposition — and found proposition-level indexing significantly outperformed passage-level for both retrieval and downstream QA under a fixed compute budget. Their pipeline fine-tuned a FlanT5-Large model ("propositionizer" — weights on Hugging Face) to decompose passages into propositions; the resulting FactoidWiki indexed English Wikipedia at ~257M propositions.

Why it works is the same small-to-big argument pushed to the limit: the smallest possible self-contained unit embeds most precisely, and expansion back to the parent section restores context at query time. The risks are equally clear: proposition counts run roughly 2–3× sentence count — and ≈6× passage count — in the paper's own FactoidWiki index (257M propositions vs 114M sentences vs 41M passages on the same Wikipedia dump), so index size and embedding cost grow accordingly; narrative answers lose flow (mitigate with parent expansion); and decomposition can silently drop facts — so measure coverage.

python
# s4_propositions.py — atomic-fact (proposition-level) indexing units.
"""Propositional (atomic-fact) chunking.

decompose_fn is injected: in production an LLM rewrites each section into
self-contained atomic propositions (Dense X Retrieval, EMNLP 2024). Each
proposition becomes a retrievable unit that still knows its parent section.
"""

import re
from dataclasses import dataclass, field


@dataclass
class Chunk:
    chunk_id: str
    doc_id: str
    index: int
    text: str
    kind: str = "proposition"
    parent_id: str | None = None
    section_path: str = ""
    meta: dict = field(default_factory=dict)


def proposition_chunks(doc_id: str, section_path: str, section_text: str,
                       decompose_fn, base_index: int = 0) -> list[Chunk]:
    """One chunk per proposition; parent_id points back at the section."""
    props = [p.strip() for p in decompose_fn(section_text) if p.strip()]
    return [
        Chunk(chunk_id=f"{doc_id}:{section_path}:{base_index + i}",
              doc_id=doc_id, index=base_index + i, text=p,
              parent_id=f"{doc_id}:{section_path}", section_path=section_path)
        for i, p in enumerate(props)
    ]


def coverage(section_text: str, props: list[str]) -> float:
    """Fraction of the section's content words that appear in >=1 proposition.
    A crude completeness check: propositions shouldn't silently drop facts."""
    words = {w for w in re.findall(r"[a-z0-9]+", section_text.lower())
             if len(w) > 3}
    prop_words = {w for p in props for w in re.findall(r"[a-z0-9]+", p.lower())}
    return len(words & prop_words) / max(len(words), 1)


# ---------- demo ----------

SECTION = ("Section 4.2 — Returns. Unused tools may be returned within 45 days "
           "for a full refund. Opened power tools can only be returned if they "
           "are defective, and a return authorisation number is required. "
           "Shipping costs on change-of-mind returns are paid by the customer.")

# Canned stand-in for the LLM decomposition (illustrative).
CANNED_PROPOSITIONS = [
    "Unused Acme tools may be returned within 45 days for a full refund.",
    "Opened power tools can only be returned if they are defective.",
    "A return authorisation number is required for defective opened tools.",
    "The customer pays shipping costs on change-of-mind returns.",
]


def demo_decompose(text: str) -> list[str]:
    return CANNED_PROPOSITIONS


if __name__ == "__main__":
    chunks = proposition_chunks("handbook", "Returns", SECTION, demo_decompose)
    for c in chunks:
        print(f"{c.chunk_id}\n  parent={c.parent_id}\n  {c.text}\n")
    print(f"word coverage of section by propositions: "
          f"{coverage(SECTION, CANNED_PROPOSITIONS):.0%}")
Output · real — canned propositions, real coverage math17 lines
handbook:Returns:0
  parent=handbook:Returns
  Unused Acme tools may be returned within 45 days for a full refund.

handbook:Returns:1
  parent=handbook:Returns
  Opened power tools can only be returned if they are defective.

handbook:Returns:2
  parent=handbook:Returns
  A return authorisation number is required for defective opened tools.

handbook:Returns:3
  parent=handbook:Returns
  The customer pays shipping costs on change-of-mind returns.

word coverage of section by propositions: 92%

In production decompose_fn is an LLM call with a prompt like "Rewrite the text as a list of atomic, self-contained propositions — one fact each, resolve all pronouns and references explicitly, keep numbers and named entities exact." Each proposition is embedded and pointed at its parent section; at query time you expand hits back to the parent exactly as in Part 2. The decomposition prompt is worth iterating on: propositions that keep referents explicit ("the Pro plan", not "it") are what make them independently retrievable.


Part 5: Document-specific recipes#

Every recipe below is the same three-step shape: parse the document's own structure into Blocks → pack blocks into chunks → attach the metadata retrieval and citation need. First the shared toolkit — save the block below as blocks.py; every recipes/*.py snippet that follows is a complete file (it shows the import/from blocks import … lines it needs). Python puts the script's own directory on sys.path, so from blocks import … only resolves when blocks.py sits beside the recipe that imports it: either save blocks.py inside recipes/ as well and run python3 recipes/legal.py, or ignore the recipes/ prefix and keep every file flat in one directory.

Each recipe ends with a worked example: a short input and its output. The input call is a snippet you paste under an if __name__ == "__main__": guard (or into a Python prompt) after the recipe file's code; the Output: blocks print one line per block or chunk — roughly kind, level, a metadata dict and the first 60 or so characters of repr(text) — using a three-line for loop you can write yourself. They are shortened renderings, not the raw object dumps.

python
# blocks.py — shared toolkit for the document-specific recipes (lesson 05.7).
"""blocks.py — shared toolkit for the document-type recipes (lesson 05.7).
A Block is a typed piece of document; blocks_to_chunks packs them without
breaking structural units. Pure stdlib."""

import hashlib
import re
from dataclasses import dataclass, field


@dataclass
class Block:
    kind: str                       # heading|para|list|code|table|clause|qa|turn|record|figure|caption|footnote|equation|email
    text: str
    level: int = 0                  # heading/clause depth
    meta: dict = field(default_factory=dict)


@dataclass
class RChunk:
    chunk_id: str
    doc_id: str
    index: int
    text: str
    kind: str = "chunk"
    section_path: str = ""        # "> "-joined heading breadcrumb
    prev_id: str | None = None    # neighbour pointers — filled by blocks_to_chunks
    next_id: str | None = None    #   (05.6 calls them prev_chunk_id/next_chunk_id)
    parent_id: str | None = None  # hierarchical recipes set this (Part 2 pattern)
    token_count: int | None = None   # filled downstream by your tokenizer (03.7)
    char_start: int | None = None    # source offsets when the parser supplies them
    char_end: int | None = None      #   (05.2/05.3 ParsedDocument)
    embed_text: str | None = None    # optional override, as in 05.6's Chunk
    meta: dict = field(default_factory=dict)

    def embed_input(self) -> str:
        """What the embedding model should see — the same contract as 05.6's
        Chunk.embed_input(): the section_path breadcrumb prepended to `text`.
        Embed THIS, not bare `text`: heading text ("Refund policy",
        "ARTICLE I") lives only in section_path, so embedding `text` alone
        loses every heading from the index. Enrichment prefixes (contextual
        retrieval, multi-vector views) prepend on top of this."""
        if self.embed_text:
            return self.embed_text
        crumb = self.section_path
        return f"{crumb}\n\n{self.text}" if crumb else self.text


def _sentences(text: str) -> list[str]:
    return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]


def split_long(text: str, max_chars: int) -> list[str]:
    """Split an over-size block: paragraphs first, then sentences, then hard cut."""
    pieces, buf = [], ""
    for para in re.split(r"\n\s*\n", text):
        for sent in _sentences(para):
            cand = sent if not buf else f"{buf} {sent}"
            if len(cand) > max_chars and buf:
                pieces.append(buf)
                buf = sent
            else:
                buf = cand
    if buf:
        pieces.append(buf)
    out = []
    for p in pieces:
        while len(p) > max_chars:
            out.append(p[:max_chars])
            p = p[max_chars:]
        if p:
            out.append(p)
    return out


HARD_KINDS = {"code", "table", "clause", "qa", "record", "figure", "email",
              "turn_window", "equation", "caption", "module_header"}


def _boundary(buf_kinds: list[str], kind: str) -> bool:
    """True when a chunk boundary is required between buf and this block kind."""
    buf_hard = {k for k in buf_kinds if k in HARD_KINDS}
    if not buf_hard and kind not in HARD_KINDS:
        return False                       # soft + soft: pack freely
    if kind in HARD_KINDS and buf_hard == {kind}:
        return False                       # same hard kind continues
    if not buf_hard:
        return bool(buf_kinds)             # soft buf + hard newcomer: isolate it
    return True                            # buf holds a hard kind, new differs


def blocks_to_chunks(doc_id: str, blocks: list[Block], max_chars: int = 1200,
                     strategy: str = "blocks-v1") -> list[RChunk]:
    """Pack blocks into chunks. Structural kinds (HARD_KINDS) never mix with a
    different kind. Heading path becomes the section_path breadcrumb."""
    chunks: list[RChunk] = []
    buf, buf_meta, buf_kinds = "", {}, []
    headings: list[tuple[int, str]] = []

    def flush():
        nonlocal buf, buf_meta, buf_kinds
        if buf.strip():
            path = " > ".join(t for _, t in headings)
            cid = f"{doc_id}:{strategy}:{len(chunks):04d}-" + \
                  hashlib.sha256(buf.encode()).hexdigest()[:8]
            chunks.append(RChunk(cid, doc_id, len(chunks), buf.strip(),
                                 kind="+".join(sorted(set(buf_kinds))),
                                 section_path=path, meta=dict(buf_meta)))
        buf, buf_meta, buf_kinds = "", {}, []

    for b in blocks:
        if b.kind == "heading":
            flush()
            while headings and headings[-1][0] >= b.level:
                headings.pop()
            headings.append((b.level, b.text.strip()))
            continue
        piece = b.text.strip()
        if not piece:
            continue
        if len(piece) > max_chars:
            flush()
            for part in split_long(piece, max_chars):
                path = " > ".join(t for _, t in headings)
                cid = f"{doc_id}:{strategy}:{len(chunks):04d}-" + \
                      hashlib.sha256(part.encode()).hexdigest()[:8]
                chunks.append(RChunk(cid, doc_id, len(chunks), part,
                                     kind=b.kind, section_path=path,
                                     meta=dict(b.meta)))
            continue
        cand = f"{buf}\n\n{piece}" if buf else piece
        if buf and (len(cand) > max_chars or _boundary(buf_kinds, b.kind)):
            flush()
            buf = piece
        else:
            buf = cand
        buf_kinds.append(b.kind)
        buf_meta.update(b.meta)
    flush()
    # neighbour pointers over the finished sequence — Part 2's window_expand
    # and the eval harness consume these unchanged
    for i, c in enumerate(chunks):
        c.prev_id = chunks[i - 1].chunk_id if i else None
        c.next_id = chunks[i + 1].chunk_id if i + 1 < len(chunks) else None
    return chunks

Two contracts make recipe output compose with the rest of this lesson (and with 05.6's Chunk):

  • embed_input() folds section_path into the embedded text — headings are retrieval signal, but they are not part of text (that would pollute display and BM25). Always embed c.embed_input(), never c.text.
  • Pointers — blocks_to_chunks fills prev_id/next_id over the chunk sequence, so query-time expansion (2.3) works unchanged. parent_id, token_count and char_start/char_end stay unset here on purpose: hierarchical recipes (chapter→section) set parent_id themselves, and offsets/token counts come from the parser and tokenizer downstream (05.2/05.3, 03.7).

All worked examples below were produced by running this code on the toy inputs shown beside each output; outputs are real.

Contracts are numbered hierarchies — clauses (12.1, 12.1.1), articles, schedules — and the numbering is the structure. The recipe keeps each clause whole (cross-references like "subject to Section 8.2" only resolve if the referenced clause is retrievable intact), preserves the hierarchy as level, and lets the breadcrumb carry "Article II > 12.1".

python
# recipes/legal.py — clause-aware segmentation for contracts.
import re
from blocks import Block

_CLAUSE_RE = re.compile(r"(?m)^\s*(\d+(?:\.\d+)*)([.\)])?\s+(?=[A-Z\"“'])")
_ARTICLE_RE = re.compile(r"(?im)^\s*(ARTICLE|SECTION|SCHEDULE|EXHIBIT)\s+([IVXLC0-9]+|[A-Z])\b[:.\-—]?\s*(.*)$")


def legal_blocks(text: str) -> list[Block]:
    """Each numbered clause -> one block, level = numbering depth;
    articles/schedules -> headings."""
    blocks: list[Block] = []
    marks = []
    for m in _ARTICLE_RE.finditer(text):
        marks.append((m.start(), "heading", m.group(0).strip()))
    for m in _CLAUSE_RE.finditer(text):
        marks.append((m.start(), "clause", m.group(1)))
    marks.sort()
    seen, unique = set(), []
    for pos_, kind, label in marks:
        if pos_ not in seen:
            seen.add(pos_)
            unique.append((pos_, kind, label))
    for i, (start, kind, label) in enumerate(unique):
        end = unique[i + 1][0] if i + 1 < len(unique) else len(text)
        body = text[start:end].strip()
        if kind == "heading":
            lvl = 0 if any(w in label.upper() for w in ("SCHEDULE", "EXHIBIT")) else 1
            blocks.append(Block("heading", label.split(".")[0].strip()[:80], level=lvl))
            rest = body[len(label):].strip()
            if rest:
                blocks.append(Block("para", rest))
        else:
            blocks.append(Block("clause", body, level=label.count(".") + 1,
                                meta={"clause_no": label}))
    return blocks

# usage: chunks = blocks_to_chunks(doc_id, legal_blocks(contract_text), strategy="legal-v1")

Worked example — input (a toy contract excerpt):

text
ARTICLE I — DEFINITIONS
1.1 "Affiliate" means any entity controlling, controlled by, or under common control with a party.
1.2 "Confidential Information" means all non-public information disclosed by either party.

ARTICLE II — OBLIGATIONS
2.1 Each party shall hold Confidential Information in strict confidence.
2.1.1 This obligation survives termination for five years.

SCHEDULE A — FEES
The annual licence fee is $10,000 payable each January.
Output · — the blocks legal_blocks produces8 lines
kind=heading  lvl=1 clause=-      'ARTICLE I — DEFINITIONS'
kind=clause   lvl=2 clause=1.1    '1.1 "Affiliate" means any entity controlling, controlled by,'
kind=clause   lvl=2 clause=1.2    '1.2 "Confidential Information" means all non-public informat'
kind=heading  lvl=1 clause=-      'ARTICLE II — OBLIGATIONS'
kind=clause   lvl=2 clause=2.1    '2.1 Each party shall hold Confidential Information in strict'
kind=clause   lvl=3 clause=2.1.1  '2.1.1 This obligation survives termination for five years.'
kind=heading  lvl=0 clause=-      'SCHEDULE A — FEES'
kind=para     lvl=0 clause=-      'The annual licence fee is $10,000 payable each January.'

Pitfalls: naive numbering regexes false-positive on cross-references and dates ("Section 12.3 requires…", "3.5 million units") — require the number at line start followed by a capital or defined-term quote, and consider the document's own numbering style. Definitions ("“X” means…") deserve their own chunk kind so a query for a defined term lands on the definition, not just clauses that use it. Keep entire clauses whole even when long — splitting a clause mid-sentence breaks the referent. Store clause_no in metadata for citations ("see clause 12.1.1").

5.2 Technical documentation and API docs#

Docs sites and API references are heading trees with code samples that must stay intact. The recipe: headings → heading blocks (level = depth), fenced code → code blocks (never split — HARD_KINDS isolates them), parameter lists and endpoint signatures kept with their section, and version/product_area attached as metadata since docs are versioned.

python
# recipes/techdocs.py — Markdown-ish docs -> blocks (same parser serves
# Markdown wikis, READMEs and most docs-site exports). Tilde fences (~~~)
# are valid CommonMark too, so both are recognised.
import re
from blocks import Block


def md_blocks(text: str) -> list[Block]:
    """Headings, fenced code, lists, tables, quotes, paragraphs -> Blocks.
    Consecutive list items become ONE list block and consecutive table rows ONE
    table block, so a table or a bullet list is never torn apart row by row."""
    blocks: list[Block] = []
    para: list[str] = []
    run: list[str] = []          # current run of list items or table rows
    run_kind = ""
    in_fence = False
    fence_buf: list[str] = []
    fence = ""

    def flush_para():
        if para:
            blocks.append(Block("para", "\n".join(para)))
            para.clear()

    def flush_run():
        nonlocal run_kind
        if run:
            blocks.append(Block(run_kind, "\n".join(run)))
            run.clear()
        run_kind = ""

    def add_run(kind: str, line: str):
        nonlocal run_kind
        flush_para()
        if run_kind != kind:
            flush_run()
            run_kind = kind
        run.append(line)

    for line in text.splitlines():
        s = line.strip()
        bt = chr(96) * 3   # backtick fence, built without literal backticks
        if not in_fence and (s.startswith(bt) or s.startswith("~~~")):
            flush_para()
            flush_run()
            in_fence = True
            fence = s[0] * 3
            continue
        if in_fence and s.startswith(fence):
            blocks.append(Block("code", "\n".join(fence_buf)))
            fence_buf = []
            in_fence = False
            continue
        if in_fence:
            fence_buf.append(line)
            continue
        m = re.match(r"^(#{1,6})\s+(.*)", line)
        if m:
            flush_para()
            flush_run()
            blocks.append(Block("heading", m.group(2).strip(), level=len(m.group(1))))
        elif re.match(r"^\s*([-*+]|\d+[.)])\s+", line):
            add_run("list", s)
        elif s.startswith("|") and s.count("|") >= 2:
            # CommonMark tables may omit the trailing pipe ("| a | b"), so a
            # row only needs a leading pipe plus one more -- not a closing one.
            add_run("table", s)
        elif s.startswith(">"):
            flush_para()
            flush_run()
            blocks.append(Block("quote", s.lstrip("> ")))
        elif s:
            flush_run()
            para.append(line.rstrip())
        else:
            flush_para()
            flush_run()
    flush_para()
    flush_run()
    if fence_buf:
        blocks.append(Block("code", "\n".join(fence_buf)))
    return blocks

# chunks = blocks_to_chunks(doc_id, md_blocks(doc_text), strategy="md-v1")
# then stamp meta={"doc_version": "2025.2", "product": "billing"} on each chunk

Worked example — input (toy Markdown; the ~~~ fence is valid CommonMark and md_blocks accepts both fence styles):

text
# Refund policy

Customers may request a refund within 30 days.

## Exceptions

- Digital goods are non-refundable once downloaded.
- Gift cards never expire.

| Item | Window |
|---|---|
| Tools | 45 days |

~~~python
refund = min(amount, cap)
~~~

Output — blocks_to_chunks("docs", md_blocks(text), max_chars=200), printed one line per chunk as [kind] path=<breadcrumb> :: <first 60 characters>:

text
[para] path='Refund policy' :: 'Customers may request a refund within 30 days.'
[list] path='Refund policy > Exceptions' :: '- Digital goods are non-refundable once downloaded.\n- Gift c'
[table] path='Refund policy > Exceptions' :: '| Item | Window |\n|---|---|\n| Tools | 45 days |'
[code] path='Refund policy > Exceptions' :: 'refund = min(amount, cap)'

Pitfalls: code fences must never be split — a half-function embeds as nonsense and retrieves as noise; if a code block exceeds max_chars, keep it whole or split at statement boundaries with tree-sitter (5.5). Table detection is deliberately shallow — any line starting with | and containing a second | becomes a table block, with or without a |---| delimiter row, so a stray pipe-led prose line will be misread; normalise tables upstream (a good HTML→Markdown converter emits clean pipe rows) rather than teaching the chunker to guess. Versioned docs need version in metadata or the 2024 and 2026 versions of the same page pollute each other's results. API docs: keep each endpoint's parameter table with its description — orphaning "limit (integer, optional)" from "GET /v1/items" makes it unanswerable. Note that blocks_to_chunks isolates table and code blocks from the prose before them (the HARD_KINDS rule), so a table lands in its own chunk; the breadcrumb ("API > GET /v1/items") then carries the endpoint name, and if the lead-in sentence matters, copy it into the table block's text before packing.

5.3 Scientific papers#

(For PDF papers parsed with Docling or Unstructured, compare this recipe with the library chunkers in 05.6, section 4.5.1 — they keep headings and tables as typed elements.)

Papers have rigid structure: abstract, numbered sections (1., 1.1), captions ("Figure 2:", "Table 3:"), equations, and references. The recipe treats numbered headings as structure, keeps captions adjacent to their content, isolates equations, and puts references in their own chunks (they're lookup targets, not prose).

python
# recipes/papers.py
import re
from blocks import Block

_PAPER_SEC_RE = re.compile(r"(?m)^\s*(\d+(?:\.\d+)*)(?:\.)?\s{1,3}([A-Z][A-Za-z &\-]{2,60})\s*$")
_CAPTION_RE = re.compile(r"(?im)^\s*(Figure|Fig\.?|Table|Algorithm)\s+\d+[:\.\-]?\s*(.*)$")
# display-math markers only: "$$...$$", "\[...\]", "\(...\)", \begin{equation|align|gather}.
# Deliberately NOT "$...$" — "Costs $5 and $10" is currency, not an equation.
_EQUATION_RE = re.compile(
    r"\$\$|\\\[|\\\(|\\begin\{(?:equation|align\*?|gather\*?|multline)\}")


def paper_blocks(text: str) -> list[Block]:
    """Numbered sections -> headings; a caption line opens a 'caption' block
    that also absorbs the description lines beneath it (blank line ends it) —
    a caption without its figure/table text is a half-answer; display-math
    lines -> 'equation'; abstract/references -> headings."""
    blocks: list[Block] = []
    para: list[str] = []
    cap: list[str] = []

    def flush_para():
        if para:
            blocks.append(Block("para", "\n".join(para).strip()))
            para.clear()

    def flush_cap():
        if cap:
            blocks.append(Block("caption", "\n".join(cap).strip()))
            cap.clear()

    for line in text.splitlines():
        s = line.strip()
        is_special_head = bool(
            re.match(r"(?i)^(abstract|keywords?|references|appendix)\b", s)
            and len(s) < 60)
        is_sec_head = bool(_PAPER_SEC_RE.match(s) and len(s) < 70)
        if is_special_head or is_sec_head:
            flush_para()
            flush_cap()
            if is_special_head:
                blocks.append(Block("heading", s.rstrip(".:"), level=1))
            else:
                m = _PAPER_SEC_RE.match(s)
                blocks.append(Block("heading", f"{m.group(1)} {m.group(2).strip()}",
                                    level=m.group(1).count(".") + 1))
        elif _CAPTION_RE.match(s):
            flush_para()
            flush_cap()
            cap.append(s)                       # description lines join below
        elif _EQUATION_RE.search(s):
            flush_para()
            flush_cap()
            blocks.append(Block("equation", s))
        elif s:
            (cap if cap else para).append(s)    # open caption absorbs its description
        else:
            flush_para()
            flush_cap()
    flush_para()
    flush_cap()
    return blocks

Worked example — input (toy paper excerpt; note the currency line and the caption+description pair):

text
1. Introduction
Transformers changed NLP. Serving costs $5 and $10 per unit depending on tier.

1.1 Background
Earlier models used recurrence.

Figure 1: Architecture overview.
The encoder reads input tokens and produces contextualised representations.

2. Method
We propose late chunking.
$$L = -\sum_i p_i \log q_i$$

Table 2: Results on three benchmarks.
Late chunking beats early chunking on all three.

References
[1] Devlin et al. 2019.
Output · — the blocks paper_blocks produces11 lines
kind=heading   lvl=1 '1 Introduction'
kind=para      lvl=0 'Transformers changed NLP. Serving costs $5 and $10 per unit '
kind=heading   lvl=2 '1.1 Background'
kind=para      lvl=0 'Earlier models used recurrence.'
kind=caption   lvl=0 'Figure 1: Architecture overview.\nThe encoder reads input tok'
kind=heading   lvl=1 '2 Method'
kind=para      lvl=0 'We propose late chunking.'
kind=equation  lvl=0 '$$L = -\\sum_i p_i \\log q_i$$'
kind=caption   lvl=0 'Table 2: Results on three benchmarks.\nLate chunking beats ea'
kind=heading   lvl=1 'References'
kind=para      lvl=0 '[1] Devlin et al. 2019.'

And the chunks blocks_to_chunks packs them into — the caption block keeps its description inside the same chunk, and embed_input() prepends the breadcrumb:

text
[para]     path='1 Introduction'                  :: 'Transformers changed NLP. Serving costs $5 and $10 per unit depending on tier.'
[para]     path='1 Introduction > 1.1 Background' :: 'Earlier models used recurrence.'
[caption]  path='1 Introduction > 1.1 Background' :: 'Figure 1: Architecture overview.\nThe encoder reads input tokens and produces contextualised representations.'
[para]     path='2 Method'                        :: 'We propose late chunking.'
[equation] path='2 Method'                        :: '$$L = -\\sum_i p_i \\log q_i$$'
[caption]  path='2 Method'                        :: 'Table 2: Results on three benchmarks.\nLate chunking beats early chunking on all three.'
[para]     path='References'                      :: '[1] Devlin et al. 2019.'

Pitfalls: two-column PDFs interleave text — fix that upstream in 05.2/05.3, don't patch it here. Equations are nearly unsearchable as text; store them as blocks with meta={"kind": "equation"} and expect queries about them to fail unless you also index a description. The equation detector keys on display-math markers ($$, \[ \], \begin{equation}) — currency like "Costs $5 and $10" correctly stays prose, and single-$ inline math does too (usually fine: it's inline). A caption block absorbs the lines beneath it until a blank line — if your extractor emits the whole figure region as one blob, feed caption and description as adjacent lines. Captions without their figures are half an answer — keep caption+description together and link the figure asset in metadata. arXiv HTML gives you real heading structure; a scanned PDF needs 05.4's OCR route first.

5.4 Financial reports and SEC-style filings#

Filings are tables with footnotes. The recipe emits three chunk kinds: a table card (title + shape + column headers + sample rows — answers "what does this table contain"), row-group chunks (N rows with the header line repeated in every chunk — answers "what was Q2 revenue for segment X"), and footnote chunks (the asterisk notes that qualify the numbers).

python
# recipes/financial.py
from blocks import RChunk


def financial_chunks(doc_id: str, title: str, headers: list[str],
                     rows: list[list[str]], footnotes: list[str] | None = None,
                     rows_per_chunk: int = 15, strategy: str = "fin-v1") -> list[RChunk]:
    """Overview chunk + row-group chunks with the header line repeated +
    footnote chunks. rows: list of cell lists aligned to `headers`."""
    chunks: list[RChunk] = []
    head = " | ".join(headers)
    overview = f"{title}\nColumns: {head}\n{len(rows)} data rows.\nSample rows:\n" + \
               "\n".join(" | ".join(r) for r in rows[:3])
    chunks.append(RChunk(f"{doc_id}:{strategy}:0000", doc_id, 0, overview,
                         kind="table_overview", meta={"rows": len(rows)}))
    for gi in range(0, len(rows), rows_per_chunk):
        group = rows[gi:gi + rows_per_chunk]
        body = f"{title} (rows {gi + 1}-{gi + len(group)} of {len(rows)})\n{head}\n" + \
               "\n".join(" | ".join(r) for r in group)
        chunks.append(RChunk(f"{doc_id}:{strategy}:{len(chunks):04d}", doc_id,
                             len(chunks), body, kind="table_rows",
                             meta={"row_start": gi + 1, "row_end": gi + len(group)}))
    for fn in footnotes or []:
        chunks.append(RChunk(f"{doc_id}:{strategy}:{len(chunks):04d}", doc_id,
                             len(chunks), f"{title} — footnote\n{fn}", kind="footnote"))
    return chunks

Worked example — input:

python
financial_chunks("10q", "Revenue by segment", ["Segment", "Q1", "Q2"],
                 [["Cloud", "10", "12"], ["On-prem", "8", "7"]],
                 footnotes=["Q2 includes a one-time licence."], rows_per_chunk=1)
Output4 lines
[table_overview] 'Revenue by segment'
[table_rows]     'Revenue by segment (rows 1-1 of 2)'
[table_rows]     'Revenue by segment (rows 2-2 of 2)'
[footnote]       'Revenue by segment — footnote'

Pitfalls: repeating headers in every row-chunk is non-negotiable — "1.1M | 12%" without column names is unanswerable. Wide tables (20+ columns) defeat row-grouping; split into column groups (identity+key metrics vs detail columns) or rely on the card chunk + a table-aware query path. Multi-year comparisons need the year in every cell's context — prepend "FY2024 vs FY2025" to the chunk text. XBRL/structured filings: if you have the XBRL, prefer structured extraction (link 05.3) over chunking the rendered table.

5.5 Source code#

Code has a real syntax tree, so use it. Two levels: the stdlib ast module handles Python well enough for function/class-level chunks; tree-sitter handles 100+ languages with the same walk.

python
# recipes/code_ast.py — stdlib ast: one block per top-level def/class,
# module header (docstring + imports) kept as context.
import ast
from blocks import Block


def code_blocks_ast(source: str, filename: str) -> list[Block]:
    tree = ast.parse(source)
    blocks: list[Block] = []
    header_parts: list[str] = []
    if ast.get_docstring(tree):
        header_parts.append(ast.get_docstring(tree))
    for node in tree.body:
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            header_parts.append(ast.get_source_segment(source, node) or "")
    if header_parts:
        blocks.append(Block("module_header", "\n".join(p for p in header_parts if p),
                            meta={"file": filename}))
    docstring_node = tree.body[0] if ast.get_docstring(tree) else None
    for node in tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
            seg = ast.get_source_segment(source, node) or ""
            kind = "class" if isinstance(node, ast.ClassDef) else "function"
            blocks.append(Block(kind, seg, meta={
                "file": filename, "name": node.name,
                "lineno": node.lineno,
                "end_lineno": getattr(node, "end_lineno", node.lineno),
            }))
        elif isinstance(node, (ast.Import, ast.ImportFrom)) or node is docstring_node:
            continue
        else:
            seg = ast.get_source_segment(source, node)
            if seg:
                blocks.append(Block("module", seg, meta={"file": filename}))
    return blocks

Worked example — input (a toy module):

python
SRC = '''"""Invoice helpers."""
import re
from decimal import Decimal

TAX_RATE = Decimal("0.08")

def line_total(qty, price):
    return qty * price

class Invoice:
    def __init__(self, number):
        self.number = number
        self.lines = []
'''
code_blocks_ast(SRC, "invoice.py")
Output4 lines
kind=module_header  name=-          lines=---
kind=module         name=-          lines=---
kind=function       name=line_total lines=7-8
kind=class          name=Invoice    lines=10-13

For other languages or finer granularity (methods inside classes, call graphs), tree-sitter is the upgrade — current bindings (tree-sitter==0.26.0, grammars like tree-sitter-python==0.25.0, verified on PyPI as of November 2026):

python
# tree_sitter_blocks.py — optional upgrade for the code recipe (5.5):
# AST-aware splitting for non-Python languages. Needs the Setup install:
#   uv add tree-sitter tree-sitter-python
"""Parse source with tree-sitter and print its named-node tree — the units
you'd turn into blocks (function_definition, class_definition, ...)."""

import tree_sitter_python as tspython
from tree_sitter import Language, Parser

PY_LANGUAGE = Language(tspython.language())
parser = Parser(PY_LANGUAGE)

SOURCE = '''"""Invoice helpers."""
import re
from decimal import Decimal

TAX_RATE = Decimal("0.08")

def line_total(qty, price):
    return qty * price

class Invoice:
    def __init__(self, number):
        self.number = number
        self.lines = []
'''

# walk the tree: node.type gives "function_definition", "class_definition",
# "call", "argument"...; node.start_byte/node.end_byte slice the source.
# Chunk at function_definition and class_definition nodes; keep the
# module docstring + imports as a header block (same shape as ast version).
tree = parser.parse(SOURCE.encode("utf8"))


def walk(node, depth: int = 0) -> None:
    print("  " * depth + f"{node.type} [{node.start_byte}:{node.end_byte}]")
    for child in node.named_children:
        walk(child, depth + 1)


if __name__ == "__main__":
    walk(tree.root_node)

Pitfalls: a function bigger than your chunk budget should stay whole (it's one semantic unit) or be split at statement boundaries via the tree, never mid-expression. Attach file_path, qualified_name (Invoice.total) and line range to every chunk — code questions are almost always "where is X defined". Imports and module docstrings go in a header block so "what does this module depend on" is answerable. For whole-repo retrieval, repo-map style chunks (file trees + signatures, à la aider's repo map) beat per-file chunks for "where should I look" queries — preview Module 08A.

5.6 Markdown, wiki and knowledge-base articles#

These are already structured text — the recipe is md_blocks + blocks_to_chunks with heading breadcrumbs, plus two KB-specific touches: resolve or annotate [[wiki links]] (a link target is retrieval context — "see [[Refund Policy]]" should carry that page's title) and treat front matter (---\ntitle: ...\n---) as document metadata, not a chunk.

python
# recipes/kb.py — thin wrapper: md_blocks + wiki-link annotation.
import re
from blocks import Block
from techdocs import md_blocks   # recipes/techdocs.py from 5.2

_WIKILINK = re.compile(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]")


def kb_blocks(text: str) -> list[Block]:
    blocks = md_blocks(text)
    for b in blocks:
        links = _WIKILINK.findall(b.text)
        if links:
            b.meta["wiki_links"] = [t for t, _ in links]
    return blocks

Worked example — input:

text
# Refund policy
See [[Returns Policy]] for the full rules.
Customers may request a refund within 30 days.
Output · — kb_blocks(text) (note wiki_links in meta)2 lines
kind=heading   lvl=1 'Refund policy'
kind=para      lvl=0 meta={'wiki_links': ['Returns Policy']} 'See [[Returns Policy]] for the full rules.\nCustomers may req'

Pitfalls: don't re-chunk what Markdown already structures — heading hierarchy is your segmentation; blocks_to_chunks handles the rest. Wikis have transclusion and templates that flatten unpredictably; parse to the rendered form if you can (05.3). Knowledge bases with per-article versioning need article_version metadata or stale answers outrank current ones — the exact failure from the module thesis.

5.7 FAQs and Q&A pairs#

The simplest recipe: one pair = one chunk, question first (questions embed better than answers — users ask questions). Variants: split multi-part answers into sub-pairs sharing the question; for FAQ categories, add a category chunk that lists the questions (a "table of contents" chunk that answers "what can I ask about billing?").

python
# recipes/faq.py
from blocks import RChunk


def faq_chunks(doc_id: str, items: list[tuple[str, str]],
               strategy: str = "faq-v1") -> list[RChunk]:
    """One chunk per Q&A pair; the question leads the text."""
    return [
        RChunk(f"{doc_id}:{strategy}:{i:04d}", doc_id, i,
               f"Q: {q.strip()}\nA: {a.strip()}", kind="qa",
               meta={"question": q.strip()})
        for i, (q, a) in enumerate(items)
    ]

Worked example — input:

python
faq_chunks("help", [("How do I reset my password?",
                     "Go to Settings > Security and choose Reset."),
                    ("Is there a mobile app?", "Yes, for iOS and Android.")])
Output2 lines
help:faq-v1:0000 :: Q: How do I reset my password?
help:faq-v1:0001 :: Q: Is there a mobile app?

Pitfalls: a pair whose answer exceeds your budget still stays whole or splits with the Q repeated on each piece (never orphan the A from its Q). Community FAQs have near-duplicates — dedup at the pair level in 05.5 before chunking, or top-k fills with paraphrases. For support-ticket FAQs mined from real tickets (05.1's JSON source), keep ticket_id/resolved metadata — "was this answer actually accepted" is signal.

5.8 Email and threads#

Mailboxes are message streams with quoted-reply noise. The recipe splits on message boundaries, lifts headers (From/To/Date/Subject) into metadata, strips quoted chains (On … wrote:, -----Original Message-----, >-prefixed lines), and — for threads — reconstructs conversation order by References/In-Reply-To or subject+time proximity, emitting one chunk per thread (or per message for long threads, with thread_id shared).

python
# recipes/email.py
import re
from blocks import Block

_QUOTE_RES = [
    re.compile(r"(?im)^On .{5,120} wrote:\s*$"),
    re.compile(r"(?im)^-+\s*Original Message\s*-+\s*$"),
    re.compile(r"(?im)^From:\s.*$"),
    re.compile(r"(?im)^_{5,}\s*$"),
]


def email_blocks(text: str) -> list[Block]:
    """Mailbox export -> one Block per message; headers -> meta; quoted replies stripped."""
    blocks: list[Block] = []
    parts = re.split(r"(?m)^(?=From )", text)
    if len(parts) == 1:
        parts = re.split(r"\n\n(?=From: )", text)
    for part in parts:
        if not part.strip():
            continue
        head, _, body = part.partition("\n\n")
        meta = {}
        for line in head.splitlines()[:15]:
            m = re.match(r"(From|To|Cc|Date|Subject):\s*(.*)", line)
            if m:
                meta[m.group(1).lower()] = m.group(2).strip()
        cut = len(body)
        for rx in _QUOTE_RES:
            m = rx.search(body)
            if m:
                cut = min(cut, m.start())
        clean = body[:cut].strip()
        if clean:
            blocks.append(Block("email", clean, meta=meta))
    return blocks

Worked example — input (one message that quotes an earlier one; the quoted reply is stripped, and so is everything after it):

text
From: alice@acme.com
To: bob@acme.com
Date: Mon, 3 Feb 2025 09:12:00 +0000
Subject: Invoice INV-2042

Hi Bob,

Please find invoice INV-2042 attached for $1,240.

On Fri, 31 Jan 2025 16:40:00 +0000, Bob wrote:
> Can you send the invoice?

Thanks,
Alice
Output · — email_blocks(text)1 line
meta={'from': 'alice@acme.com', 'to': 'bob@acme.com', 'date': 'Mon, 3 Feb 2025 09:12:00 +0000', 'subject': 'Invoice INV-2042'} :: 'Hi Bob,\n\nPlease find invoice INV-2042 attached for $1,240.'

Pitfalls: this recipe cuts at the first quote marker, so anything after the quote is lost: the closing "Thanks, Alice" above, or the whole answer in a "bottom-posted" reply (written below the quoted text). Real mail clients mix top- and bottom-posting, so test on your own mailbox before trusting it, or use a dedicated reply-parser library. Quoted text is the #1 email chunking bug — an unstripped thread embeds the same reply 4× and floods top-k with duplicates (dedup won't catch it; the texts differ). Attachments are not text: extract them upstream (05.2/05.3) and link via metadata. Thread vs message granularity is a real decision — threads preserve "he said / she replied" context but get long fast; message-level with thread_id + expansion is the safer default. Enron-style corpora have headers in weird encodings — decode in 05.5 first.

5.9 Chat and Slack exports#

Chat is turn-based with implicit context ("yes", "the second one"). The recipe windows turns — by count and characters — keeps speaker labels and timestamps, groups thread replies under their parent, and treats channel/topic boundaries as hard splits. A window of ~8–20 turns or ~500–1,500 characters is a typical starting point; tune on your eval.

python
# recipes/chat.py
import re
from blocks import Block

_TURN_RE = re.compile(
    r"^\[?(?P<ts>\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?)?\]?\s*"
    r"(?P<who>[^:()]{1,40}?)\s*(?:\(thread[:\s]+(?P<thread>[^)\s]+)\))?\s*:\s*(?P<text>.*)$")


def chat_blocks(lines: list[str], turns_per_window: int = 8,
                max_chars: int = 900) -> list[Block]:
    """Turns -> windows; speaker labels and timestamps kept in text+meta.
    A turn tagged '(thread <id>)' (Slack's thread_ts analogue) never shares a
    window with another thread — thread boundaries are hard splits and the id
    lands in meta['thread_ts'], so thread Q&A stays attached to its parent."""
    turns = []
    for line in lines:
        m = _TURN_RE.match(line.strip())
        if m:
            turns.append((m.group("ts") or "", m.group("who").strip(),
                          m.group("thread"), m.group("text").strip()))
    blocks: list[Block] = []
    buf: list[str] = []
    buf_thread = None

    def flush():
        nonlocal buf, buf_thread
        if buf:
            meta = {"turns": len(buf)}
            if buf_thread:
                meta["thread_ts"] = buf_thread
            blocks.append(Block("turn_window", "\n".join(buf), meta=meta))
            buf, buf_thread = [], None

    for ts, who, thread, text in turns:
        if buf and thread != buf_thread:
            flush()                        # never mix threads in one window
        line = f"[{ts}] {who}: {text}" if ts else f"{who}: {text}"
        cand = buf + [line]
        if buf and (len(cand) > turns_per_window or
                    sum(len(x) for x in cand) > max_chars):
            flush()
        buf.append(line)
        if buf_thread is None:
            buf_thread = thread
    flush()
    return blocks

Worked example — input (ten generated turns; turns 6–7 carry a (thread …) tag, Slack's thread_ts analogue):

python
LINES = [f"[2025-02-03T09:0{i}:00] {'Alice' if i % 2 else 'Bob'}: message number {i} about the deploy"
         for i in range(10)]
LINES[6] = LINES[6].replace("Bob:", "Bob (thread 1728000123.000100):")
LINES[7] = LINES[7].replace("Alice:", "Alice (thread 1728000123.000100):")
chat_blocks(LINES, turns_per_window=4, max_chars=500)

Output — four windows; the thread never mixes with channel turns and its id lands in meta['thread_ts']:

text
turns=4 thread=-                    :: '[2025-02-03T09:00:00] Bob: message number 0 about '...
turns=2 thread=-                    :: '[2025-02-03T09:04:00] Bob: message number 4 about '...
turns=2 thread=1728000123.000100    :: '[2025-02-03T09:06:00] Bob: message number 6 about '...
turns=2 thread=-                    :: '[2025-02-03T09:08:00] Bob: message number 8 about '...

Pitfalls: "yes"/"ok" turns are pure noise until windowed with their antecedent — never chunk single turns. Slack threads need thread_ts in metadata or thread answers detach from questions. Channel/topic/day boundaries are natural chunk boundaries; a 3-day debugging session as one chunk dilutes everything. Emoji reactions and bot messages: keep or drop deliberately (bots like deploy notifications are often the answer to "when did X ship").

5.10 Meeting transcripts and subtitles#

Speech is continuous; the useful units are speaker turns grouped by topic or time. For subtitles (SRT/VTT), cues carry timestamps — group them into windows, keep [hh:mm:ss] prefixes so "what was decided in the first 10 minutes" is answerable, and detect speaker labels ("Alice:", "SPEAKER 1:") when the source has them.

python
# recipes/transcripts.py
import re
from blocks import Block

_CUE_RE = re.compile(r"(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*-->\s*"
                     r"(\d{2}):(\d{2}):(\d{2})[,.](\d{3})")
# "Alice:" / "SPEAKER 1:" style labels at the start of cue text
_SPEAKER_RE = re.compile(
    r"^(?P<who>[A-Z][A-Za-z0-9 .'’\-]{0,40}|SPEAKER[_ ]?\d+):\s+")


def transcript_blocks(srt_text: str, max_turns: int = 6) -> list[Block]:
    """SRT/VTT cues -> speaker-turn windows with timestamp meta.

    A 'Name:'/'SPEAKER n:' prefix is detected per cue: a speaker change
    flushes the window, so one speaker's run of cues stays together, and the
    labels present land in meta['speakers']. The label also stays inline in
    the text — it is real content for the embedder."""
    cues = []
    for chunk in re.split(r"\n\s*\n", srt_text.strip()):
        lines = [l for l in chunk.splitlines() if l.strip()]
        tm = next((l for l in lines if _CUE_RE.search(l)), None)
        if not tm:
            continue
        text = " ".join(l for l in lines if l != tm and not l.strip().isdigit())
        start = tm.split("-->")[0].strip()
        m = _SPEAKER_RE.match(text)
        cues.append((start, m.group("who").strip() if m else None, text))
    blocks: list[Block] = []
    buf: list[str] = []
    buf_spk: list[str] = []
    last_who = None

    def flush():
        nonlocal buf, buf_spk
        if buf:
            meta = {"cues": len(buf)}
            if buf_spk:
                meta["speakers"] = sorted(set(buf_spk))
            blocks.append(Block("turn_window", "\n".join(buf), meta=meta))
            buf, buf_spk = [], []

    for start, who, text in cues:
        if buf and who != last_who:
            flush()                        # speaker change = turn boundary
        buf.append(f"[{start}] {text}")
        if who:
            buf_spk.append(who)
        last_who = who
        if len(buf) >= max_turns:
            flush()
    flush()
    return blocks

Worked example — input (toy SRT; cues 3–4 share a speaker and merge into one turn):

text
1
00:00:01,000 --> 00:00:04,000
Alice: Let's start with the roadmap.

2
00:00:05,000 --> 00:00:09,000
Bob: Agreed, embeddings first.

3
00:00:10,000 --> 00:00:14,000
Alice: Then chunking strategy.

4
00:00:15,000 --> 00:00:18,000
Alice: Agreed — evaluate before adopting.

Output — transcript_blocks(srt, max_turns=2); speaker changes flush the window and meta['speakers'] records who is inside:

text
cues=1 speakers=['Alice'] :: "[00:00:01,000] Alice: Let's start with the roadmap."
cues=1 speakers=['Bob']   :: '[00:00:05,000] Bob: Agreed, embeddings first.'
cues=2 speakers=['Alice'] :: '[00:00:10,000] Alice: Then chunking strategy.\n[00:00:15,000] Alice: Agreed — evaluate before adopting.'

Pitfalls: auto-captions have no punctuation and mangled names — clean in 05.5, and don't trust speaker labels blindly (diarization errors assign the wrong name; keep speaker_confidence if available). Timestamps in text are cheap insurance for "around minute 12" queries. Topic segmentation (an LLM pass over windows, or embedding-shift detection) beats fixed windows for long meetings — one "budget review" chunk beats six windows that each contain two topics.

5.11 Product catalogues and structured records#

Records are already atomic — the recipe is one record per chunk, rendered through a stable template so every record has identical shape. Templating matters: "Acme Drill (DR-200): $129.00 USD, stock 14, rating 4.6" embeds and answers far better than raw JSON field order.

python
# recipes/records.py
from blocks import RChunk


class _SafeDict(dict):
    def __missing__(self, key):
        return ""


def record_chunks(doc_id: str, records: list[dict], template: str,
                  id_field: str = "id", strategy: str = "rec-v1") -> list[RChunk]:
    """One record per chunk, rendered through a stable template."""
    out = []
    for i, rec in enumerate(records):
        text = template.format_map(_SafeDict(rec))
        out.append(RChunk(f"{doc_id}:{strategy}:{i:04d}", doc_id, i, text,
                          kind="record", meta={"record_id": str(rec.get(id_field, i))}))
    return out

Worked example — input:

python
TMPL = "{name} ({sku}): {price} {currency}, stock {stock}."
record_chunks("catalog", [
    {"name": "Acme Drill", "sku": "DR-200", "price": "129.00", "currency": "USD", "stock": 14},
    {"name": "Acme Saw",   "sku": "SW-110", "price": "89.50",  "currency": "USD", "stock": 3}],
    TMPL)
Output2 lines
Acme Drill (DR-200): 129.00 USD, stock 14.
Acme Saw (SW-110): 89.50 USD, stock 3.

Pitfalls: template design is the whole game — include the fields users ask about (price, specs, compatibility) and exclude internal IDs that only add noise. For large catalogues, hybrid retrieval (dense + BM25 on SKU/model-number fields) is mandatory — "DR-200" is a lexical lookup, not a semantic one. Records with long descriptions still fit one chunk; only split a record if it exceeds the embedding model's limit, and then keep the header fields on every piece.

5.12 Tables#

Covered in depth for financial tables in 5.4; the general recipe adds three modes: row-level (groups of N rows + repeated headers — for lookup queries), table-level (small tables whole, with caption — for "what does the warranty table say"), and summary + rows (a card chunk describing shape/sample + row chunks for detail). Wide tables split by column groups; long tables split by rows; merged cells need upstream repair in 05.3.

python
# recipes/tables.py
from blocks import RChunk


def table_row_chunks(doc_id: str, title: str, headers: list[str],
                     rows: list[list[str]], rows_per_chunk: int = 10,
                     strategy: str = "tbl-v1") -> list[RChunk]:
    """Row-level units with header repeated + one 'table card' chunk."""
    chunks: list[RChunk] = []
    head = " | ".join(headers)
    card = (f"Table: {title}\nShape: {len(rows)} rows x {len(headers)} columns\n"
            f"Columns: {head}\nFirst rows:\n" +
            "\n".join(" | ".join(r) for r in rows[:3]))
    chunks.append(RChunk(f"{doc_id}:{strategy}:0000-card", doc_id, 0, card,
                         kind="table_card", meta={"rows": len(rows)}))
    for gi in range(0, len(rows), rows_per_chunk):
        group = rows[gi:gi + rows_per_chunk]
        body = f"{title}\n{head}\n" + "\n".join(" | ".join(r) for r in group)
        chunks.append(RChunk(f"{doc_id}:{strategy}:{len(chunks):04d}", doc_id,
                             len(chunks), body, kind="table_rows",
                             meta={"row_start": gi + 1, "row_end": gi + len(group)}))
    return chunks

Worked example — input:

python
table_row_chunks("fin", "Q2 Revenue", ["Product", "Q1", "Q2", "Growth"],
                 [["Drill", "1.0M", "1.1M", "+10%"], ["Saw", "0.8M", "0.9M", "+12%"],
                  ["Sander", "0.5M", "0.4M", "-20%"]], rows_per_chunk=2)
Output3 lines
[table_card] 'Table: Q2 Revenue :: rows None-None'
[table_rows] 'Q2 Revenue :: rows 1-2'
[table_rows] 'Q2 Revenue :: rows 3-3'

Pitfalls: the header line repeated in every chunk is the single most important detail — a row chunk without column names is unanswerable. Spanned headers ("2024 | 2025" over "Q1 Q2 Q3 Q4") must be flattened to full column names upstream. For very large or complex tables, consider sending the table region to a vision model or extracting to structured data and rendering rows as sentences ("Acme Drill sold 1.1M units in Q2, up 10%") — sentence-form rows embed better than pipe-delimited rows.

5.13 Slides#

(If you parse decks with Unstructured or Docling, their chunk_by_title and HybridChunker output is a baseline to compare against: 05.6, section 4.5.1.)

One slide per chunk: title + bullets + speaker notes (notes are often where the real explanation lives). Deck-level context (presentation title, date, section) goes in metadata or a prepended breadcrumb.

python
# recipes/slides.py
from blocks import RChunk


def slide_chunks(doc_id: str, deck_title: str, slides: list[dict],
                 strategy: str = "slides-v1") -> list[RChunk]:
    """One chunk per slide: title + bullets + speaker notes."""
    out = []
    for i, s in enumerate(slides):
        parts = [f"{deck_title} — slide {i + 1}: {s.get('title', '')}"]
        parts += [f"- {b}" for b in s.get("bullets", [])]
        if s.get("notes"):
            parts.append(f"Speaker notes: {s['notes']}")
        out.append(RChunk(f"{doc_id}:{strategy}:{i:04d}", doc_id, i,
                          "\n".join(parts), kind="slide", meta={"slide": i + 1}))
    return out

Worked example — input:

python
slide_chunks("deck", "Q3 Review", [
    {"title": "Revenue", "bullets": ["Up 8% YoY", "Enterprise drove growth"],
     "notes": "Emphasise retention."},
    {"title": "Risks", "bullets": ["Churn in SMB"]}])
Output2 lines
Q3 Review — slide 1: Revenue | notes=True
Q3 Review — slide 2: Risks | notes=False

Pitfalls: bullet fragments ("- up 8%") are meaningless alone — the slide title is their context, which is why it leads every chunk. Decks with heavy animation/transition text extract garbage — parse pptx via 05.3's python-pptx route and keep slide order. Charts-as-images need VLM descriptions (05.4) or they're invisible to text retrieval.

5.14 Long-form books and manuals#

toc-driven hierarchy: parts → chapters → sections, with cross-references ("see Chapter 3", "per Section 2.1") preserved inside chunks. md_blocks handles most of it when the book is already Markdown/AsciiDoc; for print-layout books, headings come from font-size heuristics in 05.2/05.3 — feed those as heading blocks. Keep the index/glossary as their own chunk kind: "what does X mean" should hit the glossary entry.

python
# recipes/books.py — chapter/section detection on top of md_blocks.
import re
from blocks import Block
from techdocs import md_blocks   # recipes/techdocs.py from 5.2

_CHAPTER_RE = re.compile(r"(?im)^\s*(chapter|part|book|volume)\s+[^\n]{1,60}$")


def book_blocks(text: str) -> list[Block]:
    """Promote 'Chapter N ...'/'Part ...' lines to top-level headings, then md_blocks."""
    marked = _CHAPTER_RE.sub(lambda m: "\n# " + m.group(0).strip() + "\n", text)
    return md_blocks(marked)

Worked example — input:

text
Chapter 1 Introduction
This chapter covers the warranty.

Chapter 2 Returns
- 45-day window
- Defective only

Output — book_blocks(text); chapter lines became level-1 headings and feed blocks_to_chunks breadcrumbs:

text
kind=heading   lvl=1 'Chapter 1 Introduction'
kind=para      lvl=0 'This chapter covers the warranty.'
kind=heading   lvl=1 'Chapter 2 Returns'
kind=list      lvl=0 '- 45-day window\n- Defective only'

Pitfalls: books have front matter (preface, TOC, copyright) that isn't content — drop or tag it. Cross-references only work if the target section is independently retrievable — keep sections whole. Very long books suit parent-child (Part 2) with chapter-as-parent. Technical manuals: keep procedures (numbered steps) whole — splitting "step 3 of 5" from its context breaks the procedure.

5.15 Forms and invoices#

Fields are structured data, not chunks. An invoice's invoice_no, total, due_date belong in a record store and in filterable metadata (05.8), queried by exact match — not embedded as prose. Only the narrative parts (notes, descriptions, terms text) become chunks.

python
# recipes/forms.py
import re
from blocks import Block, RChunk, blocks_to_chunks


def form_to_record(fields: dict) -> dict:
    """Normalise form fields into a structured record (not a chunk)."""
    return {re.sub(r"[^a-z0-9]+", "_", k.lower()).strip("_"): v
            for k, v in fields.items()}


def narrative_chunks(doc_id: str, text: str, strategy: str = "form-narr-v1") -> list[RChunk]:
    """Only the free-text parts of a form become chunks."""
    blocks = [Block("para", p) for p in re.split(r"\n\s*\n", text) if p.strip()]
    return blocks_to_chunks(doc_id, blocks, strategy=strategy)

Worked example — input:

python
form_to_record({"Invoice No": "INV-2042", "Total Amount": "$1,240.00",
                "Due Date": "2025-03-01"})
narrative_chunks("inv-2042",
    "Customer requests net-30 terms on invoice INV-2042.\n\n"
    "Dispute over line 3 resolved offline; credit note CN-77 issued.")
Output2 lines
record={'invoice_no': 'INV-2042', 'total_amount': '$1,240.00', 'due_date': '2025-03-01'}
chunk: 'Customer requests net-30 terms on invoice INV-2042.\n\nDispute over line 3 resolved offline; credit note CN-77 issued.'

Pitfalls: don't embed "Field: value" pairs for retrieval — "What was the total?" is a structured query, and a vector search over field noise returns the wrong invoice. Line items on an invoice are tabular — treat them like 5.12 rows if they need retrieval at all. For schema extraction from form images, that's structured output (03.4) + metadata design (05.8), not chunking.

5.16 Multilingual corpora#

Sentence boundaries differ by script: Latin/Cyrillic/Greek use terminal punctuation + space; Thai, Lao, Khmer, Myanmar have no inter-word spaces and need dictionary-based segmentation; Chinese/Japanese need punctuation-aware splitting with different terminal marks. Detect language per document (05.5's lingua/fastText), route to the right splitter, and never apply the space-regex to a no-space language — you'll get one giant "sentence".

python
# recipes/i18n.py
import re
from blocks import _sentences   # the space-script splitter from blocks.py


def split_sentences_i18n(text: str, lang: str) -> list[str]:
    """Language-aware sentence boundaries.
    'space'   : Latin/Cyrillic/etc. — regex on terminal punctuation + space.
    'dict'    : no whitespace (Thai, Lao, Khmer, Myanmar) — dictionary max-match.
    'cjk'     : Chinese/Japanese — punctuation-based boundaries."""
    if lang in ("th", "lo", "km", "my"):
        # production: real word-segmentation dict (pythainlp, underthesea...);
        # here the caller pre-segments and we window the tokens
        words = text.split()
        return [" ".join(words[i:i + 8]) for i in range(0, len(words), 8)] or [text]
    if lang in ("zh", "ja"):
        parts = re.split(r"(?<=[。!?!?])", text)
        return [p.strip() for p in parts if p.strip()] or [text]
    return _sentences(text) or [text]

Worked example — input:

python
split_sentences_i18n("one two three four five six seven eight nine ten eleven", "th")
split_sentences_i18n("。!?", "zh")
split_sentences_i18n("One sentence. Another one!", "en")
Output3 lines
th: ['one two three four five six seven eight', 'nine ten eleven']
zh: ['。', '!', '?']
en: ['One sentence.', 'Another one!']

Pitfalls: code-switched documents (English tech doc with Hindi examples) need per-span language detection, not per-document. Right-to-left scripts (Arabic, Hebrew) keep logical order in text but visual order in PDFs — fix upstream. Token counts explode for non-Latin scripts (02.2) — your max_chars budget silently becomes a different token budget per language; measure tokens, not characters, for CJK.

5.17 Mixed-media documents#

PDFs and docs mix text with figures, charts and photos. The text chunks normally; each image/figure becomes a chunk containing its caption + VLM-generated description + page number — the description is the retrievable text (generated upstream via 05.4's OCR/VLM route or 03.6's multimodal input; never embed raw image bytes as text).

python
# recipes/media.py
from blocks import Block


def media_blocks(items: list[dict]) -> list[Block]:
    """items: {caption, description, page}. Text+description form the chunk;
    the image itself is never 'chunked'."""
    blocks = []
    for it in items:
        text = it.get("caption", "")
        if it.get("description"):
            text = f"{text}\n{it['description']}".strip()
        blocks.append(Block("figure", text,
                            meta={"page": it.get("page"), "has_image": True}))
    return blocks

Worked example — input:

python
media_blocks([{"caption": "Fig 3: Latency vs chunk size",
               "description": "Line chart showing p50 latency rising with chunk size.",
               "page": 12}])
Output1 line
kind=figure meta={'page': 12, 'has_image': True} :: 'Fig 3: Latency vs chunk size\nLine chart showing p50 latency '

Pitfalls: a figure chunk with only "Figure 3" and no description is dead weight — require descriptions or drop the chunk. Charts need data-level descriptions ("latency rises from 40ms to 120ms as chunk size grows") not "a line chart" — prompt the VLM for values. Decorative images (logos, rules) should be filtered before this stage. Keep page/bbox in metadata for citations back to the source. A different route skips figure descriptions altogether by embedding whole page images with a visual document retriever (the ColPali/ColQwen line); it trades a larger index for not parsing at all, and you still keep text chunks for keyword search and exact citations — the trade-off is laid out in 05.2, section 8.5, and the retrieval side belongs to Module 06 and Module 09.


Part 6: Chunking for different retrieval modes#

Deep-dive

The same document should not necessarily produce the same chunks for every retrieval path. Dense, sparse and hybrid retrieval reward different properties, and "just put everything in the prompt" is a legitimate fourth option for small corpora.

Mode What it rewards Chunk tendency Enrichment that helps most Typical failure if ignored
Dense (embeddings) Semantic completeness, self-contained meaning Medium–large; context-rich Contextual retrieval, multi-vector, breadcrumbs Pronoun/reference chunks ("It costs…") rank poorly
Sparse (BM25/lexical) Exact terms, phrases, identifiers Smaller, lexically complete; phrases intact Contextual BM25, keyword view, header repetition Table rows without headers; acronyms never expanded
Hybrid Both Middle ground; union of candidates Everything above + rank fusion Optimising only for dense starves BM25's exact-match strength
Long-context stuffing Nothing — no retrieval Large or whole-doc N/A (no index) Corpus outgrows the window; cost/latency per query soars

6.1 Dense retrieval#

Dense rewards chunks whose embedding captures the whole meaning — so self-contained units win: parent-child expansion, contextual prefixes, breadcrumbs ("Handbook > Warranty > Claims"), and multi-vector question views. Chunk size can run larger than sparse optimum because the embedding averages meaning; the constraint is the embedding model's input limit and the dilution effect from 1.2. Late chunking (4.1) is a dense-only upgrade — it needs token-level embeddings sparse indexes can't use.

6.2 Sparse (BM25) and hybrid#

BM25 rewards lexical completeness: the exact words a user types must appear in the chunk. That pushes toward smaller chunks with intact phrases, repeated headers (tables!), expanded acronyms, and — counterintuitively — contextual BM25 where the generated context supplies vocabulary the chunk lacks. Anthropic's 49% figure was specifically the embeddings+BM25 combination; BM25 alone benefits from the same context prefix.

For hybrid (dense + BM25 fused by rank, e.g. reciprocal rank fusion — the details live in Module 06), the chunk must serve both masters: big enough to embed well, lexically rich enough for BM25. This is where contextual retrieval earns its keep — it improves both indexes from one preprocessing pass.

6.3 Long-context stuffing vs retrieval#

Anthropic's contextual-retrieval post opens with the honest option: if your knowledge base fits in ~200K tokens (roughly 500 pages), you can skip retrieval entirely and put it all in the prompt — prompt caching makes repeated calls cheap. The crossover isn't just size: retrieval adds a failure mode (the right chunk isn't retrieved) but removes a cost (you only pay for relevant context). Stuffing wins on small, high-value corpora where every query might touch anything; retrieval wins on large corpora, cost-sensitive workloads, and when you need citations to specific chunks. Chunking still matters even when stuffing — for citation, versioning and incremental updates (Part 8).

6.4 Choosing under constraints#

The honest summary: there is no universal optimum. Chunk size optima differ by retrieval mode, document type, query mix and embedding model — the published numbers (Anthropic's 49%, Dense X Retrieval's proposition gains, semantic-chunking papers) are real but corpus-specific. The engineering answer is a small eval harness on your own question set (Part 7), a decision table for defaults, and the discipline to measure before and after every change.

6.5 What the independent evidence says (as of November 2026)#

Three sources are worth knowing, because they are the ones that test chunking choices outside a vendor's own marketing:

  • Chroma's "Evaluating Chunking Strategies for Retrieval" (Smith and Troynikov, technical report, July 2024). It scores retrieval at the token level (recall, precision, IoU — intersection over union of retrieved and relevant tokens) instead of per document. It reports that strategy choice moves recall by up to about 9%; that a widely used default (800-token chunks with 400-token overlap, the OpenAI Assistants default at the time) gave a weak recall-versus-efficiency trade-off; that a tuned RecursiveCharacterTextSplitter at roughly 200 tokens with no overlap was consistently strong; and that an LLM-driven chunker reached the highest recall but was slow and costly. Treat the specific sizes as starting points to test, not rules — the datasets and embedding models are fixed in that report and yours are not.
  • Qu, Tu and Bao, "Is Semantic Chunking Worth the Computational Cost?" (arXiv:2410.13070, October 2024), found the extra compute of semantic chunking was not justified by consistent gains over fixed-size chunking. The details are in 05.6.
  • Merola and Singh, "Reconstructing Context: Evaluating Advanced Chunking Strategies for RAG" (arXiv:2504.19754, April 2025), compared late chunking with contextual retrieval and found a coherence-versus-compute trade-off (see 4.1).

The pattern across all three is the one this lesson keeps repeating: the techniques are real, the gains are corpus-dependent, and the cheap baseline (well-tuned recursive splitting plus structure-aware recipes) is harder to beat than vendor posts suggest. Adopt an advanced technique when your harness from Part 7 shows it winning on your questions, not when a benchmark elsewhere does.

Part 7: Evaluating chunking quality#

You cannot pick a chunking strategy by argument — you measure it on your questions. The metric that matters most is hit rate: for a set of real questions with known answer-bearing text, does the retrieved context contain the answer? Everything else (chunk coherence, size distribution, duplicates) is diagnostic.

python
# eval_lifecycle.py — hit@k eval harness + chunk lifecycle demo (lesson 05.7).
"""Chunking evaluation harness (lesson 05.7).

The retriever is a lexical stand-in (word overlap) so the whole thing runs
with no API keys; swap `retrieve` for your real vector/BM25/hybrid stack.
"""

import hashlib
import re
from dataclasses import dataclass, field


def _words(text: str) -> set[str]:
    return set(re.findall(r"[a-z0-9]+", text.lower()))


def retrieve(query: str, index: list[dict], k: int = 3) -> list[dict]:
    """index entries: {"id", "embed_text", "context_text"}.
    Scores on embed_text (what was indexed), returns entries ranked."""
    q = _words(query)
    scored = []
    for e in index:
        shared = len(q & _words(e["embed_text"]))
        if shared:
            scored.append((shared / max(len(q), 1), e))
    scored.sort(key=lambda t: -t[0])
    return [e for _, e in scored[:k]]


QUESTIONS = [
    {"q": "how long is the warranty on the drill?", "answer": "two-year"},
    {"q": "can I return an opened power tool?", "answer": "defective"},
    {"q": "who pays shipping on change-of-mind returns?", "answer": "customer"},
    {"q": "where do I register the tool for a claim?", "answer": "30 days"},
]

HANDBOOK = [
    ("Warranty", "Every Acme Drill carries a two-year limited warranty against defects in materials and workmanship. The warranty covers the motor, chuck and battery pack but excludes wear items such as drill bits and abrasives."),
    ("Returns", "Unused tools may be returned within 45 days for a full refund. Opened power tools can only be returned if they are defective; contact support for a return authorisation number. Shipping costs on change-of-mind returns are paid by the customer."),
    ("Claims", "To make a warranty claim, register the tool within 30 days of purchase and keep your receipt."),
]


def flat_index(sections, size=140):
    idx = []
    for sec, text in sections:
        body = f"{sec}\n{text}"
        for i in range(0, len(body), size):
            piece = body[i:i + size]
            idx.append({"id": f"{sec}:{i}", "embed_text": piece, "context_text": piece})
    return idx


def sentence_index(sections):
    sents = [(sec, s.strip()) for sec, text in sections
             for s in re.split(r"(?<=[.!?])\s+", text)]
    idx = []
    for i, (sec, s) in enumerate(sents):
        ctx = " ".join(x for _, x in sents[max(0, i - 1):i + 2])
        idx.append({"id": f"s{i}", "embed_text": s, "context_text": f"{sec}\n{ctx}"})
    return idx


def parent_index(sections):
    by_sec = dict(sections)
    sents = [(sec, s.strip()) for sec, text in sections
             for s in re.split(r"(?<=[.!?])\s+", text)]
    return [{"id": f"s{i}", "embed_text": s,
             "context_text": f"{sec}\n{by_sec[sec]}"}
            for i, (sec, s) in enumerate(sents)]


def evaluate(index, questions, k=3):
    """hit@k: is the answer-bearing text inside the top-k returned CONTEXTS?"""
    hits = 0
    details = []
    for item in questions:
        got = retrieve(item["q"], index, k=k)
        ok = any(item["answer"] in e["context_text"] for e in got)
        hits += ok
        details.append((item["q"], ok, [e["id"] for e in got]))
    return hits / len(questions), details


if __name__ == "__main__":
    strategies = {
        "flat-140": flat_index(HANDBOOK),
        "sentence+window": sentence_index(HANDBOOK),
        "sentence->parent": parent_index(HANDBOOK),
    }
    for name, idx in strategies.items():
        score, details = evaluate(idx, QUESTIONS, k=3)
        print(f"{name:<20} hit@3 = {score:.0%}  ({len(idx)} index entries)")
        for q, ok, ids in details:
            print(f"    {'HIT ' if ok else 'MISS'} {q!r} -> {ids}")


# ---------- chunk lifecycle: versioned config + stable ids ----------

@dataclass(frozen=True)
class ChunkingConfig:
    strategy: str                 # e.g. "parent-child"
    version: int                  # bump when rules/params change
    params: dict = field(default_factory=dict)

    @property
    def label(self) -> str:
        return f"{self.strategy}-v{self.version}"


def stable_chunk_id(doc_id: str, cfg: ChunkingConfig, index: int,
                    text: str) -> str:
    """Deterministic: same doc + same config + same position + same text ->
    same id, so unchanged chunks keep their embeddings across re-ingests."""
    payload = "|".join([doc_id, cfg.label, str(index), text])
    return f"{doc_id}:{cfg.label}:{index:04d}-" + \
           hashlib.sha256(payload.encode()).hexdigest()[:10]


def reindex_cost(n_chunks: int, price_per_mtok: float) -> float:
    """Rough full-reindex embedding cost: chunks x ~chunk_tokens x price.
    Plug your embedding model's real price (Module 06 has the current table)."""
    chunk_tokens = 400
    return n_chunks * chunk_tokens / 1_000_000 * price_per_mtok


if __name__ == "__main__":
    cfg_v1 = ChunkingConfig("parent-child", 1, {"parent_chars": 1200, "child_chars": 300})
    cfg_v2 = ChunkingConfig("parent-child", 2, {"parent_chars": 1200, "child_chars": 450})
    print(f"config v1: {cfg_v1.label}   v2: {cfg_v2.label}")
    for cfg in (cfg_v1, cfg_v2):
        cid = stable_chunk_id("handbook", cfg, 0, "Every Acme Drill carries a two-year warranty.")
        print(f"  {cid}")
    print(f"\nfull re-embed of 50k chunks @ $0.02/Mtok: "
          f"${reindex_cost(50_000, 0.02):.2f}")
Output · real21 lines
flat-140             hit@3 = 100%  (5 index entries)
    HIT  'how long is the warranty on the drill?' -> ['Warranty:0', 'Returns:140', 'Claims:0']
    HIT  'can I return an opened power tool?' -> ['Returns:0', 'Returns:140', 'Claims:0']
    HIT  'who pays shipping on change-of-mind returns?' -> ['Returns:140', 'Returns:0', 'Claims:0']
    HIT  'where do I register the tool for a claim?' -> ['Claims:0', 'Returns:140', 'Warranty:0']
sentence+window      hit@3 = 100%  (6 index entries)
    HIT  'how long is the warranty on the drill?' -> ['s1', 's0', 's4']
    HIT  'can I return an opened power tool?' -> ['s3', 's5']
    HIT  'who pays shipping on change-of-mind returns?' -> ['s4', 's5']
    HIT  'where do I register the tool for a claim?' -> ['s5', 's2', 's3']
sentence->parent     hit@3 = 100%  (6 index entries)
    HIT  'how long is the warranty on the drill?' -> ['s1', 's0', 's4']
    HIT  'can I return an opened power tool?' -> ['s3', 's5']
    HIT  'who pays shipping on change-of-mind returns?' -> ['s4', 's5']
    HIT  'where do I register the tool for a claim?' -> ['s5', 's2', 's3']

config v1: parent-child-v1   v2: parent-child-v2
  handbook:parent-child-v1:0000-5ecb980ce1
  handbook:parent-child-v2:0000-7f81e1f70a

full re-embed of 50k chunks @ $0.02/Mtok: $0.40

The other diagnostics, cheaply:

  • Token-level precision, recall and IoU — the measures Chroma's report uses (6.5). If each question has the exact answer-bearing span marked (start and end character offsets) instead of a substring, you can compute how many retrieved tokens were relevant (precision), how many relevant tokens were retrieved (recall), and their overlap ratio (IoU). They expose a failure that hit@k hides: a chunker that always returns huge chunks scores a perfect hit rate while wasting most of the context window.
  • Context sufficiency — hit@k only proves the answer text was retrieved; check the top-1/top-3 context actually lets a model answer (LLM judge or human sample).
  • Chunk coherence — sample 20 random chunks; a human can spot mid-sentence cuts and orphaned references in minutes.
  • Duplicates — identical or near-identical chunks in top-k waste slots; measure pairwise similarity on a sample.
  • Size distribution — a text histogram of chunk token counts exposes pathological tails (a 5-token sliver next to a 4k-token monster).

Part 8: The chunk lifecycle#

Deep-dive

Chunking is not a one-time decision — it's a versioned pipeline stage whose output is embedded, indexed, cited and incrementally maintained. Three rules keep it sane:

  1. Version the config. A ChunkingConfig (strategy name + version + params) is part of every chunk's lineage — store it on the chunk or index. When you change a size, a recipe or an enrichment prompt, bump version.
  2. Make IDs stable. stable_chunk_id(doc_id, cfg, index, text) is deterministic: same doc + same config + same position + same text → same ID → the incremental pipeline (05.9) can reuse that chunk's embedding and only re-embed what changed. Change the strategy → IDs change → full re-embed (that's correct: different chunking means different vectors). One limit of this toy scheme: index is part of the hash, so inserting a paragraph mid-document shifts every later ID; the position-free, occurrence-numbered scheme in 05.8, section 3.3 avoids that and is what 05.9's pipeline uses.
  3. Estimate re-embedding before you commit. reindex_cost(n_chunks, price_per_mtok) gives the order of magnitude — 50k chunks ≈ $0.40 at $0.02/Mtok for 400-token chunks; measure your real chunk-token average and your model's price (Module 06 has current prices). Contextual retrieval adds its own re-index cost (3.1) on top of embeddings.

Schema evolution note: adding a metadata field (05.8) doesn't require re-embedding; changing embed_text (context prefix, breadcrumb, question views) does, because the vector changes even though text doesn't — keep embed_text derivation inside the versioned config so this is explicit.


Part 9: Choosing under constraints#

flowchart TD
    Q1{"What does the doc look like?"}
    Q1 -- "structured records / forms / invoices" --> R1["One record per chunk or structured store — not prose chunks"]
    Q1 -- "numbered clauses / contracts" --> R2["Clause-aware recipe (5.1) + parent-child"]
    Q1 -- "headings + code / docs / markdown" --> R3["md_blocks recipe (5.2/5.6) + breadcrumbs"]
    Q1 -- "tables dominate" --> R4["Row-group + header repeat + table card (5.4/5.12)"]
    Q1 -- "source code" --> R5["AST/tree-sitter functions+classes (5.5)"]
    Q1 -- "turns / messages / cues" --> R6["Windowed turns with speaker+time meta (5.9/5.10)"]
    Q1 -- "Q&A pairs" --> R7["One pair per chunk, question first (5.7)"]
    Q1 -- "mixed / prose" --> Q2{"Retrieval mode?"}
    Q2 -- "dense only" --> R8["Medium chunks + contextual retrieval or parent-child"]
    Q2 -- "BM25/hybrid" --> R9["Lexically rich chunks + contextual BM25 + headers repeated"]
    Q2 -- "corpus < ~200K tokens" --> R10["Consider stuffing; chunk anyway for citations/versioning"]
    R8 --> E["Evaluate on your question set (Part 7)"]
    R9 --> E
    R10 --> E

Decision table (defaults — verify on your data):

Document type Default recipe Retrieval unit Return unit Watch out for
Contracts/legal Clause blocks Clause Parent clause-group Cross-references, definitions
Tech docs/API Heading tree Section chunk Section + code intact Versioning, code fences
Papers Section blocks Section Section + caption Two-column PDFs, equations
Filings/tables Row groups + card Row group Row group + header Wide tables, footnotes
Source code AST defs Function/class Function + header Giant files, repo-level queries
Markdown/wiki Heading tree Section Section Wiki links, templates
FAQs Q&A pair Pair Pair Duplicate questions
Email Thread/message Message or thread Thread Quoted replies
Chat/Slack Turn window Window Window + thread parent Context-free turns
Transcripts Speaker window Window Window + timestamps Diarization errors
Catalogues Record Record Record SKU lexical lookups
Slides Slide+notes Slide Slide Fragment bullets
Books/manuals Chapter/section Section Section Cross-references
Forms/invoices Structured record Field query Record Don't embed fields
Multilingual Per-language sentences Sentence/para Paragraph Token budgets per script
Mixed-media Text + figure desc Figure/text Figure + caption Missing descriptions

Anti-patterns:

  • Chunking before cleaning (05.5) — you index the noise.
  • One splitter for every document type — a contract and a chat log have different atomic units.
  • Splitting code fences, tables or clauses mid-unit to hit a size target.
  • Returning the retrieval unit to the generator when it can't answer (the 1.2 trap).
  • Re-chunking without bumping the config version — your evals stop meaning anything.
  • Treating Anthropic's 49% or any paper's number as a promise for your corpus.
  • Embedding fields/records as prose instead of structured lookup.

Failure gallery:

Symptom Likely cause Fix
Answers cite mid-sentence fragments Chunk cut inside a unit Structure-aware recipe; HARD_KINDS
"It/they/this" chunks rank but can't answer No expansion/context Parent-child, window expansion, contextual retrieval
Table answers attach numbers to wrong rows Header not repeated / rows reordered Header line in every row chunk; keep row order
Same content returned 4× Quoted email replies / template pages Strip quotes upstream; dedup in 05.5
Code answers are syntactically broken Split mid-function AST/tree-sitter units
Stale answer outranks current No version/date metadata Version fields + freshness (05.8/05.9)
BM25 misses paraphrases, dense misses exact IDs Single-mode retrieval Hybrid + contextual BM25
Index 3× bigger after "improvement" Multi-vector/context without budget check Measure index size; prune views
Re-chunk changed nothing measurable Eval too easy / wrong metric Harder question set, hit@1, context sufficiency

Common misconceptions#

Misconception Reality
"There's one best chunk size." Optimum depends on retrieval mode, doc type and model; measure on your questions (Part 7).
"Bigger chunks are always safer." They dilute embeddings, waste context and hurt precision — retrieve small, return big instead.
"Contextual retrieval is a prompt trick, not engineering." It's a versioned index-time pipeline with real cost accounting; the prompt is one component.
"Late chunking works with any embedding API." It needs token-level embeddings; only long-context models that expose them (Jina, Voyage) support it as of November 2026.
"Propositions replace chunks." They replace the indexing unit; you still expand to parent context for the generator.
"RAPTOR is just a bigger parent-child." It builds an LLM-generated abstraction tree, not the document's own structure — different cost and failure profile.
"Multi-vector means ColBERT." Different technique: several whole-text views per chunk vs per-token late interaction (Module 06).
"Once chunked, done." Chunking config is versioned lineage; strategy changes trigger re-embedding (Part 8, 05.9).
"LLM-based chunking is always better." Cost/latency per document and hallucination risk; semantic/LLM chunking shows mixed evidence — evaluate (05.6 covers the basics).

Key takeaways#

  • Chunking has three separable decisions: segmentation (05.6 + recipes), indexing representation (context, multi-vector, late chunking) and expansion (parent-child, windows, neighbours). Techniques compose across them.
  • Retrieve small, synthesise big is the master pattern: parent-child, sentence-window, auto-merging and query-time expansion are all instances.
  • Contextual retrieval (Anthropic, Sep 2024) prepends an LLM context sentence to each chunk for both embedding and BM25; published gains 35%/49%/67% on their eval; ~$1.02/M doc tokens with prompt caching — verify on your data.
  • Multi-vector indexes several views (text/summary/question/keywords) per chunk; question views exploit the query-document register gap (doc2query/HyDE lineage).
  • Late chunking pools contextualised token vectors per chunk — supported by Jina v3/v4 and Voyage context models, not by the hosted OpenAI/Google embedding APIs (and Anthropic has no embedding API at all). It is not a boundary finder, and independent evidence (6.5) shows a coherence-versus-efficiency trade-off against contextual retrieval.
  • RAPTOR builds LLM summary trees for overview+detail retrieval; propositions index atomic facts — both pay indexing cost for retrieval precision.
  • Seventeen document-type recipes share one Block → blocks_to_chunks toolkit; the recipe's job is finding the document's atomic unit.
  • Dense, BM25, hybrid and stuffing want different chunks; evaluate hit-rate on your own question set before adopting any technique.
  • Chunking config is versioned lineage: stable IDs make incremental updates cheap; strategy changes mean re-embedding.

Terms introduced in this lesson#

Term One-line definition
Parent-child chunking Small children embedded for search; larger parents returned to the generator
Small-to-big retrieval The pattern of retrieving a small unit and synthesising from a larger one
Sentence-window retrieval Embed single sentences; return a window of surrounding sentences (LlamaIndex)
Auto-merging retrieval Promote retrieved leaf chunks to their parent when enough siblings hit (LlamaIndex)
Window/chunk expansion Query-time expansion of a hit to its neighbours or parent
Contextual retrieval Prepending LLM-generated per-chunk context before embedding and BM25 indexing (Anthropic)
Contextual embeddings / contextual BM25 The two halves of contextual retrieval
Multi-vector representation Several embeddings of different views of one chunk, all resolving to it
Hypothetical question generation Generating questions a chunk answers, for embedding (doc2query/HyDE lineage)
doc2query / HyDE Query-prediction document expansion / hypothetical-document embedding techniques
Late chunking Embedding the whole document, then mean-pooling token vectors per chunk span
Long late chunking Late chunking over overlapping macro-chunks for docs exceeding the context window
RAPTOR Recursive Abstractive Processing for Tree-Organized Retrieval — LLM summary trees
Proposition / propositional chunking Atomic, self-contained fact as the indexing unit (Dense X Retrieval)
Propositionizer The fine-tuned model that decomposes text into propositions
Block / recipe A typed document piece / the per-type splitter producing them
Table card / row-group chunk Overview chunk / header-repeating row chunks for tabular data
ChunkingConfig / stable chunk ID Versioned chunking parameters / deterministic ID enabling incremental reuse
Hit rate / context sufficiency Retrieval eval metrics: answer text retrieved / retrieved context can answer

All terms are also collected in the glossary.


Exercises#

  1. Parent-child (2.2): run s2_parent_child.py, then change child_chars to 150 and 500. How do child count and parent coverage change? Which size retrieves best on the demo query?
  2. Expansion trade-off (2.3): in s2_expand.py, expand before=2, after=2 on the same hit. Which irrelevant neighbour sneaks in, and what does that argue for parent-child over flat windows?
  3. Contextual retrieval cost (3.1): call indexing_cost twice — first with Anthropic's stated assumptions (10k chunks, 800 chunk tokens, 8k doc tokens, 100 context tokens) and the Claude 3 Haiku prices they used in September 2024 ($0.25 in / $1.25 out per Mtok, cache read at 10% of input, cache write at 1.25× input), then with a current Haiku-class price (Claude Haiku 5.5, ≤100K-token prompts: $0.10 in / $0.50 out, cache read $0.01, 5-minute cache write $0.125 per Mtok — pricing, as of November 2026). Divide each total by the number of million document tokens (10k chunks × 800 tokens ÷ 1M = 8M). How do the two results compare to Anthropic's $1.02/M doc tokens figure, and which of the three cost terms (fresh input, cached input, generated context) is largest?
  4. Multi-vector (3.2): add a keywords-only retrieval pass to s3_multivec.py and a query "SOC 2" — which view wins and why?
  5. Late chunking (4.1): in s4_late_chunk.py, set ALPHA=0.0 (no document context) and ALPHA=0.8. How do the cosine gaps move? What does that say about the dilution trade-off?
  6. RAPTOR (4.2): change fanout to 2 in s4_raptor.py and count the summary nodes produced for 6 leaves. Extrapolate the LLM-call count for 10k chunks at fanout 3 vs 10.
  7. Propositions (4.3): write a decompose_fn that splits SECTION on sentence boundaries only (no LLM) and run coverage on it. Compare with the canned LLM propositions' 92%. What does the sentence splitter's score tell you — and, more importantly, what does coverage not measure that makes the canned propositions the better index units?
  8. Recipe choice (Part 5): pick one document from the running corpus (a contract, the help centre, a transcript). Write its *_blocks() adapter and run blocks_to_chunks; inspect three chunks for broken units.
  9. Eval harness (Part 7): add a fifth question whose answer needs two sections — for example "can I return an opened drill, and is it still under warranty?" — and let answer be a list of substrings that must all appear in the combined top-k contexts (all(a in ctx for a in answers)). Run each strategy at k=1, 2 and 3. Which misses, and what does that say about k, expansion and the parent-child approach?
  10. Lifecycle (Part 8): bump ChunkingConfig to version 3 with child_chars=600, regenerate stable_chunk_ids for the same text, and explain which chunks the incremental pipeline would re-embed.

Hints and worked answers#

These were checked by running the lesson's code (Python 3.14 locally; the code is version-agnostic).

  1. Parent-child. With child_chars=150 the demo makes 9 children (one per sentence, since every sentence is under 150 characters); at 260 it makes 4; at 500 it makes 3 (one per section). The parent count stays 3 because parents follow sections, not child_chars. Smaller children embed more precisely but cost more vectors and need the parent fetch; at 500 the child is nearly the parent and the benefit of "small to big" shrinks. The demo query returns the Returns parent first at every size, so the toy corpus cannot rank the sizes — which is the lesson of Part 7.
  2. Expansion. before=2, after=2 around c2 returns all five chunks: c0 and c1 (useful warranty context) but also c3 and c4, two Returns sentences unrelated to the question. Position-based windows cross topic boundaries; a parent is a semantic boundary. That is the argument for parent-child.
  3. Cost. Pass the optional price_cache_write argument (0.3125 for Claude 3 Haiku, 1.25× its $0.25 input price; 0.125 for Haiku 5.5) for the "with write" figures. Results for 10k chunks (= 8M document tokens): Claude 3 Haiku prices give $5.38 without the cache write and about $7.88 with it, i.e. roughly $0.67 and $0.98 per million document tokens, close to Anthropic's $1.02 (the post does not publish the exact arithmetic, so a small residual is expected). Haiku 5.5 prices give $2.15 and $3.15 in total, about $0.27 and $0.39 per million document tokens. All three prices fell by the same factor (2.5×) from Claude 3 Haiku to Haiku 5.5 for input, output and cache read, so the no-write total falls exactly 2.5×. Per chunk, the largest term at Claude 3 Haiku prices is the fresh input (850 tokens × $0.25 = about 40%), then the cached document read (8,000 × $0.025 = about 37%), then the 100 generated tokens (about 23%) — the caching discount is what stops the 8,000-token document from dominating.
  4. Multi-vector. On a keywords-only pass, "SOC 2" scores 0 for features because the toy tokenizer splits the query into soc and 2 while the keyword view holds the single token soc2; the tiny non-zero score on price-pro is a hash collision, not a match. Query "soc2" and features wins (0.52). The lesson is practical: lexical-style views need the same normalisation (SOC 2 vs SOC2, hyphens, case) on both sides.
  5. Late chunking. With ALPHA=0.0 the pronoun chunks' late and early cosines are identical (0.196 and 0.204 — no document context flows in; chunk 0 differs slightly, 0.693 vs 0.704, because pooled per-token vectors are averaged and renormalised differently from one bag-of-words vector). With ALPHA=0.8 they rise to 0.479 and 0.492, while the self-contained chunk 0 falls to 0.661: more context helps referring chunks and dilutes self-contained ones.
  6. RAPTOR. fanout=2 over 6 leaves yields 5 summary nodes (three at level 1, one at level 2, one at level 3; a lone node is carried up unchanged). The summary-call count is about N/(k−1): roughly 5,000 LLM calls for 10k chunks at fanout 3 and about 1,100 at fanout 10 — wider fan-out is cheaper but each summary compresses more and loses detail.
  7. Propositions. A sentence splitter gives 4 pieces (the heading counts as one) and 100% word coverage, because the pieces are just the original text. Coverage only detects dropped words; it says nothing about whether each unit is self-contained. The LLM-style propositions score lower (92%) yet are better index units because they resolve references ("the customer pays…", "unused Acme tools") that a plain sentence leaves implicit. Always pair coverage with a read-through of the units.
  8. Recipe choice. A good answer shows three chunks and names the unit each one holds, not a transcript of code. Look for: a clause split mid-sentence, a table row without its header, a code fence cut in half, a pronoun chunk with no antecedent.
  9. Eval harness. On the toy retriever, all three strategies miss at k=1 and k=2 for that question and recover only at k=3, when a Returns hit finally appears among the results. The answer is spread across two sections, so no single parent or window covers it; the fix is a larger k, query decomposition (Module 07) or a retriever that scores sections rather than sentences — not a bigger chunk.
  10. Lifecycle. Bumping to version 3 changes the label (parent-child-v3), so every ID changes and every chunk is re-embedded — a deliberate full re-index, priced with reindex_cost. Only a change that leaves doc, config version, position and text identical keeps an ID. Changing a metadata field alone changes none of these inputs, so nothing is re-embedded.

Check yourself#

  1. What are the three separable decisions in chunking, and which lesson/part owns each?
  2. Why does "retrieve small, synthesise big" beat one-size-fits-all chunking?
  3. What does contextual retrieval prepend to each chunk, and to which two indexes?
  4. Why does contextual retrieval need prompt caching to be affordable?
  5. What's the difference between contextual embeddings and contextual BM25?
  6. Name the four multi-vector "views" and the research technique behind question views.
  7. What does late chunking do differently from naive chunking, and which models support it?
  8. What is a RAPTOR tree, and when is it worth its cost?
  9. What is a proposition, and why does proposition-level indexing help retrieval?
  10. For a support-ticket FAQ export, what's the atomic chunk unit and why?
  11. Why must table row chunks repeat the header line?
  12. Why are form fields stored as records rather than chunks?
  13. Which retrieval mode benefits most from contextual BM25, and why?
  14. What metric does the Part 7 harness compute, and what is its main limitation?
  15. What makes a chunk ID "stable", and why does that matter for incremental updates?

Further resources#


← 05.6 — Chunking Strategies | Module 05 overview | 05.8 — Metadata Design →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close