Skip to main content
Intermediate Architecture & Engineering 12 min read Python 3.12 + Vector Search / RAG

RAG Architecture Explained: Embeddings, Vector Search & Chunking

Ground LLMs on private documents reliably with semantic chunking, cosine similarity vector retrieval, and strict citation prompts.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last updated: Verification Policy

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.

Python 3.12
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])
Expected Output
Top retrieved: tuition-policy score= 0.9994
Step-by-Step Execution
  1. Normalized dot product measures angular closeness cleanly regardless of text scale.
  2. 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.

Optional Next Step

Have Questions About Learning Generative AI Structured Cohorts?

Request the PBCP syllabus & weekend batch schedule from an Academic Counselor.

View PBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.