💬 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:

  1. Knowledge cutoff: Training data stops at a fixed date—the model has no idea what happened afterward.
  2. Hallucinations: When unsure, the model will confidently fabricate an answer.
  3. 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
2
3
4
5
6
7
User Question
↓
[1. Retrieval] Convert the question into a vector and search the knowledge base for the most relevant passages
↓
[2. Augmented] Inject the retrieved passages into the prompt as context
↓
[3. Generation] The LLM generates an answer grounded in that context

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import anthropic
import voyageai
import numpy as np

# 1. Prepare the knowledge base (a collection of document chunks)
documents = [
"RAG stands for Retrieval-Augmented Generation.",
"Embedding converts text into numerical vectors that capture semantics.",
"Chunking splits long documents into smaller segments for precise retrieval.",
# ... more document chunks
]

# 2. Embed and store in the knowledge base (mark documents with input_type="document")
vo = voyageai.Client()
doc_embeddings = np.asarray(
vo.embed(documents, model="voyage-3", input_type="document").embeddings,
dtype=np.float32,
)
# Explicitly apply L2 normalization: dot product equals cosine similarity only for unit vectors
doc_embeddings = doc_embeddings / np.linalg.norm(doc_embeddings, axis=1, keepdims=True)

# 3. Retrieve: embed the user query and find the most similar documents
def retrieve(query, top_k=2):
query_vec = np.asarray(
vo.embed([query], model="voyage-3", input_type="query").embeddings[0],
dtype=np.float32,
)
query_vec = query_vec / np.linalg.norm(query_vec)
similarities = np.dot(doc_embeddings, query_vec) # dot product of unit vectors = cosine similarity
top_indices = np.argsort(similarities)[-top_k:][::-1]
return [documents[i] for i in top_indices]

# 4. Augment + Generate: inject retrieved chunks into the prompt for the model to answer
client = anthropic.Anthropic()

def answer(query):
contexts = retrieve(query)
prompt = f"""Answer the question based on the reference material below. If the answer is not in the material, say "I'm not sure".

Reference material:
{chr(10).join(f'- {c}' for c in contexts)}

Question: {query}"""

response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text

# Try it out
print(answer("What is RAG?"))

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.dot equals cosine similarity **only when vectors are L2-normalized (unit length)**—voyage-3 outputs 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import re

def rerank(query, candidates, top_k=3):
"""Rerank candidate chunks with Claude while handling variations in model output format"""
if not candidates:
return []

prompt = f"""Rank the following document chunks by relevance to the question.
Question: {query}
Candidate chunks:
{chr(10).join(f'{i+1}. {c}' for i, c in enumerate(candidates))}
Return the {top_k} most relevant chunk numbers, separated by commas. Return numbers only."""

try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=64,
messages=[{"role": "user", "content": prompt}]
)
raw_text = response.content[0].text
except Exception:
# Fall back to initial retrieval order on API failure to avoid blocking the main path
return candidates[:top_k]

# Extract numbers via regex, deduplicate, and bounds-check to handle extra LLM explanation text
seen = set()
selected = []
for num in re.findall(r"\d+", raw_text):
idx = int(num) - 1
if 0 <= idx < len(candidates) and idx not in seen:
seen.add(idx)
selected.append(candidates[idx])
if len(selected) == top_k:
break

return selected if selected else candidates[:top_k]

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def contextualize(chunk, full_document):
"""Add context to a chunk"""
prompt = f"""<document>
{full_document}
</document>

Here is a chunk from the document:
<chunk>
{chunk}
</chunk>

Provide a succinct 1-2 sentence context situating this chunk within the overall document. Return only the context and nothing else."""

response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=100,
messages=[{"role": "user", "content": prompt}]
)
context = response.content[0].text
return f"{context}\n{chunk}" # context + original chunk

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:

  1. 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 ripgrep and glob scan disk in milliseconds against ground truth.
  2. 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 agent grep a symbol and follow the call chain with read_file preserves intact context.
  3. Code search favors exact literal matching over fuzzy semantics: When tracing where ErrNotFound is handled or which route mounts AuthMiddleware, regex and exact string search beat cosine similarity every time.
  4. 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.md and letting the agent inspect live files via grep/glob is 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:


Series Navigation