The short answer

#

Retrieval-augmented generation (RAG) means that, at request time, you search your own documents for the passages relevant to the user's question and put those passages into the prompt alongside the question. The model then answers from your material rather than from whatever it absorbed in training. It is a search step bolted on to the front of an ordinary API call, nothing more exotic than that. If your whole corpus fits comfortably in the context window and rarely changes, you do not need RAG: put everything in a cached system prompt and ask. You need RAG when the corpus is too large, changes often, differs per user, or when sending all of it on every request is money you would rather not spend.


_11
const chunks = await search(question, 5); // your retrieval step
_11
_11
const response = await client.messages.create({
_11
model: 'claude-sonnet-5-5',
_11
max_tokens: 1024,
_11
system: 'Answer using only the provided context. If it is not there, say so.',
_11
messages: [{
_11
role: 'user',
_11
content: `Context:\n${chunks.map((c) => c.content).join('\n\n')}\n\nQuestion: ${question}`,
_11
}],
_11
});

How it works

#

A language model only knows two things: what it learned in training, and what is in the prompt in front of it. It has never seen your internal wiki, your product database or the support ticket from this morning. The context window is the only way in. RAG is just a disciplined way of deciding what goes through that door.

The pipeline has five steps, and you build it once:

  1. Chunk. Split each document into passages of a few hundred tokens, ideally along headings and paragraphs so each chunk makes sense on its own.
  2. Embed. Run every chunk through an embedding model, which turns text into a vector of numbers where similar meanings end up close together. Anthropic does not offer embeddings; Voyage AI's voyage-3 family (recommended by Anthropic) or OpenAI's text-embedding-3-small are common choices.
  3. Store. Save each chunk's text, its vector and some metadata (source, heading) in a database that can search by vector. Postgres with the pgvector extension is enough for most applications.
  4. Retrieve. When a question comes in, embed it with the same model and fetch the five or ten chunks whose vectors are closest.
  5. Prompt. Assemble those chunks and the question into a message and call the model as usual.

Steps one to three happen when documents change. Steps four and five happen on every request. The model never sees your whole corpus; it sees a handful of passages chosen because they look relevant.

How to choose

#

When a big prompt is enough

Current models accept a 1M-token context window. At roughly four characters per token, that is a few thousand pages of prose. A product manual, a policy handbook, your API reference or a mid-sized codebase will fit with room to spare. If the corpus is also fairly stable, the simplest design wins: put the documents in the system prompt, mark them for caching, and let every request reuse them. Cached reads cost about a tenth of normal input tokens.


_10
const response = await client.messages.create({
_10
model: 'claude-sonnet-5-5',
_10
max_tokens: 1024,
_10
system: [
_10
{ type: 'text', text: instructions },
_10
{ type: 'text', text: allDocs, cache_control: { type: 'ephemeral' } },
_10
],
_10
messages: [{ role: 'user', content: question }],
_10
});
_10
console.log(response.usage.cache_read_input_tokens); // should be large after the first call

Measure the corpus with client.messages.countTokens() before deciding. Many teams build a retrieval pipeline for a corpus that would have fitted in one prompt.

When RAG wins

The corpus is large. If it does not fit, retrieval is the only option. But RAG also wins well before that point on cost. Sending 500K tokens on every request at $2 per million (Sonnet) is $1 per request uncached and still about $0.10 when cached. Retrieving five chunks of 500 tokens sends 2,500 tokens, a fraction of a cent.

The corpus changes often. Prompt caching is a prefix match: change one document early in the prompt and everything after it is re-cached. With RAG you re-embed only the documents that changed.

The data is per user. You cannot cache one giant prompt per customer. Retrieving the rows that belong to the current user, with a WHERE clause, is natural in a database and awkward anywhere else.

You want to show sources. A prompt built from five identifiable chunks can cite them. A prompt built from a thousand pages cannot, at least not reliably.

Cite your sources

Number the chunks when you assemble the prompt, ask the model to reference them, and show the sources in your UI. This is the single biggest trust improvement you can make, and it is also how you debug retrieval: if the cited chunk is wrong, retrieval is the problem, not the model.


_15
type Chunk = { source: string; heading: string; content: string };
_15
_15
function buildPrompt(question: string, chunks: Chunk[]): string {
_15
const context = chunks
_15
.map((c, i) => `[${i + 1}] ${c.source} > ${c.heading}\n${c.content}`)
_15
.join('\n\n');
_15
return [
_15
'Answer the question using only the numbered sources below.',
_15
'Cite sources inline as [1], [2]. If the sources do not contain the answer, say so.',
_15
'',
_15
context,
_15
'',
_15
`Question: ${question}`,
_15
].join('\n');
_15
}

Combine both

The two approaches are not exclusive. Cache the stable core (instructions, a style guide, a schema, the most-asked-about documents) in the system prompt, and retrieve the long tail into the user message. Keep the retrieved text after the cached block so it does not break the cache.

Common pitfalls

#
  • Reaching for RAG first. A 1M-token window and caching cover far more cases than they did a few years ago. Count your tokens before you build a pipeline.
  • Putting retrieved text before the cached block. Caching is a prefix match. Retrieved chunks change every request, so they belong in the user message, after anything you want cached.
  • Trusting retrieval blindly. If nothing relevant exists, the top five results are still returned and the model may answer from them anyway. Tell it to say when the context does not contain the answer, and consider a similarity threshold.
  • Retrieving too much. Twenty loosely related chunks dilute the prompt and cost more. Start with five and tune against real questions.
  • Letting embeddings go stale. When a document changes, delete its chunks and re-embed it. Old chunks that contradict new ones are worse than no chunks.
  • Skipping evaluation. Keep twenty or so real questions with known good answers and run them whenever you change chunking, the embedding model or the prompt.
#

quick question

Was this resource helpful?