Understanding RAG: How Retrieval-Augmented Generation Gives AI External Memory
💬 hippo: RAG has been one of the hottest patterns in applied AI since 2024. The problem it solves is straightforward: grounding LLM responses in real reference material instead of letting the model guess from memory. Drawing on Anthropic’s official Cookbook RAG guide, this post walks you from first principles to a working implementation.
1. Why RAG?
LLMs are powerful, but they have three structural limitations:
- Knowledge cutoff: Training data stops at a fixed date—the model has no idea what happened afterward.
- Hallucinations: When unsure, the model will confidently fabricate an answer.
- No access to private data: It cannot see a single word of your internal docs or company databases.
RAG (Retrieval-Augmented Generation) directly addresses all three. The idea is intuitive: instead of asking the model to answer from memory, have it look up relevant material first and generate its answer from what it found.
Think of it this way: prompting an LLM directly is a closed-book exam; adding RAG turns it into an open-book exam. Open-book doesn’t guarantee a perfect score, but it dramatically cuts down on making things up.
2. How RAG Works
A RAG pipeline runs in three stages: Retrieve → Augment → Generate.
1 | User Question |
Here are the core building blocks behind each stage:
2.1 Embeddings
An embedding converts a piece of text into a numeric array (vector) that captures its semantic meaning. Texts with similar meanings land close together in vector space; unrelated texts sit far apart.
For example, "What is machine learning?" and "What is ML?" end up very close in high-dimensional space, while "What is machine learning?" and "What's for lunch today?" are far apart.
Popular embedding models include OpenAI’s text-embedding-3-small and Voyage AI’s voyage-3.
2.2 Vector Databases
A vector database is purpose-built for storing and querying vectors—common choices include Pinecone, Weaviate, Chroma, and Milvus. Their core capability is semantic search: retrieving relevant content by meaning rather than exact keyword overlap.
2.3 Chunking
Chunking splits long documents into smaller segments (typically a few hundred to ~1,000 tokens), which are embedded and stored individually. If you index an entire document as a single unit, retrieval precision suffers—when a user asks a specific question, you want the exact relevant passage back, not a 50-page file.
💬 hippo: Chunking is the most overlooked—and highest-leverage—knob in a RAG pipeline. Chunks that are too large dilute retrieval precision; chunks that are too small lose surrounding context. There is no universal magic number; you have to tune it to your document structure and query patterns.
3. What a Minimal RAG System Looks Like
Following Level 1 Basic RAG in Anthropic’s Cookbook, here is a minimal implementation using Python, the Anthropic SDK, and Voyage AI:
1 | import anthropic |
How the three stages map directly to the code:
| Stage | Code Location | What It Does |
|---|---|---|
| Retrieve | retrieve() |
Embeds the query, computes similarity against document vectors, and returns the top-k chunks |
| Augment | Prompt assembly in answer() |
Injects the retrieved chunks into the prompt as context |
| Generate | client.messages.create() |
Has Claude answer strictly from the provided context |
💬 hippo: Two engineering habits worth building early: first,
np.dotequals cosine similarity **only when vectors are L2-normalized (unit length)**—voyage-3outputs normalized vectors by default, but skipping explicit normalization will cause silent score drift if you ever swap embedding models. Second, use a dedicated vector database in production (Pinecone, Chroma, pgvector, etc.). Either way, the core loop never changes: retrieve relevant context, inject it into the prompt, and let the model answer. No magic involved.
4. Advanced RAG Optimizations
A minimal pipeline works, but retrieval quality is rarely production-ready out of the box. Anthropic’s Cookbook lays out a clean optimization ladder:
4.1 Basic RAG → Summary Indexing
Problem: Raw document chunks often contain noisy details that muddy similarity matching.
Fix: Generate a concise summary for each chunk and index the summaries for retrieval. Matching against summaries sharpens precision and surfaces more focused passages.
Impact: In Anthropic’s benchmarks, end-to-end accuracy rose from 71% to 81%.
4.2 Reranking
Problem: Vector similarity search is a coarse filter—it routinely pulls in marginally relevant candidates.
Fix: Cast a wider net during initial retrieval (e.g., top-20 or more), then use an LLM to rerank the candidates and keep only the most relevant top-k.
1 | import re |
4.3 Contextual Retrieval (Anthropic’s Recommended Approach)
Introduced by Anthropic in 2024, Contextual Retrieval rests on a simple insight: prepend document-level context to every chunk before embedding it.
Naive chunking slices text blindly—once a passage is cut out, everything before and after it disappears. Contextual Retrieval uses an LLM to write a short contextual header for each chunk prior to indexing:
1 | def contextualize(chunk, full_document): |
Embedding the combined context summary + raw chunk dramatically improves retrieval accuracy. According to Anthropic’s evaluation, **retrieval failure rates drop by 67%**—at a cost of just $1.02 per million document tokens when paired with prompt caching.
4.4 Emerging Directions
- GraphRAG: Uses knowledge graphs alongside or in place of pure vector search, excelling at multi-hop reasoning across documents.
- Agentic RAG: Lets an AI agent decide whether to retrieve, what to query, and whether the evidence is sufficient, iterating over multiple turns until satisfied.
💬 hippo: GraphRAG and Agentic RAG are still evolving rapidly, so we won’t go deep here. For most production workloads today, Contextual Retrieval + Reranking is already a formidable baseline.
5. When to Use RAG—and Its Limitations
When RAG Fits Well
| Use Case | Description |
|---|---|
| Enterprise knowledge base Q&A | Employees query internal docs, policies, and FAQs in natural language |
| Customer support bots | Ground answers in product documentation instead of generic chitchat |
| Legal / financial document analysis | Surface relevant clauses across large specialized document corpora |
| Codebase Q&A | Answering questions like “How is authentication implemented in this repo?” |
When Not to Use RAG
Anthropic’s official recommendation: If your knowledge base is under 200K tokens (roughly 150K words), putting the entire corpus directly into the prompt outperforms RAG. Modern Claude context windows are large enough that standing up a vector database for a small dataset is unnecessary complexity.
Limitations of RAG
- Chunking breaks context: Slicing documents severs surrounding narrative (Contextual Retrieval mitigates this).
- Vector similarity ≠ semantic understanding: Semantically close queries phrased differently can miss, while lexically similar passages with different meanings can produce false hits.
- Indexing and maintenance overhead: Every corpus update requires re-embedding, and chunking heuristics need ongoing tuning.
6. Going Deeper: Why Doesn’t Claude Code Use Traditional Vector RAG?
Earlier we listed “codebase Q&A” as a RAG use case. Yet if you have used Claude Code or Google Antigravity (AGY), you will notice something counterintuitive: neither builds a local vector database—instead, they search live code directly with grep, glob, and read_file.
That isn’t a shortcut. Code repositories have fundamentally different engineering properties from general document corpora:
- Code changes constantly; vector indexes are inherently stale: Edit one line or switch a Git branch and the working tree changes immediately. Keeping a vector index synced in real time is expensive and prone to stale reads, whereas
ripgrepandglobscan disk in milliseconds against ground truth. - Fixed-size chunking shreds code semantics: Code depends on exact symbol definitions, type declarations, call chains, and cross-file
imports. Splitting by token count cuts function signatures away from their implementations or drops critical middleware and config files. Letting the agentgrepa symbol and follow the call chain withread_filepreserves intact context. - Code search favors exact literal matching over fuzzy semantics: When tracing where
ErrNotFoundis handled or which route mountsAuthMiddleware, regex and exact string search beat cosine similarity every time. - Lower security and privacy overhead: There is no need to chunk and upload a private repository to a third-party embedding API or remote vector store—everything stays local and is read on demand.
This reveals a clean division of labor between two retrieval paradigms:
| Dimension | Traditional Vector RAG (incl. Contextual Retrieval) | Agentic Live Retrieval (grep/glob + Context Engineering) |
|---|---|---|
| Typical workload | Company policies, support docs, large unstructured PDF/Wiki corpora | Actively changing codebases, local config files, log debugging |
| Retrieval strength | Semantic paraphrase matching (e.g., “expense reimbursement” matching “travel allowance claim”) | Exact symbol tracing and iterative multi-hop drill-down |
| Data freshness | Depends on offline or near-real-time re-indexing | Reads live disk state with zero lag |
| Primary cost center | Offline chunking, embeddings, and vector store upkeep | Runtime context window budget and tool-call turn control |
💬 hippo: In a coding agent, writing an architecture map into
CLAUDE.md/AGENTS.mdand letting the agent inspect live files viagrep/globis essentially a leaner form of Agentic Retrieval and Context Engineering. To dig deeper into coding-agent loops and runtime scaffolding, see How Claude Code Works and Understanding the Agent Harness.
7. Summary
| Takeaway | In One Line |
|---|---|
| What RAG is | A technique that lets an LLM look up reference material before answering |
| Core pipeline | Retrieve (find relevant passages) → Augment (inject into prompt) → Generate (answer from context) |
| Key components | Chunking, embeddings, vector databases, semantic search |
| Advanced optimizations | Summary indexing, reranking, Contextual Retrieval |
| When to skip it | Stuff the prompt directly if your corpus is < 200K tokens; use agentic live retrieval for fast-moving codebases |
Recommended Resources:
- Anthropic Cookbook: RAG Guide — Primary reference for this post, including full runnable code and evaluation methodology
- Contextual Retrieval — Anthropic’s retrieval optimization method that cuts retrieval failure rates by 67%
Series Navigation
- Index: Claude Code in Practice · Series Index
- Previous: Guarding Your Claude Code Workflow with Hooks
- Further Reading: Google Antigravity (AGY) Field Guide · Series Index








