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.
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
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.
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.
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.
Cos of q and c equals q dot c, over the length of q times the length of c.
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 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.
Chapter 1
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.
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.
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.
N equals the ceiling of L minus O, over S minus O.
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.
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).
Chapter 2
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?
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.
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.
P-split equals the larger of zero and f minus one minus O, over S minus O.
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.
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:
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.
Chapter 3
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.
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.
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).
Chapter 4
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:
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.
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.
Chapter 5
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.
T is about L over c.
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.
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.
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.
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.
Chapter 6
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.
Call the embedding of sentence i ei. The distance between sentence i and the next is di.
D-i equals one minus cos of e-i and e-i-plus-one.
Score two neighbouring sentences with cosine similarity. Subtract the score from 1. A big d-i means the topic changed between them.
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.
Tau equals the P-th percentile of d-one through d-n-minus-one.
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.
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.
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.
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.
Chapter 7
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.
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.
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.
Chapter 8
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.
Recall at k equals H over Q.
Run every question. Count the ones whose answer span sits whole in one of the top k chunks. Divide the count H by Q.
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.
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.
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.
K times S is at most C minus R.
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 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.
Chapter 9
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.
The ruler is your text. Bars are chunks; pink bars are the top three for the query. Try the same question under each chunker.
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.
Chapter 10
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.
| Term | What it is | Number from this page |
|---|---|---|
| Cosine similarity | q·c / (|q||c|): how far two vectors point the same way | 0.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 |
| Psplit | max(0, f − 1 − O)/(S − O) | 0.54 at O = 0; 0 at O = 54, for f = 55, S = 100 |
| Storage factor | S/(S − O) | 1.25 for S = 100, O = 20 |
| Sliding window | w sentences, moved by a step below w | w = 3, step 2: 0 orphans, 8 sentences stored for 6 |
| Recursive splitter | blank line, line, space, any; merge up to S | 7 chunks at S = 200, 14 at S = 100 |
| Tokens T | about L / c, c near 4 for English | 2,000 chars: 500 tokens, 51% kept at a 256 limit |
| Semantic threshold τ | P-th percentile of the jumps d-i | 0.20 at P = 80: 3 chunks for 3 topics |
| recall@k | H / Q | 5/6 = 0.83 at S = 200, k = 1 |
| Context budget | k·S ≤ C − R | k ≤ 12 for C = 8,000, R = 2,000, S = 500 |
| Chunker | Cuts at | Breaks | Use it for |
|---|---|---|---|
| Fixed size | every S characters or tokens | words, numbers, facts | a quick baseline |
| Sentences | sentence ends | references across sentences | plain prose with no structure |
| Recursive | the strongest separator that fits | long paragraphs, at spaces | the general default |
| Semantic | the largest jumps in meaning | size control; costs an embedding per sentence | long text with topic drift |
| By heading | the document’s own headings | nothing, but sections need a size cap | Markdown, HTML, structured PDFs |
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))
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.
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.