Why chunking matters
A RAG system never sends a whole book to the LLM. It sends only the few chunks that match the question. So the chunks are the "units of knowledge" your bot can find. Cut badly and the answer is either split across pieces or buried inside a giant piece.
Analogy: notes for an exam. One sticky note per idea is easy to find. Notes torn mid-sentence are useless. One giant note with the whole chapter is hard to scan. Chunking is deciding how big each note should be and where to tear the page.
2.1 Chunk size
TODO 1 — Split the document with RecursiveCharacterTextSplitter (10% overlap) and store the chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=int(size * 0.1)) chunks = text_splitter.split_documents(documents)
RecursiveCharacterTextSplitter tries to cut at paragraph breaks first, then line breaks, then spaces, and only cuts inside a word as a last resort. That is why it is the usual default.
chunk_size=50 -> 16 chunks chunk_size=150 -> 6 chunks chunk_size=400 -> 2 chunks The medium (150) chunks look like this: [1] 'The human heart is a muscular organ that pumps blood through the circulatory system.' [2] 'This blood delivers oxygen and nutrients to the body and removes metabolic waste. The heart' [3] 'has four chambers: the right atrium, the right ventricle, the left atrium, and the left ventricle.' [4] 'The average adult heart beats about 60 to 100 times per minute. The circulatory system consists of the heart,' [5] 'blood vessels, and blood. It is a vital part of the human body, responsible for transporting essential substances.' [6] 'A healthy lifestyle, including regular exercise and a balanced diet, is crucial for cardiovascular health.'
TODO 2 — Store the chunks of this size in their own Chroma collection
db = Chroma.from_documents( chunks, embeddings, collection_name=f"heart_chunks_{size}", ids=[f"{size}-{i}" for i in range(len(chunks))], )
Each size gets its own collection (like a separate table), so the three experiments do not mix.
We pass our own ids: if you run the cell twice, Chroma updates the same ids instead of storing duplicates
(duplicates would make the same chunk appear 2–3 times in your results).
TODO 3 — Retrieve the k most similar chunks from this vector store
retrieved_docs = db.similarity_search(query, k=min(k, len(chunked_documents[size])))
With 400-character chunks there are only 2 chunks, so asking for 3 would print a warning. min(k, ...) avoids that.
What you should see
| Size | Typical result | Verdict |
|---|---|---|
| 50 | Fragments like "the body and removes metabolic waste. The heart" | Too small: the idea is split across chunks |
| 150 | Whole sentences: "The human heart is a muscular organ that pumps blood through the circulatory system." | Best for this text: one idea per chunk |
| 400 | Half of the article in one block | Too large: the answer is buried, and you send many unneeded tokens to the LLM |
There is no universal best size. For real documents start around 500–1,000 characters with 10–20% overlap, then test with real questions.
2.2 Fixed-length chunking
The "pure" fixed-length splitter (separator="") cuts exactly every 100 characters, even inside words:
'# Machine Learning Fundamentals\n\nMachine learning is a subset of artificial intelligence that enable' 's computers to learn and improve from experience without being explicitly programmed.\n\n## Types of M' 'achine Learning\n\n### Supervised Learning\nSupervised learning uses labeled training data to learn a m'
TODO 4 — Fixed-length chunks of up to 200 characters that only cut at line breaks, with 20 characters overlap
fixed_length_splitter = CharacterTextSplitter(chunk_size=200, chunk_overlap=20, separator="\n") chunks = fixed_length_splitter.split_text(text)
separator="\n" means "only cut at the end of a line". chunk_size=200 is a maximum: lines are packed into a chunk until the next line would go over 200.
Chunk 1 (length: 184): # Machine Learning Fundamentals Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed. ---------------------------------------- Chunk 2 (length: 174): ## Types of Machine Learning ### Supervised Learning Supervised learning uses labeled training data to learn a mapping function from input to output. Common examples include: ---------------------------------------- Chunk 3 (length: 139): - Classification: Predicting categories (spam/not spam) - Regression: Predicting continuous values (house prices) ### Unsupervised Learning ---------------------------------------- Chunk 4 (length: 198): Unsupervised learning finds hidden patterns in data without labeled examples: - Clustering: Grouping similar data points - Dimensionality reduction: Reducing feature space ### Reinforcement Learning ---------------------------------------- Chunk 5 (length: 106): An agent learns through interaction with an environment, receiving rewards or penalties for actions taken.
Chunk 3 ends with the heading ### Unsupervised Learning, but its text is in chunk 4. The heading and its content were separated. Fixed-length chunking does not understand structure. Parts 2.3 and 2.4 fix this in two different ways.
2.3 Semantic chunking
How it works, in plain words:
- Split the text into sentences.
- Embed every sentence (OpenAI
text-embedding-3-small). - Measure the distance between each sentence and the next one.
- Where the distance is unusually large (by default, bigger than 95% of all the gaps), start a new chunk.
TODO 5 — Create a SemanticChunker with OpenAI embeddings and split the text into Documents
semantic_splitter = SemanticChunker(OpenAIEmbeddings(model="text-embedding-3-small")) docs = semantic_splitter.create_documents([text])
You get chunks of different lengths, each about one topic. The exact cut points depend on the embeddings, so two learners can get slightly different chunks. That is normal.
SemanticChunker lives in langchain-experimental, a package that is being retired. It works today. The four steps above are simple enough to write yourself in about 15 lines if you ever need to replace it.
2.4 Structure-based chunking
TODO 6 — Split the Markdown text at the headings listed above
markdown_splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on) md_header_splits = markdown_splitter.split_text(text)
Chunk 1:
Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed.
Metadata: {'Header 1': 'Machine Learning Fundamentals'}
----------------------------------------
Chunk 2:
Supervised learning uses labeled training data to learn a mapping function from input to output. Common examples include:
- Classification: Predicting categories (spam/not spam)
- Regression: Predicting continuous values (house prices)
Metadata: {'Header 1': 'Machine Learning Fundamentals', 'Header 2': 'Types of Machine Learning', 'Header 3': 'Supervised Learning'}
----------------------------------------
Chunk 3:
Unsupervised learning finds hidden patterns in data without labeled examples:
- Clustering: Grouping similar data points
- Dimensionality reduction: Reducing feature space
Metadata: {'Header 1': 'Machine Learning Fundamentals', 'Header 2': 'Types of Machine Learning', 'Header 3': 'Unsupervised Learning'}
----------------------------------------
Chunk 4:
An agent learns through interaction with an environment, receiving rewards or penalties for actions taken.
Metadata: {'Header 1': 'Machine Learning Fundamentals', 'Header 2': 'Types of Machine Learning', 'Header 3': 'Reinforcement Learning'}Every chunk is exactly one section, and the metadata remembers its "address" in the document (chapter → section → sub-section). You can show it as the source of an answer, filter on it, or add it to the chunk text before embedding so the search knows the topic.
The text sat inside indented code, so every line started with 4 spaces. The Markdown splitter ignores those spaces, but character-based splitters count them, which wastes chunk space and stores junk. Cleaning text before chunking is a good habit.
2.5 HyDE (Hypothetical Document Embeddings)
The problem: questions and documents are written in different "languages". Shoppers say running shoes; catalogues say Pegasus trainers. The trick: let the LLM write a fake document that looks like the real ones, and search with that.
Top products WITHOUT HyDE: - Adidas Ultraboost sneakers for men , Marathon Shoes (score: 1.59)
Only one product matched, and only because its title contains the word Shoes.
TODO 7 — Ask the LLM to write a hypothetical answer (fake product listings) for the shopper's query
hyde_prompt = ( "You write product titles for an online shoe store.\n" f"A shopper searched for: '{shopper_query}'.\n" "Write 4 short product titles (brand, model, key feature) that would perfectly match this search. " "One title per line, no numbering." ) hyde_answer = llm.invoke(hyde_prompt).text
We tell the LLM who it is (a writer of product titles), what the shopper typed, and the exact format we want. The answer is never shown to the user. It is only used as better search words.
Nike Air Zoom Pegasus 41 Road Running Trainers Adidas Ultraboost Light Running Shoes for Men Asics Gel-Kayano 31 Stability Running Trainers New Balance Fresh Foam X 1080 Cushioned Running Sneakers
TODO 8 — Search again with the query + hypothetical answer and print the top 3 products
hyde_query = shopper_query + " " + hyde_answer scores_hyde = bm25.get_scores(hyde_query.lower().split())
Top products WITH HyDE: - Nike Air Zoom Pegasus trainers (score: 10.07) - Adidas Ultraboost sneakers for men , Marathon Shoes (score: 9.50) - New Balance Fresh Foam trail trainers (score: 9.23)
The fake answer is full of catalogue words (Pegasus, Ultraboost, Fresh Foam, Gel-Kayano, trainers), so BM25 now finds all the real running shoes. Scores jump from about 1.6 to about 10.
The original HyDE idea embeds the fake answer and does a vector search with it ("answer-to-answer" matching is easier than "question-to-answer"). We used BM25 here only because word overlap is easy to see. The same code pattern works with db.similarity_search(hyde_answer).
Which strategy when?
| Strategy | Good for | Watch out for |
|---|---|---|
| Recursive / fixed-length | Plain text, quick start, any document | Can separate headings from their content |
| Semantic | Long text that drifts between topics (transcripts, articles) | One embedding call per sentence: slower and costs more |
| Structure-based | Docs with headings: policies, manuals, Markdown, HTML | One section can be very long, so split it further with a recursive splitter |
| HyDE (a retrieval trick, not a chunker) | Short or vague questions; questions worded differently from documents | One extra LLM call per question (latency + cost) |
Answers to "Think about it"
A sentence cut at a chunk boundary would otherwise exist only as two halves, and neither half would match the question well. Overlap repeats the edge text so the full sentence appears in at least one chunk.
Structure-based first (one chunk per section, headings saved as metadata), then a recursive splitter for any section that is still too long. The headings also make answers easy to cite ("Leave Policy → Maternity Leave").
When the text has no structure but changes topic often, such as meeting transcripts or long articles, and answer quality matters more than indexing cost. It is a one-time cost when you build the index.
We never show the fake answer to anyone. We only use its words or its "shape" to find real documents. The final answer still comes from the real retrieved documents.
The chunk about clustering carries Header 3: Unsupervised Learning. We can prepend the headings to the chunk text before embedding, filter by section, or show the user where the answer came from.
Common errors and fixes
| You see | Fix |
|---|---|
AuthenticationError / 401 | Your OpenAI key is missing or wrong. Check the .env file, then restart the notebook kernel. |
NotFoundError: model gpt-6-luna | Your OpenAI account cannot use this model yet. See the SME guide's "model fallback" note. |
| The same chunk appears several times in the results | You stored chunks twice without ids. Restart the kernel and run the notebook from the top. |
Number of requested results 3 is greater than number of elements | Only a warning. Use k=min(k, number_of_chunks) as in the solution. |
| Markdown splitter returns 1 chunk only | Your text has no lines starting with # (for example, a PDF converted to plain text). Structure-based splitting needs real headings. |