Retrieval-Augmented Generation grounds an LLM in your own data by retrieving relevant passages at query time and adding them to the prompt.
INDEXING (offline)
documents -> clean/parse -> chunk -> embed -> store (vector DB + metadata)
QUERY (online)
question -> (rewrite) -> embed -> top-k search -> (rerank)
-> build prompt with context -> LLM -> answer + citations
- Cheaper and fresher than fine-tuning for knowledge
- Gives citations and access control per document
- Quality is limited by retrieval: bad context in, bad answer out
An embedding model maps text to a vector so that similar meaning means nearby vectors. Use the same model for documents and queries.
Cosine similarity: angle between vectors; most common for text
Dot product: same as cosine if vectors are normalized; fastest
Euclidean (L2): straight-line distance
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
emb = model.encode(["what is a vector db?", "HNSW graph index"],
normalize_embeddings=True) # shape (2, 384)
score = emb[0] @ emb[1] # cosine (normalized)
Changing the embedding model means re-embedding everything
Fixed size + overlap: simple baseline, e.g. 300-800 tokens with 10-20% overlap
Recursive / structure-aware: split on headings, paragraphs, sentences, code blocks
Semantic: split where embedding similarity between sentences drops
Parent-child: retrieve small chunks, return the larger parent for context
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_text(doc)
Attach metadata (source, title, section, date, ACL) to every chunk
Flat (brute force): exact, slow at scale; fine up to ~100k vectors
HNSW: layered proximity graph; high recall and speed, high memory; the usual default
IVF: clusters vectors, searches the nearest nprobe clusters; lower memory
PQ (product quantization): compresses vectors; trades accuracy for memory
DiskANN: graph index designed for SSD-resident large datasets
Key HNSW knobs:
M: graph connectivity; more = better recall, more memory
efConstruction: build-time search width
efSearch: query-time width: the recall vs latency dial
import faiss, numpy as np
d = 384
xb = np.random.rand(10000, d).astype("float32")
index = faiss.IndexFlatIP(d) # exact inner product (use normalized vecs)
index.add(xb)
D, I = index.search(xb[:1], k=5) # distances, ids
hnsw = faiss.IndexHNSWFlat(d, 32) # M=32
hnsw.hnsw.efSearch = 64
hnsw.add(xb)
faiss.write_index(hnsw, "index.faiss")
FAISS is a library, not a database: no metadata filtering or persistence layer
CREATE EXTENSION vector;
CREATE TABLE docs (
id bigserial PRIMARY KEY,
content text,
metadata jsonb,
embedding vector(384)
);
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);
-- <-> L2 <#> negative inner product <=> cosine distance
SELECT id, content, 1 - (embedding <=> $1) AS similarity
FROM docs
WHERE metadata->>'tenant' = 'acme'
ORDER BY embedding <=> $1
LIMIT 5;
Great when you already run Postgres: joins, transactions and filters in one place
import chromadb
client = chromadb.PersistentClient(path="./chroma")
col = client.get_or_create_collection("docs")
col.add(ids=["1", "2"],
documents=["HNSW is a graph index", "IVF clusters vectors"],
metadatas=[{"src": "a"}, {"src": "b"}]) # embeds with default model
res = col.query(query_texts=["graph based search"], n_results=2,
where={"src": "a"})
res["documents"], res["distances"]
from qdrant_client import QdrantClient, models
c = QdrantClient(":memory:") # or QdrantClient(url="http://localhost:6333")
c.create_collection("docs", vectors_config=models.VectorParams(
size=384, distance=models.Distance.COSINE))
c.upsert("docs", points=[models.PointStruct(
id=1, vector=vec, payload={"src": "a", "text": "..."})])
hits = c.query_points("docs", query=qvec, limit=5,
query_filter=models.Filter(must=[models.FieldCondition(
key="src", match=models.MatchValue(value="a"))])).points
pgvector: you already use Postgres; moderate scale; transactional data
Qdrant / Weaviate / Milvus: dedicated, scalable, rich filtering and hybrid search
Pinecone: fully managed, minimal ops
Chroma / LanceDB: embedded, great for prototypes and local apps
FAISS: in-process library for research and batch jobs
OpenSearch / Elasticsearch: you need strong keyword search plus vectors
Decide with your data size, filter needs, ops capacity and latency targetDense vectors capture meaning but miss exact terms (IDs, error codes, names). BM25 keyword search catches those. Combine both.
# Reciprocal Rank Fusion: merge ranked lists without tuning score scales
def rrf(rankings, k=60):
scores = {}
for ranking in rankings: # e.g. [bm25_ids, vector_ids]
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
fused = rrf([bm25_top50, vector_top50])[:20]
Retrieve broadly (top 20-100) with fast vectors, then rerank with a cross-encoder that reads query and passage together, and keep the best 3-8.
from sentence_transformers import CrossEncoder
rr = CrossEncoder("BAAI/bge-reranker-base")
pairs = [(query, c) for c in candidates]
scores = rr.predict(pairs)
top = [c for _, c in sorted(zip(scores, candidates), reverse=True)][:5]
Reranking is often the single largest precision gain for the cost
Query rewriting: resolve pronouns and context from chat history into a standalone query
Multi-query: generate several paraphrases, search each, fuse results
HyDE: have the LLM write a hypothetical answer and embed that instead of the question
Decomposition: split complex questions into sub-questions
Metadata filters / routing: let the LLM choose the collection or filter first
Retrieval:
Recall@k: is the right chunk in the top k?
MRR: how high is the first relevant result?
nDCG: graded relevance with position discount
Generation:
Faithfulness: is the answer supported by the retrieved context?
Answer relevance: does it address the question?
Context precision / recall: was the context focused and complete?
Build a labeled set of 50-200 real questions before tuning anything- Answer is split across chunks: increase chunk size/overlap or use parent-child retrieval
- Right document exists but is not retrieved: add hybrid search, better chunking, or query rewriting
- Retrieved but ignored ("lost in the middle"): rerank, retrieve fewer chunks, place best first
- Hallucinated answer when nothing relevant exists: add a similarity threshold and an "I don't know" path
- Stale answers: re-index on document change, store updated_at metadata
- Stuffing too much context: raises cost and lowers accuracy
- Enforce document-level permissions with metadata filters at query time
- Cite sources in every answer
- Version your embedding model and chunking config; plan re-indexing
- Cache embeddings and frequent queries; monitor latency per stage
- Log queries, retrieved chunks and feedback to find failures
- Defend against prompt injection inside retrieved documents