RAG end to end
Retrieval-augmented generation (RAG) is the pattern where you look up relevant material first and then ask a language model to answer using only that material. It sounds simple, and the first demo usually works in an afternoon. The hard part is everything after the demo: messy documents, queries that do not look like the text they need, and answers that sound right but are not supported. This doc is the map for the rest of the track.
Why it matters
A model only knows what was in its training data and what you put in its context window. Your company handbook, last week's tickets and this morning's price list are in neither. RAG closes that gap without retraining anything. It also gives you three properties that fine-tuning does not: you can update knowledge by re-indexing instead of re-training, you can show citations, and you can enforce access control at retrieval time so a user never sees chunks they are not allowed to read.
The term comes from the 2020 paper by Lewis and colleagues, which paired a dense retriever with a seq2seq generator. Today the components are different (hosted embedding APIs, vector databases, frontier LLMs), but the shape is the same: retrieve, then generate.
There is one honest question to ask before you build anything: do you need retrieval at all? Context windows are now large enough that a small corpus can just be pasted into the prompt. A 2024 study by Li and colleagues found that long-context models beat RAG on average quality when given enough budget, while RAG kept a large cost advantage. Their hybrid, Self-Route, tries RAG first and falls back to the full context only when the model judges the retrieved chunks insufficient. That is a good mental model: long context is the expensive, simple option; RAG is the cheap, engineered option; many production systems use both. Also keep in mind the "Lost in the Middle" finding: models use information at the start and end of a long input more reliably than information buried in the middle, so stuffing everything in is not free even when it fits.
How it works
A RAG system has two pipelines that share one index.
The offline (ingestion) pipeline turns source documents into searchable units:
- Parse files into clean text and structure (headings, tables, page numbers).
- Chunk the text into passages small enough to embed and cite.
- Enrich chunks with metadata (source, tenant, date, permissions) and optionally with generated context.
- Embed each chunk into a vector, and usually also build a keyword (BM25) index.
- Store vectors, text and metadata in an index.
The online (query) pipeline answers a question:
- Optionally rewrite the query (fix typos, expand acronyms, split multi-part questions).
- Retrieve candidates with vector search, keyword search, or both, filtered by metadata.
- Rerank candidates with a stronger model and keep the best few.
- Build a prompt with the chunks, their source ids and clear instructions.
- Generate an answer with citations, and log everything for evaluation.
Rendering diagram…
Every box in that diagram is a place where quality leaks. Bad parsing loses tables. Bad chunking splits a definition from the term it defines. A general-purpose embedding model may not know your jargon. Pure vector search misses exact part numbers. Without reranking, the right chunk sits at position 14 and never reaches the model. The rest of this track takes these boxes one at a time.
Reference architecture
Here is what a single request looks like in a typical production service, including the access-control filter that people forget until a security review.
Rendering diagram…
A few design notes I would put on the whiteboard:
- Retrieve wide, then narrow. Fetch 30 to 100 candidates cheaply, then spend a more expensive model on picking the best handful.
- Filters belong in the index query, not in post-processing. Filtering after retrieval can leave you with zero results.
- Keep chunk ids stable so citations, feedback and eval labels survive re-indexing.
- Log the retrieved set for every request. You cannot debug or evaluate what you did not record.
Code
The smallest honest RAG loop: embed a few chunks, retrieve by cosine similarity, and generate a cited answer. In production you would swap the in-memory list for a vector database, but the shape stays the same.
import os
import numpy as np
from openai import OpenAI
client = OpenAI()
EMBED_MODEL = "text-embedding-3-small"
CHAT_MODEL = os.environ.get("RAG_MODEL", "gpt-4.1-mini")
chunks = [
{"id": "hr-12", "text": "Employees accrue 1.5 vacation days per month of service."},
{"id": "hr-13", "text": "Unused vacation days carry over up to a maximum of 10 days."},
{"id": "it-04", "text": "Laptops are refreshed every three years by the IT team."},
]
def embed(texts: list[str]) -> np.ndarray:
resp = client.embeddings.create(model=EMBED_MODEL, input=texts)
vecs = np.array([d.embedding for d in resp.data], dtype=np.float32)
return vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
chunk_vecs = embed([c["text"] for c in chunks])
def retrieve(query: str, k: int = 2) -> list[dict]:
q = embed([query])[0]
scores = chunk_vecs @ q
top = np.argsort(-scores)[:k]
return [chunks[i] for i in top]
def answer(query: str) -> str:
context = "\n".join(f"[{c['id']}] {c['text']}" for c in retrieve(query))
prompt = (
"Answer using only the sources below. Cite source ids in brackets. "
"If the sources do not contain the answer, say you do not know.\n\n"
f"Sources:\n{context}\n\nQuestion: {query}"
)
resp = client.responses.create(model=CHAT_MODEL, input=prompt)
return resp.output_text
print(answer("How many vacation days can I carry over?"))
Notice the instruction to say "I do not know". Without it, the model will happily fill gaps from its own training data, which defeats the point.
Trade-offs and pitfalls
- Demo quality is not production quality. Ten hand-picked questions over three clean PDFs tells you nothing. Build an eval set from real queries early.
- Chunk size is a trade-off, not a constant. Small chunks retrieve precisely but lose context; big chunks carry context but dilute the embedding and cost tokens.
- Vector search alone misses exact matches like SKUs, error codes and names. Most mature systems end up hybrid.
- More context is not always better. Passing 40 chunks increases cost, latency and the chance the model fixates on the wrong one.
- Freshness and deletes are real work. Plan how a deleted or edited source document gets removed from the index, and how quickly.
- Security lives in retrieval. If a chunk reaches the prompt, assume the user can extract it. Enforce permissions with metadata filters.
- Long context is a valid baseline. For a corpus that fits comfortably in the window and changes rarely, try just pasting it (with prompt caching) before building a pipeline.
Checklist
- Decide whether the corpus is small enough for a long-context baseline, and measure it.
- Define the offline pipeline: parse, chunk, enrich, embed, index, with stable chunk ids.
- Store tenant and permission metadata on every chunk and filter at query time.
- Retrieve wide (tens of candidates) and rerank down to a handful.
- Instruct the model to cite sources and to refuse when the sources are silent.
- Log query, retrieved ids, scores and answer for every request.
- Build an evaluation set from real queries before tuning anything.
Further reading
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Lewis et al., 2020)
- Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach (Li et al., 2024)
- Lost in the Middle: How Language Models Use Long Contexts (Liu et al., 2023)
- Introducing Contextual Retrieval (Anthropic)
- OpenAI embeddings guide