Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 9 steps

Build and Measure a RAG System
  1. 1
    Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  2. 2
    Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  3. 3
    Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  4. 4
    Vector Databases Hands-On: The Same Search in Chroma and pgvector
  5. 5
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  6. 6
    RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  7. 7
    Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  8. 8
    Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  9. 9
    Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Learning path: Build and Measure a RAG System · Step 3 of 9

Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook

Where you cut decides what search can find. Cut a 13-section employee handbook three ways in plain Python and count the damage: fixed size gives 12 chunks with 12 cut and 11 mixed, sentences give 0 cut but 9 mixed, and headings give 13 clean chunks that know their source.

Chaand Sheikh

·27 November 2026Retrieval and RAG

What you will learn

  • Cut a document three ways: fixed size with overlap, whole sentences, and by heading
  • Measure each cut with two checks: does it cut a sentence, does it mix topics
  • See what overlap buys and what it costs
  • Store the source and heading with every chunk so answers can be traced

Before you start

  • Basic Python strings and regular expressions
  • Why RAG Exists

Chunking is how you cut a document into pieces before search can use it. It sounds like housekeeping, but it decides what can be found: every later stage of a RAG system only ever sees those pieces. Search can only find what a chunk holds.

We'll try three ways to cut the same document, measure each one with two simple checks, and see which one keeps the answer whole. Everything here is standard-library Python, with no API key.

Where does the knife go?

Think of cutting a layered cake for a party. Slices too big, and nobody can eat one; in search, that's one chunk holding many topics. Slices too small, and the topping falls off; a fact loses what it was about. The best way is to cut along the layers, so each slice is one whole piece. Same cake, same knife. What changes is where you cut.

One handbook, one question

Brightfield's employee handbook, handbook.md, has 13 sections and 5,806 characters. An employee asks: How many days of annual leave do I get? The answer sits in one section.

Keep the whole handbook as one block and that's one chunk of 5,806 characters, where leave, expenses and security all blur together. The cut decides the answer.

load_sections reads the file and turns every ## heading into a (heading, text) pair:

import re
from pathlib import Path

HANDBOOK = Path(__file__).with_name("handbook.md")


def load_sections(path=HANDBOOK):
    sections = []
    for block in path.read_text(encoding="utf-8").split("\n## ")[1:]:
        heading, _, body = block.partition("\n")
        sections.append((heading.strip(), " ".join(body.split())))
    return sections

Way 1: fixed size, the knife does not read

def fixed_chunks(text, size=600, overlap=100):
    chunks, start = [], 0
    while start < len(text):
        chunks.append(text[start:start + size])
        if start + size >= len(text):
            break
        start += size - overlap
    return chunks

Take 600 characters, then move forward by size - overlap, so from 0 to 500, and repeat. With an overlap of 0, the first cut lands here:

chunk 1 ends:   ...you choose your own schedule, a
chunk 2 starts: s long as you complete your ag...

The word "as" is cut in half. One piece has no ending, the other has no beginning, and search only finds half of the sentence.

Overlap: a safety margin between chunks

With an overlap, each chunk starts a little before the last one ended, so those characters sit in both chunks:

OverlapChunksSentences kept whole (of 66)
01057
1001264
2001566

More overlap saves more sentences, but you store (and embed) more chunks.

Way 2: whole sentences

def sentence_chunks(text, max_chars=600):
    chunks, current = [], ""
    for sentence in re.split(r"(?<=[.!?])\s+", text):
        if current and len(current) + len(sentence) + 1 > max_chars:
            chunks.append(current)
            current = sentence
        else:
            current = (current + " " + sentence).strip()
    if current:
        chunks.append(current)
    return chunks

The regex splits the text after every ., ! or ?, giving 66 sentences. Then sentences drop into the current chunk until the next one would push it past 600 characters. The whole welcome section fits (391 characters), and there's still room, so two sentences from Working Hours drop in too. The next sentence would make 685, over the limit, so the chunk closes and that sentence starts chunk two.

No sentence is cut any more. But look at chunk one: it holds two topics, the welcome and working hours.

Way 3: cut along the section lines

The handbook already has structure. Cutting by heading takes one line:

def heading_chunks(sections):
    return [{"source": "handbook.md", "heading": h, "text": b} for h, b in sections]

Thirteen chunks, one per section, and each one stores three things: the source file, the heading, and the text. The Annual Leave chunk holds the answer, twenty-five days, and it knows exactly where it came from, so an answer built on it can name its source.

Three ways to cut the same handbook Section lines (dashed): Welcome | Working Hours | Annual Leave | Sick Leave ... Fixed every 600 characters: cuts words, crosses topics Sentences only at sentence ends: no cuts, but topics still mix Headings on the section lines: one whole topic per chunk
A schematic of where each strategy puts the knife; cut positions are illustrative, the counts below are from the real run.

Is it cut? Is it mixed?

Two small checks turn "looks fine" into numbers:

def cuts_a_sentence(chunk):
    starts_clean = chunk[0].isupper() or chunk[0].isdigit()
    ends_clean = chunk.rstrip()[-1] in ".!?"
    return not (starts_clean and ends_clean)


def topics_touched(chunk, text, sections):
    start = text.find(chunk)
    end, offset, touched = start + len(chunk), 0, 0
    for _, body in sections:
        if offset < end and start < offset + len(body):
            touched += 1
        offset += len(body) + 1
    return touched

cuts_a_sentence looks at both edges: a chunk that starts with a small letter or ends mid-word is cut. topics_touched counts how many sections a chunk reaches into; more than one means it's mixed. Running chunkers.py prints one line per strategy (fixed uses the default overlap of 100):

python chunkers.py
fixed     chunks=12  avg=575  cut=12  mixed=11
sentence  chunks=11  avg=526  cut=0   mixed=9
heading   chunks=13  avg=445  cut=0   mixed=0
StrategyChunksCutMixedKnows its heading
Fixed size + overlap 100121211No
Sentences, max 6001109No
By heading1300Yes

Only the heading cut keeps every sentence and every topic whole.

You will hear these too

  • Recursive chunking tries a big split first, then paragraphs, then sentences, until the pieces fit.
  • Semantic chunking cuts where the topic shifts.
  • Parent document chunking searches small pieces, then gives the model the whole section they came from.

Each one has the same goal: keep one idea together.

Common mistakes

  • Cutting by size when the document already has headings, paragraphs or sections.
  • Using zero overlap with a fixed-size cut. Sentences break at every boundary.
  • Throwing away the source and heading. Without them, nobody can check where an answer came from.
  • Judging a chunker by eye. Count cut sentences and mixed topics, like the two checks above.
  • Assuming one size suits every document. A handbook section and a long contract clause need different cuts.

Quick recap

  • Start with the structure the document already has.
  • If you must cut by size, keep some overlap, and accept you'll store more chunks.
  • Store the source and heading with every chunk.

Try it yourself

Call fixed_chunks with a size of 300 and an overlap of 50 (the project's python demo.py fixed "300 50" does exactly that). The run gives:

fixed     chunks=24  avg=289  cut=23  mixed=13

Smaller pieces, twice as many chunks, and still almost all of them cut. Now try 600 and 200, and compare with the overlap table above.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Build and Measure a RAG System · step 3 of 9

Previous
Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
Next post
Vector Databases Hands-On: The Same Search in Chroma and pgvector

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Related posts

The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer

Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.

Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors

Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.

Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning

A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.

Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations

Swap a toy embedder for a model that learned. Two roads (all-MiniLM-L6-v2 on your machine, or OpenAI's API with your key), three sizes (384, 1,536 and 3,072 numbers), one rule, and three use cases built on the same rank function, with real scores.

On this page

  • Where does the knife go?
  • One handbook, one question
  • Way 1: fixed size, the knife does not read
  • Overlap: a safety margin between chunks
  • Way 2: whole sentences
  • Way 3: cut along the section lines
  • Is it cut? Is it mixed?
  • You will hear these too
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.