Rana Maninder Singh
Lesson 6 of 8Generative AI

RAG Basics — Retrieve, Then Generate

Lesson opener

In one line: The RAG loop: index → retrieve → prompt → generate.

Why it matters: Grounding cuts hallucinations on private knowledge.

Before this lesson: Embeddings for search / Calling an LLM API

Before you start

ResourceLink
PreviousEmbeddings for search
NextEvaluation & safety
PrerequisitesEmbeddings for search, Calling an LLM API
Time~60 minutes

What you will learn

  • The RAG loop: index → retrieve → prompt → generate
  • Building a tiny FAQ retriever that runs offline
  • How retrieved chunks enter the LLM prompt
  • Chunking and refuse-when-empty helpers you can test without an API key

Pinned libraries

pip install -r docs/genai/requirements.txt

Pinned in docs/genai/requirements.txt:

openai>=1.40.0,<2
scikit-learn==1.5.2
numpy==2.1.3

Retrieval prototypes use scikit-learn==1.5.2. Generation examples need openai>=1.40.0,<2 and # requires: api-key. Any named chat model is as of September 2026, check the pricing page / model list before budgeting.


Why RAG

An LLM's training data is not your company policy. RAG (Retrieval-Augmented Generation) pulls relevant passages from your docs at question time, then asks the model to answer using only those passages.

Question → embed/search → top-k chunks → prompt(context + question) → answer

WHY Grounding cuts hallucinations on private knowledge.

WHEN Policy Q&A, internal runbooks, product FAQs.

A Bengaluru D2C support lead does not want the model inventing refund days. They want the FAQ sentence "3-5 banking days" quoted back. RAG is how you put that sentence into the prompt on purpose.


Offline retrieve step

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

chunks = [
    "Refunds for UPI failures post within 3-5 banking days.",
    "Password resets need the registered work email OTP.",
    "GST invoices can be re-issued from Billing > Tax profile.",
]


def retrieve(question: str, k: int = 2) -> list[str]:
    vec = TfidfVectorizer()
    X = vec.fit_transform(chunks)
    q = vec.transform([question])
    scores = cosine_similarity(q, X).ravel()
    idx = scores.argsort()[::-1][:k]
    return [chunks[i] for i in idx]


def build_prompt(question: str, passages: list[str]) -> str:
    ctx = "\n".join(f"- {p}" for p in passages)
    return (
        "Answer ONLY using the context. If missing, say you do not know.\n"
        f"Context:\n{ctx}\n\nQuestion: {question}\nAnswer:"
    )


hits = retrieve("When will my UPI money come back?")
print(hits)
print(build_prompt("When will my UPI money come back?", hits))
# requires: api-key
import os
import sys
from openai import OpenAI
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

chunks = [
    "Refunds for UPI failures post within 3-5 banking days.",
    "Password resets need the registered work email OTP.",
    "GST invoices can be re-issued from Billing > Tax profile.",
]


def retrieve(question: str, k: int = 2) -> list[str]:
    vec = TfidfVectorizer()
    X = vec.fit_transform(chunks)
    scores = cosine_similarity(vec.transform([question]), X).ravel()
    idx = scores.argsort()[::-1][:k]
    return [chunks[i] for i in idx]


def build_prompt(question: str, passages: list[str]) -> str:
    ctx = "\n".join(f"- {p}" for p in passages)
    return (
        "Answer ONLY using the context. If missing, say you do not know.\n"
        f"Context:\n{ctx}\n\nQuestion: {question}\nAnswer:"
    )


api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    print("Set OPENAI_API_KEY; never hard-code keys.", file=sys.stderr)
    sys.exit(1)

question = "When will my UPI money come back?"
hits = retrieve(question)
prompt = build_prompt(question, hits)
client = OpenAI(api_key=api_key)
try:
    resp = client.chat.completions.create(
        # Model as of September 2026, check the pricing page / model list
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,
    )
except Exception as exc:
    print(f"API call failed: {type(exc).__name__}: {exc}", file=sys.stderr)
    sys.exit(1)

print(resp.choices[0].message.content)

[!important] If retrieval is wrong, generation will be confidently wrong. Debug retrieval first.


Offline demo — simple chunker

Policies arrive as long paragraphs. Split on blank lines (or fixed size) before indexing so each chunk holds one intent.

# Offline demo: split a mini policy into FAQ-sized chunks
def chunk_paragraphs(text: str, max_chars: int = 120) -> list[str]:
    parts = [p.strip() for p in text.split("\n\n") if p.strip()]
    out: list[str] = []
    for part in parts:
        if len(part) <= max_chars:
            out.append(part)
            continue
        words = part.split()
        buf: list[str] = []
        for w in words:
            trial = (" ".join(buf + [w])).strip()
            if buf and len(trial) > max_chars:
                out.append(" ".join(buf))
                buf = [w]
            else:
                buf.append(w)
        if buf:
            out.append(" ".join(buf))
    return out


policy = (
    "Refunds for UPI failures post within 3-5 banking days.\n\n"
    "Damaged shipments need an unboxing video within 7 days of delivery.\n\n"
    "GST invoices can be re-issued from Billing > Tax profile."
)
chunks = chunk_paragraphs(policy)
print(len(chunks), chunks[0])
assert len(chunks) >= 3

Offline demo — refuse when retrieval is empty or weak

Generation should not run on empty context. Check scores before you spend tokens.

# Offline demo: decide whether to call the LLM after retrieval
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

chunks = [
    "Refunds for UPI failures post within 3-5 banking days.",
    "Password resets need the registered work email OTP.",
]


def best_score(question: str) -> float:
    vec = TfidfVectorizer()
    X = vec.fit_transform(chunks)
    return float(cosine_similarity(vec.transform([question]), X).ravel().max())


def should_generate(question: str, threshold: float = 0.1) -> bool:
    return best_score(question) >= threshold


print(should_generate("UPI refund timing"))
print(should_generate("Who is the CEO's favourite colour?"))
assert should_generate("UPI refund timing") is True

Design knobs

KnobEffect
Chunk sizeToo big → noise; too small → missing context
k (top passages)Higher k → more context & cost
OverlapHelps sentences split across boundaries
Instructions"Only use context" reduces invention

Each extra chunk adds input tokens. Revisit the cost sketch in genai2 when you raise k. Rates stay as of September 2026, check the pricing page.


Debugging order (retrieve first)

When a Hyderabad ops review says "the bot hallucinated," start with retrieval scores — not with a longer system prompt. Print the top-k chunks and cosine scores for the failing question. If the refund policy never appears in the top hits, no amount of "answer only from context" wording will invent the right day range from empty air. Fix chunk text, synonyms in the FAQ, or the embedding/TF-IDF representation first.

Only after the right passages rank highly should you inspect the generator. Common generator bugs: ignoring the "say you do not know" rule, merging two unrelated chunks into a new policy, or answering from parametric memory when context is thin. Low temperature and a strict prompt reduce drift; the refuse gate from the offline demo above stops the call when scores are weak.

Chunking mistakes show up as partial answers. If "3-5 banking days" sits in a 2,000-character blob next to shipping and GST rules, TF-IDF dilutes the match. Prefer one intent per chunk for FAQs. Add light overlap only when a sentence must stay attached to the previous heading. Re-index after every FAQ edit so staging and production do not silently disagree.

For portfolio demos, keep an offline path (retrieve + build_prompt + refuse) that runs without an API key. Add the live completion behind # requires: api-key once the offline path is green. That split matches how this course tests code and how you should gate spend in a pilot.


What good grounding looks like

A grounded reply cites or paraphrases the retrieved sentence without adding numbers the FAQ never stated. If the FAQ says "3-5 banking days," the answer may say "within 3-5 banking days" — not "usually by tomorrow" and not "instant for UPI Lite." When context is missing, the honest answer is refuse or escalate. Agents prefer a clean handoff over a confident wrong draft they must rewrite under time pressure.

Log question, top scores, chunk ids, and whether you refused. Those fields feed the golden set in genai7 and the capstone metrics in genai8. Without logs, "it worked in the demo" cannot be reproduced after a FAQ edit.

Remember the Path → Course → Lesson framing when you explain RAG to stakeholders: this is one Course inside the GenAI Path, and each Lesson builds a piece you can demo. Keep product copy on those three labels only.

Pinned versions for this course live in docs/genai/requirements.txt: openai>=1.40.0,<2, scikit-learn==1.5.2, numpy==2.1.3. Offline retrieve demos need scikit-learn; generation blocks stay behind # requires: api-key until you are ready to spend.

WHY Retrieve-then-generate is a product architecture, not a prompt trick.

WHEN Any FAQ, runbook, or policy bot where inventing numbers creates chargebacks or compliance risk.

Failure modes — RAG in Indian support

Failure modeSymptomFix
Wrong top-kFluent answer cites IT policy for a UPI questionDebug scores before the generator
Mega-chunksDiluted TF-IDF / embedding matchOne intent per chunk
No refuse gateModel invents CEO triviashould_generate / min score
Stale indexNew GST rule never appearsRe-index on every FAQ edit
Raising k blindlyToken bill up, answer muddierCost sketch + eval, not vibes

Festival-week queues in Bengaluru and Pune amplify every failure: agents paste long threads, customers mix Hindi and English, and ops wants "the bot just answers." Keep the offline retrieve + refuse path green before you attach a paid completion. Log question, scores, chunk ids, and refuse decisions so genai7 can build a golden set from real misses instead of from imagined ones.

Offline demo — count tokens in a grounded prompt

Before you raise k, measure how many approximate tokens the context section adds. Same character÷4 heuristic as genai2.

# Offline demo: approximate token cost of a RAG prompt at different k
def approx_tokens(text: str) -> int:
    return max(1, len(text) // 4) if text else 0


chunks = [
    "Refunds for UPI failures post within 3-5 banking days.",
    "Password resets need the registered work email OTP.",
    "GST invoices can be re-issued from Billing > Tax profile.",
    "Damaged shipments need an unboxing video within 7 days.",
]


def prompt_tokens(question: str, k: int) -> int:
    ctx = "\n".join(f"- {c}" for c in chunks[:k])
    prompt = (
        "Answer ONLY using the context. If missing, say you do not know.\n"
        f"Context:\n{ctx}\n\nQuestion: {question}\nAnswer:"
    )
    return approx_tokens(prompt)


q = "When will my UPI money come back?"
for k in (1, 2, 4):
    print(k, prompt_tokens(q, k))
assert prompt_tokens(q, 4) > prompt_tokens(q, 1)

Offline demo — overlap helper for split sentences

When a policy number sits on a chunk boundary, keep a short character overlap so retrieval can still see it.

# Offline demo: sliding windows with character overlap for long FAQ text
def chunk_with_overlap(text: str, size: int = 40, overlap: int = 10) -> list[str]:
    if overlap >= size:
        raise ValueError("overlap must be < size")
    out: list[str] = []
    i = 0
    while i < len(text):
        out.append(text[i : i + size])
        if i + size >= len(text):
            break
        i += size - overlap
    return out


policy = "Refunds for UPI failures post within 3-5 banking days. Then contact billing."
parts = chunk_with_overlap(policy, size=35, overlap=8)
print(len(parts), parts[0])
assert any("3-5" in p for p in parts)
assert len(parts) >= 2

Rates and model ids for the generate step stay labelled as of September 2026, check the pricing page. Do not bake FX into the retrieve gate — cost belongs in capacity planning, not in should_generate.


Verified against openai 1.40.0,<2, scikit-learn 1.5.2, numpy 2.1.3 documentation, September 2026.

Test yourself

  1. Expand the acronym RAG.
  2. What are the four stages in the loop diagram?
  3. Why not put the entire policy PDF in every prompt?
  4. What does retrieve return?
  5. What should the model say when context is missing?
  6. True or false: better prompts fix bad retrieval.
  7. Name two design knobs from the table.
  8. Why set temperature=0 for FAQ answers?
  9. Which lesson covered embeddings?
  10. True or false: RAG replaces the need for evaluation.