What is Retrieval-Augmented Generation (RAG)?

Learning path, stage 3 of 5: RAG and fine-tuning · question 1 of 10

RAG answers a question by first retrieving relevant passages from your own data, then giving them to the LLM as context, so the answer is grounded in sources the model was never trained on. It's the standard way to build "chat with your docs", support bots and internal knowledge assistants.

The pipeline

  1. Ingest: load the documents → split into chunks → embed each chunk → store in a vector index (with metadata).
  2. Retrieve: embed the user's query → find the nearest chunks. Often combined with keyword search and a reranker.
  3. Generate: put the top chunks in the prompt → "answer using only these sources, cite them".

Why use it

  • Fresh and private knowledge without retraining. Update the index, not the model.
  • Fewer hallucinations and citations users can check.
  • Access control: filter retrieval by the user's permissions.

Where it fails

  • Retrieval misses: bad chunking, vocabulary mismatch, the answer spread across many docs.
  • Too much context: relevant passages get lost among noise.
  • The model ignores the sources or blends them with its own memory.

Debug retrieval and generation separately.

Sources

Code example

tsx
1// Minimal RAG: retrieve top chunks, then answer with numbered citations.
2import Anthropic from "@anthropic-ai/sdk";
3
4declare function embed(text: string): Promise<number[]>;
5declare function vectorSearch(v: number[], k: number): Promise<{ id: string; text: string; source: string }[]>;
6
7const client = new Anthropic();
8
9export async function ragAnswer(question: string) {
10 const hits = await vectorSearch(await embed(question), 5);
11 const context = hits
12 .map((h, i) => `<source id="${i + 1}" ref="${h.source}">\n${h.text}\n</source>`)
13 .join("\n");
14
15 const res = await client.messages.create({
16 model: "claude-opus-5-5",
17 max_tokens: 1024,
18 system: "Answer only from the sources. Cite like [1]. If the sources don't cover it, say you don't know.",
19 messages: [{ role: "user", content: `${context}\n\nQuestion: ${question}` }],
20 });
21 return res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
22}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app