Hands-on exercises · Give to learners

Module 2 — Chunking Strategies and HyDE: Exercises

Hands-on exercise sheet. Try every TODO yourself before you see the solution.

For learnersAbout 60 minutesOpenAI API key needed

What you will build

One notebook, five small experiments. Each one answers a question that every RAG engineer faces:

PartQuestionTODOs
2.1Does the chunk size change what the search finds?1, 2, 3
2.2What happens if we cut every N characters (fixed-length)?4
2.3Can we cut where the meaning changes instead?5
2.4Can we use the document's own headings?6
2.5Can 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

  1. Finish the setup: 11-rag-setup/Setup_Guide_for_Learners.html (your .env file must contain OPENAI_API_KEY).
  2. Open 1_GIVE_FIRST_Starter_Code/chunking_strategies.ipynb in Jupyter or VS Code.
  3. Run the cells in order. When a cell has a # ----- TODO n line, replace the placeholder with your code, then run the cell.
Words you will see

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?"

Article
→
Split50 / 150 / 400 chars
→
Embed + store3 vector stores
→
Same questionto all three
→
Comparewhich answer is best?
TODO 1Split the document with RecursiveCharacterTextSplitter (10% overlap) and store the chunks

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
TODO 2Store the chunks of this size in their own Chroma collection
Need a hint?
  • Chroma.from_documents(chunks, embeddings, collection_name=..., ids=...)
  • Use a different collection_name per size, e.g. f"heart_chunks_{size}"
  • ids like f"{size}-{i}" stop duplicates if you run the cell twice
TODO 3Retrieve the k most similar chunks from this vector store
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]))
You are done when
  • 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.

TODO 4Fixed-length chunks of up to 200 characters that only cut at line breaks, with 20 characters overlap

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).

TODO 5Create a SemanticChunker with OpenAI embeddings and split the text into Documents
Need a hint?
  • SemanticChunker(OpenAIEmbeddings(model="text-embedding-3-small"))
  • .create_documents([text]) returns a list of Documents
You are done when the cell prints a few chunks and each chunk is about one topic. (The exact cut points can differ from your neighbour's.)

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.

TODO 6Split the Markdown text at the headings listed above

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.

Shopper queryI want running shoes
→
LLM imagines4 fake product titles
→
Search withquery + fake answer
→
Real productsfound
TODO 7Ask the LLM to write a hypothetical answer (fake product listings) for the shopper's query
Need a hint?
  • Write a prompt like: "Write 4 short product titles from an online shoe store that match: <query>"
  • llm.invoke(prompt).text gives you the text answer
TODO 8Search again with the query + hypothetical answer and print the top 3 products
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
You are done when
  • "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

  1. Why did we add 10% overlap between chunks in 2.1? What could go wrong with zero overlap?
  2. 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?
  3. Semantic chunking needs an embedding call for every sentence. When is that cost worth it?
  4. HyDE's fake answer may contain wrong facts (for example a shoe model that does not exist). Why does that not break the search?
  5. In 2.4, how could the Metadata (headings) help when a user asks "What is clustering?"

Stretch challenges