# Retrieval-Augmented Generation

**Also known as:** RAG · Grounding  
**Category:** AI Patterns (Model in the loop)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/ai/rag

*Put the answer in the prompt, and the model's job becomes reading.*

A model knows only its training data, frozen at a date. It does not know your documents or your customers. Retrieval-Augmented Generation (RAG) fixes this. Search your own documents for passages that match the question, put them in the prompt, and ask the model to answer from them. Recall becomes reading, which models do far better.

Most “RAG hallucinations” are retrieval misses: the passage with the answer never reached the prompt, so the model guessed. Fix them like a search problem — better chunking, hybrid search, reranking — and score retrieval on its own.

> **In one sentence.** RAG is a search system with a model at the end. When an answer is wrong, the search is usually the reason.

## Origin (2020)

Named by Lewis et al. (Facebook AI, 2020), who trained the retriever and the generator together. Most systems today add retrieval to a frozen model at query time instead.

## The pipeline

### Chunking

Splitting documents into pieces you can retrieve. Too small, and a passage loses the context that gave it meaning. Too large, and its embedding mixes several topics and matches none of them well.

- Split on structure: headings, sections, functions
- Overlap neighbours slightly, so a boundary does not cut an answer
- Keep metadata: source, section, date, permissions

> A manual cut every 512 characters, mid-sentence, retrieves fluent nonsense.

### The index (Vector store · hybrid index)

What makes search fast: embeddings (number vectors that capture meaning) plus a keyword index. Vectors handle paraphrase. Keywords handle the error code, product SKU and surname that vectors often miss.

- Hybrid search beats either kind alone on most real data
- Needs a refresh plan: a stale index gives stale answers

### Reranking

A second, slower pass over the top candidates that scores each one against the question directly. Fetch fifty cheaply, keep the best five. It is often the biggest single gain for a weak RAG system.

- A cross-encoder reads question and passage together: more accurate, slower
- Lets you search broadly without flooding the prompt

### The grounded prompt

The question, the retrieved passages with their sources, and clear instructions: answer from these passages, cite them, and say when they do not cover the question.

- Label each passage with its source, so citation is possible
- Order matters: models often read the middle of a long context worst

## Design rules

### Measure retrieval separately from answers

Before blaming the model, check whether the right passage reached the prompt. Recall@k (is the right passage in the top k results?) on question–passage pairs is cheap and exact, and shows which half to fix.

### Use hybrid search, then rerank

Vector search alone misses error codes, part numbers and names, so add keyword search. Fetch many candidates, say 50, then rerank to 5. Fifty passages in a prompt can bury the answer in the middle.

### Allow the answer “nothing found”

When retrieval is empty or weak, say so instead of answering from memory. Below a score threshold, skip the model call. Ask for citations, and check that each cited passage was really retrieved.

### Filter by permission inside the search

Put access control in the index query, not in a later filter, and never in the prompt. A passage that reaches the context window has already leaked, whatever the model says about it.

## A retrieval pipeline

```
src/rag/
ingest/                         # offline: runs on a schedule, not per request
  chunk.ts                      # split on structure; keep source, section, date, ACL
  embed.ts                      # batch, and version the embedding model
  index.ts                      # write vector and keyword indexes together
retrieve/                       # per request: everything before the model
  search.ts                     # hybrid, with the permission filter in the query
  rerank.ts                     # 50 candidates in, 5 out
  assemble.ts                   # label passages with sources; order them on purpose
answer.ts                       # the one model call: grounded, cited, allowed to decline
eval/                           # the two halves, scored separately
  retrieval.ts                  # recall@k: exact, no model
  answers.ts                    # is every claim backed by a retrieved passage?
```

The two halves are tested apart: eval/retrieval.ts scores recall with no model at all, so you know which half failed before anyone edits a prompt.

## Examples

### Search broadly, rerank, and allow “nothing found”

```typescript
const candidates = await index.search({
  query, limit: 50,
  filter: { tenantId: user.tenantId, acl: user.groups },  // in the query, not after
  mode: "hybrid",                       // vectors for meaning, keywords for SKUs
});

const passages = await rerank(query, candidates, { keep: 5 });

// The most important branch: nothing good was found, so do not ask the model.
if (passages.length === 0 || passages[0].score < FLOOR) {
  return { answer: null, reason: "no-supporting-passages" };
}

return model.answer({ query, passages, requireCitations: true });
```

Hybrid search with the permission filter inside the query, a rerank before anything reaches the prompt, and a score floor that stops before the model is asked at all.

### Check the citations you asked for

```typescript
const result = await model.answer({ query, passages, schema: AnswerSchema });

// Every claim must name a passage that was really retrieved. A cited id that is
// not in the set is an invented source: the clearest hallucination signal there is.
const retrieved = new Set(passages.map((p) => p.id));
const invented = result.claims.filter((c) => !retrieved.has(c.sourceId));

if (invented.length > 0) {
  metrics.increment("rag.invented_citation", invented.length);
  return { answer: null, reason: "unsupported-claims" };
}
```

Asking for citations is half the pattern. Checking them turns a hidden failure into a caught one, and it costs one Set lookup per claim.

## When to use

- Answers must come from documents you own: docs, tickets, policies
- The facts change faster than any model is retrained
- Users need to check the source, so citations matter

## When not to use

- The whole corpus fits in the context window — just include it
- The question needs all the data, like a total: use a database query
- You need a change in behaviour or format, not new knowledge

## Benefits

- Answers based on current, private documents
- Citations make answers checkable, and failures detectable in code
- Updating knowledge means re-indexing a document, not retraining

## Costs

- A second system to run: ingestion, index, refresh, monitoring
- Every request pays search latency and a much larger prompt
- Changing chunking or the embedding model means re-indexing everything

## Pitfalls

- Blaming the model for a retrieval miss, and tuning prompts for weeks.
- Fixed-size chunks that cut sentences, or split a table from its header.
- Vector search only, then surprise that error codes and part numbers never match.
- An index that goes stale because nothing re-runs ingestion.

## Similar patterns, compared

RAG and Agent Memory both put retrieved text into a prompt. What differs is who wrote that text, and that difference is a security boundary.

### Retrieval-Augmented Generation vs Agent Memory

Same search machinery, different source: RAG reads documents people curate; memory reads what the agent chose to write down. — [Agent Memory](https://layra4.dev/architectures/ai/agent-memory)

**What is genuinely the same**

- Both fetch relevant text at request time and put it in the context window
- Both usually use the same embedding index and similarity search

**What actually differs**

- People write and version the corpus; the agent writes memories during a run
- RAG is read-only at request time; memory can be written, so it can be poisoned

**Pick Retrieval-Augmented Generation when:** The facts exist apart from the conversation: documentation, policies, tickets, code.

## Related patterns

- [Agent Memory](https://layra4.dev/architectures/ai/agent-memory) — the same search, over what the agent wrote instead of your documents
- [Context Compaction](https://layra4.dev/architectures/ai/context-compaction) — what to do when retrieved passages crowd the window
- [Evaluation Harness](https://layra4.dev/architectures/ai/eval-harness) — score retrieval and answers separately, or you are guessing
- [Guardrails](https://layra4.dev/architectures/ai/guardrails) — retrieved text is untrusted input: injection arrives here
- [Search Index](https://layra4.dev/architectures/data-storage/search-index) — the keyword half of hybrid search, as a system building block

## Further reading

- *Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks* — Lewis et al. (2020) — The paper that named it.
- *Lost in the Middle: How Language Models Use Long Contexts* — Liu et al. (2023) — Why fifty passages in a prompt hurt: the middle is read worst.
- *Contextual Retrieval* — Anthropic (2024) — Adding chunk context before embedding: a large, cheap gain in recall.
