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
| Resource | Link |
|---|---|
| Course | Generative AI |
| Tokens lesson | Tokens, context & cost |
| Embeddings | Embeddings 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.txtPinned in docs/genai/requirements.txt (as of course pin set):
openai>=1.40.0,<2
scikit-learn==1.5.2
numpy==2.1.3Offline 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
| Need | Prefer | Avoid |
|---|---|---|
| Tabular churn / credit score | Classical ML (ML Fundamentals) | Stuffing rows into an LLM |
| Free-text FAQ / policy Q&A | RAG + embeddings | Fine-tuning for every FAQ edit |
| Label tickets into fixed JSON | Structured outputs + schema check | Parsing free prose with string equality |
| Monthly INR cost sketch | Token approx + FX parameter | Guessing 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.
| Piece | Counts in context? | Counts in cost? |
|---|---|---|
| System instructions | Yes | Yes (input) |
| User message | Yes | Yes (input) |
| Chat history | Yes | Yes (input) |
| Retrieved RAG chunks | Yes | Yes (input) |
| Model completion | Yes (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") == 1def 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 FalseCost 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.
| Symbol | Meaning |
|---|---|
in_tok, out_tok | Tokens per call |
price_in, price_out | USD per 1M tokens |
calls | Calls per month |
usd_to_inr | FX (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 > 0Failure 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.
| Idea | Desk note |
|---|---|
| Dimension | Length of the vector (e.g. 384 / 1536 depending on model) |
| Cosine | Dot product of L2-normalised vectors; higher = more similar |
| Chunking | Short 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 == 0import 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.0Optional 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
| Step | Why |
|---|---|
| Ask for JSON only (no markdown fences) | Parsers fail on prose wrappers |
temperature=0 for labels | Stable enums for product code |
Validate keys + types after json.loads | JSON mode is not a schema |
| Refuse on missing required fields | Do 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 TrueRAG knobs (desk)
| Knob | Typical start | Watch for |
|---|---|---|
k retrieved chunks | 3–5 | Noise vs missing context |
| Chunk size | ~200–500 tokens | Split mid-sentence policies |
| Refuse threshold | Low similarity → refuse | Hallucinated policy text |
| Temperature | 0 for FAQ answers | Creative 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)
| Role | Use |
|---|---|
system | Standing instructions (tone, refuse rules) |
user | Ticket / question |
assistant | Prior 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
- Roughly how many characters equal one English token in the planning rule?
- Name three pieces that count against the context window.
- Why pass
usd_to_inrinto the cost function instead of hard-coding FX? - What must stay the same between query and document embeddings?
- What does cosine similarity compare after L2 normalisation?
- True or false: JSON mode removes the need to validate keys and types.
- Why set
temperature=0for ticket labelling? - When should a FAQ bot refuse instead of inventing policy text?
- Which file pins
openai,scikit-learn, andnumpyfor this course? - True or false: stuffing a full PDF into every prompt is cheaper than RAG for high volume.
Related lessons
| Lesson | Topic |
|---|---|
| What GenAI is | When LLM vs classical ML |
| Tokens & cost | Windows and INR sketches |
| Calling an LLM API | Env-based secrets |
| Structured outputs | JSON validation |
| Embeddings | Ranking passages |
| RAG basics | Retrieve then generate |
| Eval & safety | Golden sets and refuse |