Chunking
Chunking large documents into small fragments before saving them to a vector DB.
Why Chunk
A model cannot swallow a 500-page document whole. On top of that, the vector of a giant document comes out blurry: a single embedding mixes all the topics at once. That is why the text is cut into pieces, and each piece gets its own vector.
Rules of Good Chunking
- Size: 512–1024 tokens per chunk is optimal;
- Overlap: 10–15% (50–100 tokens), so that the meaning is not torn apart at the seams;
- Structure: cut along headings and paragraphs, not at a fixed number of characters.
Tools in LangChain
- RecursiveCharacterTextSplitter — splits first by headings, then by paragraphs, then by sentences;
- MarkdownHeaderTextSplitter — extracts the structure of the document and enriches the chunks with metadata.
An Advanced Technique: Parent-Document Retriever
Small chunks (200 tokens) are for precise search. But the prompt receives the large parent block (2000 tokens) that the found piece belongs to. This solves the problem of losing context.