RAG from the Ground Up - Part 1
Why RAG: LLMs are frozen in time
A trained LLM is just static weights on a server. It is frozen in time.
- No recent data - new library versions or changed APIs after training are unknown.
- No private or personal data - Slack messages, internal docs, class records.
- Confident hallucination - it answers even without context.
Example
A legal-tech company hires lawyers to build precise case documents. The LLM never saw them, so RAG feeds the right documents into the prompt.
Basic idea: new info goes into the prompt. RAG = retrieve data, then generate with it. -> Retrieval Augmented Generation
When to use RAG, prompt or fine-tuning
- Small amount of new info -> just put it in the prompt. RAG adds needless system complexity.
- Thousands of documents -> RAG. Context window is too small, the model hallucinates, and unrelated data is wasteful.
- Very similar documents with subtle differences (two near-identical legal cases) -> prompt alone makes the model confuse them; RAG must find the precise one.
- Fine-tuning -> good for a lot of data and better skill at a domain, but new data means redoing the fine-tuning.
- RAG -> just add new data to the database.
Ingestion 1: Document loading and parsing
Ingestion - bringing your data into the system. Pipeline: parse -> chunk -> embed -> store.
- PDFs have tables, images and graphs made for humans. Simple parsers fail.
- HTML/XML are structured but noisy and bloat the context.
- Garbage in, garbage out. Handle images, tables and markup explicitly.
- Preserve structure (chapter -> section -> paragraph).
Clean data is the first and most important step of any RAG system.
Ingestion 2: Chunking
One vector per 1000-page book compresses everything into one point. A question about chapter 2 retrieves the whole book.
Chunking - split data into parts and embed each part. Retrieve only the 10 chunks of chapter 1 when asked about chapter 1.
| Type | How it splits |
|---|---|
| Fixed | Fixed number of words, lines or paragraphs per chunk |
| Recursive | Follows natural boundaries: paragraph, line, sentence, character |
| LLM-based | LLM decides where to cut (costlier, usually better) |
| AST | For code, split by abstract syntax tree parts |
| Structure / paragraph / parent-child | Other strategies for specific use cases |
Why fixed is bad: it cuts info mid-way. One chunk has half the information, the LLM sees only that half and hallucinates the rest.
Example
Paper-cutting: cut three papers at random into four pieces each and mix them. Finding a character name split across two pieces is hard. Same for chunks.
- Demo: fixed 100-word chunks vs recursive chunks of 61, 44, 44 words that end at natural stops.
- Check chunk quality by reading samples: is each chunk complete and independent?
- Bad chunking is the number one reason RAG systems fail.
Ingestion 3: Embeddings and vector storage
Each chunk -> embedding -> stored in a vector database. Similar meaning sits close together, so search is fast vector math.
- Vector DB stores millions of embeddings and returns the top k matches for a query.
- Tools: Pinecone (commonly preferred), Chroma DB (used in demo), pgvector for Postgres.
- Demo: OpenAI text-embedding-3-small plus Chroma; 17 documents became 90 chunks.
- Query is also embedded each time, then compared with stored embeddings.
Retrieval: semantic, keyword and hybrid search
- Semantic search - finds similar meaning (car ~ automobile ~ vehicle).
- Keyword / sparse search -> BM25. Finds exact terms: names, IDs, policy numbers, dates.
- Hybrid - use both.
Example
Query: what was Acme's total revenue in Q3 2024? Semantic-only ranked a Q2 2024 report first (distance about 0.2). Hybrid with BM25 matched the exact date and quarter and retrieved correctly. Naive RAG is bad here.
Contextual retrieval
Idea from Anthropic. Chunk alone may say only 'revenue grew by 3%'.
- An LLM reads the chunk and writes a short context line.
- Example prefix: 'This excerpt is from Acme Corporation Q3 2024...'.
- Prefix goes in front of the chunk, then re-embed and re-store.
- Done for all 90 chunks in the demo. Costs LLM calls but eases semantic and keyword matching.
Re-ranking and compression
First pass is fast and rough (semantic/hybrid search, returns many chunks). Second pass is slow and precise (re-rank, keep top 3-5). -> Re-ranking
Example
Hiring: 10,000 resumes, keywords give 200. A human reviews them and prefers 3 years in a startup over 7 years in management. Order changes after the second look.
- Bi-encoder - embeds query and document separately, compares by dot product / cosine similarity.
- Cross-encoder - passes query and document together through a transformer (attention across both) and outputs a relevance score.
- Compression - extra LLM pass removes noise so only the useful ~10% reaches the final LLM.
Full pipeline and tips
- Query transformation - clean messy queries with an LLM; generate 3-5 rephrasings so one hits.
- Prompt: answer only from context; if unsure say 'I don't have enough information'.
- Ask the model to cite sources to reduce hallucination.
- Lost in the middle - LLMs attend most to the start and end of context (U-shaped), least to the middle. Place key chunks there.
Glossary
- RAG
- Retrieval Augmented Generation: retrieve relevant data and pass it to the LLM with the prompt.
- Ingestion
- Loading, parsing, chunking, embedding and storing data.
- Chunking
- Splitting documents into smaller parts before embedding.
- Vector database
- Store of embeddings that returns the nearest matches to a query.
- BM25
- Keyword-based sparse search for exact terms.
- Hybrid search
- Combining semantic and keyword search.
- Cross-encoder
- Transformer that scores a query and document together for re-ranking.
- Re-ranking
- Second precise pass that reorders retrieved chunks.