Rana Maninder Singh
Lesson 8 of 8Generative AI

Capstone — Mini RAG over a Support FAQ

Lesson opener

In one line: End-to-end FAQ RAG: chunk → retrieve → prompt → answer → score.

Why it matters: Capstone proof is offline retrieve → refuse → golden-set pass rate, not a single lucky chat reply.

Before this lesson: RAG basics / Evaluation & safety

Before you start

ResourceLink
PreviousEvaluation & safety
NextPortfolio
PrerequisitesRAG basics, Evaluation & safety, all genai lessons
Time~90 minutes

What you will learn

  • End-to-end FAQ RAG: chunk → retrieve → prompt → answer → score
  • A portfolio-ready demo you can walk through in an Indian product review
  • Offline retrieve/refuse/score scripts that prove the loop before any paid API call

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

The offline capstone path uses scikit-learn==1.5.2 (and numpy==2.1.3 when you store dense vectors). Swap in openai>=1.40.0,<2 only after retrieve → refuse works locally. Model and price choices remain as of September 2026, check the pricing page.


Business brief

Stakeholder: Head of support, Bengaluru D2C brand.

Question: Can we draft first replies from our FAQ so agents only edit edge cases?

Constraints:

Capacity is the pain: agents drown in repeat UPI, shipping, and GST questions. Fine-tuning a model on last month's FAQ goes stale when policy changes next week. RAG keeps the source of truth in editable text files you already own.


End-to-end checklist

  1. Collect FAQ — 15–30 real Q&A pairs (payments, shipping, returns)
  2. Chunk — one intent per chunk (genai5–genai6)
  3. Retrieve — TF-IDF prototype, then swap to API embeddings if needed
  4. Generate — grounded prompt + low temperature (genai3–genai6)
  5. Validate — structured fields if you also tag intent (genai4)
  6. Evaluate — golden set + refuse rule (genai7)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

FAQ = [
    "UPI failure refunds post within 3-5 banking days.",
    "Replace damaged items within 7 days with unboxing video.",
    "GST invoices: Billing > Tax profile > Re-issue.",
]


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


def answer(question: str, threshold: float = 0.12) -> str:
    hits = retrieve(question)
    if not hits or hits[0][1] < threshold:
        return "I do not know from the FAQ - escalating to an agent."
    ctx = "\n".join(f"- {t}" for t, _ in hits)
    # Swap this return for an LLM call in your project (see genai3 / genai6).
    return f"Based on FAQ:\n{ctx}"


print(answer("When does UPI money come back?"))
print(answer("What is the CEO's favourite colour?"))

[!important] The capstone is complete when retrieve → refuse/answer works offline, and your golden-set script prints a pass rate.


Offline demo — golden-set gate for the pilot

Prove the 80% bar with the same FAQ and answer helper. Fail loudly if the pass rate slips.

# Offline demo: enforce >=80% golden-set pass rate before pilot
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

FAQ = [
    "UPI failure refunds post within 3-5 banking days.",
    "Replace damaged items within 7 days with unboxing video.",
    "GST invoices: Billing > Tax profile > Re-issue.",
]


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


def answer(question: str, threshold: float = 0.12) -> str:
    hits = retrieve(question)
    if not hits or hits[0][1] < threshold:
        return "I do not know from the FAQ - escalating to an agent."
    return "Based on FAQ:\n" + "\n".join(f"- {t}" for t, _ in hits)


GOLDEN = [
    {"q": "When does UPI money come back?", "must_include": ["3-5"], "must_not": ["favourite"]},
    {"q": "Damaged box on delivery", "must_include": ["7 days"], "must_not": ["instant"]},
    {"q": "CEO favourite colour?", "must_include": ["escalating"], "must_not": ["blue"]},
]


def passes(case: dict) -> bool:
    text = answer(case["q"]).lower()
    return all(s.lower() in text for s in case["must_include"]) and all(
        s.lower() not in text for s in case["must_not"]
    )


rate = sum(passes(c) for c in GOLDEN) / len(GOLDEN)
print("pass_rate", rate)
assert rate >= 0.8

Offline demo — escalation metrics for the review meeting

Product reviews ask two numbers: how often we help, and how often we escalate. Record both.

# Offline demo: summarise help vs escalate rates on a small question batch
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

FAQ = [
    "UPI failure refunds post within 3-5 banking days.",
    "Replace damaged items within 7 days with unboxing video.",
]


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


def classify(question: str, threshold: float = 0.12) -> str:
    hits = retrieve(question)
    if not hits or hits[0][1] < threshold:
        return "escalate"
    return "answer"


batch = [
    "UPI refund timing",
    "broken item video needed?",
    "Who designs the logo?",
]
labels = [classify(q) for q in batch]
n = len(labels)
summary = {
    "answered": labels.count("answer") / n,
    "escalated": labels.count("escalate") / n,
}
print(summary)
assert summary["escalated"] > 0

Portfolio story (what to say)

  1. Problem and capacity constraint (agents drown in repeat questions)
  2. Why RAG instead of fine-tuning
  3. Demo: good hit, refuse on unknown
  4. Metric: golden-set pass rate + escalation rate
  5. Next: API embeddings + logging (mlops patterns for production)

When you add a live LLM call, keep secrets in the environment, validate structured side-tags if you add them (genai4), and re-run the golden set. Do not invent FX or token prices in the slide — cite the provider page as of September 2026, check the pricing page.


How to run the pilot without drama

Week 0 — freeze a FAQ export (payments, shipping, returns, GST). Chunk one intent per block. Build the offline retrieve → answer/escalate path and the golden-set script until pass rate clears 80% on your labelled ten (then grow toward 20–50). Do not buy API volume yet.

Week 1 — shadow mode. For each live ticket, log what the bot would have answered or escalated, while agents keep owning sends. Compare disagreements. Tune the similarity threshold if you escalate too often or answer on weak hits. Redact PII in logs (genai7).

Week 2 — assisted draft. Agents see the grounded draft and edit. Record edit distance and escalation rate. Only then consider an OpenAI-compatible completion behind # requires: api-key, same prompt shape as genai6, temperature 0, secrets in the environment.

What "done" means for this course: the three offline demos in this lesson run clean; the refuse path fires on unknowns; the golden-set assert passes; you can narrate why RAG beat fine-tuning for a changing FAQ. Production hardening (auth, queues, dashboards) continues in MLOps. Keep Path → Course → Lesson labels in any UI you sketch.

Stakeholder language that works: "We retrieve FAQ text first, refuse when unsure, and measure pass rate before agents trust drafts." Avoid promising zero hallucinations. Promise measurable grounding and a clear escalate path for Bengaluru peak hours.

Install pins from docs/genai/requirements.txt before demos: openai>=1.40.0,<2, scikit-learn==1.5.2, numpy==2.1.3. Offline blocks need sklearn; live generation needs the OpenAI-compatible client and an env var key. Re-run python scripts/test_course_code.py docs/genai after you edit any code fence so the portfolio demo stays honest.

WHY Capstone proof is offline retrieve → refuse → golden-set pass rate, not a single lucky chat reply.

WHEN Before you ask a Bengaluru support head to trust drafts in peak hours.

Failure modes — capstone demos that impress and then break Monday

Failure modeSymptomFix
Fine-tune on last month's FAQStale after one policy editKeep RAG over editable text
No shadow weekAgents distrust draftsLog would-be answers first
Threshold too lowWeak hits become confident draftsRaise gate; re-run golden set
Secrets in the notebookKey leak in portfolio zipEnv var + # requires: api-key

Offline demo — build a grounded prompt string (no API)

Show the exact prompt you would send once retrieve succeeds. Keep this offline so CI can assert the context section is present.

# Offline demo: build the grounded user prompt from retrieved FAQ hits
FAQ = [
    "UPI failure refunds post within 3-5 banking days.",
    "Replace damaged items within 7 days with unboxing video.",
]


def build_grounded_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:"
    )


prompt = build_grounded_prompt("UPI refund timing?", FAQ[:1])
assert "3-5 banking days" in prompt
assert "Answer ONLY using the context" in prompt
print(prompt.splitlines()[0])

Offline demo — threshold sweep for escalation rate

Sweep similarity thresholds so the review meeting sees the help vs escalate trade-off as a table, not a guess.

# Offline demo: sweep refuse thresholds and report escalate rates
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

FAQ = [
    "UPI failure refunds post within 3-5 banking days.",
    "Replace damaged items within 7 days with unboxing video.",
]
QUESTIONS = [
    "UPI refund timing",
    "broken item needs video?",
    "Who designs the logo?",
]


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


def escalate_rate(threshold: float) -> float:
    scores = [top_score(q) for q in QUESTIONS]
    return sum(s < threshold for s in scores) / len(scores)


for t in (0.05, 0.12, 0.35):
    print(t, escalate_rate(t))
assert escalate_rate(0.35) >= escalate_rate(0.05)

Stakeholder language that still works: retrieve first, refuse when unsure, measure pass rate before agents trust drafts. Promise measurable grounding — not zero hallucinations. Label any model or price mention as of September 2026, check the pricing page.


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

Executive deliverables

  1. Executive one-pager — problem (agent capacity), why RAG not fine-tune, golden-set pass-rate bar, escalation rate, ask for shadow-mode approval.
  2. Offline proof — retrieve → answer/refuse → golden-set gate + threshold sweep (runnable fences in this lesson).
  3. Pilot plan — Week 0/1/2 narrative from "How to run the pilot without drama."
  4. Risk register and 90-day implementation roadmap.
  5. Scoring rubric + self-review checklist completed.

Acceptance criteria

Scoring rubric

Score 0–4; weighted /100; pass ≥ 70; no zeros.

CriterionWeight420
Grounding & refuse behaviour25%Retrieve + refuse provenAnswer-onlyHallucinated policy
Evaluation (golden set + escalate metrics)25%Pass bar + threshold sweepOne metric onlyNo eval
Pilot realism (shadow → assist)20%Week 0–2 planVague next stepsBig-bang cutover
Safety & secrets15%Env keys; PII redaction notePartialKeys in repo
Exec pack, risks, roadmap, self-review15%CompletePartialMissing

Risk register (template — figures illustrative)

IDRiskLIMitigationOwner
R1Hallucinated refund policyHHAnswer only from FAQ; refuse otherwisePilot lead
R2Stale FAQ after policy editHMRAG over editable text; refresh jobContent owner
R3Threshold too low → weak draftsMHThreshold sweep; golden-set gateEngineer
R4Agent distrust without shadow weekHMShadow logging before assisted draftSupport lead
R5API key leaked in portfolioMHEnv var only; scrub zipsEngineer
R6PII in prompt logsMHRedaction (genai7)Engineer + DPO

Implementation roadmap (90 days)

WindowOutcomeActivitiesOwner
Days 1–30Offline gate greenFAQ freeze; retrieve/refuse; golden set ≥ barEngineer
Days 31–60Shadow modeLog would-be answers; tune threshold; PII controlsSupport + Eng
Days 61–90Assisted draftsEdit-distance metric; optional live LLM behind env key; MLOps handoffPilot sponsor

Self-review checklist

#CheckYes/NoNote
1Exec one-pager has recommendation + metrics
2Offline demos run without API key
3Refuse path demonstrated
4Golden-set bar met
5Pilot weeks 0–2 documented
6No secrets in submission
7Risk register ≥ 6 rows
890-day roadmap present
9Rubric self-scores filled
10Pricing/model claims dated / "check provider page"

Test yourself

  1. What pass-rate bar does the brief set?
  2. When must the bot refuse?
  3. Name the six checklist steps.
  4. Why prefer RAG over fine-tuning for a changing FAQ?
  5. What does the sample answer return for an unknown question?
  6. Which lesson covers golden sets?
  7. True or false: inventing policy text is acceptable if it "sounds right".
  8. What goes in the portfolio demo?
  9. Which production course helps after the prototype?
  10. True or false: the offline answer function already calls an LLM.

What's next

Ship the demo to your portfolio, or revisit MLOps when you are ready to serve and monitor it.