13. RAG Chunking Strategies & HyDE#
A fast, conceptual revision guide for 13-rag-chunking-strategies. Focused on how chunk size, fixed-length splitting, semantic chunking, structure-based Markdown splitting, and HyDE (Hypothetical Document Embeddings) shape retrieval quality in RAG pipelines — without boilerplate code clutter.
Why Chunking Matters & Finding the Right Chunk Size#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Explainer.html (Part 2.1 — requires OPENAI_API_KEY)
Concept#
A RAG system does not feed an entire book or manual into the LLM; it retrieves only the top-k pieces that match a user's question. Those pieces — chunks — are the atomic "units of knowledge" your retriever can find. How you slice a document directly determines whether the right fact is retrieved cleanly, shattered across fragments, or drowned inside noisy surrounding text.
How It Works#
Splitting the same source document across isolated Chroma collections exposes the core RAG trade-off: tiny chunks shatter ideas mid-sentence, huge chunks dilute embeddings across topics, and medium chunks with 10%–20% overlap preserve complete boundary sentences.
RecursiveCharacterTextSplitteras the default baseline: Rather than cutting blindly, it tries natural boundaries in priority order — paragraph breaks first, then line breaks, then spaces, and only splits inside a word as a last resort.- Controlled comparison on the heart article: Splitting the same short text into
chunk_sizevalues of50,150, and400characters (with10%chunk_overlap) produces16,6, and2chunks respectively, each stored in its ownChromacollection (heart_chunks_{size}) so experiments do not cross-contaminate.
Key Mental Models#
- The sticky-note analogy: Think of chunks as exam study notes.
- Too small (
50chars) — Notes torn mid-sentence. A single idea is fragmented across multiple chunks, so no individual chunk scores cleanly against the query. - Just right (
150chars for this short article) — One sticky note per complete idea. Retrieval returns whole, self-contained sentences that directly answer the question. - Too large (
400chars) — Half the article on one card. Multiple topics blur the chunk's embedding vector, bury the actual answer, and waste LLM context tokens.
- Too small (
- Why overlap (
10%–20%) exists: If a key sentence falls right across a chunk boundary, zero overlap leaves only two incomplete halves. Repeating a small tail of each chunk at the start of the next ensures boundary sentences remain intact in at least one chunk. - Production starting point: There is no universal best chunk size; for real-world documents, start around
500–1,000characters with10%–20%overlap, then evaluate with real user questions.
Trade-Offs & Pitfalls#
- Idempotent indexing with explicit
ids: Passing deterministicids(e.g.,f"{size}-{i}") toChroma.from_documents(...)updates existing records on re-runs instead of inserting duplicates that make the same chunk appear multiple times in top-kresults. - Guarding
kagainst small collections: Requestingk=3from a collection with only2chunks triggers a warning; capping withk=min(k, len(chunks))keeps retrieval clean.
Code Reference#
# Run this once if the libraries are not installed yet (remove the # first):
# %pip install -q -r ../../00_Setup/requirements.txt
# --- next cell ---
import os
import getpass
from dotenv import load_dotenv
# Load API credentials from .env first; fall back to a hidden interactive prompt in notebooks.
load_dotenv() # reads OPENAI_API_KEY from a .env file if you have one
if not os.getenv("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
print("API key loaded:", bool(os.getenv("OPENAI_API_KEY")))
# --- next cell ---
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
document_text = """
The human heart is a muscular organ that pumps blood through the circulatory system.
This blood delivers oxygen and nutrients to the body and removes metabolic waste. The heart
has four chambers: the right atrium, the right ventricle, the left atrium, and the left ventricle.
The average adult heart beats about 60 to 100 times per minute. The circulatory system consists of the heart,
blood vessels, and blood. It is a vital part of the human body, responsible for transporting essential substances.
A healthy lifestyle, including regular exercise and a balanced diet, is crucial for cardiovascular health.
"""
# Wrap raw text in a LangChain Document so provenance metadata (source, page, etc.)
# is automatically inherited by every child chunk created by the splitter.
documents = [Document(page_content=document_text, metadata={"source": "heart_article"})]
# Compare three chunk granularities to observe the precision vs. context trade-off:
# tiny chunks (50) risk fragmenting sentences; large chunks (400) dilute embedding focus.
chunk_sizes = [50, 150, 400] # small, medium, large (in characters)
chunked_documents = {} # size -> list of chunks
for size in chunk_sizes:
# ----- TODO 1: Split the document with RecursiveCharacterTextSplitter (10% overlap) and store the chunks -----
# RecursiveCharacterTextSplitter tries natural boundaries in order (\n\n -> \n -> space -> char)
# and 10% overlap preserves context for facts that straddle a split boundary.
# Hint: RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=int(size * 0.1))
# Hint: splitter.split_documents(documents) returns a list of smaller Documents
chunks = [] # replace with your code
chunked_documents[size] = chunks
print(f"chunk_size={size:<4} -> {len(chunks)} chunks")
print("\nThe medium (150) chunks look like this:")
for i, chunk in enumerate(chunked_documents.get(150, []), start=1):
print(f" [{i}] {chunk.page_content!r}")
# --- next cell ---
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
# OpenAI text-embedding-3-small outputs 1,536-dim vectors; isolating each chunk size in its own
# Chroma collection lets us benchmark retrieval quality across granularities cleanly.
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vector_dbs = {} # size -> Chroma vector store
for size, chunks in chunked_documents.items():
# ----- TODO 2: Store the chunks of this size in their own Chroma collection -----
# ... (see full file: chunking_strategies.ipynb)
API key loaded: True
# Before completing TODO 1 (chunks = []):
chunk_size=50 -> 0 chunks
chunk_size=150 -> 0 chunks
chunk_size=400 -> 0 chunks
The medium (150) chunks look like this:
(none yet — fill in TODO 1 to populate chunks)
# Run this once if the libraries are not installed yet (remove the # first):
# %pip install -q -r ../../00_Setup/requirements.txt
# --- next cell ---
import os
import getpass
from dotenv import load_dotenv
# Load API credentials from .env first; fall back to an interactive hidden prompt in notebooks.
load_dotenv() # reads OPENAI_API_KEY from a .env file if you have one
if not os.getenv("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
print("API key loaded:", bool(os.getenv("OPENAI_API_KEY")))
# --- next cell ---
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
document_text = """
The human heart is a muscular organ that pumps blood through the circulatory system.
This blood delivers oxygen and nutrients to the body and removes metabolic waste. The heart
has four chambers: the right atrium, the right ventricle, the left atrium, and the left ventricle.
The average adult heart beats about 60 to 100 times per minute. The circulatory system consists of the heart,
blood vessels, and blood. It is a vital part of the human body, responsible for transporting essential substances.
A healthy lifestyle, including regular exercise and a balanced diet, is crucial for cardiovascular health.
"""
# Wrap the text in a LangChain Document so metadata ("source": "heart_article") is copied onto every chunk.
documents = [Document(page_content=document_text, metadata={"source": "heart_article"})]
# Test small (50), medium (150), and large (400) character budgets to compare retrieval precision vs. context.
chunk_sizes = [50, 150, 400] # small, medium, large (in characters)
chunked_documents = {} # size -> list of chunks
for size in chunk_sizes:
# ----- TODO 1 (solved): Split the document with RecursiveCharacterTextSplitter (10% overlap) and store the chunks -----
# Recursive splitting prefers paragraph/line/word boundaries before cutting mid-word;
# 10% overlap repeats boundary tokens so key facts are not severed across adjacent chunks.
text_splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=int(size * 0.1))
# -> chunk_overlap: 5 (size=50), 15 (size=150), 40 (size=400)
chunks = text_splitter.split_documents(documents)
# -> size=50: 15 Documents (fragmented mid-sentence)
# -> size=150: 5 Documents (each inherits metadata={'source': 'heart_article'})
# -> size=400: 2 Documents (half the article per chunk)
chunked_documents[size] = chunks
print(f"chunk_size={size:<4} -> {len(chunks)} chunks")
print("\nThe medium (150) chunks look like this:")
for i, chunk in enumerate(chunked_documents.get(150, []), start=1):
print(f" [{i}] {chunk.page_content!r}")
# --- next cell ---
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
# OpenAI text-embedding-3-small maps each chunk into a 1,536-dim vector for semantic retrieval.
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vector_dbs = {} # size -> Chroma vector store
for size, chunks in chunked_documents.items():
# ----- TODO 2 (solved): Store the chunks of this size in their own Chroma collection -----
# Separate collections per chunk_size prevent cross-granularity contamination during side-by-side queries.
db = Chroma.from_documents(
# ... (see full file: chunking_strategies.ipynb)
API key loaded: True
chunk_size=50 -> 15 chunks
chunk_size=150 -> 5 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.\nA healthy lifestyle, including regular exercise and a balanced diet, is crucial for cardiovascular health.'
Fixed-Length Chunking & Its Structural Blind Spot#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Explainer.html (Part 2.2)
Concept#
Fixed-length chunking (CharacterTextSplitter) is the simplest splitting strategy: pack characters up to a hard budget (chunk_size). Comparing pure character slicing against line-break slicing exposes both why boundary awareness matters and why character counting alone still breaks document structure.
Key Mental Models#
- Pure fixed-length (
separator=""): Cuts strictly everyNcharacters (chunk_size=100,chunk_overlap=0), slicing right through the middle of words (e.g.,enable|s,M|achine) and destroying token/meaning integrity. - Line-aware fixed-length (
separator="\n"): Treatschunk_size=200as a ceiling and packs whole lines until the next line would exceed the limit, withchunk_overlap=20. Words stay intact, producing cleaner chunks. - Pre-chunking text hygiene (
textwrap.dedent): Indented multiline strings carry leading spaces on every line. Character-based splitters count those spaces towardchunk_size, wasting budget and polluting stored chunks, so normalizing whitespace before splitting is an essential habit.
Trade-Offs & Pitfalls#
- Headings get orphaned from their content: Even with
separator="\n", a character budget does not understand document hierarchy. In the Machine Learning example, Chunk 3 ends with### Unsupervised Learning, while the explanation of unsupervised learning lands in Chunk 4. - When it works vs. when it fails: Fast, zero-cost, and predictable for flat plain text, but blind to both topic shifts and section boundaries — the exact gap solved by semantic and structure-based chunking.
Semantic Chunking (Splitting on Meaning Shifts)#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Explainer.html (Part 2.3 — requires OPENAI_API_KEY)
Concept#
Instead of counting characters or relying on formatting, semantic chunking (SemanticChunker) uses embeddings to detect where the meaning of the text shifts, placing chunk boundaries at natural topic jumps.
How It Works#
- Break the document into individual sentences.
- Embed every sentence into a vector using
OpenAIEmbeddings(model="text-embedding-3-small"). - Compute the semantic distance between each pair of adjacent sentences.
- Insert a chunk boundary wherever the distance spikes above a statistical threshold (by default, larger than 95% of all gaps in the document; configurable via parameters such as
breakpoint_threshold_type="standard_deviation").
Trade-Offs & Pitfalls#
- Variable-length, topic-coherent chunks: Chunks naturally expand or shrink to match one coherent topic rather than an arbitrary character limit.
- One-time indexing cost & latency: Requires embedding every sentence during ingestion, making indexing slower and more expensive than character splitters. Because indexing happens once while queries happen repeatedly, this cost is often worth paying for unstructured, topic-drifting text like meeting transcripts or long articles.
- Non-deterministic cut points: Exact boundaries depend on embedding geometry and threshold statistics, so minor variations across runs or models are normal.
- Library lifecycle note:
SemanticChunkercurrently lives inlangchain-experimental(which emits aDeprecationWarning), but the four-step algorithm itself is simple enough to implement directly if needed.
Structure-Based Chunking (Markdown Headers & Metadata)#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Explainer.html (Part 2.4)
Concept#
Many real-world documents — policies, manuals, wikis, technical docs, Markdown, and HTML — already encode their own logical boundaries through headings (#, ##, ###). Structure-based chunking (MarkdownHeaderTextSplitter) splits directly along those headings and attaches the full heading path to each chunk as structured metadata.
How It Works#
- Define a mapping of heading markers to metadata keys via
headers_to_split_on(#→Header 1,##→Header 2,###→Header 3). MarkdownHeaderTextSplitter.split_text(...)outputsDocumentobjects where each chunk contains one clean section and.metadatarecords its exact "address" in the document (e.g.,Header 1: Machine Learning Fundamentals→Header 2: Types of Machine Learning→Header 3: Unsupervised Learning).
Key Mental Models#
- Metadata turns chunks into addressable knowledge: Carrying the section hierarchy in
.metadataunlocks three high-value RAG capabilities:- Prepending context before embedding: Injecting the heading path into the chunk text helps embeddings understand what a chunk is about (e.g., linking clustering explicitly to Unsupervised Learning).
- Metadata filtering: Restricting retrieval to a specific chapter or policy section before or during similarity search.
- Clean source citations: Showing users exactly where an answer came from (e.g.,
Leave Policy → Maternity Leave).
- Two-stage hybrid chunking for real documents: For long structured documents (like a 300-page HR policy PDF with headings), split by structure first so headings stay attached as metadata, then pass any oversized section through
RecursiveCharacterTextSplitterto enforce a maximum chunk size.
Trade-Offs & Pitfalls#
- Requires real structural markers: If you pass plain text without
#headings (such as a naively extracted PDF converted to raw text),MarkdownHeaderTextSplitterreturns only1giant chunk. - Unbounded section sizes: A single Markdown section can span thousands of words, which is why combining structure-based splitting with a secondary recursive splitter is standard practice.
HyDE — Hypothetical Document Embeddings#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Code/chunking_strategies.ipynb, 2_SHARE_AFTER_Solution_Explainer.html (Part 2.5 — requires OPENAI_API_KEY)
Concept#
HyDE (Hypothetical Document Embeddings) is a retrieval-time technique, not a chunking strategy. It solves the vocabulary and style mismatch between short, vague user queries and real indexed documents: instead of searching with the user's raw question, an LLM first imagines a hypothetical answer written in the style of the target documents, and the retriever searches using that imagined text.
How It Works#
HyDE bridges the phrasing gap between short, colloquial shopper queries and domain-specific catalog text by prompting a fast LLM to draft plausible target passages before searching, while still grounding the final answer strictly in real retrieved items.
- The mismatch without HyDE: A shopper searches
"I want running shoes", while the catalog lists"Nike Air Zoom Pegasus trainers","Asics Gel-Kayano stability trainers", and"New Balance Fresh Foam trail trainers". Classic keyword search (BM25Okapi) finds only1item (Adidas Ultraboost sneakers for men , Marathon Shoes, score1.59) purely because it happens to contain the wordShoes. - The bridge with HyDE: Prompting
ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")to invent 4 realistic shoe-store titles produces domain-native terms (Pegasus,Ultraboost,Fresh Foam,Gel-Kayano,trainers). Searching BM25 withshopper_query + " " + hyde_answerlifts top scores from~1.6to~9–10and retrieves all three real running products. - BM25 vs. Vector Search: The notebook uses
BM25Okapiso word overlap is immediately visible, while the original HyDE pattern embeds the hypothetical document and runsdb.similarity_search(hyde_answer)— converting harder question-to-answer vector matching into answer-to-answer matching.
Key Mental Models#
- Hallucinations in the fake document are harmless: The hypothetical answer is never shown to the user. Even if the LLM invents a shoe model that does not exist in your store, its vocabulary and semantic "shape" still steer the retriever toward the right real documents, and the final grounded answer comes strictly from those retrieved documents.
- Fast, non-thinking generation: Setting
reasoning_effort="none"keeps the extra LLM call fast and direct because HyDE only needs plausible domain phrasing, not deep multi-step reasoning.
Trade-Offs & Pitfalls#
- Extra latency and cost per query: Unlike chunking (a one-time indexing step), HyDE adds an LLM call on every user search, increasing response time and API spend.
- Best reserved for hard queries: Most valuable for short, vague, or differently-worded user queries; unnecessary when users already search with exact domain terminology.
Strategy Selection & Practical Pitfalls#
Revision Notes#
Reference files: 2_SHARE_AFTER_Solution_Explainer.html, .env.example
Concept#
No single chunking or retrieval technique wins everywhere. Choosing well means matching the splitter to your document's structure and adding retrieval-time enhancements like HyDE only where query-document mismatch hurts recall.
Choosing the Right Strategy#
- Recursive / Fixed-Length (
RecursiveCharacterTextSplitter,CharacterTextSplitter):- Best for: Plain text, quick prototypes, general-purpose baselines, and as a second-pass cap on oversized sections.
- Watch out for: Can split headings away from their body text if used alone on structured docs.
- Semantic (
SemanticChunker):- Best for: Long, unstructured text that drifts across topics (meeting transcripts, essays, long-form articles) where retrieval quality outweighs one-time indexing cost.
- Watch out for: One embedding call per sentence increases indexing time and cost.
- Structure-Based (
MarkdownHeaderTextSplitter):- Best for: Documents with explicit hierarchy — policies, manuals, Markdown, HTML — where section metadata aids citations and filtering.
- Watch out for: Single sections can still be huge (follow up with a recursive splitter), and plain-text extractions without
#markers will not split at all.
- HyDE (Retrieval-time enhancement):
- Best for: Short, vague, or colloquial queries whose phrasing differs from the indexed corpus.
- Watch out for: Adds one extra LLM call (latency + cost) on every query.
Common Operational Pitfalls#
- Duplicate search results: Re-running
Chroma.from_documents(...)without explicitidsappends duplicate copies of every chunk. - Retriever
kexceeding chunk count: Passingk=3to a 2-chunk store triggers a warning; usemin(k, len(chunks)). - Single-chunk output from Markdown splitter: Usually means the input lacks
#heading syntax (e.g., raw PDF text extraction). - API & model configuration: Missing/invalid
OPENAI_API_KEYin.envcausesAuthenticationError(401), and account-restricted model names (likegpt-6-luna) raiseNotFoundErrorrequiring a fallback model.
How All Building Blocks Connect#
Revision Notes#
Chunking and HyDE operate on opposite sides of the RAG pipeline, and strong systems pair them cleanly:
Chunking shapes what units of knowledge exist in the index (paid once at ingestion), whereas HyDE and metadata filters shape how user questions locate those chunks at runtime (paid per query).
- Chunking shapes what can be found by defining clean, well-sized, metadata-rich units of knowledge at ingestion time.
- HyDE shapes how you search for it by bridging the phrasing gap between a user's question and those stored chunks at query time.
Quick Self-Check Questions#
Self-Check Questions#
Why do we add 10%–20% overlap between chunks, and what breaks with zero overlap?
Without overlap, a sentence straddling a chunk boundary is split into two incomplete halves, neither of which matches a user's query well. Overlap repeats the boundary text so the full sentence stays intact in at least one chunk.
Why did chunk_size=150 outperform both 50 and 400 on the short heart article?
50 characters fragmented single facts across multiple pieces, while 400 characters packed half the article into one blurry block with unnecessary tokens. 150 characters kept roughly one complete idea per chunk.
What is the structural flaw in CharacterTextSplitter(separator="\n") even though it avoids breaking words?
It only tracks character counts and line breaks, not document hierarchy — so a heading (like ### Unsupervised Learning) can end up at the bottom of one chunk while its explanation lands in the next.
You are building a RAG system over a 300-page HR policy PDF with clear section headings. Which chunking approach should you use?
Two-stage chunking: split by structure/headings first so every chunk stays aligned to a section and carries its heading path in metadata (useful for filtering and citations), then apply RecursiveCharacterTextSplitter to any section that is still too long.
When is the extra cost of SemanticChunker justified?
When documents lack headings or structural markers but shift topics frequently (such as meeting transcripts or long articles) and retrieval quality matters more than a one-time indexing cost.
How does MarkdownHeaderTextSplitter metadata help answer a specific query like "What is clustering?"
The chunk carries Header 3: Unsupervised Learning (plus parent headers) in .metadata, which you can prepend to the chunk before embedding for stronger retrieval, use to filter by section, or display as a clear source citation.
HyDE's hypothetical document can contain made-up facts or nonexistent product names. Why doesn't that corrupt the final RAG answer?
The hypothetical document is never shown to the user; it is used solely as a richer search query whose vocabulary and style match real indexed documents. The final answer is still generated strictly from the real retrieved documents.