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
| Resource | Link |
|---|---|
| Previous | Evaluation & safety |
| Next | Portfolio |
| Prerequisites | RAG 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.txtPinned in docs/genai/requirements.txt:
openai>=1.40.0,<2
scikit-learn==1.5.2
numpy==2.1.3The 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:
- Answers must use FAQ wording — no invented policy
- Refuse when retrieval confidence is low
- Golden-set pass rate ≥ 80% on 10 hand-labelled questions before pilot
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
- Collect FAQ — 15–30 real Q&A pairs (payments, shipping, returns)
- Chunk — one intent per chunk (genai5–genai6)
- Retrieve — TF-IDF prototype, then swap to API embeddings if needed
- Generate — grounded prompt + low temperature (genai3–genai6)
- Validate — structured fields if you also tag intent (genai4)
- 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.8Offline 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"] > 0Portfolio story (what to say)
- Problem and capacity constraint (agents drown in repeat questions)
- Why RAG instead of fine-tuning
- Demo: good hit, refuse on unknown
- Metric: golden-set pass rate + escalation rate
- 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 mode | Symptom | Fix |
|---|---|---|
| Fine-tune on last month's FAQ | Stale after one policy edit | Keep RAG over editable text |
| No shadow week | Agents distrust drafts | Log would-be answers first |
| Threshold too low | Weak hits become confident drafts | Raise gate; re-run golden set |
| Secrets in the notebook | Key leak in portfolio zip | Env 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
- Executive one-pager — problem (agent capacity), why RAG not fine-tune, golden-set pass-rate bar, escalation rate, ask for shadow-mode approval.
- Offline proof — retrieve → answer/refuse → golden-set gate + threshold sweep (runnable fences in this lesson).
- Pilot plan — Week 0/1/2 narrative from "How to run the pilot without drama."
- Risk register and 90-day implementation roadmap.
- Scoring rubric + self-review checklist completed.
Acceptance criteria
- [ ] Golden-set pass-rate bar stated and offline assert passes (course brief bar, typically ≥80% on labelled set).
- [ ] Refuse/escalate path fires on unknown questions (no invented policy text).
- [ ] Portfolio story covers problem, RAG choice, demo, metrics, next hardening (mlops).
- [ ] Secrets never in notebook;
# requires: api-keyonly when live. - [ ] Risk register ≥ 6 rows; 90-day roadmap with owners.
- [ ] Rubric ≥ 70; self-review checklist complete.
Scoring rubric
Score 0–4; weighted /100; pass ≥ 70; no zeros.
| Criterion | Weight | 4 | 2 | 0 |
|---|---|---|---|---|
| Grounding & refuse behaviour | 25% | Retrieve + refuse proven | Answer-only | Hallucinated policy |
| Evaluation (golden set + escalate metrics) | 25% | Pass bar + threshold sweep | One metric only | No eval |
| Pilot realism (shadow → assist) | 20% | Week 0–2 plan | Vague next steps | Big-bang cutover |
| Safety & secrets | 15% | Env keys; PII redaction note | Partial | Keys in repo |
| Exec pack, risks, roadmap, self-review | 15% | Complete | Partial | Missing |
Risk register (template — figures illustrative)
| ID | Risk | L | I | Mitigation | Owner |
|---|---|---|---|---|---|
| R1 | Hallucinated refund policy | H | H | Answer only from FAQ; refuse otherwise | Pilot lead |
| R2 | Stale FAQ after policy edit | H | M | RAG over editable text; refresh job | Content owner |
| R3 | Threshold too low → weak drafts | M | H | Threshold sweep; golden-set gate | Engineer |
| R4 | Agent distrust without shadow week | H | M | Shadow logging before assisted draft | Support lead |
| R5 | API key leaked in portfolio | M | H | Env var only; scrub zips | Engineer |
| R6 | PII in prompt logs | M | H | Redaction (genai7) | Engineer + DPO |
Implementation roadmap (90 days)
| Window | Outcome | Activities | Owner |
|---|---|---|---|
| Days 1–30 | Offline gate green | FAQ freeze; retrieve/refuse; golden set ≥ bar | Engineer |
| Days 31–60 | Shadow mode | Log would-be answers; tune threshold; PII controls | Support + Eng |
| Days 61–90 | Assisted drafts | Edit-distance metric; optional live LLM behind env key; MLOps handoff | Pilot sponsor |
Self-review checklist
| # | Check | Yes/No | Note |
|---|---|---|---|
| 1 | Exec one-pager has recommendation + metrics | ||
| 2 | Offline demos run without API key | ||
| 3 | Refuse path demonstrated | ||
| 4 | Golden-set bar met | ||
| 5 | Pilot weeks 0–2 documented | ||
| 6 | No secrets in submission | ||
| 7 | Risk register ≥ 6 rows | ||
| 8 | 90-day roadmap present | ||
| 9 | Rubric self-scores filled | ||
| 10 | Pricing/model claims dated / "check provider page" |
Test yourself
- What pass-rate bar does the brief set?
- When must the bot refuse?
- Name the six checklist steps.
- Why prefer RAG over fine-tuning for a changing FAQ?
- What does the sample
answerreturn for an unknown question? - Which lesson covers golden sets?
- True or false: inventing policy text is acceptable if it "sounds right".
- What goes in the portfolio demo?
- Which production course helps after the prototype?
- True or false: the offline
answerfunction already calls an LLM.