How do you chunk documents for RAG?

Learning path, stage 3 of 5: RAG and fine-tuning · question 2 of 10

Chunking splits documents into pieces small enough to retrieve precisely but large enough to make sense on their own. Typical choices are 200–1000 tokens with 10–20% overlap, splitting on the document's structure (headings, paragraphs, code blocks) rather than at a fixed character count.

Strategies

  • Fixed size + overlap: simple and a reasonable baseline. Can cut sentences or ideas in half.
  • Recursive or structural: split by heading, then paragraph, then sentence. Respects meaning.
  • Format-aware: Markdown sections, HTML elements, code by function or class, tables kept whole.
  • Semantic: start a new chunk where embedding similarity between sentences drops.
  • Parent-child: retrieve small chunks for precision, then pass the bigger parent section to the LLM.

Make chunks stand on their own

  • Add the title, section path and source URL to each chunk as metadata, or as a text prefix.
  • Contextual retrieval: have an LLM write a 1–2 sentence summary of where the chunk sits in the document and prepend it before embedding (and before BM25 indexing). In Anthropic's tests this cut failed retrievals by 49%, and by 67% when combined with reranking.

Tune with data

There's no single right size. Measure retrieval recall@k on real questions for a few chunk sizes.

Sources

Code example

tsx
1// Structure-aware chunker: split Markdown by headings, then pack paragraphs
2// up to a size limit with overlap, keeping the heading path as context.
3interface Chunk { text: string; heading: string; source: string }
4
5export function chunkMarkdown(md: string, source: string, maxChars = 2000, overlap = 200): Chunk[] {
6 const chunks: Chunk[] = [];
7 const sections = md.split(/^(?=#{1,3} )/m); // each section starts at a heading
8
9 for (const section of sections) {
10 const heading = section.match(/^#{1,3} (.+)$/m)?.[1] ?? "";
11 const body = section.replace(/^#{1,3} .+\n?/, ""); // heading goes in as a prefix, not twice
12 const paras = body.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
13 let buf = "";
14 for (const p of paras) {
15 if (buf && buf.length + p.length > maxChars) {
16 chunks.push({ text: `${heading}\n\n${buf}`, heading, source });
17 buf = buf.slice(-overlap); // carry a tail forward as overlap
18 }
19 buf += (buf ? "\n\n" : "") + p;
20 }
21 if (buf.trim()) chunks.push({ text: `${heading}\n\n${buf}`, heading, source });
22 }
23 return chunks;
24}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app