Retrieval-Augmented Generation (RAG) Explained Step by Step

How RAG works: chunking, embeddings, vector search, prompt assembly and generation, plus when RAG beats fine-tuning and how to evaluate it.

Published December 1, 2026

A language model only knows what was in its training data, which is frozen in time and never included your company's documents. Retrieval-Augmented Generation (RAG) fixes that by looking up relevant information at question time and putting it into the prompt, so the model answers from your sources and can cite them. It is the most common way to build assistants over documentation, policies, tickets and knowledge bases.

The concept

RAG has two phases. Indexing happens ahead of time: documents are split into chunks, each chunk is turned into an embedding (a vector of numbers capturing its meaning), and the vectors are stored in a vector index along with the original text and metadata.

Querying happens per question: the question is embedded, the most similar chunks are retrieved (often combined with keyword search and re-ranked), and the top results are inserted into the prompt with instructions to answer only from them and cite sources. The model then generates an answer grounded in that context.

Indexing pipeline

splitmodelstoreDocumentsPDF, HTML, MDChunk300-800 tokensEmbedvectorsVector index+ text + metadata
Indexing: done once, refreshed as documents change.

Query flow

UserAppVector indexLLMquestionembed questiontop-k similar chunkschunks + sourcesprompt: context + questiongrounded answer + citationsanswer
Query time: retrieve, assemble, generate.

RAG vs alternatives

ApproachBest forWeakness
Prompt with full docsSmall corpora that fit in contextCost and dilution as docs grow
RAGLarge, changing knowledge; citations neededRetrieval quality is the bottleneck
Fine-tuningStyle, format, narrow skillsPoor at injecting fresh facts; costly to update
RAG + fine-tuningDomain style plus fresh factsMore moving parts

Practical examples

Minimal RAG with PostgreSQL + pgvector

Store chunks with embeddings, retrieve by cosine distance.

CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (id bigserial PRIMARY KEY, doc text, content text, embedding vector(1536));
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

SELECT doc, content FROM chunks
ORDER BY embedding <=> $1      -- $1 = question embedding
LIMIT 5;

Prompt assembly

Instruct the model to stay within the provided context.

SYSTEM = """Answer using only the context below. If the answer is not in the context,
say you don't know. Cite sources as [doc name]."""
context = "\n\n".join(f"[{c.doc}]\n{c.content}" for c in top_chunks)
prompt = f"Context:\n{context}\n\nQuestion: {question}"

Simple evaluation set

Measure retrieval and answers against known questions.

[
  {"question": "How many days do customers have to request a refund?", "expected_doc": "refund-policy.md", "answer_contains": "30 days"},
  {"question": "Which plans include SSO?", "expected_doc": "pricing.md", "answer_contains": "Enterprise"}
]

Common mistakes

  • Chunks that cut tables, code or sentences in half.
  • Pure vector search for queries full of IDs, error codes or names (add keyword search).
  • No evaluation set, so changes are judged by vibes.
  • Stale indexes that never update when documents change.

Key takeaways

  • RAG retrieves relevant text at query time and grounds the answer in it.
  • Indexing = chunk, embed, store; querying = embed, retrieve, assemble, generate.
  • Retrieval quality determines answer quality.
  • Build an evaluation set before tuning anything.

FAQ

Is RAG dead now that context windows are huge?

No. Large windows let you pass more context, but retrieval still controls cost, latency and focus on the right material, especially for large or changing corpora.

Which embedding model should I use?

Pick a strong general model from your provider or an open model, then compare on your own evaluation set; domain fit matters more than leaderboard rank.

How many chunks should I retrieve?

Commonly 3-10 after re-ranking. Measure: too few misses answers, too many adds noise and cost.

More AI articles