Context and retrieval

RAG Engineering

RAG answers questions from your documents. Documents are split into chunks and indexed; a question retrieves the most relevant chunks; the model answers from those chunks and cites them. The simulator below runs real keyword, vector, and hybrid retrieval on sample documents.

What Is RAG?0:58 · beginner

The RAG lifecycleBeginner

Indexing happens once per document change; retrieval and generation happen per question.

documents → extract → clean → chunk → embed → vector index
question → (rewrite) → retrieve → rerank → assemble context → generate → cite → evaluate

Embeddings and cosine similarityIntermediate

An embedding model turns text into a vector so that similar meanings are close together. Search compares the question’s vector with every chunk’s vector, usually by cosine similarity. The simulator uses TF-IDF vectors instead of a learned embedding model: they match shared words, not meanings, and are labelled that way.

cos(a, b) = (a · b) / (‖a‖ ‖b‖)

Keyword, vector, and hybrid retrievalIntermediate

Keyword search (BM25) is exact on names, codes, and rare terms; vector search finds paraphrases. Hybrid retrieval runs both and merges the rankings, often with reciprocal rank fusion.

RRF(d) = Σ_rankings 1 / (k + rank(d)),  k = 60

Reranking, query rewriting, filteringAdvanced

A reranker re-scores the top candidates with a more accurate model. Query rewriting expands or clarifies the question before search. Metadata filters (product, date, tenant) narrow the search space and enforce access control.

Grounding and citationsAdvanced

Instruct the model to answer only from the retrieved passages, cite them, and say when they do not contain the answer. Evaluate faithfulness (is every claim supported?) separately from answer relevance.

Tenant-aware access controlAdvanced

In multi-tenant systems, filter by tenant before retrieval, not after generation. A document the user may not read must never reach the context window.

Key takeaways

  • Hybrid retrieval combines exact and fuzzy matching.
  • Ground answers in retrieved text and cite it.
  • Enforce access control at retrieval time.
Experiment with chunking first