5. Retrieval-Augmented Generation

Teaching models to look things up

A language model's knowledge is frozen at training time. Ask it about a library released last week and it will either hallucinate or admit ignorance. Ask it about your company's internal API and it has nothing to work with. Retrieval-augmented generation — RAG — fixes this by giving the model access to external knowledge at inference time. Instead of relying solely on what it memorized during training, it can look things up.

RAG is the workhorse behind documentation chatbots, enterprise search, coding assistants that understand your codebase, and any system where the model needs knowledge it wasn't trained on.

The Core Idea

RAG adds a retrieval step before generation:

  1. User asks a question
  2. Retrieve relevant documents from a knowledge base
  3. Augment the prompt with the retrieved documents
  4. Generate a response grounded in the retrieved context
User: "How do I configure rate limiting in our API?"

    ┌──────────┐
    │ Retrieve │ ──→ searches internal docs
    └────┬─────┘
         │ top 3 matching docs
         ▼
    ┌──────────┐
    │ Augment  │ ──→ adds docs to prompt
    └────┬─────┘
         │
         ▼
    ┌──────────┐
    │ Generate │ ──→ answers using retrieved context
    └──────────┘

Without retrieval, the model would guess based on common rate limiting patterns. With retrieval, it answers using your actual configuration docs, middleware code, and internal conventions.

Embedding-Based Retrieval

The most common retrieval mechanism uses vector embeddings. The idea: convert both documents and queries into high-dimensional vectors where semantically similar texts end up close together.

How embeddings work

An embedding model (like text-embedding-3-large or similar) maps text to a fixed-dimensional vector — typically 768 to 3072 dimensions. These vectors capture semantic meaning:

  • "How to configure rate limiting" → [0.12, -0.34, 0.56, ...]
  • "Setting up request throttling" → [0.11, -0.33, 0.55, ...] (nearby!)
  • "Best Italian restaurants in Tokyo" → [-0.78, 0.42, -0.15, ...] (far away)

The distance between vectors (typically cosine similarity) measures semantic relatedness. This is why RAG can find relevant documents even when the user's query uses different words than the documents.

The indexing pipeline

Before you can retrieve anything, you need to index your knowledge base:

Documents → Chunk → Embed → Store in vector DB

Chunking — splitting documents into pieces — is where most RAG quality is won or lost. Too large and you waste context window space on irrelevant text. Too small and you lose the surrounding context that makes the chunk meaningful.

function chunkDocument(text: string, options: ChunkOptions): Chunk[] {
  const { maxTokens = 512, overlap = 50 } = options;
  const sentences = splitIntoSentences(text);
  const chunks: Chunk[] = [];
  let current: string[] = [];
  let currentTokens = 0;

  for (const sentence of sentences) {
    const tokens = countTokens(sentence);
    if (currentTokens + tokens > maxTokens && current.length > 0) {
      chunks.push({
        text: current.join(" "),
        tokens: currentTokens
      });
      // Keep overlap sentences for context continuity
      const overlapSentences = current.slice(-3);
      current = [...overlapSentences];
      currentTokens = overlapSentences.reduce(
        (sum, s) => sum + countTokens(s), 0
      );
    }
    current.push(sentence);
    currentTokens += tokens;
  }

  if (current.length > 0) {
    chunks.push({ text: current.join(" "), tokens: currentTokens });
  }

  return chunks;
}

Overlap between chunks ensures that information split across a chunk boundary isn't lost. Without overlap, a critical sentence at the boundary of two chunks might not match any query well enough to be retrieved.

Retrieval at query time

When a user asks a question:

  1. Embed the query using the same embedding model
  2. Find the K nearest vectors in the database (typically K = 3-10)
  3. Return the corresponding text chunks
async function retrieve(
  query: string,
  k: number = 5
): Promise<RetrievedChunk[]> {
  const queryEmbedding = await embed(query);
  const results = await vectorDB.search(queryEmbedding, { topK: k });

  return results.map(r => ({
    text: r.document.text,
    score: r.similarity,
    source: r.document.metadata.source
  }));
}

Chunking Strategies

The right chunking strategy depends on your content:

Fixed-size chunking

Split every N tokens with M tokens of overlap. Simple, works for homogeneous text like documentation or articles.

Semantic chunking

Split at natural boundaries — paragraph breaks, section headings, function definitions. Produces chunks that are self-contained units of meaning.

// For code: chunk by function/class
function chunkCode(source: string, lang: string): Chunk[] {
  const tree = parseAST(source, lang);
  return tree.topLevelNodes.map(node => ({
    text: node.text,
    metadata: {
      type: node.type,     // "function", "class", "import"
      name: node.name,     // "handleRequest", "AuthService"
      file: source.path
    }
  }));
}

Hierarchical chunking

Create chunks at multiple levels of granularity. A document might have a full-page chunk, section chunks, and paragraph chunks. At retrieval time, search the fine-grained chunks but return the parent chunk for context.

Document-type-specific chunking

Document type Chunking strategy
Prose/docs Paragraph or section boundaries
Code Function/class/module boundaries
API docs One chunk per endpoint
Chat logs One chunk per conversation turn
Tables/CSV One chunk per row group with header

Reranking

Vector similarity is a rough signal. The top 20 results from embedding search might contain 5 highly relevant chunks, 10 somewhat relevant ones, and 5 false positives. A reranker takes those initial results and re-scores them with a more powerful model.

Query + 20 candidates → Reranker → top 5 reranked results

Rerankers (like cross-encoders) process the query and each candidate together, which gives them much more signal than comparing pre-computed embeddings. The tradeoff is speed — reranking is slower because it runs a model on each candidate pair.

Two-stage retrieval:

  1. Recall stage: vector search returns top 20-50 candidates (fast, approximate)
  2. Precision stage: reranker selects top 3-5 (slow, accurate)

This is the standard production pattern. You cast a wide net with embeddings and narrow it with a reranker.

Hybrid Search

Embeddings capture semantic similarity but miss exact matches. If someone searches for "ERR_CONN_REFUSED", a semantic search might return results about network errors in general but miss the document that contains that exact error code.

Hybrid search combines:

  • Vector search — semantic similarity via embeddings
  • Keyword search — exact matching via BM25 or similar
async function hybridSearch(query: string, k: number): Promise<Chunk[]> {
  const [vectorResults, keywordResults] = await Promise.all([
    vectorDB.search(embed(query), { topK: k * 2 }),
    keywordIndex.search(query, { topK: k * 2 })
  ]);

  // Reciprocal rank fusion
  return fuseResults(vectorResults, keywordResults, k);
}

Reciprocal Rank Fusion (RRF) combines ranked lists by summing reciprocal ranks. A document ranked #1 in vector search and #3 in keyword search gets a combined score of 1/1 + 1/3 = 1.33. This simple formula works surprisingly well at combining different ranking signals.

RAG for Code

Code RAG has unique challenges:

Code is structured, not natural language. A function's meaning depends on its type signatures, imports, and the functions it calls — not just its text. Effective code RAG indexes these relationships.

Identifiers matter. The function name calculateTaxWithholding is semantically meaningful, but standard embedding models might not weight it heavily enough. Augmenting chunks with explicit metadata (function name, file path, class name) helps.

Dependencies create context. Understanding a function often requires seeing its dependencies. Code RAG systems build dependency graphs and retrieve not just the matching function but its most important callees and callers.

// Code chunk with rich metadata
{
  text: "function calculateTax(income: number, state: string): number { ... }",
  metadata: {
    file: "src/tax/calculator.ts",
    name: "calculateTax",
    type: "function",
    imports: ["TaxBracket", "STATE_RATES"],
    calledBy: ["processPayroll", "generateW2"],
    calls: ["lookupBracket", "applyDeductions"]
  }
}

This is how coding assistants understand large codebases. They don't load every file into context — they index the codebase, retrieve the relevant pieces, and let the model work with a focused subset.

Prompt Augmentation Patterns

Once you've retrieved relevant chunks, how do you present them to the model?

Simple stuffing

Concatenate retrieved chunks into the prompt:

Use the following context to answer the question.

Context:
---
[chunk 1 text]
Source: docs/rate-limiting.md
---
[chunk 2 text]
Source: src/middleware/throttle.ts
---

Question: How do I configure rate limiting in our API?

This works, but the model may hallucinate beyond the provided context or ignore chunks that contradict its training data.

Cite-your-sources

Ask the model to ground its answer in specific chunks:

Answer the question using ONLY the provided context.
For each claim, cite the source document in [brackets].
If the context doesn't contain enough information, say so.

This dramatically reduces hallucination because the model is forced to trace each statement back to a source. If it can't cite a source, it should acknowledge the gap rather than fabricate.

Multi-turn retrieval

For complex questions, retrieve in multiple rounds:

  1. Initial retrieval based on the user's question
  2. Model reads retrieved context and identifies what's missing
  3. Model formulates a more specific search query
  4. Second retrieval fills the gaps
  5. Model generates a complete answer

This is the retrieval equivalent of chain-of-thought — letting the model refine its information needs iteratively.

Evaluation

RAG systems have two failure modes: retrieval failures (the right document wasn't found) and generation failures (the document was found but the model misused it). You need to measure both.

Retrieval metrics:

  • Recall@K — of the relevant documents, how many appeared in the top K results?
  • Precision@K — of the top K results, how many were actually relevant?
  • MRR (Mean Reciprocal Rank) — how high did the first relevant result appear?

Generation metrics:

  • Faithfulness — does the answer only contain information from the retrieved context?
  • Answer relevance — does the answer actually address the question?
  • Groundedness — can each claim in the answer be traced to a specific source?

Build a test set of question-answer-source triples and evaluate regularly. RAG quality degrades silently as your knowledge base changes — automated evaluation catches drift before users do.

Common Pitfalls

Chunking too aggressively. Tiny chunks (50-100 tokens) lose context. The chunk "returns a boolean" is useless without knowing what returns a boolean.

Ignoring metadata. Chunks without source information make the model unable to cite sources or reason about recency/authority.

Stale indexes. If your knowledge base changes but your embeddings don't get re-indexed, the model retrieves outdated information. Set up incremental re-indexing.

Over-retrieval. Stuffing 20 chunks into context dilutes the model's attention. 3-5 highly relevant chunks outperform 15 moderately relevant ones.

No fallback. When retrieval finds nothing relevant, the model should say "I don't have information about that" — not hallucinate an answer. Instruct this behavior explicitly in the system prompt.

Try It — RAG Explorer

Embedding Space

Select a query to see how it maps into the 2D embedding space. The closest document chunks are retrieved as context for the model. Adjust K to control how many results are returned.

Chunking Explorer

Paste text below and adjust chunk size and overlap to see how the text gets split. Overlapping regions appear in both adjacent chunks.

What's Next

RAG gives a model access to external knowledge. Tool use gives it the ability to act. Context management keeps everything within budget. The next article combines all three into the pattern that powers autonomous AI systems: the agentic loop.