Lesson 23.1 · 1 of 7 · 4 min read · Reviewed 24 Nov 2026
Chunking strategies
By the end, you can
- Choose a chunking strategy.
- Use overlap and structure to keep ideas together.
Strategies
| Strategy | How | Good for |
|---|---|---|
| Fixed size | Every N tokens | Quick baseline |
| Fixed size with overlap | N tokens, sliding by N minus overlap | Ideas crossing boundaries |
| Structural | Split on headings, sections, paragraphs | Manuals, policies, docs |
| Semantic | Split where topic shifts (by embedding change) | Long unstructured text |
| Document-specific | Code by function; tables by row group; chats by turn | Special formats |
Size
There’s no universal best. Typical starting points are a few hundred tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. with 10 to 20% overlap. Then test: run your question set (chapter 26) with two or three sizes and compare retrieval recall.
Keep useful metadata
Attach to each chunkChunking: Splitting documents into smaller passages before embedding and indexing them.: document title, section heading, page, date. Prepending the heading path to the chunk text often helps:
Returns policy > Footwear > Worn items
Footwear that has been worn outdoors may be returned only if faulty...
Parent and child chunks
Retrieve with small chunks (precise matching), but pass the larger parent section to the model (more context). Many frameworks support this “small to big” pattern.
Key points
- Chunks should hold one complete idea: too small loses context, too big dilutes relevance.
- Split on structure (headings, paragraphs, sections) rather than fixed character counts where you can.
- Small overlaps between chunks help when an idea crosses a boundary; test sizes on your own questions.
Chunk a policy three ways
Chunk the same policy by fixed size, fixed size with overlap, and by headings, and check which keeps a rule with its exception.
You will have: Three chunkers and a table showing chunk counts and whether the footwear rule and its exception share a chunk.
Steps
- Read the policy: the footwear rule and its exception sit in one section, across a sentence boundary.
- Write fixed(): chunks of 12 words with no overlap.
- Write overlapping(): chunks of 12 words that start every 8 words.
- Write structural(): one chunk per heading, with the heading path prepended.
- Report, for each method, whether one chunk contains both 'unworn' and 'faulty'.
Done when
- fixed() splits the rule from its exception.
- structural() keeps them together and prefixes each chunk with its heading.
- The table prints a chunk count for each method.
Open in the Playground No API key needed.
Starter code (Python)
POLICY = """# Returns
## Clothing
Clothing may be returned within 60 days with a receipt.
## Footwear
Footwear may be returned within 30 days if it is unworn and in its box. Footwear worn outdoors may be returned only if it is faulty.
## Refunds
Refunds go back to the original payment method within five working days."""
def body_words(text):
return [w for line in text.splitlines() if not line.startswith("#") for w in line.split()]
def fixed(text, size=12):
# TODO: consecutive chunks of `size` words, no overlap
return [" ".join(body_words(text))]
def overlapping(text, size=12, stride=8):
# TODO: chunks of `size` words starting every `stride` words
return [" ".join(body_words(text))]
def structural(text):
# TODO: one chunk per "## " heading, text prefixed with "Returns > <heading>: "
return [text]
def together(chunks):
return any("unworn" in c and "faulty" in c for c in chunks)
for name, fn in [("fixed", fixed), ("overlap", overlapping), ("structural", structural)]:
cs = fn(POLICY)
print(f"{name}: {len(cs)} chunks, rule and exception together: {together(cs)}")
Show a solution
POLICY = """# Returns
## Clothing
Clothing may be returned within 60 days with a receipt.
## Footwear
Footwear may be returned within 30 days if it is unworn and in its box. Footwear worn outdoors may be returned only if it is faulty.
## Refunds
Refunds go back to the original payment method within five working days."""
def body_words(text):
return [w for line in text.splitlines() if not line.startswith("#") for w in line.split()]
def fixed(text, size=12):
ws = body_words(text)
return [" ".join(ws[i:i + size]) for i in range(0, len(ws), size)]
def overlapping(text, size=12, stride=8):
ws = body_words(text)
out = []
for i in range(0, len(ws), stride):
out.append(" ".join(ws[i:i + size]))
if i + size >= len(ws):
break
return out
def structural(text):
top, out, current, lines = "", [], None, []
for line in text.splitlines():
if line.startswith("# "):
top = line[2:].strip()
elif line.startswith("## "):
if current:
out.append(f"{top} > {current}: " + " ".join(lines))
current, lines = line[3:].strip(), []
elif line.strip():
lines.append(line.strip())
if current:
out.append(f"{top} > {current}: " + " ".join(lines))
return out
def together(chunks):
return any("unworn" in c and "faulty" in c for c in chunks)
for name, fn in [("fixed", fixed), ("overlap", overlapping), ("structural", structural)]:
cs = fn(POLICY)
print(f"{name}: {len(cs)} chunks, rule and exception together: {together(cs)}")
print("example structural chunk:", structural(POLICY)[1][:60] + "...")