The RAG Field Guide
A working-knowledge reference on Retrieval-Augmented Generation, high level to low level: the 2026 production architecture end to end, a fully working local pipeline for a 48GB Apple Silicon MacBook Pro, reference designs across AWS, Azure and GCP, RAGAS-based evaluation, and the interview questions you're actually likely to get. 2026 Edition.
Overview & Principles
What RAG actually is, the problems in pure LLMs it fixes, and how to choose between RAG, fine-tuning and long context.
Retrieval-Augmented Generation is an architecture that fetches external knowledge at inference time and grounds the LLM's answer on it. The canonical loop is Index → Query → Retrieve → Augment → Generate: documents are pre-processed into chunks and embedded into a vector index; at query time the system retrieves the most relevant chunks, augments the prompt with them, and the LLM generates an answer grounded in that context — ideally with citations.
- RAG grounds an LLM in your own data by retrieving relevant chunks at query time and injecting them into the prompt — it remains the 2026 default for factual, citable, frequently-changing knowledge, beating fine-tuning (which teaches form, not facts) and long-context stuffing (roughly 20x more expensive at scale) for most enterprise use cases.
- The 2026 production stack has settled on a repeatable shape: structure-aware chunking → hybrid retrieval (dense + BM25 fused with Reciprocal Rank Fusion) → cross-encoder reranking → grounded generation, wrapped in an agentic/self-corrective loop and measured continuously with RAGAS-style metrics (faithfulness, context precision/recall, answer relevancy).
- On a 48GB Apple Silicon MacBook Pro you can run a fully local, private RAG system today: a 27–35B model at 4-bit (Qwen 3.5-class, ~24–28GB) or a lighter gpt-oss-20b/Mistral-Small (~15GB) via Ollama's MLX backend, a tiny local embedding model, and an embedded vector store.
Key findings
- Retrieval, not the LLM, is the bottleneck. Naive "chunk → embed → cosine top-k → stuff prompt" is a prototype, not production. Chunking choice alone can swing recall by up to 9% on the same corpus.
- Hybrid search + reranking is the new baseline. In Anthropic's contextual-retrieval benchmark, combining contextual embeddings with contextual BM25 reduced the top-20-chunk retrieval failure rate by 49% (5.7%→2.9%); adding reranking on top pushed that to a 67% reduction (5.7%→1.9%).
- Embedding leaderboards are volatile. Google's
gemini-embedding-001leads proprietary APIs (MTEB Multilingual mean task score 68.32). Alibaba'sQwen3-Embedding-8Bleads open-weight (70.58, Apache 2.0). - Vector DB choice is dominated by your existing platform, not benchmarks. pgvector if on Postgres, Pinecone for zero-ops, Qdrant for open-source speed, Milvus for billions of vectors, Chroma/LanceDB for local prototyping.
- All three hyperscalers now ship managed RAG — AWS Bedrock Knowledge Bases, Azure AI Search + Foundry, Google Vertex AI RAG Engine.
- Agentic RAG is the dominant emerging pattern for 2026 — retrieval moves inside an agent loop deciding when/what/whether to retrieve, with self-corrective (Self-RAG, CRAG) and graph (GraphRAG) variants for high-stakes/relational data.
Why RAG exists — limitations of pure LLMs it addresses
Hallucination
LLMs generate plausible but fabricated content. RAG grounds outputs in retrieved source text, making answers verifiable.
Knowledge cutoff
A model only knows its training data. RAG injects fresh or proprietary information without retraining.
Domain specificity
General models lack knowledge of internal tickets, contracts, or catalogs. RAG supplies it at query time.
Cost of fine-tuning
Re-training weights to add or update facts is slow, expensive, and goes stale. RAG updates by re-indexing — no gradient updates.
Core concepts
Retrieval — finding the most relevant pieces of information for a query (dense, sparse, or hybrid). Augmentation — inserting retrieved context into the prompt. Generation — the LLM produces the final grounded answer.
RAG vs. fine-tuning vs. long context
Fine-tuning teaches form, not facts — style, tone, schema, structured-citation format, refusal behavior, reasoning patterns. It is not a search index; facts go stale and cannot be cited. LoRA/QLoRA are the only approaches most teams should consider in 2026 — the old "1,000 examples minimum" rule no longer holds; 200–500 curated examples often suffice for classification/extraction.
Long context (Claude ~1M tokens, Gemini ~2M, Llama 4 Scout 10M) lets you skip retrieval and stuff everything in. But it's roughly 20–24x more expensive than RAG at production volume and slower (2–5s for 100k tokens vs ~1.2s for RAG). It shines for "global" queries needing whole-corpus comprehension and corpora under ~200k tokens; RAG wins for fine-grained fact extraction over large corpora.
| Approach | Accuracy (reported) | Best for |
|---|---|---|
| RAG (optimized) | 78–85% | Large/changing corpora, citations, cost control |
| Long context | 82–88% (only <50 docs) | Small corpora, whole-document comprehension |
| Hybrid RAG + fine-tuning | 88–92% | Production systems needing both facts and format |
Use RAG when knowledge updates frequently, needs citations/grounding, or is a large proprietary corpus. Use fine-tuning to adapt style/format or teach reasoning skills. Use long context when the corpus fits the window and you want zero retrieval infrastructure. The 2026 default is often RAG + a small LoRA adapter: tune the interface, retrieve the content.
Key tradeoffs
- Retrieval quality vs. latency
- Chunk size: small = fragmented context, large = diluted/irrelevant tokens
- Recall vs. precision
- Managed convenience vs. cost/control
- Freshness (re-index) vs. stability
When NOT to use RAG
Deep multi-hop reasoning over structured relationships (consider GraphRAG); pure style adaptation (fine-tune); tiny static corpora that fit in context.
Architecture & Pipeline
The 2026 production shape, end to end — from raw documents to a ranked, embedded index. The piece most candidates can name but can't draw.
Fig. 1 — Documents are chunked and embedded offline into a vector index; at query time the same embedding model encodes the question, hybrid retrieval pulls candidates from that index, a cross-encoder reranks them, and the LLM generates a grounded answer — with evaluation metrics feeding back into retrieval tuning.
Data ingestion pipeline
Data ingestion pipeline. Source documents (PDF, DOCX, HTML, MD, CSV) are loaded, parsed, cleaned, chunked, embedded, and upserted into a vector store with metadata. Re-run (or incrementally synced) whenever the corpus changes.
Document loaders/parsers. For complex PDFs with tables and figures, LLM-based or layout-aware parsers (AWS Bedrock Data Automation, Google Document AI, Unstructured, LlamaParse) substantially outperform naive text extraction.
Chunking / splitting strategies
- Fixed-size — split every N tokens/characters. Simplest; fine for uniform content. Recursive 512-token splitting is a strong pragmatic default (ranked first in a Feb-2026 benchmark across seven strategies); ~1024 tokens near peak faithfulness in some studies.
- Recursive character/token splitting — split on a hierarchy of separators (paragraphs → sentences → words) to respect natural boundaries.
- Semantic chunking — embed successive sentences, cut where cosine distance exceeds a threshold (a thematic shift) — coherent, self-contained chunks.
- Document-structure-aware — split Markdown by headings, PDFs by sections, code by functions — best when documents have strong inherent boundaries.
- Advanced: Contextual Retrieval (Anthropic, Sept 2024) — prepend an LLM-generated per-chunk summary before embedding. Also: late chunking, small-to-big / parent-document retrieval.
Use a layout-aware parser (Document AI / Bedrock Data Automation / Unstructured), extract tables separately to markdown/CSV, chunk by document structure (~512–1024 tokens) with overlap, attach page/section metadata, and consider contextual retrieval summaries per chunk.
Embedding models (2026 landscape)
MTEB (56+ tasks) is the standard benchmark, but the overall average hides retrieval-specific performance — use NDCG@10 for RAG, and always run your own retrieval eval since public scores don't always transfer to your corpus.
| Model | MTEB | Context | Dims | Cost / 1M tok | Self-host |
|---|---|---|---|---|---|
| gemini-embedding-001 | 68.32 | 2,048 | 3072 (flex) | $0.15 | No |
| Qwen3-Embedding-8B | 70.58 (multiling.) | 32,000 | 7168 (flex) | Free | Yes (Apache 2.0) |
| voyage-3-large | ~67+ | 32,000 | 2048 (flex) | $0.06 | No |
| text-embedding-3-large | 64.6 | 8,192 | 3072 (flex) | $0.13 | No |
| Cohere embed-v4 | 65.2 | 128,000 | 1024 | $0.10 | VPC/on-prem |
| BGE-M3 | 63.0 | 8,192 | 1024 | Free | Yes (MIT) |
| NV-Embed-v2 | 69.32 | 32,768 | 4096 | Free | Yes (CC-BY-NC) |
| Nomic embed-text-v1.5 | ~62+ | 8,192 | 768 (flex) | $0.10 | Yes |
| all-MiniLM-L6-v2 | 56.3 | 512 | 384 | Free | Yes |
Notable open-weight ceiling model: KaLM-Embedding-Gemma3-12B (72.32 aggregate MMTEB Borda). Voyage publishes domain-specific variants (voyage-law-2, voyage-finance-2, voyage-code-3). Most models now support Matryoshka (MRL) dimension truncation — e.g., OpenAI large 3,072→1,024 dims cuts storage 3x for ~2% quality loss.
Always use the same embedding model for documents and queries — vectors must live in the same space.
Vector databases / stores
Pinecone
Fully managed. Zero-ops, scales to billions; built-in inference (embeddings + reranking), full-text hybrid search, BYOC. Serverless ~$0.30–$0.40 per 1M reads plus storage.
Weaviate
Open source. Strong hybrid (vector + BM25 + metadata) search, built-in vectorization modules, GraphQL.
Qdrant
Open source. Rust-based, fastest open-source engine (p99 ~12ms at 10M vectors, 10–25% faster than Weaviate/Milvus), best free tier, native sparse (SPLADE, miniCOIL) and ColBERT multi-vector.
Milvus / Zilliz Cloud
Open source / managed. Purpose-built for billions of vectors at lower cost; requires engineering resources.
Chroma
Open source, embedded. Developer-first, great for prototyping/MVPs; object-storage backend and collection forking.
pgvector
Open source (Postgres extension). Default when Postgres is your platform (<~100M vectors). SQL filtering, joins, transactional consistency, HNSW since v0.5. pgvectorscale adds iterative index scans.
FAISS
Open source library. Meta's library (not a full DB) — in-process ANN index, great for local/embedded and research.
Pick by your existing data-platform commitment first; ANN benchmarks are tie-breakers. Embeddings are portable across stores — migrations typically take 1–3 days.
Indexing strategies
- Flat (brute force) — exact search, compares query to every vector. Perfect recall, slowest; fine for small sets.
- IVF (Inverted File) — partitions vectors into clusters (Voronoi cells); searches only nearest cells. Faster, approximate, needs training.
- HNSW (Hierarchical Navigable Small World) — the dominant graph-based ANN index. Builds a multi-layer proximity graph (like a skip list): the top layer has few nodes with long-range links for coarse navigation, the bottom layer has all nodes with short-range links for fine-grained accuracy. Each node's max layer is chosen by an exponentially decaying probability (
l = floor(-ln(uniform(0,1)) · mL),mL = 1/ln(M)). Search enters at the top, greedily hops toward the nearest neighbor, then descends layer by layer. Achieves logarithmic search complexity with high recall.M — connections per node efConstruction — build-time candidate list efSearch — query-time candidate list (↑ = better recall, slower)
Retrieval, Generation & Orchestration
How a query actually becomes a ranked context window, and the frameworks and patterns that wire it together.
Retrieval strategies
- Dense — embed query, find nearest vectors (semantic; bi-encoder). Captures meaning but is "lossy" — compresses a paragraph to one point.
- Sparse / BM25 — classic lexical ranking; excellent for exact terms, IDs, rare tokens.
- Hybrid — run both, fuse with Reciprocal Rank Fusion (RRF) — the 2026 baseline, since dense-only lost on nearly every public benchmark. RRF (Cormack, Clarke & Büttcher, SIGIR '09) sums
1/(k+rank), typically k=60. - Reranking with cross-encoders — after retrieving top-50/100, a cross-encoder jointly encodes (query, doc) pairs and re-scores, keeping top 5–10. Adds ~20–50ms but 5–15 MRR points, and combats "lost in the middle." Leading rerankers: Cohere Rerank (rerank-v3.5, Rerank 4 Fast/Pro), self-hostable BGE-reranker-v2-m3 (Apache 2.0), Jina reranker v2, Voyage rerank-2.5, Qwen3 reranker.
A bi-encoder embeds query and document separately into vectors compared by cosine — fast, scalable, used for first-stage retrieval, but misses fine-grained interactions. A cross-encoder concatenates query and document and processes them jointly through a transformer, modeling token-level interactions for far more accurate relevance — but requires one forward pass per candidate, so it's used only to rerank a shortlist.
Query transformation techniques
- Query expansion — augment with synonyms/related terms for vocabulary coverage.
- HyDE (Hypothetical Document Embeddings) — prompt an LLM to generate a hypothetical answer, then embed that for retrieval — bridges the semantic gap between short questions and long documents. Risk: the fake document can introduce hallucinated details.
- Multi-query — generate N reformulations, retrieve in parallel, merge/dedupe/rerank — improves intent coverage at the cost of complexity.
- Query rewriting (rewrite-retrieve-read) and RAG-Fusion (multi-query + RRF) are related patterns.
Generation / LLM component
Retrieved, reranked context is inserted into a prompt template instructing the model to answer only from context, cite sources, and refuse when context is insufficient. A confidence/similarity threshold can trigger fallback to a direct answer with a disclaimer.
Orchestration frameworks
LangChain
(+ LangGraph for stateful/cyclic agent graphs, LangSmith for observability) — broadest ecosystem (~350+ integrations, ~92k GitHub stars), best for complex agents; carries a complexity tax for simple RAG.
LlamaIndex
A RAG-specialist with rich index structures and data-ingestion focus; roughly half the code and ~30% less memory for pure RAG.
Haystack 2.0
(deepset) Production-first, typed, testable DAG pipelines with clean component boundaries; first-class document-store support (Elasticsearch, OpenSearch, Weaviate, Pinecone, Qdrant, pgvector).
Advanced patterns
- Agentic RAG — retrieval embedded in a multi-agent/decision loop where an LLM controls when/what/whether to retrieve, with query decomposition, validation, synthesis. The dominant enterprise pattern in 2026, often built on LangGraph.
- Graph RAG (Microsoft GraphRAG, mid-2024) — build a knowledge graph during ingestion; retrieve graph neighborhoods and LLM-generated community summaries — handles global, relational, multi-hop queries that flat vector search misses.
- Self-RAG (Asai et al., 2023) — trains the model to emit reflection tokens deciding when to retrieve, whether passages are relevant, whether output is supported.
- Corrective RAG (CRAG) (Yan et al., 2024) — a lightweight evaluator classifies retrieved docs as correct/ambiguous/incorrect and triggers web search or re-query when confidence is low.
- Multi-hop retrieval — iterative retrieve-reason-retrieve for questions requiring evidence chained across documents.
Evaluation & Observability
Where most RAG systems actually fail, and how to measure it before users find out.
Evaluation frameworks and metrics
RAGAS is the standard framework. Core metrics:
- Faithfulness — factual consistency of the answer with retrieved context (proportion of claims verifiable against chunks).
- Answer Relevancy — how well the answer addresses the query.
- Context Precision — are relevant chunks ranked highly / what fraction of retrieved context is relevant.
- Context Recall — does retrieved context contain all the ground-truth information needed.
Most failures are retrieval, not generation. High faithfulness + low context recall = the retriever is missing evidence (common on multi-hop) while the generator answers coherently from partial context.
Discrete IR metrics: Precision@k, Recall@k, MRR, NDCG@10 (with labeled gold documents). Other tools: DeepEval (CI/CD quality gates), Future AGI fi.evals, TruLens, Arize Phoenix.
Caching & monitoring
Caching layers. Semantic caching (embed queries, return cached answers for near-duplicate queries), embedding caches, and prompt/KV caches cut cost and latency.
Monitoring / observability. Log retrieved chunks, scores, latencies, token usage, user feedback; trace every call (LangSmith, Arize Phoenix, traceAI); run runtime guardrails for hallucination and PII; feed eval metrics back into chunking/reranker/index tuning.
Local / Laptop Implementation
A fully private, offline RAG stack that runs comfortably on a 48GB Apple Silicon MacBook Pro.
Why local RAG. Full data sovereignty and privacy — no bytes leave the machine, deployable behind an air gap. Apple Silicon's unified memory (UMA) lets the GPU use the full RAM pool, running models that exceed any consumer GPU's VRAM.
The runtime stack (2026)
- Ollama for day-to-day ergonomics — as of v0.19 (preview, ~March 30–31, 2026) its Apple Silicon backend switched to Apple's MLX framework: Ollama's own M5 Max benchmark on Qwen3.5-35B-A3B showed decode jump from 58→112 tok/s and prefill 1,154→1,810 tok/s vs the prior Metal backend. Requires >32GB unified memory. Enable via
OLLAMA_USE_MLX=1. - MLX / mlx-lm for maximum performance and fine-tuning — Apple's native framework, generally ~10–30% faster than llama.cpp on newer chips (up to 20–87% for sub-14B models); the advantage narrows at 27B+ where both saturate memory bandwidth.
- llama.cpp when you need portability and fine-grained control.
- LM Studio for a GUI.
Recommended local LLMs for 48GB
Leave ~25–30% for macOS. Rule of thumb: ~0.6GB per billion parameters at Q4; usable memory ≈ 70–75% of total.
| Tier | Model | Footprint (Q4) | Notes |
|---|---|---|---|
| Sweet spot | Qwen 3.5/3.6 27B (dense) | ~26GB | ~12–16 tok/s |
| Sweet spot | Qwen 3.5 35B-A3B (MoE) | ~28GB | only ~3.3B active → near-8B speeds, ~36–92 tok/s |
| Max headroom | gpt-oss-20b (Apache 2.0, MoE, MXFP4) | ~14GB | loads in ~16GB, leaves room for long context |
| Max headroom | Mistral Small 24B | ~14–15GB | solid general-purpose |
| Avoid | Llama 3.3 70B | ~43–54GB (Q4) | doesn't fit comfortably; 64GB is the practical threshold |
Recommended local embedding models
All have negligible footprint on 48GB.
| Model | Params | Dims | Context | Size |
|---|---|---|---|---|
| nomic-embed-text v1.5 (best default) | 137M | 768 | 8,192 | ~274MB |
| bge-m3 (dense+sparse+ColBERT) | 567M | 1024 | 8,192 | ~1.2GB |
| mxbai-embed-large | 335M | 1024 | 512 | ~670MB |
| snowflake-arctic-embed2 | 568M | 1024 | 8,192 | ~1.2GB |
| qwen3-embedding:0.6b / 4b | 0.6B / 4B | — | — | 639MB / 2.5GB (MTEB 64.33/69.45) |
Note: for nomic-embed-text set num_ctx to 8192 and prefix inputs with search_document: / search_query:.
Vector store options for a laptop
Chroma (embedded, PersistentClient), LanceDB (serverless, embedded, on-disk), FAISS (in-process index), Qdrant local mode (:memory: or embedded). All comfortably handle tens/hundreds of thousands of chunks in <1–2GB RAM.
Setup
# Runtime
brew install ollama
ollama serve # v0.19+ uses MLX on Apple Silicon
ollama pull qwen3:30b # or gpt-oss:20b / mistral-small
ollama pull nomic-embed-text
# Python libs
pip install langchain langchain-community langchain-ollama \
chromadb sentence-transformers pypdf \
mlx mlx-lm # optional: direct MLX path
Full working pipeline (LangChain + Ollama + Chroma)
from langchain_community.document_loaders import PyPDFDirectoryLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_ollama import OllamaEmbeddings, ChatOllama
from langchain_community.vectorstores import Chroma
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
# 1. LOAD
docs = PyPDFDirectoryLoader("./documents").load()
# 2. CHUNK (recursive, ~512 tokens pragmatic default, 10% overlap)
splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200)
chunks = splitter.split_documents(docs)
# 3. EMBED + 4. INDEX (local, on-disk)
embeddings = OllamaEmbeddings(model="nomic-embed-text")
vs = Chroma.from_documents(chunks, embeddings, persist_directory="./chroma_db")
# 5. RETRIEVE
retriever = vs.as_retriever(search_kwargs={"k": 5})
# 6. GENERATE (local LLM)
llm = ChatOllama(model="qwen3:30b", temperature=0)
prompt = ChatPromptTemplate.from_template(
"Answer ONLY from the context. If insufficient, say so.\n\n"
"Context:\n{context}\n\nQuestion: {question}")
def format_docs(d): return "\n\n".join(x.page_content for x in d)
chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt | llm | StrOutputParser())
print(chain.invoke("What is the refund policy?"))
Direct MLX generation (maximum speed)
from mlx_lm import load, generate
model, tokenizer = load("mlx-community/Qwen3-30B-4bit")
print(generate(model, tokenizer, prompt=my_prompt, max_tokens=512))
Performance / memory tips for Apple Silicon + 48GB
- Plan on ~34–36GB usable (macOS reserves ~25–30%). Example budget: macOS/apps ~12GB + LLM Q4 ~26GB + embeddings ~1.2GB + KV cache ~4GB + vector store ~1GB ≈ 44GB (tight); drop to gpt-oss-20b for a roomy ~35GB.
- KV cache scales with context length — long context can add tens of GB, a common gotcha that pushes a tight setup into swap. Keep context modest or use models with efficient (e.g., sliding-window) attention.
- MoE models (only a few billion active params) run fast because only active experts stay hot in the working set.
- Ollama/llama.cpp/MLX use the GPU (Metal), not the Neural Engine, which stays idle. M5-class chips add GPU neural accelerators boosting prefill/TTFT.
- Monitor Activity Monitor memory pressure and
ollama ps; overcommitting degrades silently (paged through slow paths) rather than failing loudly. - Use Matryoshka dimension truncation to shrink the vector store; batch embedding at ingest for MLX efficiency.
Cloud Implementations
Reference data flows for AWS, Azure and Google Cloud — all converge on the same managed shape.
AWS
Reference data flow. Documents land in Amazon S3 → Bedrock Knowledge Bases orchestrates ingestion (parsing via Bedrock Data Automation for complex PDFs, chunking, embedding via Titan or Cohere models) → vectors written to a vector store (OpenSearch Serverless default, Aurora PostgreSQL/pgvector, or the new S3 Vectors for cost) → at query time, API Gateway → Lambda calls Bedrock's RetrieveAndGenerate API → Bedrock queries the vector store and generates the answer with a Bedrock foundation model (Claude or Amazon Nova) with citations. Step Functions orchestrate multi-stage ingestion; SageMaker hosts custom embedding/reranker models. Kendra is the alternative managed intelligent-search retriever. AgentCore (re:Invent 2025) is the production agent runtime for RAG that grows into actions.
Knowledge Bases save weeks of custom development. Historically, OpenSearch Serverless had a hard minimum of 4 OCUs (2 indexing + 2 search) at $0.24/OCU-hour ≈ $701/month even at zero traffic. Update: AWS made OpenSearch Serverless NextGen GA on May 28, 2026 with scale-to-zero and no minimum-OCU requirement — the ~$701 floor now applies only to Classic redundant collections. For small/medium KBs also consider Aurora pgvector (from ~$30/month) or S3 Vectors (GA Dec 2, 2025) which can cut vector storage/query cost by up to 90% vs. specialized vector DBs, supporting up to 2B vectors per index (up to 20T per bucket) at ~100ms-or-less latency.
Azure
Reference data flow. Documents in Azure Blob Storage → parsed by Azure AI Document Intelligence → embedded via Azure OpenAI embedding models → indexed in Azure AI Search (vector + keyword + semantic ranking, hybrid) → at query time a Foundry agent (or Azure OpenAI "On Your Data") combines the query with hybrid search results and generates a grounded, cited answer via an Azure OpenAI model. Azure Functions handle serverless orchestration; Azure Machine Learning for custom models; Semantic Kernel or Prompt Flow (visual DAG orchestration) for chaining.
Azure AI Studio is now Microsoft/Azure AI Foundry (unified platform, 1,800+ model catalog beyond OpenAI — Phi, Llama, Mistral, Cohere). Foundry IQ is the unified knowledge/grounding layer connecting SharePoint, OneLake, Blob, and web. The legacy Assistants API retires August 26, 2026, replaced by the Foundry Agent Service on the Responses API. Azure AI Search now supports agentic retrieval (LLM-driven query planning). Pin API versions in production.
Cost/complexity: tightest fit for Microsoft shops; Azure AI Search tiers scale with storage/replicas; PTU (provisioned throughput) buys predictable capacity vs. standard pay-per-token.
Google Cloud
Reference data flow. Source docs in Cloud Storage (GCS) → parsed by Document AI → embedded via Vertex AI text embeddings (gemini-embedding-001 / text-embedding-005) → indexed in Vertex AI Vector Search (formerly Matching Engine) → Vertex AI RAG Engine (GA) orchestrates retrieve → rerank → generate with Gemini (Model Garden also offers Llama/Claude). Cloud Run / Cloud Functions host the API; Pub/Sub triggers ingestion. RAG Engine can manage vector storage for you (RagManagedDb) or plug into Vector Search, Pinecone, or Weaviate. Vertex AI Search (and Gemini Enterprise) is the fully-managed, lower-code alternative.
Cost/complexity: RAG Engine + managed DB is the fastest path; Vector Search gives managed scalable ANN. Rough cost for 1,000 single-page docs: embeddings ~$1–2, Vector Search storage ~$20/month, queries ~$0.0001 each, Gemini generation ~$1.25/1M input tokens. Choose Vertex AI Search for no-code/business users, LangChain + Vector Search for engineer flexibility.
All three converge on the same managed shape: storage → parse → embed → vector index → retrieve → generate. Pick by your existing cloud commitment. Managed services trade cost for speed-to-production; roll-your-own (LangChain/LlamaIndex + a vector DB) trades ops effort for control and portability.
Recommendations
What to actually do with all of the above, roughly in priority order.
- Start simple, then harden. Ship a baseline (recursive ~512-token chunks, a strong embedding model, HNSW vector store, top-k retrieval) with an eval harness (RAGAS + a labeled gold set) in week one. Measure retrieval and generation separately — don't tune blind.
- Adopt the 2026 baseline once past the demo: hybrid retrieval (dense + BM25 + RRF) → cross-encoder reranker (Cohere Rerank or self-hosted BGE-reranker-v2-m3) → top 5–10 chunks → grounded, citation-forced prompt. This is the single highest-leverage upgrade over naive RAG.
- Choose components by constraint, not hype: embedding model by corpus/latency/self-hosting needs; vector DB by existing platform; framework by task (LlamaIndex for pure RAG, LangChain/LangGraph for agents, Haystack for production pipelines).
- Cloud: use the managed RAG service of your incumbent cloud to reach production fast; on AWS prefer OpenSearch Serverless NextGen, Aurora pgvector, or S3 Vectors over Classic redundant collections for small/cost-sensitive KBs.
- Local/48GB Mac: Ollama v0.19+ (MLX) with a 27–35B Q4 model (or gpt-oss-20b for headroom) + nomic-embed-text + Chroma/LanceDB. Watch KV-cache growth on long context.
- Escalate patterns by need: multi-query/HyDE for short/ambiguous queries; agentic/CRAG/Self-RAG for high-stakes accuracy; GraphRAG for relational/multi-hop questions.
Low context recall → fix retrieval/chunking before touching the model. Corpus under ~200k tokens → consider skipping RAG for long-context injection. Need style/format, not facts → add a LoRA adapter, don't expand RAG. Crossing ~100M vectors → move from pgvector to Milvus/dedicated engines. Reranker latency over budget → use a smaller/faster reranker or reduce candidate pool.
Caveats
Where to apply healthy skepticism to this guide itself.
- Fast-moving landscape. Model names, MTEB rankings, cloud service names, and pricing change monthly. Verify the live MTEB leaderboard, vendor pricing, and current model tags before committing.
- Local performance numbers are largely community-reported/estimated, not lab-verified, and vary by chip (M3/M4/M5), quantization, and context length. Verify with
ollama pull/ollama psand your own benchmarks. - Benchmark scores rarely transfer to your corpus. Always run a retrieval eval on a sample of your own data.
- Ollama's MLX backend and Qwen3-Embedding support are new/preview — confirm embedding support on your Ollama version.
- Some cited sources are vendor blogs and community posts; primary sources (arXiv, official docs, vendor release notes) were preferred where possible, but treat single-source quantitative claims as directional.
Interview Questions
Grouped by depth. Click a question to reveal the model answer — write your own version in your own words before reading it.
Conceptual
coreWhat is RAG and why use it over fine-tuning?
Retrieval-Augmented Generation retrieves relevant external context at query time and grounds the LLM's answer on it. Use it over fine-tuning when knowledge changes frequently, must be cited, or is a large proprietary corpus — RAG updates by re-indexing (no retraining); fine-tuning teaches form, not facts, and goes stale.
coreWhat problems with pure LLMs does RAG solve?
Hallucination (grounding), knowledge cutoff (fresh data), domain specificity (proprietary data), and the cost/staleness of fine-tuning.
coreRAG vs. long-context — when do you pick which?
Long context for whole-corpus "global" comprehension and small corpora; RAG for fine-grained fact retrieval, large corpora, citations, and cost control (long context is ~20x more expensive at scale).
coreName the three core stages of RAG.
Retrieval, augmentation, generation (preceded by offline indexing).
coreWhat is a hallucination and how does RAG reduce it?
Confident but fabricated output; RAG constrains the model to answer from retrieved, verifiable source text and cite it.
Technical / implementation
coreHow does HNSW indexing work?
A multi-layer proximity graph (skip-list-like): sparse top layers with long links for coarse navigation, dense bottom layer with all nodes and short links for accuracy. Search enters at the top, greedily hops toward the query vector, descends layer by layer. Logarithmic complexity; tuned by M, efConstruction, efSearch.
coreFlat vs. IVF vs. HNSW?
Flat = exact brute force (perfect recall, slow); IVF = cluster-and-prune (fast, approximate, needs training); HNSW = graph ANN (fast, high recall, higher memory).
coreBi-encoder vs. cross-encoder?
Bi-encoder embeds query and doc separately (fast, first-stage retrieval); cross-encoder encodes them jointly (accurate, token-level interaction, used to rerank a shortlist because it's too slow for the full corpus).
evalContext precision vs. context recall?
Precision = of the retrieved chunks, what fraction is relevant / are relevant chunks ranked high (measures noise). Recall = of all information needed, what fraction was retrieved (measures completeness/misses). Low recall + high faithfulness = retriever missing evidence.
evalWhat is faithfulness?
Factual consistency of the generated answer with the retrieved context — the proportion of answer claims verifiable against the chunks.
coreDense vs. sparse vs. hybrid retrieval?
Dense = semantic embeddings; sparse = BM25 keyword; hybrid = both fused via RRF (the 2026 baseline).
coreWhat is RRF?
Reciprocal Rank Fusion (Cormack et al., SIGIR '09) — combines multiple ranked lists by summing 1/(k+rank) (typically k=60), robust and score-agnostic.
coreWhat is HyDE?
Generate a hypothetical answer with an LLM, embed it, and retrieve with that — bridges the question-document semantic gap; risk: hallucinated details.
practicalHow would you chunk a 500-page PDF with tables?
Layout-aware parser (Document AI / Bedrock Data Automation / Unstructured), extract tables separately to markdown/CSV, structure-aware chunking (~512–1024 tokens) with overlap, attach page/section metadata, consider contextual retrieval (per-chunk summaries).
coreWhy add a reranker?
First-stage retrieval optimizes recall (top-50/100); a cross-encoder reranker re-scores for precision, keeping the best 5–10, adding 5–15 MRR points for ~20–50ms.
practicalHow do you pick chunk size?
Empirically via eval; recursive ~512 tokens is a strong default, ~1024 near peak faithfulness in some studies; too small fragments context, too large dilutes and wastes tokens.
coreSame or different embedding model for query and docs?
Same model — query and document vectors must live in the same space.
coreWhat is Matryoshka (MRL)?
Embeddings trained so leading dimensions carry most information, letting you truncate (e.g., 3072→1024) to cut storage with small quality loss.
evalHow do you evaluate a RAG system?
Separate retrieval (context precision/recall, Recall@k, NDCG@10) from generation (faithfulness, answer relevancy) using RAGAS/DeepEval on a labeled gold set, in CI.
practicalHow do you reduce latency?
Semantic caching, smaller/faster embedding models, ANN tuning (efSearch), fewer/reranked chunks, streaming generation, smaller generation models.
practicalWhy use metadata filtering?
Pre-filter by date/department/type/permissions before/with vector search to cut noise and enforce security trimming.
coreWhat is agentic RAG?
Retrieval inside an agent loop that decides when/what/whether to retrieve, with decomposition, validation, and iterative refinement (often LangGraph).
coreSelf-RAG vs. Corrective RAG (CRAG)?
Self-RAG uses learned reflection tokens to decide retrieval/relevance/support; CRAG uses a lightweight evaluator classifying docs as correct/ambiguous/incorrect and triggers fallback (e.g., web search).
coreWhen would you use GraphRAG?
When queries need relational/multi-hop reasoning or global corpus summaries that flat vector search misses; build a knowledge graph + community summaries.
System design
scenarioDesign a RAG system for a customer-support chatbot with 1M documents.
Ingestion: loaders + layout-aware parsing → structure-aware chunking → embed (managed API or self-hosted BGE/Qwen3) → managed vector DB (Pinecone/OpenSearch/Vector Search) with metadata + access controls.
Query: query rewriting/expansion → hybrid retrieval (dense + BM25 + RRF) → cross-encoder rerank → top-5 into a grounded, citation-forced prompt → mid-size LLM.
Cross-cutting: semantic cache, PII/guardrails, confidence-threshold fallback/escalation to human, RAGAS eval in CI, observability/logging, incremental re-indexing. 1M docs is small — pgvector/Qdrant is viable; use managed for zero-ops.
scenarioHow do you handle multi-tenant data isolation?
Namespace/collection per tenant or mandatory metadata filters enforced server-side; never rely on prompt instructions for security.
scenarioHow do you keep the index fresh?
Event-driven incremental sync (e.g., S3/Blob triggers → ingestion), scheduled re-sync, and delete/upsert on document change.
scenarioHow would you debug "the answers are wrong"?
Check retrieval first (context recall) — the answer usually isn't retrieved; then chunking, then reranking, then the generation prompt. Measure each stage separately.
scenarioHow do you control cost at scale?
Semantic caching, smaller embedding dims (MRL), cheaper vector store (pgvector/S3 Vectors), two-stage retrieval (small model first), and avoid long-context stuffing.
scenarioHow do you prevent prompt injection via retrieved content?
Treat retrieved text as untrusted, sandbox tool use, instruction-defense prompts, output guardrails, and provenance/citation checks.
Glossary
Every term used in this guide, in one place.
- RAG
- Retrieval-Augmented Generation; fetching external knowledge at inference time to ground an LLM's answer.
- Embedding
- A dense numeric vector representing the meaning of text (or other data) in high-dimensional space.
- Vector database
- A store optimized for similarity search over embeddings with metadata filtering.
- Chunking
- Splitting documents into smaller retrievable units before embedding.
- Token
- A sub-word unit of text; models process and are priced per token.
- Cosine similarity
- Similarity metric = cosine of the angle between two vectors; common for embeddings.
- Dot product / Euclidean distance
- Alternative vector distance metrics.
- HNSW
- Hierarchical Navigable Small World; multi-layer graph ANN index for fast approximate search.
- IVF
- Inverted File index; clusters vectors and searches only nearest clusters.
- Flat index
- Exact brute-force nearest-neighbor search.
- ANN
- Approximate Nearest Neighbor search; trades slight accuracy for large speed gains.
- Reranking
- Reordering retrieved candidates by relevance, usually with a cross-encoder.
- Cross-encoder
- Model that jointly encodes (query, doc) for accurate but slow relevance scoring.
- Bi-encoder
- Model that encodes query and doc separately into comparable vectors (fast retrieval).
- Hybrid search
- Combining dense (semantic) and sparse (keyword) retrieval.
- BM25
- Classic sparse lexical ranking function based on term frequency and inverse document frequency.
- RRF
- Reciprocal Rank Fusion; merges multiple ranked lists score-agnostically (sum of 1/(k+rank)).
- Context window
- The max tokens a model can process at once (prompt + output).
- Hallucination
- Confident but fabricated/unsupported model output.
- Semantic search
- Retrieval by meaning via embeddings rather than exact keywords.
- Dense retrieval
- Retrieval using dense embedding vectors.
- Sparse retrieval
- Retrieval using high-dimensional sparse (keyword) vectors.
- RAGAS
- A framework of metrics for evaluating RAG pipelines.
- Faithfulness
- Factual consistency of the answer with retrieved context.
- Answer relevancy
- How well the answer addresses the query.
- Context precision
- Fraction of retrieved context that is relevant / whether relevant chunks rank high.
- Context recall
- Fraction of needed ground-truth information present in retrieved context.
- NDCG@k
- Normalized Discounted Cumulative Gain; ranking-quality metric at cutoff k.
- MRR
- Mean Reciprocal Rank; average of 1/rank of the first relevant result.
- Recall@k / Precision@k
- Presence/quality of relevant docs within top-k.
- HyDE
- Hypothetical Document Embeddings; embed an LLM-generated hypothetical answer for retrieval.
- Query expansion
- Augmenting a query with synonyms/related terms.
- Multi-query
- Generating several query reformulations and merging results.
- Query rewriting
- Reformulating the user question into a retrieval-friendly query.
- Agentic RAG
- RAG embedded in an autonomous agent loop that decides when/what to retrieve.
- GraphRAG
- RAG over a knowledge graph with community summaries for relational/global queries.
- Self-RAG
- Model emits reflection tokens governing retrieval and self-critique.
- Corrective RAG (CRAG)
- Evaluator grades retrieved docs and triggers fallback retrieval.
- Multi-hop retrieval
- Iterative retrieval chaining evidence across documents.
- Chunk overlap
- Shared tokens between adjacent chunks to preserve boundary context.
- Semantic chunking
- Splitting where embedding similarity between segments drops (topic shift).
- Recursive splitting
- Splitting on a hierarchy of separators to respect structure.
- Matryoshka (MRL)
- Embeddings truncatable to fewer dimensions with minimal quality loss.
- Vector index
- The data structure enabling fast similarity search (HNSW/IVF/flat).
- efSearch / efConstruction / M
- HNSW tuning parameters (query breadth / build breadth / connectivity).
- Top-k retrieval
- Returning the k most similar chunks.
- Metadata filtering
- Restricting search by structured attributes (date, type, permissions).
- Embedding dimension
- The length of an embedding vector (e.g., 768, 1024, 3072).
- Ingestion pipeline
- The offline load→parse→chunk→embed→index workflow.
- Grounding
- Constraining generation to retrieved evidence.
- Citation
- Reference to the source chunk supporting an answer.
- Semantic cache
- Cache keyed on query meaning to reuse answers for near-duplicate queries.
- KV cache
- Cached attention keys/values speeding generation; grows with context length.
- Quantization
- Reducing model weight precision (e.g., 4-bit) to shrink memory/speed inference.
- MLX
- Apple's native ML framework optimized for Apple Silicon unified memory.
- Ollama
- A local LLM runtime/CLI; uses MLX on Apple Silicon since v0.19.
- llama.cpp
- Portable C/C++ LLM inference engine (GGUF models).
- Unified memory (UMA)
- Apple Silicon's shared CPU/GPU memory pool.
- LoRA / QLoRA
- Parameter-efficient fine-tuning methods (low-rank adapters).
- Foundation model
- A large pretrained model (e.g., Claude, Gemini, GPT, Titan) used for generation.