What you will build
One notebook, five small experiments. Each one answers a question that every RAG engineer faces:
| Part | Question | TODOs |
|---|---|---|
| 2.1 | Does the chunk size change what the search finds? | 1, 2, 3 |
| 2.2 | What happens if we cut every N characters (fixed-length)? | 4 |
| 2.3 | Can we cut where the meaning changes instead? | 5 |
| 2.4 | Can we use the document's own headings? | 6 |
| 2.5 | Can an LLM's fake answer help us search better (HyDE)? | 7, 8 |
Time: about 60 minutes · API key needed: Yes (OpenAI). Total cost for this notebook: well under one rupee.
Before you start
- Finish the setup: 11-rag-setup/Setup_Guide_for_Learners.html (your
.envfile must containOPENAI_API_KEY). - Open 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb in Jupyter or VS Code.
- Run the cells in order. When a cell has a
# ----- TODO nline, replace the placeholder with your code, then run the cell.
Chunk: a small piece of a bigger document. Overlap: a few characters repeated at the start of the next chunk, so a sentence cut in half still appears whole somewhere. Vector store: a database that saves chunks with their embeddings and finds the closest ones to a question.
2.1 Finding a good chunk size
Story: We cut a short article about the human heart into chunks of 50, 150 and 400 characters, store each version in its own vector store, and ask all three the same question: "What is the primary function of the heart and its connection to the circulatory system?"
You should get 16, 6 and 2 chunks.
Need a hint?
RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=int(size * 0.1))splitter.split_documents(documents)returns a list of smaller Documents
Need a hint?
Chroma.from_documents(chunks, embeddings, collection_name=..., ids=...)- Use a different
collection_nameper size,e.g. f"heart_chunks_{size}" - ids like
f"{size}-{i}"stop duplicates if you run the cell twice
Need a hint?
db.similarity_search(query, k=...)returns a list of Documents- A small store may have fewer than k chunks, so use
min(k, len(chunked_documents[size]))
- The counts print as 16 / 6 / 2
- All three chunk sizes print up to 3 results
- You can say which size gave the cleanest answer, and why
2.2 Fixed-length chunking
Story: The simplest idea: cut every N characters. The notebook first shows the "pure" version that cuts anywhere (look at the broken words). Then you build a better version that only cuts at line breaks.
You should get 5 chunks, each at most 200 characters.
Need a hint?
CharacterTextSplitter(chunk_size=200, chunk_overlap=20, separator="\n").split_text(text)returns a list of strings
2.3 Semantic chunking
Story: Instead of counting characters, embed each sentence and cut where two neighbouring sentences are far apart in meaning (a topic jump).
Need a hint?
SemanticChunker(OpenAIEmbeddings(model="text-embedding-3-small")).create_documents([text])returns a list of Documents
2.4 Structure-based chunking (Markdown headings)
Story: Our text already has headings (#, ##, ###). Cut at the headings, and remember which heading each chunk belongs to.
You should get 4 chunks. Look at the Metadata line under each one.
Need a hint?
MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on).split_text(text)returns Documents that carry the headings in .metadata
2.5 HyDE: search with a fake answer
Story: A shopper types "I want running shoes". The product titles say trainers, sneakers, Ultraboost, Pegasus... almost no words match. Keyword search (BM25) finds only one product. HyDE fixes this: ask an LLM to imagine what matching products would be called, and search with that imagined text.
Need a hint?
- Write a prompt like:
"Write 4 short product titles from an online shoe store that match: <query>" llm.invoke(prompt).textgives you the text answer
Need a hint?
hyde_query = shopper_query + " " + hyde_answer- Lower-case and split it into words, then
bm25.get_scores(words) np.argsort(scores)[::-1][:3]gives the indexes of the 3 best products
- "WITHOUT HyDE" shows only 1 product
- "WITH HyDE" shows 3 running products (for example Pegasus, Ultraboost, Fresh Foam, Gel-Kayano) with much higher scores
Think about it
- Why did we add 10% overlap between chunks in 2.1? What could go wrong with zero overlap?
- You are building a RAG bot over a 300-page HR policy PDF with clear section headings. Which strategy would you start with, and why?
- Semantic chunking needs an embedding call for every sentence. When is that cost worth it?
- HyDE's fake answer may contain wrong facts (for example a shoe model that does not exist). Why does that not break the search?
- In 2.4, how could the
Metadata(headings) help when a user asks "What is clustering?"
Stretch challenges
- 2.1: Try
chunk_size=100and250. Where is the "sweet spot" for this article? - 2.3: Pass
breakpoint_threshold_type="standard_deviation"toSemanticChunker. Do the cut points change? - 2.5: Change the shopper query to "something for trekking in the hills". Does HyDE find the Woodland boots?