Rana Maninder Singh
Lesson 9 of 9Generative AI

GenAI / LLM Desk Reference

Lesson opener

In one line: This lesson covers genai / llm desk reference in plain English, with steps you can reuse at work.

Why it matters: This skill shows up in day-to-day analysis and delivery work.

Before this lesson: Nothing, this is a starting point.

Before you start

ResourceLink
CourseGenerative AI
Tokens lessonTokens, context & cost
EmbeddingsEmbeddings for search

Printable desk card for tokens, cost, embeddings, and RAG knobs — not a path course. Pair with the GenAI lessons when you need a formula or snippet without re-reading the full narrative.


Pinned libraries

pip install -r docs/genai/requirements.txt

Pinned in docs/genai/requirements.txt (as of course pin set):

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

Offline demos below use the standard library plus numpy==2.1.3 and scikit-learn==1.5.2. Any live API example needs openai>=1.40.0,<2 and a key from the environment — never a hard-coded secret. Prices and model names are planning figures: re-check the provider pricing page before budgeting.


Quick map — when to use what

NeedPreferAvoid
Tabular churn / credit scoreClassical ML (ML Fundamentals)Stuffing rows into an LLM
Free-text FAQ / policy Q&ARAG + embeddingsFine-tuning for every FAQ edit
Label tickets into fixed JSONStructured outputs + schema checkParsing free prose with string equality
Monthly INR cost sketchToken approx + FX parameterGuessing from "feels cheap"

Indian workplace example: a Bengaluru support bot that answers UPI / refund FAQs should retrieve FAQ chunks, not paste the whole policy PDF into every call.


Tokens — planning unit

English rule of thumb: 1 token ≈ 4 characters ≈ 0.75 words. Hindi–English mix, GSTIN strings, and code often use more tokens. Always measure with the provider tokenizer before you lock a budget.

PieceCounts in context?Counts in cost?
System instructionsYesYes (input)
User messageYesYes (input)
Chat historyYesYes (input)
Retrieved RAG chunksYesYes (input)
Model completionYes (output budget)Yes (output)
def approx_tokens(text: str) -> int:
    return max(1, len(text) // 4)


prompt = "Summarise this Bengaluru sprint retro in 5 bullets."
print(approx_tokens(prompt))
assert approx_tokens("") == 1
assert approx_tokens("abcd") == 1
def context_fits(pieces: list[str], window: int, reserve_out: int) -> bool:
    used = sum(max(1, len(p) // 4) for p in pieces)
    return used + reserve_out <= window


ok = context_fits(
    ["You are a support bot.", "Order unpaid but UPI success SMS."],
    window=8000,
    reserve_out=500,
)
print(ok)
assert ok is True
assert context_fits(["x" * 40000], 1000, 100) is False

Cost sketch (USD → INR)

Providers usually price per 1M tokens for input and output separately. Pass usd_to_inr explicitly so finance can swap the FX without editing code.

SymbolMeaning
in_tok, out_tokTokens per call
price_in, price_outUSD per 1M tokens
callsCalls per month
usd_to_inrFX (pass every time)
def monthly_rupees(
    in_tok: int,
    out_tok: int,
    price_in: float,
    price_out: float,
    calls: int,
    usd_to_inr: float,
) -> float:
    usd = calls * (
        (in_tok / 1_000_000) * price_in + (out_tok / 1_000_000) * price_out
    )
    return usd * usd_to_inr


# Planning numbers only — re-check provider pricing (as of Sep 2026 sketches)
inr = monthly_rupees(1200, 300, 0.15, 0.60, 50_000, 83.0)
print(round(inr, 2))
assert inr > 0

Failure modes that blow Indian SaaS budgets: counting only the user question, ignoring output drafts, hard-coding FX, and stuffing full PDFs instead of RAG chunks (Tokens lesson).


Embeddings — dims and similarity

Same embedding model for documents and queries. Cosine similarity ranks FAQ passages offline with TF-IDF vectors (scikit-learn==1.5.2) before you wire a paid embedding API.

IdeaDesk note
DimensionLength of the vector (e.g. 384 / 1536 depending on model)
CosineDot product of L2-normalised vectors; higher = more similar
ChunkingShort FAQ paragraphs beat multi-page blobs
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


docs = [
    "UPI debit success but order still unpaid",
    "How to reset password for the merchant portal",
    "GST invoice download for last month",
]
q = "money gone from bank but cart unpaid"
vec = TfidfVectorizer().fit(docs + [q])
X = vec.transform(docs)
qv = vec.transform([q])
scores = cosine_similarity(qv, X).ravel()
best = int(np.argmax(scores))
print(best, round(float(scores[best]), 4))
assert best == 0
import numpy as np


def l2_normalize(v: np.ndarray) -> np.ndarray:
    n = float(np.linalg.norm(v))
    return v if n == 0 else v / n


def cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(np.dot(l2_normalize(a), l2_normalize(b)))


a = np.array([1.0, 0.0, 0.0])
b = np.array([0.8, 0.2, 0.0])
print(round(cosine(a, b), 4))
assert cosine(a, a) == 1.0

Optional API shape (skipped in CI — needs a key):

# requires: api key
# openai>=1.40.0,<2 — key from env only
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
resp = client.embeddings.create(model="text-embedding-3-small", input="refund policy")
print(len(resp.data[0].embedding))

Structured outputs checklist

StepWhy
Ask for JSON only (no markdown fences)Parsers fail on prose wrappers
temperature=0 for labelsStable enums for product code
Validate keys + types after json.loadsJSON mode is not a schema
Refuse on missing required fieldsDo not invent urgency flags
import json


REQUIRED = {"intent", "urgent", "summary"}


def validate_ticket_label(raw: str) -> dict:
    data = json.loads(raw)
    missing = REQUIRED - set(data)
    if missing:
        raise ValueError(f"missing keys: {sorted(missing)}")
    if not isinstance(data["urgent"], bool):
        raise TypeError("urgent must be bool")
    return data


sample = '{"intent": "refund", "urgent": true, "summary": "UPI paid, order unpaid"}'
out = validate_ticket_label(sample)
print(out["intent"], out["urgent"])
assert out["urgent"] is True

RAG knobs (desk)

KnobTypical startWatch for
k retrieved chunks3–5Noise vs missing context
Chunk size~200–500 tokensSplit mid-sentence policies
Refuse thresholdLow similarity → refuseHallucinated policy text
Temperature0 for FAQ answersCreative drift on refunds

Retrieve → ground prompt → generate → evaluate on a golden set (RAG basics, Eval & safety). Prefer RAG over fine-tuning when FAQs change weekly in a Pune ops handbook.


Message roles (API shape)

RoleUse
systemStanding instructions (tone, refuse rules)
userTicket / question
assistantPrior model turns in history

Keep secrets in env vars (OPENAI_API_KEY). Never commit keys. Rate limits often surface as HTTP 429 — backoff and reduce batch size.



How to use this card at work

Print or pin the tables, then open only the matching course lesson when a row needs a longer WHY. In Bengaluru and Pune standups, lead with units stakeholders already use — INR, orders, tickets — and name the pinned library versions so a teammate can reproduce the same snippet tomorrow. Prefer seasonal naive or a classical baseline beside any fancy number; desk cards exist to stop tribal knowledge, not to replace the full lessons.

Keep secrets in environment variables. Treat prices, FX rates, and model names as dated planning figures and re-check the provider or finance page before you budget. Prefer fail-closed behaviour for payouts and quarantine for dashboard freshness, the same way production pipelines do. If a formula here disagrees with a lesson that was updated later, trust the lesson and file a content fix.

Schedule an owner who re-runs the Monday scripts. Cards without owners quietly rot after the first festival week. Link official docs from Sources so reviews stay grounded. Use Indian workplace examples (UPI, GSTIN, IST calendars) without inventing APIs or hard-coding keys.

Verified against the pinned course libraries documentation, September 2026.

Test yourself

  1. Roughly how many characters equal one English token in the planning rule?
  2. Name three pieces that count against the context window.
  3. Why pass usd_to_inr into the cost function instead of hard-coding FX?
  4. What must stay the same between query and document embeddings?
  5. What does cosine similarity compare after L2 normalisation?
  6. True or false: JSON mode removes the need to validate keys and types.
  7. Why set temperature=0 for ticket labelling?
  8. When should a FAQ bot refuse instead of inventing policy text?
  9. Which file pins openai, scikit-learn, and numpy for this course?
  10. True or false: stuffing a full PDF into every prompt is cheaper than RAG for high volume.

Related lessons

LessonTopic
What GenAI isWhen LLM vs classical ML
Tokens & costWindows and INR sketches
Calling an LLM APIEnv-based secrets
Structured outputsJSON validation
EmbeddingsRanking passages
RAG basicsRetrieve then generate
Eval & safetyGolden sets and refuse