Learning Objectives
- Contrast Retrieval-Augmented Generation (RAG) vs model fine-tuning (LoRA) by cost, freshness, and traceability.
- Compute cosine similarity over normalized dense vectors in pure Python to understand vector database scoring.
- Design hybrid retrieval (dense embeddings + BM25 lexical search) to prevent exact-keyword misses.
Prerequisites
- Python fundamentals and basic JSON/HTTP familiarity
Why LLMs Need Grounded Retrieval (RAG)
Large Language Models freeze world knowledge at training cutoff and carry zero visibility into your company’s internal HR policies, product documentation, or yesterday’s codebase commits. Retrieval-Augmented Generation (RAG) solves this at query time: retrieve top relevant source chunks first, inject them with strict citation rules into the prompt context, and instruct the model to refuse answering outside verified evidence.
Ingestion Pipeline vs Query Pipeline
- Offline Ingestion: Load & clean documents → split on structural headings (e.g., 300–500 tokens with 15% overlap) → generate embedding vectors → upsert vectors + metadata (URL, section, ACL role) into Qdrant or PostgreSQL
pgvector. - Online Query: Embed query + run lexical BM25 → fuse results with Reciprocal Rank Fusion (RRF) → apply metadata tenant/role filter → generate grounded cited answer.
Practice AI interview scenarios on MockAttempt Spoken AI Interviews or build LangGraph & Qdrant pipelines in our Generative AI & Agentic AI Career Program.
Practical Programming Examples
Pure-Python Cosine Similarity Vector Retriever (Zero Wrapper Magic)
Implement normalized cosine similarity scoring over document vectors to rank the closest semantic match deterministically.
import math
def cosine_similarity(a: list[float], b: list[float]) -> float:
dot = sum(x * y for x, y in zip(a, b, strict=True))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return 0.0 if norm_a == 0 or norm_b == 0 else dot / (norm_a * norm_b)
chunks = [
("tuition-policy", "Fee is INR 45,000 + 18% GST in 3 monthly splits.", [0.91, 0.25, 0.10]),
("aws-lab", "Always configure AWS Budgets before launching NAT Gateways.", [0.12, 0.88, 0.41]),
]
query_vec = [0.90, 0.22, 0.08]
ranked = sorted(
((doc_id, round(cosine_similarity(query_vec, vec), 4), text) for doc_id, text, vec in chunks),
key=lambda row: row[1],
reverse=True,
)
print("Top retrieved:", ranked[0][0], "score=", ranked[0][1])
Top retrieved: tuition-policy score= 0.9994
- Normalized dot product measures angular closeness cleanly regardless of text scale.
- The query vector aligns near 1.0 with `tuition-policy` and ranks it top-1 before sending context to an LLM.
Common Mistakes to Avoid
- Splitting chunks blindly mid-sentence or splitting markdown tables, severing pricing numbers from their headers.
- Passing untrusted retrieved documents into prompts without metadata ACL filtering or prompt-injection defenses.
Production Best Practices
- Combine dense vector similarity + BM25 lexical search (Hybrid RRF) so exact error codes and IDs match too.
- Measure retrieval Recall@k and answer Faithfulness on a curated golden evaluation dataset before modifying prompts.
Technical Interview Relevance
Cornerstone GenAI Engineer interview system design question covering chunk sizing, Hybrid Search, RRF, and RAG evaluation.
Practice & Self-Check Questions
Why must permission/ACL filtering happen BEFORE or inside vector search rather than after?
Filtering after retrieving top-k risks filling all `k` slots with unauthorized documents and then dropping them, leaving zero valid chunks or leaking data.