RAG (Retrieval-Augmented Generation)

In one sentence

Before the model answers, search your own data for the most relevant passages and put them in the prompt, so the answer is grounded in fresh, private, citable sources instead of memory.

Analogy: An open-book exam: the student (the LLM) still has to reason and write, but first looks up the right pages instead of answering from memory — and can point to the page.

Indexing runs offline whenever sources change; every user question runs the online path against that index.

How it works

  • The model's weights stay frozen; the knowledge lives in an index you control and can refresh in minutes.
  • Offline, you parse, chunk, embed and store documents, usually with BM25 alongside the vectors.
  • Online, you rewrite the query, retrieve ~50 candidates this user may read, rerank to 3–8, then generate with citations.
  • Most wrong answers are retrieval failures: the passage was mangled by parsing, split across chunks, or ranked #40.
  • Plain RAG is weak at multi-hop and corpus-wide questions; reach for GraphRAG, agentic RAG or SQL over metadata.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your internal RAG assistant gives wrong answers. The team already swapped the LLM twice and rewrote the prompt, with no improvement. What should you do first?

Go deeper

Full explanation

RAG retrieves relevant passages from your own data at question time and puts them in the prompt, so the LLM answers from evidence instead of memory. The weights stay frozen; the knowledge lives in an index you control. Lewis et al. (2020) coined the term for a dense retriever and a generator fine-tuned end to end; today it means any retrieve-then-generate pipeline.

It has two paths:

Why it wins: knowledge that is fresh (re-index in minutes, no retraining), private, permission-scoped and citable, with fewer hallucinations.

Where it fails: most wrong answers are retrieval failures — the passage was mangled by parsing, split across chunks, or ranked #40. Plain RAG is also weak at multi-hop and corpus-wide questions ("which contracts expire this quarter?"); reach for GraphRAG & knowledge graphs, Agentic RAG or SQL over metadata. Evaluate retrieval and generation separately (Evaluating RAG).

Code Online path: retrieve, rerank, assemble, generate
pythonOnline path: retrieve, rerank, assemble, generate
from openai import OpenAI

client = OpenAI()
MODEL = "gpt-4.1-mini"  # any chat model

def answer(question: str, user) -> str:
    # 1. Recall: hybrid search, filtered to what this user may read
    candidates = hybrid_search(question, k=50, acl=user.groups)
    # 2. Precision: keep the few chunks that actually answer it
    chunks = rerank(question, candidates, keep=5)
    # 3. Assemble: numbered sources so the model can cite them
    context = "\n\n".join(
        f"[{i}] {c.title} ({c.updated})\n{c.text}" for i, c in enumerate(chunks, 1)
    )
    prompt = (
        "Answer ONLY from the sources below and cite them like [1]. "
        "If they don't contain the answer, say you don't know.\n\n"
        f"Sources:\n{context}\n\nQuestion: {question}"
    )
    # 4. Generate (low temperature: we want faithful, not creative)
    resp = client.chat.completions.create(
        model=MODEL, temperature=0,
        messages=[{"role": "user", "content": prompt}],
    )
    return resp.choices[0].message.content
Real example

An HR assistant for a 5,000-person company indexes ~20,000 Confluence and SharePoint pages: ~150,000 chunks of ~500 tokens, embedded once for ~$1.50 with text-embedding-3-small. An employee asks "How many remote days does the Madrid office allow?". Hybrid search returns 50 chunks the employee is allowed to see; the reranker keeps 5, including the Madrid policy edited last Tuesday. The LLM answers "3 days a week" and links that page. Without RAG it would have guessed from training data — or invented a policy.

Trade-offs +4 · −4

+ You gain

  • Update knowledge in minutes by re-indexing; no retraining.
  • Citations make answers verifiable and auditable.
  • Access control is enforced at retrieval: the model only sees what the user may see.
  • Cheaper and far easier to update than fine-tuning for injecting facts.

− You pay

  • Quality is capped by retrieval: if the right chunk isn't found, the model can't use it.
  • Many moving parts to build, evaluate and keep in sync: parsers, index, reranker, prompts.
  • Adds latency before the first token and a per-query retrieval cost.
  • Weak at multi-hop reasoning and aggregations over the whole corpus.

Use it when

The answer lives in documents that change, are private, or must be cited: support, internal knowledge, legal, product docs. It's the default for knowledge problems, before fine-tuning.

Avoid it when

The whole corpus fits cheaply in the context window (Long context vs RAG), the task is about behavior or format rather than knowledge, or the question is an aggregation that SQL answers exactly.

Numbers to know 4
  • Typical online shape: retrieve ~50 → rerank → 3–8 chunks of ~300–800 tokens in the prompt.
  • Indexing is cheap: 75M tokens with text-embedding-3-small ($0.02 per 1M, list price as of 2026) ≈ $1.50.
  • Retrieval + reranking usually add ~100–400 ms before the first token; generation dominates total latency.
  • The original RAG paper retrieved from ~21M Wikipedia passages of 100 words.
Common pitfalls 4
  • Tuning prompts and swapping LLMs when the real problem is retrieval: measure recall@k first.
  • Never looking at parsed text: tables flattened to number soup, footers in every chunk.
  • Stuffing 20+ chunks "to be safe": more noise, more cost, and the middle gets ignored.
  • Filtering permissions after generation instead of at retrieval — the answer has already leaked.
Interview questions 3

Answer out loud first, then reveal.

Walk me through how you'd build RAG for an internal knowledge assistant.Show answer

Two paths. Offline: connectors pull from Confluence, Drive and tickets; a layout-aware parser keeps headings and tables; I chunk on structure at ~400–500 tokens, embed, and store vectors plus BM25 with metadata — source, date, ACL. Online: rewrite the query with the chat history, run hybrid search for ~50 candidates filtered by the user's groups, rerank to 5, and prompt the model to answer only from numbered sources with citations, or abstain. Around it: an eval set of real questions, per-stage tracing, and incremental re-indexing so content is fresh within minutes.

RAG, fine-tuning or long context: how do you choose?Show answer

They solve different problems. RAG is for knowledge: facts that change, are private, or need citations and access control. Fine-tuning is for behavior: format, tone, a narrow skill, or a shorter prompt; it's a poor way to inject facts because they're hard to update or attribute. Long context works when the relevant corpus is small and query volume is low, ideally with prompt caching; beyond that, cost per query, latency and lost-in-the-middle effects favor retrieval. Often I combine them: RAG for facts, a light fine-tune for output style.

What are the main ways RAG fails in production?Show answer

I group them by stage. Ingestion: bad parsing, stale or duplicated content, missing permission metadata. Retrieval: the answer isn't in the top-k because of chunking, a weak embedding model, or no lexical search for IDs and codes. Ranking: it was retrieved but buried. Generation: the model ignores the context, blends sources, or answers when it should abstain. Plus questions RAG can't serve, like aggregations over the whole corpus. So I measure each stage separately — recall@k, context precision, faithfulness — not just end-to-end accuracy.

Deep dive 2

The upgrade path, in order

Naive RAG — embed chunks, take the top 5 by cosine, stuff the prompt — demos well and fails on exact terms, tables and long-tail questions. The order I upgrade in, measuring each step on an eval set:

  1. Inspect and fix parsing and chunking.
  2. Add Lexical search & BM25 for Hybrid search & RRF.
  3. Add Reranking (cross-encoders) over a wider pool.
  4. Query transformation (rewrite, HyDE) for vague or conversational queries.
  5. Contextual retrieval if chunks lose their context.
  6. Agentic RAG only when questions genuinely need several retrieval hops.

Every step adds latency and cost, so stop when the evals plateau.

Assembling the prompt

Number each chunk and include its title, source and date, so the model can cite [2] and the UI can render a link. Instruct it to answer only from the sources and to say "I don't know" when they don't cover the question — abstaining is a feature. Keep only the chunks that survived reranking: models use information at the start and end of a long context better than in the middle (Liu et al., Lost in the Middle), so put the strongest evidence first. Place the stable instructions before the retrieved text so Prompt caching can reuse that prefix.