Embeddings & RAG
Semantic search and retrieval-augmented generation — embedding models, cosine similarity, vector databases and approximate nearest-neighbour indexes (HNSW, IVF), chunking, hybrid search and re-ranking, the RAG pipeline, evaluation, and common failure modes.
LLMs only know what was in their training data — not your company's docs, yesterday's tickets or a private codebase. Retrieval-augmented generation (RAG) fixes this: find relevant information at query time and put it in the prompt. The retrieval part usually relies on embeddings.
Embeddings
An embedding model maps text (or images, audio, code) to a vector — typically 384 to 3,072 numbers — such that similar meanings land close together, even with no words in common.
"How do I reset my password?" → [0.12, -0.48, 0.33, …]
"I forgot my login credentials" → [0.10, -0.45, 0.36, …] ← close
"Best biryani in Hyderabad" → [-0.71, 0.05, -0.22, …] ← farSimilarity is usually cosine similarity (or the dot product of normalised vectors — Math for ML):
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # small open model, 384 dimensions
docs = ["Reset your password from Settings → Security.",
"Refunds are processed within 5 business days.",
"Our office is closed on public holidays."]
D = model.encode(docs, normalize_embeddings=True) # (3, 384)
q = model.encode("I forgot my login", normalize_embeddings=True)
scores = D @ q # cosine similarities
print(docs[int(np.argmax(scores))]) # → the password-reset docEmbedding models are trained with contrastive learning: pull matching pairs (question/answer, query/clicked document, image/caption) together and push non-matching pairs apart. Uses beyond RAG: semantic search, recommendations, deduplication, clustering, classification and anomaly detection.
Vector search at scale
Comparing a query with every stored vector (exact k-nearest-neighbour search) is O(n·d) — fine for 100k vectors, too slow for 100 million. Approximate nearest neighbour (ANN) indexes trade a little recall for huge speed-ups:
| Index | Idea | Notes |
|---|---|---|
| HNSW (hierarchical navigable small world) | A multi-layer proximity graph; greedily walk from coarse to fine layers toward the query | Excellent recall and speed; memory-hungry; the most popular |
| IVF (inverted file) | Cluster vectors with k-means; search only the nearest few clusters | Lower memory; tune clusters probed |
| Product quantisation (PQ) | Compress vectors into short codes | Billions of vectors in RAM; lower accuracy |
| DiskANN / ScaNN | Graph or quantised indexes optimised for SSDs and speed | Very large scale |
Vector databases and libraries: FAISS (library), pgvector (PostgreSQL extension), Pinecone, Weaviate, Qdrant, Milvus, Chroma, plus vector search in Elasticsearch/OpenSearch, Redis and MongoDB. Key features: metadata filtering ("only documents this user may see, updated this year"), hybrid search, and updates without full rebuilds.
The RAG pipeline
Indexing
- Load and clean documents: extract text from PDFs/HTML, keep structure (headings, tables), attach metadata (source, date, permissions).
- Chunk them into passages small enough to be specific but large enough to be self-contained — often 200–800 tokens with some overlap, ideally split on structure (sections, paragraphs). Prepending the document title and section heading to each chunk improves retrieval.
- Embed each chunk and store vectors + text + metadata.
Query time
- (Optionally) rewrite the question — resolve "it" from chat history, expand acronyms, or split multi-part questions.
- Retrieve candidates — usually hybrid: vector search (meaning) plus keyword/BM25 search (exact terms, IDs, names), merged with reciprocal rank fusion. Apply permission and metadata filters.
- Re-rank the top ~50 with a cross-encoder model that reads query and passage together — much more accurate than embedding similarity — and keep the best 5–10.
- Generate: put the passages in the prompt with instructions to answer only from them and cite sources.
def answer(question: str, user) -> str:
candidates = hybrid_search(question, k=50, filter={"allowed_groups": user.groups})
top = rerank(question, candidates)[:6]
context = "\n\n".join(f'<doc id="{d.id}" title="{d.title}">\n{d.text}\n</doc>' for d in top)
prompt = (f"{context}\n\nAnswer the question using only the documents above. "
f"Cite document ids in brackets. If they don't contain the answer, say you don't know.\n\n"
f"Question: {question}")
return llm(prompt)Why RAG
| Benefit | Because |
|---|---|
| Up-to-date knowledge | Update the index, not the model |
| Private data | Data stays in your systems; per-user permissions at retrieval |
| Fewer hallucinations | Answers grounded in retrieved text |
| Verifiability | Citations to sources |
| Cost | No retraining |
Long-context models reduce the need for retrieval on small corpora (just include everything), but retrieval still wins on large or permission-sensitive corpora, cost and latency.
Evaluating RAG
Evaluate the retriever and the generator separately:
| Stage | Metrics |
|---|---|
| Retrieval | Recall@k (is the needed passage in the top k?), MRR, nDCG — on a labelled set of questions and relevant passages |
| Generation | Faithfulness / groundedness (claims supported by retrieved text), answer relevance and correctness, citation accuracy |
| End to end | Task success, user feedback, "I don't know" rate when the answer truly isn't available |
Tools like RAGAS and LLM-as-judge rubrics help, but calibrate them against human judgements.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Right document never retrieved | Bad chunking, vocabulary mismatch, missing keyword search | Structure-aware chunks with titles, hybrid search, query rewriting |
| Retrieved but answer wrong | Too many irrelevant chunks; key info split across chunks | Re-ranking, fewer/larger chunks, parent-document retrieval |
| Confident answer not in sources | Weak grounding instructions | Require citations; allow "I don't know"; check faithfulness |
| Stale or conflicting info | Old versions indexed | Metadata (dates, versions), deduplication, re-indexing pipeline |
| Data leaks across users | No access control at retrieval | Filter by permissions before results reach the LLM |
| Prompt injection from documents | Untrusted content treated as instructions | Delimit content, instruct the model to treat it as data, limit tool permissions |
Beyond basic RAG
- Agentic RAG: the LLM decides when and what to search, possibly over several rounds and sources (search engines, SQL databases, APIs).
- GraphRAG: build a knowledge graph of entities and relations for questions that need connecting many documents.
- Multimodal RAG: retrieve images, tables and charts with multimodal embeddings.
- Contextual retrieval: add LLM-generated context to each chunk before embedding so chunks make sense in isolation.
- Embeddings map content to vectors where similar meaning means nearby; compare with cosine similarity.
- ANN indexes (HNSW, IVF, PQ) make vector search fast at scale; vector databases add filtering and updates.
- RAG: chunk and embed documents offline; at query time retrieve (hybrid), re-rank, and generate with citations.
- RAG keeps knowledge fresh, private and verifiable without retraining.
- Evaluate retrieval (recall@k) and generation (faithfulness) separately.
- Most failures are retrieval failures: fix chunking, add keyword search and re-ranking, enforce permissions, guard against prompt injection.