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.

Advanced 5 min readLesson 13 of 14

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, …]  ← far

Similarity is usually cosine similarity (or the dot product of normalised vectors — Math for ML):

Python
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 doc

Embedding 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:

IndexIdeaNotes
HNSW (hierarchical navigable small world)A multi-layer proximity graph; greedily walk from coarse to fine layers toward the queryExcellent recall and speed; memory-hungry; the most popular
IVF (inverted file)Cluster vectors with k-means; search only the nearest few clustersLower memory; tune clusters probed
Product quantisation (PQ)Compress vectors into short codesBillions of vectors in RAM; lower accuracy
DiskANN / ScaNNGraph or quantised indexes optimised for SSDs and speedVery 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 (offline)Query time (online)DocumentsPDFs, wiki, ticketsChunk + embedVector index+ keyword indexUser questionRetrieve top-khybrid + filtersRe-rankLLManswer with citations

Indexing

  1. Load and clean documents: extract text from PDFs/HTML, keep structure (headings, tables), attach metadata (source, date, permissions).
  2. 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.
  3. Embed each chunk and store vectors + text + metadata.

Query time

  1. (Optionally) rewrite the question — resolve "it" from chat history, expand acronyms, or split multi-part questions.
  2. 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.
  3. 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.
  4. Generate: put the passages in the prompt with instructions to answer only from them and cite sources.
Python
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

BenefitBecause
Up-to-date knowledgeUpdate the index, not the model
Private dataData stays in your systems; per-user permissions at retrieval
Fewer hallucinationsAnswers grounded in retrieved text
VerifiabilityCitations to sources
CostNo 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:

StageMetrics
RetrievalRecall@k (is the needed passage in the top k?), MRR, nDCG — on a labelled set of questions and relevant passages
GenerationFaithfulness / groundedness (claims supported by retrieved text), answer relevance and correctness, citation accuracy
End to endTask 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

SymptomLikely causeFix
Right document never retrievedBad chunking, vocabulary mismatch, missing keyword searchStructure-aware chunks with titles, hybrid search, query rewriting
Retrieved but answer wrongToo many irrelevant chunks; key info split across chunksRe-ranking, fewer/larger chunks, parent-document retrieval
Confident answer not in sourcesWeak grounding instructionsRequire citations; allow "I don't know"; check faithfulness
Stale or conflicting infoOld versions indexedMetadata (dates, versions), deduplication, re-indexing pipeline
Data leaks across usersNo access control at retrievalFilter by permissions before results reach the LLM
Prompt injection from documentsUntrusted content treated as instructionsDelimit 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.
Key takeaways
  • 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.