Skip to content
Sesha's Blog
Go back

RAG from Scratch, Part 1: Chunking

Edit page

RAG from Scratch series: Part 0: Overview · Part 1: Chunking · Next: Part 2: Embeddings, tokens, and metadata

The 47-character chunk

The tutorial I learned chunking from showed a fixed-size splitter cutting text every 50 characters. Its first chunk was:

"Artificial Intelligence is transforming industr"

That looks plausible until you count it. It’s 47 characters. A real 50-character cut of the same text gives:

"Artificial Intelligence is transforming industries"

It’s a small slip, and tutorial outputs are usually illustrations rather than real runs. But it taught me the most useful habit in this whole topic: never trust a chunker you haven’t printed.

for i, c in enumerate(chunks):
    print(i, len(c), repr(c))

The rest of this post builds two chunkers from scratch so you can see exactly what they do.

Why chunk at all?

An embedding model turns text into a fixed-length vector, for example 384 or 1,536 numbers, no matter how much text goes in. If you embed a 100-page document as one vector, that vector is an average of every topic in the document. It ends up loosely similar to many queries and strongly similar to none.

There are three more reasons to split:

Chunking turns one blurry vector into many sharp ones, each about a single topic.

Five ways to chunk

StrategyHow it splitsStrengthWeakness
Fixed-sizeEvery N characters or tokensSimple, predictableCuts mid-sentence, ignores meaning
RecursiveTries paragraphs, then lines, then words, then charactersRespects natural boundariesStill driven by size, not meaning
Document-basedBy structure: headings, sections, code blocks, tablesFollows how the author organized the contentNeeds a layout-aware parser
SemanticEmbeds sentences and cuts where neighbors stop being similarSplits at topic shiftsExtra embedding cost
AgenticAn LLM extracts standalone statements, then groups themGroups related ideas from anywhere in the textMany LLM calls; slow, costly, non-deterministic

This post implements the first two, since they’re the foundation the others build on.

Fixed-size chunking from scratch

The simplest chunker cuts every chunk_size characters. To avoid losing facts that land on a boundary, it steps forward by chunk_size - overlap, so the end of each chunk repeats at the start of the next:

def fixed_size_chunks(text, chunk_size, overlap):
    if overlap >= chunk_size:
        raise ValueError("overlap must be smaller than chunk_size")
    step = chunk_size - overlap
    chunks, start = [], 0
    while start < len(text):
        chunks.append(text[start:start + chunk_size])
        if start + chunk_size >= len(text):
            break
        start += step
    return chunks

The overlap >= chunk_size check matters: without it, step would be zero or negative, and the loop would never advance.

Here’s the output on a short four-sentence text with chunk_size=50 and overlap=10:

chunk 1 (50 chars): 'Artificial Intelligence is transforming industries'
chunk 2 (50 chars): 'industries. It has applications in healthcare, fin'
chunk 3 (50 chars): 'hcare, finance, and education.\n\nMachine learning m'
chunk 4 (50 chars): 'learning models learn patterns from data.\nDeep lea'
chunk 5 (50 chars): '.\nDeep learning uses neural networks with many lay'
chunk 6 (14 chars): 'h many layers.'

You can see both the overlap working (“industries” appears at the end of chunk 1 and the start of chunk 2) and the core problem: chunks end in the middle of words like “fin” and “lay”. The embedding of chunk 3 has to make sense of “hcare, finance”.

Recursive chunking from scratch

Recursive chunking fixes this by trying the most natural separator first and only falling back to cruder ones when a piece is still too big. The order is: paragraph breaks (\n\n), then line breaks (\n), then spaces, and only as a last resort, individual characters.

def _split(text, chunk_size, separators):
    if len(text) <= chunk_size:
        return [text]
    sep, rest = separators[0], separators[1:]
    if sep == "":  # last resort: hard cut by characters
        return [text[i:i + chunk_size] for i in range(0, len(text), chunk_size)]
    parts = text.split(sep)
    out = []
    for i, part in enumerate(parts):
        piece = part + (sep if i < len(parts) - 1 else "")  # keep the separator
        if len(piece) <= chunk_size:
            out.append(piece)
        else:
            out.extend(_split(piece, chunk_size, rest))  # recurse with next separator
    return out

Splitting alone leaves many tiny pieces, so a second step merges neighbors back together until they approach chunk_size:

def _merge(pieces, chunk_size):
    chunks, current = [], ""
    for piece in pieces:
        if len(current) + len(piece) <= chunk_size:
            current += piece
        else:
            if current.strip():
                chunks.append(current.strip())
            current = piece
    if current.strip():
        chunks.append(current.strip())
    return chunks

On the same text with chunk_size=60:

chunk 1 (58 chars): 'Artificial Intelligence is transforming industries. It has'
chunk 2 (51 chars): 'applications in healthcare, finance, and education.'
chunk 3 (49 chars): 'Machine learning models learn patterns from data.'
chunk 4 (52 chars): 'Deep learning uses neural networks with many layers.'

Every chunk now ends on a whole word, and chunks 3 and 4 are clean sentences, because the line break was a natural place to cut. Chunk 1 still splits a sentence, because the first paragraph is longer than 60 characters and had to fall back to splitting on spaces. That’s the trade-off: recursive chunking respects boundaries, but it’s still driven by size, not meaning.

My version leaves out overlap to keep the logic readable. The library version below includes it.

The same thing with LangChain

In practice, you’d use LangChain’s splitters, which implement the same ideas:

from langchain_text_splitters import (
    CharacterTextSplitter,
    RecursiveCharacterTextSplitter,
)

fixed = CharacterTextSplitter(separator="", chunk_size=50, chunk_overlap=10)
recursive = RecursiveCharacterTextSplitter(
    separators=["\n\n", "\n", " ", ""], chunk_size=60, chunk_overlap=10
)

chunks = recursive.split_text(text)

Expect small differences from the scratch output. LangChain strips whitespace from chunk edges and handles overlap during merging, so chunk lengths vary a little. Print the chunks and compare them yourself.

Overlap: cheap insurance

Overlap exists for one failure in particular. Without it, a policy document might split like this:

"...employees are entitled to 12 days of" | "paid sick leave per calendar year..."

Neither chunk answers “How many sick days do I get?” With overlap, the second chunk begins “to 12 days of paid sick leave…”, and the full fact survives in one place.

The cost is redundancy: more storage, more embedding calls, and the same sentence can be retrieved twice. A reasonable starting point is 10–20% of the chunk size.

Choosing a chunk size

Chunk size fails in two opposite directions:

A common starting point is 200–500 tokens with some overlap. But the right answer depends on your documents and your users’ questions, which is why Part 4 of this series covers how to measure it rather than guess.

Tables and images

Tables and images don’t embed well as raw content, because users ask questions in natural language. The usual fix is to embed an LLM-written summary of the table or image, store the raw content alongside it, and pass the raw content to the LLM when the summary is retrieved. You find with the summary and answer with the data. This is called the multi-vector retriever pattern.

Run it yourself

From the root of the rag-scratch-to-speciality repo:

uv sync
uv run python code/chunking/fixed_recursive_scratch.py

The last lines of the output reproduce the opening example:

The blog's 'Chunk 1' is 47 chars, not 50.
A real 50-char cut gives: 'Artificial Intelligence is transforming industries'

To run the LangChain version:

uv sync --group lib
uv run --group lib python code/chunking/fixed_recursive_lib.py

Full code: fixed_recursive_scratch.py · fixed_recursive_lib.py

Takeaways

Next: Part 2: Embeddings, tokens, and metadata


Edit page
Share this post:

Previous Post
RAG from Scratch, Part 0: What This Series Covers
Next Post
RAG from Scratch, Part 2: Embeddings, Tokens, and Metadata