RAG
An architecture that retrieves relevant external documents at query time and injects them into an LLM prompt for grounded, up-to-date answers
Table of Contents
Interactive Playground
Tap or drag to interact with the demoWhat is RAG?
An architecture that retrieves relevant external documents at query time and injects them into an LLM prompt for grounded, up-to-date answers. It is a core concept in Retrieval & RAG within AI / ML.
Core Principles
RAG (Retrieval-Augmented Generation) addresses two fundamental limits of LLMs: stale training cutoffs and lack of access to private domain data, both of which trigger hallucinations.
Instead of repeatedly fine-tuning model weights, RAG splits external documents into indexed chunks offline. At query time, the system retrieves the most relevant passages, augments the LLM prompt with those grounded facts, and generates a verified answer—complete with verifiable source citations—without retraining the model.
Practical Takeaways
- Combine Hybrid Search with Reranking: Pure vector similarity struggles with exact product SKUs, error codes, and proper nouns. Pair dense vector search with lexical BM25, then pass the top ~20 candidates through a Cross-Encoder reranker to send only the sharpest 3–5 chunks to the LLM.
- Treat chunking as a first-class problem: Blind fixed-character splits sever tables and paragraphs. Chunk along semantic boundaries (headings, sections) and prepend document titles or breadcrumbs to every chunk.
- Enforce grounding and citations: Instruct the model to cite retrieved passages explicitly and abstain when evidence is absent, plus enforce document-level access control (ACL) before retrieval.
Notable Examples
- Perplexity AI: Pairs real-time web retrieval with LLM synthesis so every claim links directly to live source URLs.
- Enterprise Knowledge Assistants: Index internal wikis, Slack threads, and docs behind user permissions so teams can query institutional memory safely.
- Customer Support Copilots: Pull live policy docs and ticket history to draft accurate, policy-compliant responses.
Practical Code Snippet
Copy and drop straight into your projectexport async function answerWithRAG(question: string) { // 1. Embed query & retrieve top-K chunks from vector DB const queryVector = await embed(question); const docs = await vectorDB.search(queryVector, { topK: 4 }); // 2. Inject retrieved context into the prompt const context = docs.map((d) => `[${d.source}] ${d.text}`).join("\n\n"); return llm.generate({ system: "Answer strictly using the provided context and cite sources.", prompt: `Context:\n${context}\n\nQuestion: ${question}`, });}