Text Chunking

Cut a 187-character warranty paragraph every 100 characters and the word “purchase” splits in two. No chunk holds the warranty term. Cut at sentence ends and it stays whole.

Pick a chunker and drag the chunk size. Watch the yellow fact: whole, or cut. Then we build, piece by piece, fixed cuts, overlap, sentence windows, recursive splitting, token limits, semantic breakpoints, heading-aware splits and the measurement that picks a size.

You need a little Python and the idea that a model can turn text into a vector. We build the rest from zero.

Cut the paragraph

100

The paragraph is an illustrative owner’s guide made up for this page. The chunkers run live in your browser; the recursive one follows LangChain’s RecursiveCharacterTextSplitter with its default separators.

Chapter 0

One Vector Cannot Hold a Manual

See why a whole document blurs into one point, and why we cut it into chunks first

A customer asks your support bot: “How long is the XR-7 warranty?” The answer is one sentence in a 40-page owner’s guide. The system must find that sentence before a language model can quote it.

Search runs on embeddings. An embedding model turns a text into a vector, and texts with similar meaning get vectors that point the same way. You embed the question, compare it with the stored vectors, and fetch the best texts. This is the retrieval step of RAG, retrieval-augmented generation (see the RAG lesson and vector embeddings).

Why not store the whole guide as one vector? One vector has one direction. The guide covers warranty, installation, power, maintenance, faults and service. Average six directions and the result points at none of them.

Average six topics into one vector

Teal arrows are the six sections. Blue is their average, the one-vector guide. Pink is the query. Turn the query and compare the scores.

15°

An illustrative two-number picture. Real embeddings have hundreds of numbers (all-MiniLM-L6-v2 gives 384), but the averaging problem is the same.

How do we score “points the same way”? Call the query’s vector q and a stored text’s vector c. The score is the cosine similarity: the cosine of the angle between the two arrows.

Say it aloud

Cos of q and c equals q dot c, over the length of q times the length of c.

cos(q, c)
cos of q and c the score, from −1 to 1. One means the arrows point the same way.
q · c
q dot c the dot product: multiply matching numbers and add them up.
|q|
the length of q the square root of the sum of q’s numbers squared.
|c|
the length of c the same for the stored text’s vector.
In plain words

Multiply q and c number by number and add. Divide by the two lengths, so only the direction counts. Fetch the texts with the highest scores.

With numbers

With made-up numbers: q = (1, 0.2) and the warranty section c = (0.9, 0.3). q · c = 0.9 + 0.06 = 0.96. |q| = 1.02 and |c| = 0.95, so the score is 0.96 / 0.97 = 0.99. The guide’s average (0.2, 0.6) scores only 0.50.

So we cut the document into chunks: pieces of text, each about one idea, each with its own vector. Chunking is the choice of where to cut. A cut in the wrong place splits a fact, and no later step can join it again.

The failure. Symptom: the bot says it cannot find a fact that is in the document. Measure: search your chunk list for the answer sentence. If no chunk holds it whole, the chunker broke it. Fix: change where you cut, as the next chapters show.

The road

  1. Fixed size: cut every S characters, and count the chunks.
  2. Overlap: the chance a fact breaks, and what overlap costs.
  3. Sentences: whole sentences, and the reference a cut still breaks.
  4. Recursive: paragraphs first, then lines, then words. The hero’s fourth chunker.
  5. Tokens: the limit where an embedding model stops reading.
  6. Semantic: cut where the topic jumps.
  7. Structure: headings, code and tables decide the cuts.
  8. Size: measure recall at k and fit the context window.
  9. Lab: every chunker on your own text, with a live search.
  10. Field guide: terms, numbers, code and links.
Why does one vector for a whole six-section guide match a warranty question badly?

Chapter 1

Cut Every S Characters

Cut the text at fixed positions, count the chunks, and watch a fact break in half

The simplest chunker counts characters and cuts every S of them. It needs no knowledge of the language. It is fast and gives the same chunks every time.

Take the hero’s warranty paragraph, 187 characters long. Cut every 100 characters. Chunk 1 ends with “date of purch” and chunk 2 starts with “ase.” The warranty term, 55 characters, sits across the cut, so neither chunk holds it.

Overlap repeats the last O characters of one chunk at the start of the next. The window then moves forward by the stride, S minus O, not by S.

Slide the window

Each bar is one chunk. Purple is overlap. Yellow is the warranty term. Change S and O and find a setting that keeps the term whole.

100
20

The overlap is capped at S minus 10 so the window always moves. The paragraph is illustrative.

How many chunks will you store? Call the text length in characters L, the chunk size S and the overlap O. Call the number of chunks N.

Say it aloud

N equals the ceiling of L minus O, over S minus O.

N
N the number of chunks, when L is longer than S. A shorter text is one chunk.
⌈ ⌉
the ceiling of round up to the next whole number, because a partial chunk is still a chunk.
L
L the text length in characters.
O
O the overlap: characters each chunk repeats from the one before.
S − O
S minus O the stride: how far the window moves each time. S is the chunk size.
In plain words

Take the length L and remove one overlap O, because the first chunk has no overlap to repeat. Divide by the stride, S minus O. Round up. That is N.

With numbers

The paragraph: L = 187, S = 100, O = 20. (187 − 20) / 80 = 2.09, rounded up to N = 3. A 10,000-character guide with S = 500 and O = 50 gives 9,950 / 450 = 22.1, so 23 chunks.

The code below stops as soon as a chunk reaches the end of the text. A loop that runs while start < len(text) makes extra chunks: with L = 300, S = 100 and O = 50 it makes 6, and the sixth lies wholly inside the fifth.

pythondef fixed_chunks(text: str, size: int = 500, overlap: int = 50) -> list[str]:
    assert 0 <= overlap < size
    stride, start, chunks = size - overlap, 0, []
    while True:
        chunks.append(text[start:start + size])
        if start + size >= len(text):     # this chunk reached the end
            return chunks
        start += stride

len(fixed_chunks("x" * 187, 100, 20))   # 3

The failure. Symptom: answers that quote half a word or half a number. Measure: for each test question, check whether its answer sentence appears whole in some chunk. Fix: add overlap (Chapter 2) or cut only at boundaries the text already has (Chapters 3 and 4).

A 1,000-character text is cut with S = 300 and O = 50. How many chunks?

Chapter 2

How Often a Fact Breaks

Measure the chance that a cut lands inside a fact, and pay for overlap in storage

A fact here is a span of text that a question needs whole, like the 55-character warranty term. In a long document, facts start at every possible place relative to the cuts. So the useful question is a rate: what share of facts does a chunker break?

Drop facts on the windows

The bars are chunk windows. Each short line is a fact at a random place: green if some window holds it whole, red if not. Press Drop 200, then change f, S and O.

55
100
0

Fact positions are random, so each drop differs a little from the formula. Overlap is capped at S minus 10.

Count it exactly. Call the fact length in characters f, and keep S for the chunk size and O for the overlap. Call the chance that no chunk holds the fact whole Psplit.

Say it aloud

P-split equals the larger of zero and f minus one minus O, over S minus O.

Psplit
P-split the share of facts that no chunk holds whole. A fact longer than S always splits.
max(0, …)
the larger of zero and a negative count of bad positions means none.
f
f the fact length in characters.
O
O the overlap in characters.
S − O
S minus O the stride: the number of different start positions inside one window step.
In plain words

Inside one stride there are S minus O places a fact can start. It breaks when it starts in the last f minus 1 minus O of them. Divide that count by the stride.

With numbers

The warranty term: f = 55, S = 100. With O = 0, Psplit = 54 / 100 = 0.54. With O = 20, it is 34 / 80 = 0.43. With O = 54, it is 0: every 55-character fact lands whole in some chunk.

The rule hides a guarantee: an overlap of f − 1 characters keeps every fact of length f whole. The hero’s 100-character cut with 50 of overlap misses the warranty term by one character, because the term is 55 long and needs O = 54.

Overlap costs storage. Each chunk holds S characters but only S − O of them are new:

stored text / original text ≈ S / (S − O)  ·  100 / 80 = 1.25  ·  500 / 450 = 1.11  ·  100 / 50 = 2.00

So 20 characters of overlap on 100-character chunks means 25% more text to embed and store. Near-duplicate chunks also crowd the top results.

The failure. Symptom: some answers arrive with their last words missing. Measure: find the typical length of your answer spans and compute Psplit for your S and O. Fix: raise O toward f − 1, or cut at sentence ends so most facts never straddle a cut.

Facts are 41 characters long. Chunks have S = 200 and O = 40. What share of facts break?

Chapter 3

Cut at Sentence Ends

Keep every sentence whole, then find the reference that a sentence cut still breaks

A better rule never cuts inside a sentence. Split the text at full stops, question marks and exclamation marks. Then group whole sentences into chunks. In the hero, the Sentences chunker keeps the warranty term whole at every size.

Sentence detection has traps. “Dr. Lee” and “3.5 volts” hold full stops that do not end a sentence. Libraries such as spaCy and NLTK use rules and trained models for these cases.

The harder failure is meaning. In the water-cycle text below, sentence 3 starts “It cools” and sentence 5 starts “Those droplets”. Each points back to the sentence before it. Cut between them and a chunk talks about “those droplets” with no droplets in it. Its vector is weaker, and the model that reads it lacks the subject.

Group the sentences

Each card is a sentence. Brackets are chunks. A red card starts with a reference whose subject sits in no shared chunk. Change the window and the step.

2
2

The step stops at w, so the window never skips a sentence. We wrote the six sentences for this page.

A sliding window fixes the orphans. Each chunk holds w sentences and the window moves by a step smaller than w. With w = 3 and step 2, every sentence shares a chunk with the one before it. The cost is 8 stored sentences instead of 6.

Watch the second loop. range(0, n − w + 1, step) looks right, but with n = 6, w = 3 and step 2 it starts chunks at 0 and 2 only. Sentence 6 is in no chunk, so search can never return it.

pythondef sentence_windows(sentences: list[str], w: int = 3, step: int = 2) -> list[str]:
    assert 1 <= step <= w
    out, i = [], 0
    while True:
        out.append(" ".join(sentences[i:i + w]))
        if i + w >= len(sentences):   # the last sentence is in
            return out
        i += step

The failure. Symptom: retrieved chunks open with “It”, “This” or “Those”. Measure: count the chunks whose first word is a pronoun, and check that every sentence index appears in some chunk. Fix: a sliding window, or cut at paragraphs (Chapter 4).

A chunk reads “Those droplets gather into clouds. In time, rain carries the water back down.” What is wrong with it?

Chapter 4

Try the Biggest Break First

Split at paragraphs, then lines, then spaces, and cut inside a word only as a last resort

Authors mark their own boundaries. A blank line ends a paragraph, and a paragraph is often one topic. A recursive splitter tries the strongest boundary first and falls back to weaker ones only for pieces that are still too long.

LangChain’s RecursiveCharacterTextSplitter works in four steps:

  1. Pick the first separator in the list that appears in the text. The default list is a blank line, a line break, a space, and the empty string, which cuts anywhere.
  2. Split the text at that separator.
  3. Keep each piece shorter than S. Split each longer piece again with the rest of the list.
  4. Merge neighbouring small pieces back together while the merged chunk stays within S characters.

Split the guide recursively

Blue blocks are the guide’s paragraphs. Teal bars are chunks. Each cut mark says where it fell: green at a blank line or sentence end. Drag S down until cuts leave the paragraph breaks.

200

A port of the splitter’s algorithm, checked against a Python copy on this guide. Overlap is 0 here. The guide is illustrative.

With S = 200, the 929-character guide splits into 7 chunks: the title and the six sections, every cut on a blank line. With S = 100, the sections no longer fit, so the splitter falls back to spaces. It makes 14 chunks, and 5 of the cuts fall in the middle of a sentence, like the one after “24 months from the”.

The default list has no sentence separator. Add “. ” after the line break, and long paragraphs break at sentence ends before they break at spaces. Set keep_separator="end" too. The class default keeps each separator at the start of the next piece, so chunks would open with “. It covers”.

pythonfrom langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=200,                       # measured by len(), so characters
    chunk_overlap=0,
    separators=["\n\n", "\n", ". ", " ", ""],
    keep_separator="end",                 # the full stop stays with its sentence
)
chunks = splitter.split_text(guide)          # list[str]

Overlap in this splitter is counted in whole pieces. It carries over the last pieces of a chunk whose total length fits within chunk_overlap, so the overlap ends on a word or sentence boundary.

The failure. Symptom: chunks from a recursive splitter still end mid-sentence. Measure: count chunks whose last character is not a full stop. Fix: add sentence separators to the list, or raise S until most paragraphs fit.

Why does the splitter try a blank line before a space?

Chapter 5

Count in Tokens, Not Characters

Convert characters to tokens, and find the text an embedding model drops without a warning

Models do not read characters. They read tokens, pieces of words from a fixed vocabulary (see the tokenization lesson). Model limits are counted in tokens, so chunk sizes should be too.

Every embedding model has an input limit. The open model all-MiniLM-L6-v2 truncates input longer than 256 word pieces, its tokens. The text past the limit never reaches the vector, and no error appears. A fact in the tail of a long chunk is unsearchable.

How many tokens is a chunk? Call its length in characters L and the average number of characters per token c. Call the token count T.

Say it aloud

T is about L over c.

T
T the number of tokens in the chunk.
L
L the chunk length in characters.
c
c characters per token, on average. OpenAI’s guide puts it near 4 for common English text.
In plain words

Divide the chunk length L by c to estimate T. If T is above the model’s limit, the model reads the first part and drops the rest.

With numbers

A 2,000-character chunk with c = 4 has about T = 500 tokens. all-MiniLM-L6-v2 keeps 256 of them, so 256 / 500 = 51% of the chunk is embedded. The last 980 characters or so are invisible to search.

Find the dropped tail

The bar is one chunk. Teal is what the model reads. Red is what it drops. Grow the chunk and watch where the limit cuts.

2,000
4.0

The 256 limit is from the all-MiniLM-L6-v2 model card; 512 is the input size of BERT-style models. c is an average and varies with the tokenizer and the text.

Count with the model’s own tokenizer, and let the splitter use it:

pythonfrom transformers import AutoTokenizer
from langchain_text_splitters import RecursiveCharacterTextSplitter

tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
n = len(tok(chunk)["input_ids"])              # counts the two special tokens too

splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(
    tok, chunk_size=200, chunk_overlap=20)    # sizes now in tokens

The failure. Symptom: facts near the end of long chunks are never retrieved. Measure: tokenize every chunk with the model’s tokenizer and list those over the limit. Fix: size chunks in tokens, below the limit.

A 1,600-character chunk, about 4 characters per token, goes into a model with a 256-token limit. About how much of it is embedded?

Chapter 6

Cut Where the Topic Jumps

Embed each sentence, measure the jump between neighbours, and cut at the largest jumps

Every rule so far reads punctuation. Semantic chunking reads meaning. It embeds each sentence and cuts where two neighbours point in different directions.

  1. Split the text into sentences.
  2. Embed each sentence.
  3. Measure the distance between each pair of neighbours.
  4. Cut wherever the distance is above a threshold.

Call the embedding of sentence i ei. The distance between sentence i and the next is di.

Say it aloud

D-i equals one minus cos of e-i and e-i-plus-one.

di
d-i the jump after sentence i. Near 0 means the same topic.
cos
cos the cosine similarity from Chapter 0.
ei
e-i the embedding of sentence i.
ei+1
e-i-plus-one the embedding of the next sentence.
In plain words

Score two neighbouring sentences with cosine similarity. Subtract the score from 1. A big d-i means the topic changed between them.

With numbers

With made-up numbers: e1 = (0.6, 0.8) and e2 = (0.8, 0.6) have cosine 0.96, so d1 = 0.04, the same topic. Against (1, 0) the cosine of e2 is 0.8, so the jump is 0.20.

Which jumps count as cuts? Most tools rank them. Call the threshold τ and the percentile P.

Say it aloud

Tau equals the P-th percentile of d-one through d-n-minus-one.

τ
tau the threshold. Cut after sentence i when d-i is above tau.
percentileP
the P-th percentile of the value P percent of the way up the sorted list.
d1 … dn−1
d-one through d-n-minus-one all the jumps between the n sentences.
In plain words

Sort the jumps d-i. Read off the value P percent of the way up. That is tau. Cut at every jump larger than tau.

With numbers

The 12 sentences below have 11 jumps. At P = 80, the position is 0.8 × 10 = 8, so τ is the 9th smallest jump, 0.20. Only 0.62 and 0.71 are larger: 2 cuts, 3 chunks, one per topic.

Set the percentile

Each bar is one jump d-i. The warm line is tau. Bands below are the chunks. The text has three topics: power, care and faults. Find the P that gives three chunks.

80

The jumps are illustrative values, not the output of a real model. The percentile uses linear interpolation, as numpy does by default.

LlamaIndex’s SemanticSplitterNodeParser defaults to the 95th percentile. It also embeds each sentence together with one neighbour on each side (buffer_size=1), which smooths the jumps. At 95 here, only the largest jump cuts, so power and care share a chunk.

The failure. Symptom: one chunk is ten times longer than the rest. Measure: plot the chunk lengths in tokens and check the largest against the embedding limit. Fix: run a recursive splitter inside each semantic chunk to cap its size. Remember the cost too: one embedding per sentence before any chunk exists.

You raise P from 80 to 95. What happens to the number of chunks?

Chapter 7

Let the Headings Decide

Split at headings, keep code and tables whole, and carry the heading path with every chunk

Many documents already mark their topics. Markdown has # headings, HTML has h1 to h6, and a PDF has larger, bolder heading lines. A structure-aware chunker cuts at these marks.

Two kinds of content must stay whole. A code block cut in half no longer runs. A table row cut off from its header row is a list of values with no names.

Cut by size or by heading

The column is the guide: headings, prose, a code block and a table. Warm lines are cuts. Red marks a cut inside code or a table. Then switch on the heading path and run the query.

200

The guide and the query are illustrative. Scores come from a toy word-count embedder (Chapter 8), not a real model.

Fixed cuts at 200 characters land at positions 200 and 400. The cut at 400 falls inside the fault table, so the row “Steady red | Blown fuse” lands in a chunk without the header row that names the columns.

LangChain’s MarkdownHeaderTextSplitter splits at the heading marks you list. It returns documents with the text in page_content and the heading path in metadata. It does not treat a # inside a fenced code block as a heading.

pythonfrom langchain_text_splitters import MarkdownHeaderTextSplitter

splitter = MarkdownHeaderTextSplitter(
    headers_to_split_on=[("#", "h1"), ("##", "h2")])   # strip_headers=True by default
docs = splitter.split_text(guide_md)
docs[3].metadata        # {'h1': "XR-7 Owner's Guide", 'h2': 'Warranty claims'}
texts = [" > ".join(d.metadata.values()) + "\n" + d.page_content for d in docs]  # embed these

The splitter removes heading lines from the text by default, so put the path back before you embed. In the device, “How do I file a claim?” shares no word with any section body, and every score is 0. With the path, the “Warranty claims” section is the only one that scores.

The failure. Symptom: a retrieved table row without its header, or code that stops mid-function. Measure: count chunks that open a code fence and never close it, and table rows with no header row. Fix: split at headings and keep each code block and table as one unit.

What does a heading-aware chunker give you that a semantic chunker does not?

Chapter 8

Pick the Size by Measuring

Measure recall at k on your own questions, and fit the chunks into the model’s context

Too small, and a chunk loses the words that make it findable: “24 months” with no “warranty” in sight. Too large, and one vector averages several topics while the model reads text it does not need.

Write a small test set: questions, each with the answer span it needs. Call the number of questions Q. For each one, fetch the top k chunks. Count a hit when one of them holds the answer span whole. Call the number of hits H.

Say it aloud

Recall at k equals H over Q.

recall@k
recall at k the share of questions whose answer is in the top k chunks.
H
H the hits: questions with the whole answer span in their top k.
Q
Q the number of test questions.
In plain words

Run every question. Count the ones whose answer span sits whole in one of the top k chunks. Divide the count H by Q.

With numbers

In the device, at S = 200 and k = 1, the search finds five of six answers: recall@1 = 5 / 6 = 0.83. At S = 60 it is 3 / 6 = 0.50, because small chunks split the answers.

Sweep the chunk size

Green is recall at k. Pink is the text sent to the model per question. Drag S and find the smallest size with full recall.

200

Six made-up questions on the 929-character guide, cut by the recursive splitter. Search uses a toy embedder: word counts after dropping common words, scored by cosine. A real model finds synonyms this one misses.

The miss at S = 200: “How do I make a warranty claim?” fetches the warranty section, which shares the word “warranty”. The answer is in the service section. At S = 1000 recall is perfect, but each question sends the whole guide. Recall alone rewards one giant chunk, so read it next to the cost.

Call the model’s context window C tokens, and the tokens you reserve for instructions, the question and the answer R. With chunk size S in tokens, k chunks must fit.

Say it aloud

K times S is at most C minus R.

k
k the number of chunks you send.
S
S the chunk size, here in tokens.
C
C the model’s context window in tokens.
R
R the tokens reserved for everything that is not a chunk.
In plain words

Take the window C and remove the reserve R. Divide what is left by the chunk size S. The whole number you get is the largest k you can send.

With numbers

With made-up numbers: C = 8,000 and R = 2,000 leave 6,000 tokens. At S = 500, k can be 12. At S = 1,200, k can be only 5.

Or take both sides: search small chunks for a sharp match, then send the parent section that holds it. LangChain’s ParentDocumentRetriever and LlamaIndex’s AutoMergingRetriever build this.

The failure. Symptom: a chunk size copied from a blog post and never checked. Measure: recall@k and text sent over a sweep of S, on real questions. Fix: choose the smallest S that reaches the recall you need.

Of 40 test questions, 34 have their answer span in the top 3 chunks. What is recall@3?

Chapter 9

The Chunking Lab

Run every chunker on your own text, then search it and see which chunk wins

Paste any text, or keep the owner’s guide. Pick a chunker, set its knobs, and ask a question. The lab cuts the text, embeds every chunk with the toy embedder, and ranks the chunks by cosine. With a preset question it also checks whether the top chunks hold the answer.

Cut, embed, search

The ruler is your text. Bars are chunks; pink bars are the top three for the query. Try the same question under each chunker.

200
0
80

Overlap applies to Fixed and Recursive; the percentile applies to Semantic. It embeds each sentence with one neighbour on each side, as LlamaIndex does, but with the toy embedder, so its cuts are rough. Everything runs in your browser.

Three runs to try. First, Fixed at S = 100 with no overlap: the warranty question finds a chunk, but the answer is cut. Second, Recursive at S = 200: every preset but the claim question lands in the top chunk. Third, Semantic: watch how the cuts move with P while the size is not capped.

In the lab, a question’s top chunk scores 0.45 but does not hold the answer. What should you check first?

Chapter 10

Field Guide

Keep the terms, the numbers, the checks and the code in one place

Cut where the text already breaks: headings, then paragraphs, then sentences. Size the chunks in tokens, under the embedding limit. Keep code and tables whole, carry the heading path, and pick the size by measuring recall at k against the text you send.

TermWhat it isNumber from this page
Cosine similarityq·c / (|q||c|): how far two vectors point the same way0.99 for the warranty section, 0.50 for the whole guide
Chunk count N⌈(L − O)/(S − O)⌉3 for L = 187, S = 100, O = 20
Psplitmax(0, f − 1 − O)/(S − O)0.54 at O = 0; 0 at O = 54, for f = 55, S = 100
Storage factorS/(S − O)1.25 for S = 100, O = 20
Sliding windoww sentences, moved by a step below ww = 3, step 2: 0 orphans, 8 sentences stored for 6
Recursive splitterblank line, line, space, any; merge up to S7 chunks at S = 200, 14 at S = 100
Tokens Tabout L / c, c near 4 for English2,000 chars: 500 tokens, 51% kept at a 256 limit
Semantic threshold τP-th percentile of the jumps d-i0.20 at P = 80: 3 chunks for 3 topics
recall@kH / Q5/6 = 0.83 at S = 200, k = 1
Context budgetk·S ≤ C − Rk ≤ 12 for C = 8,000, R = 2,000, S = 500
ChunkerCuts atBreaksUse it for
Fixed sizeevery S characters or tokenswords, numbers, factsa quick baseline
Sentencessentence endsreferences across sentencesplain prose with no structure
Recursivethe strongest separator that fitslong paragraphs, at spacesthe general default
Semanticthe largest jumps in meaningsize control; costs an embedding per sentencelong text with topic drift
By headingthe document’s own headingsnothing, but sections need a size capMarkdown, HTML, structured PDFs

Checklist before you index

  1. Every chunk is under the embedding model’s token limit, counted with its own tokenizer.
  2. No code block or table is cut in two.
  3. Each chunk carries its source and heading path.
  4. Every sentence of the source appears in at least one chunk.
  5. Overlap is at most the length of a typical answer span.
  6. recall@k is measured on real questions with known answer spans, over a sweep of S.

The core in code

pythonimport numpy as np
from langchain_text_splitters import RecursiveCharacterTextSplitter
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")   # 384 numbers per text

def recall_at_k(doc, tests, size, k):
    splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(
        model.tokenizer, chunk_size=size, chunk_overlap=0,
        separators=["\n\n", "\n", ". ", " ", ""], keep_separator="end")
    chunks = splitter.split_text(doc)
    C = model.encode(chunks, normalize_embeddings=True)           # (n_chunks, 384)
    hits = 0
    for question, answer in tests:
        q = model.encode(question, normalize_embeddings=True)       # (384,)
        top = np.argsort(-(C @ q))[:k]                               # cosine = dot of unit vectors
        hits += any(answer in chunks[i] for i in top)
    return hits / len(tests), len(chunks)

for size in (64, 128, 256):                                          # tokens; MiniLM reads at most 256
    print(size, recall_at_k(guide, tests, size, k=3))

Where it sits

Chunking is the first step of RAG. The chunks become vector embeddings, compared with similarity metrics and stored in a vector database. Tokenization sets the limits you size against. Embedding benchmarks help you pick the model, and multimodal RAG extends the pipeline to images and tables.

The takeaway. A chunk is the unit your system can find. Cut where the document already breaks, keep each fact and table whole, and choose the size from a measurement, not a default.

Keep going

RAG · CS 329Z: RAG · Vector embeddings · Vector databases · Tokenization · Semantic caching

Sources for the library facts: the LangChain langchain_text_splitters source (RecursiveCharacterTextSplitter, MarkdownHeaderTextSplitter), the LlamaIndex SemanticSplitterNodeParser source, and the all-MiniLM-L6-v2 model card.

Now press Present or Teach and explain from memory: why one vector fails, how often a fact breaks, why the splitter tries a blank line first, and how recall at k picks the size. Then go back to the hero, choose Recursive, and drag S down to 100. Say why the warranty term breaks again.

Text Chunking Strategies
Next: RAG · Back to Gleams