Rana Maninder Singh
Lesson 1 of 8Generative AI

What Generative AI Is (And When Not to Use It)

Lesson opener

In one line: Generative AI predicts the next words (or pixels) to draft text, code, or images - unlike classifiers that only pick from a fixed label set.

Why it matters: Teams waste money when they use an LLM for a simple score, or a classifier when they need open-ended drafts grounded in docs.

Before this lesson: Deep Learning Capstone / What AI actually is

Before you start


What you will learn

  • How generative AI differs from classical ML and deep learning classifiers
  • When an LLM is the right tool — and when a simpler model wins
  • How to encode that decision as data you can review with stakeholders
  • The builder stack this course covers: API calls → embeddings → RAG → evaluation

Pinned libraries for this course

Install the course pins once and reuse them across lessons:

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

This lesson itself uses only the Python standard library for offline demos. Later lessons use scikit-learn and numpy for retrieval prototypes, and the openai SDK only in blocks tagged # requires: api-key. Model names and list prices change — treat any named model or dollar rate in this course as as of September 2026, check the pricing page before you budget.


Three tools, three jobs

ApproachWhat it doesTypical output
Classical ML (ml1–ml12)Maps tabular features → label/scoreChurn probability, segment
Deep learning (dl1–dl8)Learns from images/text tensorsClass label, embedding
Generative AIPredicts the next tokens of text (or image/code)Paragraphs, JSON, SQL drafts

WHY Generative models create new text; classifiers pick from a fixed label set.

WHEN You need drafting, summarising, Q&A over documents, or structured extraction — not a churn score.

A classifier answers "which bucket?" An LLM answers "what words come next?" That sounds abstract until you put it next to a Hyderabad SaaS backlog. Predicting who churns is a bucket problem. Drafting a polite refund email from a policy PDF is a next-token problem. Mixing them up wastes money and trust.


The business decision

Stakeholder: Ops lead at a Hyderabad SaaS company.

RequestPreferWhy
"Predict who churns next month"Classical MLFixed labels + metrics you can audit
"Classify support ticket screenshots"Deep learning / CNNImage input
"Draft a reply from our policy PDF"GenAI + RAGOpen-ended text grounded in docs
"Replace our Excel forecast"Classical ML / statsNumbers + explainability

[!important] "Use AI" is not a requirement. Pick the simplest tool that meets the metric.

Demo 1 — Decision table as data

Stakeholders argue in meetings. Engineers argue in tables. Encode the preference rule as data you can print, unit-test, and extend when a new request type appears.

# Offline demo: encode GenAI vs classical-ML decisions as reviewable data
DECISIONS = [
    {
        "request": "Predict who churns next month",
        "prefer": "classical_ml",
        "why": "Fixed labels and audit metrics",
    },
    {
        "request": "Classify support ticket screenshots",
        "prefer": "deep_learning",
        "why": "Image input needs a vision model or CNN",
    },
    {
        "request": "Draft a reply from our policy PDF",
        "prefer": "genai_rag",
        "why": "Open-ended text grounded in company docs",
    },
    {
        "request": "Replace our Excel revenue forecast",
        "prefer": "classical_ml",
        "why": "Numbers plus explainability beat fluent prose",
    },
]


def prefer_for(request: str) -> str:
    for row in DECISIONS:
        if row["request"] == request:
            return row["prefer"]
    raise KeyError(f"unknown request: {request}")


for row in DECISIONS:
    print(f"{row['prefer']:15} | {row['request']}")

assert prefer_for("Predict who churns next month") == "classical_ml"
print("decision table OK:", len(DECISIONS), "rows")

Walk this table with the ops lead before anyone buys API credits. If a row feels wrong, change the data — not a prompt.


Heuristics that look like GenAI (and fail)

Teams sometimes ship a "smart" ticket router that is really string length or keyword counting. That is fine for a baseline. It is not GenAI. Compare a length heuristic to a tiny classical classifier so you feel the difference before you reach for an LLM.

Demo 2 — Length heuristic vs a tiny classifier

# Offline demo: length heuristic vs a tiny sklearn classifier on toy tickets
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

tickets = [
    "UPI deducted but order unpaid in Bengaluru",
    "Wi-Fi password reset for Pune office",
    "GSTIN update on tax invoice",
    "Refund for cancelled grocery order delayed",
    "VPN not connecting after laptop wipe",
    "Invoice PDF missing CGST line",
]
# 1 = payment/refund style, 0 = IT/admin style (toy labels)
y = [1, 0, 0, 1, 0, 0]


def length_heuristic(text: str) -> int:
    # Naive: long tickets "feel" like payment disputes — often wrong
    return 1 if len(text) >= 36 else 0


clf = Pipeline(
    [
        ("vec", CountVectorizer()),
        ("lr", LogisticRegression(max_iter=500)),
    ]
)
clf.fit(tickets, y)

probe = "Amount gone via UPI, booking still pending"
print("length heuristic:", length_heuristic(probe))
print("classifier label:", int(clf.predict([probe])[0]))
print("classes learned:", sorted(set(y)))

The length heuristic is free and often wrong. The classifier learns word patterns from labelled tickets — still classical ML, still cheaper than an LLM for a fixed label set. Reach for GenAI when the output must be new prose or flexible JSON, not when you only need payment vs it.


Cost of picking the wrong tool

Wrong tool cost is not only API invoices. It is also rework, compliance risk, and agent time. Sketch it in numbers so the budget conversation stays concrete. Rates and FX move — pass them in; never bake a silent default.

Demo 3 — Cost-of-wrong-tool sketch

# Offline demo: sketch monthly cost of using GenAI where classical ML fits
def wrong_tool_monthly_inr(
    tickets_per_day: int,
    genai_cost_per_ticket_inr: float,
    classical_cost_per_ticket_inr: float,
    rework_hours_per_week: float,
    engineer_hourly_inr: float,
) -> dict:
    """Compare GenAI-on-everything vs classical ML for a fixed-label task."""
    days = 30
    weeks = 4
    genai = tickets_per_day * days * genai_cost_per_ticket_inr
    classical = tickets_per_day * days * classical_cost_per_ticket_inr
    rework = rework_hours_per_week * weeks * engineer_hourly_inr
    return {
        "genai_path_inr": round(genai + rework, 2),
        "classical_path_inr": round(classical, 2),
        "extra_inr_if_genai": round((genai + rework) - classical, 2),
    }


# Illustrative INR unit costs for planning only — not provider list prices
sketch = wrong_tool_monthly_inr(
    tickets_per_day=400,
    genai_cost_per_ticket_inr=0.8,
    classical_cost_per_ticket_inr=0.02,
    rework_hours_per_week=6,
    engineer_hourly_inr=1500,
)
print(sketch)
assert sketch["extra_inr_if_genai"] > 0

Use this sketch when someone proposes "just put GPT on churn." Classical ML still wins on fixed labels. Save GenAI budget for drafting and grounded Q&A — the jobs this course builds next.


Failure modes when GenAI is the wrong default

WHY A polished demo is not a production requirement.

WHEN Before you buy credits or rewrite a working classifier.

Teams in Bengaluru and Pune sometimes route every ticket through an LLM because a chat demo looked impressive. Three failure modes show up fast: (1) fixed-label routing that logistic regression already solves cheaper and with clearer metrics, (2) inventing refund or GST timelines that contradict the company FAQ, (3) burning API budget on tasks where a template email plus a lookup table would do. Write the failure mode next to each row in the decision table so ops can veto the GenAI path before credits burn. If leadership still wants "AI on everything," keep classical ML on the labelled path and reserve GenAI for drafting and grounded Q&A — the split this course builds next.

What this course builds

  1. API calls — send a prompt, get a completion (genai3)
  2. Structured outputs — JSON the app can parse (genai4)
  3. Embeddings — vectors for semantic search (genai5)
  4. RAG — retrieve your docs, then generate (genai6)
  5. Evaluation & safety — catch hallucinations before production (genai7)
  6. Capstone — a mini RAG over a support FAQ (genai8)

This is the builder track. The AI Prompting course teaches chat skills without code; here you wire models into scripts. You will measure tokens and cost (genai2), call an OpenAI-compatible API with secrets in the environment (genai3), validate JSON (genai4), rank passages (genai5), ground answers in retrieved FAQ text (genai6), and refuse when confidence is low (genai7).

Official provider docs (OpenAI models overview, Anthropic Claude docs) describe what each family of models can do. They do not tell you which tool fits your Hyderabad backlog — that decision stays with you and the tables above.

Demo 4 — Request router (string rules, not an LLM)

Before you buy GenAI for ticket routing, prove a keyword router is too weak — or good enough. This offline counter scores a tiny rule set so you can compare it later to a classical classifier or an LLM.

# Offline demo: keyword router baseline for payment vs IT tickets
RULES = {
    "payments": ("upi", "refund", "invoice", "gst", "debit"),
    "it": ("vpn", "wifi", "wi-fi", "password", "laptop"),
}


def route(ticket: str) -> str:
    lower = ticket.lower()
    scores = {
        label: sum(1 for kw in kws if kw in lower) for label, kws in RULES.items()
    }
    best = max(scores, key=scores.get)
    return best if scores[best] > 0 else "unknown"


assert route("UPI deducted but order unpaid") == "payments"
assert route("VPN not connecting after wipe") == "it"
assert route("Team lunch next Friday") == "unknown"
print({t: route(t) for t in ("UPI refund", "Wi-Fi reset", "hello")})

Demo 5 — Stakeholder veto checklist as data

Ops leads veto GenAI paths for compliance reasons. Encode the veto checklist so a PR can assert every new use-case was reviewed.

# Offline demo: encode stakeholder veto checks before spending API credits
CHECKS = [
    ("fixed_label_task", False),  # True would mean classical ML fits
    ("needs_new_prose", True),
    ("pii_in_prompt_ok", False),
    ("budget_approved_inr", True),
]


def may_use_genai(checks: list[tuple[str, bool]]) -> bool:
    by_name = dict(checks)
    if by_name["fixed_label_task"]:
        return False
    if not by_name["needs_new_prose"]:
        return False
    if not by_name["budget_approved_inr"]:
        return False
    if by_name["pii_in_prompt_ok"]:
        return False  # refuse until redaction exists
    return True


assert may_use_genai(CHECKS) is True
bad = [("fixed_label_task", True), ("needs_new_prose", True), ("pii_in_prompt_ok", False), ("budget_approved_inr", True)]
assert may_use_genai(bad) is False
print("genai allowed:", may_use_genai(CHECKS))

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

Test yourself

  1. Name one task better suited to classical ML than GenAI.
  2. Name one task better suited to GenAI than a classifier.
  3. What does an LLM generate, token by token?
  4. How does this course differ from AI Prompting?
  5. What does RAG stand for (preview)?
  6. True or false: leadership saying "use AI" means you must use an LLM.
  7. Which prior course covers learned word vectors?
  8. What does Demo 1 store that a slide deck usually does not?
  9. Give one Hyderabad/India workplace example from this lesson.
  10. True or false: GenAI always beats classical ML on tabular churn.