Sub topic 1
Where chunking sits in a RAG pipeline
Prerequisites
This chapter assumes you already know four things:
- Basic Python: functions, lists, strings, and dictionaries.
- What an embedding is, and that vector similarity search returns the stored vectors closest to a query vector.
- The general idea of retrieval-augmented generation (RAG): retrieve relevant text first, then ask a language model to answer using it.
- What a token is: the unit of text a language model reads, usually a word or part of a word.
You do not need a vector database or an API key. The code in this chapter runs with the Python standard library.
The pipeline in one view
A RAG system has two phases. The indexing phase runs ahead of time, whenever documents change. The query phase runs each time a user asks a question.
Indexing has four steps:
- Load the source documents (PDFs, web pages, wiki articles, tickets, code) and convert them to text.
- Chunk the text into smaller pieces.
- Embed each chunk, which means turning it into a vector with an embedding model.
- Store the vectors, the chunk text, and any metadata in an index.
The query phase has four more:
- Embed the user's question with the same embedding model.
- Retrieve the top k chunks whose vectors are closest to the question vector.
- Assemble a prompt from the question and those chunks.
- Generate an answer with a language model.
Chunking is the second step of indexing. It looks like a small preprocessing detail, but every later step depends on its output.
What chunking decides
Chunking decides the unit of retrieval. The index never contains "documents". It contains chunks. When a user asks a question, the system can return only whole chunks, never half a chunk and never a sentence that you did not store as its own piece. Three things follow from that.
- What the embedding represents. One vector summarizes one chunk. A chunk that covers three unrelated topics produces a vector that sits between them and matches none of them well.
- What the model sees. The generator receives the retrieved chunks and nothing else from the corpus. If the answer is split across two chunks and only one is retrieved, the model has half of it.
- How much the prompt costs. Each retrieved chunk consumes context window space. Large chunks use up the budget with fewer results. Small chunks leave room for more, but each carries less context.
Because the chunk is fixed at indexing time, a poor choice cannot be repaired during the query phase. A better embedding model or a smarter prompt will not recover a fact that was cut in half before it was embedded. To change chunking you must re-chunk, re-embed, and re-index the affected documents.
What goes in and what comes out
A chunker takes a document's text and returns a list of pieces. In practice you want each piece to carry more than text, so a common output shape is a dictionary per chunk.
def make_chunks(doc_id, text, splitter):
"""Wrap raw pieces from any splitter into records ready for indexing."""
records = []
for i, piece in enumerate(splitter(text)):
records.append({
"id": f"{doc_id}#{i}",
"doc_id": doc_id,
"position": i,
"text": piece,
})
return records
def split_paragraphs(text):
return [p.strip() for p in text.split("\n\n") if p.strip()]
doc = (
"Refunds are issued within 14 days.\n\n"
"To request a refund, open a ticket.\n\n"
"Shipping is free over 50 dollars."
)
for record in make_chunks("policy", doc, split_paragraphs):
print(record["id"], "->", record["text"])The output is:
policy#0 -> Refunds are issued within 14 days.
policy#1 -> To request a refund, open a ticket.
policy#2 -> Shipping is free over 50 dollars.Three details matter later in the tutorial:
- The
idties a chunk back to its source. Evaluation (a later chapter) needs this to check whether retrieval found the right place. doc_idandpositionare metadata. They let you show citations, fetch neighboring chunks, and delete or refresh everything from one document when it changes.splitteris a parameter. The rest of the pipeline does not care how pieces were produced, which makes it easy to compare strategies by swapping one function.
A failure you can see
Here is a small, concrete case of chunking harming retrieval. Suppose a policy document contains this passage:
> The warranty lasts two years. It does not cover water damage.
Because block quotes are not allowed in this tutorial's format, treat that sentence pair as the document text. Now split it every 40 characters.
text = "The warranty lasts two years. It does not cover water damage."
size = 40
pieces = [text[i:i + size] for i in range(0, len(text), size)]
for p in pieces:
print(repr(p))Output:
'The warranty lasts two years. It does n'
'ot cover water damage.'The cut falls in the middle of the word "not". The second chunk reads "ot cover water damage." A question such as "Does the warranty cover water damage?" now matches a chunk that has lost its negation. The embedding model sees "ot cover water damage" and the generator may conclude the opposite of the truth.
The text was correct, the embedding model was fine, and the language model was fine. The error was introduced by a boundary. This is the main reason to treat chunking as a design decision and not a default setting.
How chunking interacts with the other steps
Each stage places a constraint on chunking, and chunking places a constraint back on each stage.
| Stage | What it needs from chunks | What chunking changes |
|---|---|---|
| Loading and cleaning | Plain text, with structure cues such as headings kept if you want to use them | If cleaning strips headings or table layout, structure-aware chunking is no longer possible |
| Embedding | Text within the model's input limit, and about one topic | Oversized chunks are truncated or rejected. Mixed-topic chunks give blurry vectors |
| Storage | A bounded number of chunks | Smaller chunks mean more vectors, more storage, and a slower or costlier index |
| Retrieval | Chunks that can match the wording of a question | Boundaries decide whether the matching words and the answer are in the same chunk |
| Prompt assembly | Chunks that fit in the context budget with room for the question and answer | Chunk size times k must stay under the budget |
| Generation | Self-contained text the model can quote or paraphrase | A chunk that starts mid-sentence or uses "it" with no referent invites errors |
A rough budget check shows how the constraints combine. Suppose your model has an 8,000-token context window. You reserve 1,000 tokens for instructions and the question, and 1,000 for the answer. That leaves 6,000 tokens for retrieved text. With k = 5, each chunk can average at most 1,200 tokens. With k = 10, the limit drops to 600. The values of chunk size and k must be chosen together.
def max_chunk_tokens(context_window, reserved_prompt, reserved_answer, k):
available = context_window - reserved_prompt - reserved_answer
if available <= 0:
raise ValueError("reserved tokens exceed the context window")
return available // k
print(max_chunk_tokens(8000, 1000, 1000, 5))
print(max_chunk_tokens(8000, 1000, 1000, 10))This prints 1200 and then 600. The function gives an upper bound, not a recommendation. Later chapters explain why the best chunk size is usually well below it.
Where chunking can go wrong, by stage
Most chunking problems show up far from the chunker. Knowing which symptom points to which cause saves debugging time.
- The right document is retrieved but the answer is wrong. The relevant sentence may sit in a neighboring chunk that was not retrieved. Look at boundaries and overlap.
- Retrieved chunks look related but do not contain the answer. Chunks may be too large, so the vector reflects the general topic. Look at chunk size.
- Exact terms such as error codes are not found. The chunk may include so much surrounding text that the term has little weight in the vector. Look at chunk size, and consider keyword search alongside vectors.
- Answers cite fragments that make no sense alone. Chunks lack context such as the section title or the subject of a pronoun. Look at metadata and context enrichment.
- Indexing fails or results are silently cut off. Chunks may exceed the embedding model's input limit. Check token counts, not character counts.
- Quality dropped after a document update. Old chunks of the changed document may still be in the index. Use
doc_idto delete them before inserting new ones.
Chunking is a tunable parameter
Because the chunker is a plain function between loading and embedding, you can treat its settings the same way you treat any other hyperparameter: choose a starting value, measure, and adjust. The measurement part is covered in a later chapter on recall@k. For now, remember the order of work this implies:
- Pick a reasonable default based on your content and embedding model.
- Build a small set of real questions with known answer locations.
- Compare configurations on that set.
- Re-index only when the data shows a clear gain.
The chapters that follow move from the constraints (why we chunk, tokens and limits, size and overlap) to specific strategies (fixed-size, recursive, sentence-based, structure-aware, semantic, parent-child), then to enrichment, evaluation, and choosing among them.
Exercise
A team's RAG system has an 8,000-token context window. They reserve 500 tokens for instructions and the question and 1,500 tokens for the answer, and they retrieve k = 8 chunks. What is the largest average chunk size, in tokens, that fits? Then explain in one sentence why changing the chunking strategy later requires re-embedding.
Show answer
Available space is 8,000 - 500 - 1,500 = 6,000 tokens. Divided by 8 chunks, the limit is 750 tokens per chunk on average. Re-embedding is required because each vector summarizes one specific chunk of text, so changing where the boundaries fall changes the text of every chunk, and the stored vectors no longer match it.
Exercise
Users report that the system answers "Is water damage covered?" with "Yes", but the source text says "It does not cover water damage." Retrieval returns a chunk beginning "ot cover water damage." Which pipeline stage introduced the error, and what is the first thing you would change?
Show answer
The chunking stage introduced it, because a fixed character split cut the word "not" in half. The first change is to split on natural boundaries such as sentence or word boundaries (or add overlap) so that a negation is never separated from the words it modifies, then re-chunk, re-embed, and re-index.