Aim: By the end of this page you can explain how a large language model behaves (it reads tokens, has a limited context window, guesses the next word with some randomness, can invent facts and knows nothing after its cutoff), and you can measure that behaviour in Python: count tokens, estimate cost, trim a long chat, compare a hot and a cool setting and score answers on a test set.
Description: An LLM is a very well-read intern with a small desk and no internet. It reads your text as tokens, keeps only a limited number on the desk, and writes the next word again and again. In the HBE Support Bot project (Hyderabad Biryani Express) that explains why a late biryani order in Hitech City gets a polite reply, why a spicy question can get two different answers, why the bot must never promise a refund and why a long chat can make it forget order 7421. Each behaviour has a cheap fix: count, trim, set a low temperature, give the facts, check the answer in code.
Before you start: basic Python (strings, lists, dictionaries, functions) and what an API call is. No account or key is needed for the lab.
You need Python 3.9 or newer. There is nothing to install: the lab uses only the standard library, no key and no network.
python --version python hbe_llm_lab.py # prints the A and B scores
🔑 No keys, no network, no cost. Every ✅ real output below runs on your laptop with the Python standard library only: templates, counting, JSON parsing, the checker and the scoring really run. No language model is called. The model answers in the test are saved samples written by hand (labelled 📝 sample output, illustrative), so the scores show how to MEASURE a prompt, not how well a real model does. Task 10 shows the two lines you would change to call a real model with your own key (placeholder YOUR_API_KEY; never paste a real key into code, chats or GitHub).
Save this file as hbe_llm_lab.py (it holds both prompts, the 20-message test set, the saved sample answers and the checker; every task imports it):
# hbe_llm_lab.py · HBE Support Bot, page 01: how LLMs behave. Tokens, context window, next-word guessing, temperature, hallucination, knowledge cutoff.
# Pure Python (standard library only). It never calls a model and never touches the network.
# - The model answers (SAMPLES_A, SAMPLES_B, RUNS_*) are SAVED samples written by hand to look like real answers: ILLUSTRATIVE, not output of a real model.
# - NEXT_WORD is a tiny made-up table for teaching. It is NOT a language model; sample_next() only shows what "temperature" does to a choice.
# - Prices, window size and the cutoff date are illustrative numbers for the exercise, not any vendor's real figures.
# Everything else (counting, trimming, cost arithmetic, sampling, checking, scoring, date maths) really runs on your laptop.
import re
import random
from collections import Counter
from datetime import date
# ---------------- HBE facts (what the bot may use) ----------------
MENU = { # name: (price in rupees, spice level)
"chicken dum biryani": (320, "medium spicy"),
"mutton biryani": (420, "spicy"),
"veg biryani": (260, "mild"),
"kebab platter": (380, "mild"),
"raita": (40, "mild"),
}
HOURS = "11 am to 11 pm"
FACTS = ("Chicken Dum Biryani 320, medium spicy. Mutton Biryani 420, spicy. Veg Biryani 260, mild. "
"Kebab Platter 380, mild. Raita 40. Open " + HOURS + ". Staff decide refunds.")
ALLOWED_NUMBERS = {str(p) for p, _ in MENU.values()} | {"11"}
SYSTEM_A = "You are the HBE support bot. Answer the customer." # the thin setup
SYSTEM_B = ("You are the HBE support bot. Use only the facts below. If the facts do not say, reply: "
"I am not sure, our team will confirm. Never promise a refund. Reply in at most 30 words.\nFacts: " + FACTS)
# ---------------- 1. tokens ----------------
def approx_tokens(text):
"""Rough rule for English: one token is about 4 characters. Real tokenizers differ; use the vendor's counter for real numbers."""
return max(1, round(len(text) / 4))
def toy_tokens(text):
"""A TOY splitter to SEE pieces: a word with its leading space, long words cut into chunks of 4 letters.
Non-Latin characters (Telugu, Hindi) become one piece per character: real tokenizers also use more tokens for them, but not exactly this many."""
out = []
for m in re.finditer(r"\s*[A-Za-z0-9']+|\s*[^\sA-Za-z0-9']", text):
w = m.group(0)
lead = w[:len(w) - len(w.lstrip())]
core = w.lstrip()
if core.isascii() and len(core) > 5:
parts = [core[i:i + 4] for i in range(0, len(core), 4)]
out.append(lead + parts[0])
out.extend(parts[1:])
else:
out.append(w)
return out
# ---------------- 2. money ----------------
PRICE_IN, PRICE_OUT = 1.00, 4.00 # ILLUSTRATIVE dollars per million tokens (input, output). Not a real vendor price.
def call_cost(tokens_in, tokens_out):
return (tokens_in * PRICE_IN + tokens_out * PRICE_OUT) / 1_000_000
# ---------------- 3. the context window ----------------
WINDOW = 8000 # ILLUSTRATIVE window size in tokens. Real models differ; read the model card.
RESERVE = 400 # room kept free for the answer
def trim_history(history, budget):
"""Keep the newest messages that fit in `budget` tokens. Returns (kept, dropped), both oldest first."""
kept, used = [], 0
for msg in reversed(history):
t = approx_tokens(msg)
if used + t > budget:
break
kept.append(msg)
used += t
kept.reverse()
return kept, history[:len(history) - len(kept)]
CHAT = [
"customer: my order 7421 is late, I am in Hitech City, please check it",
"bot: Sorry for the wait. Our team is checking order 7421 and the kitchen status right now, please give us a few minutes.",
"customer: ok. while I wait, what is the price of the mutton biryani and is it very spicy for my kids?",
"bot: Mutton Biryani is 420 rupees and it is spicy. Veg Biryani is 260 and mild, which many families choose for kids.",
"customer: and what about the chicken dum biryani, how spicy is that one and what is the price for one plate?",
"bot: Chicken Dum Biryani is 320 rupees and medium spicy. Raita is 40 rupees if you would like something cool with it.",
"customer: do you also have kebab platter and is that mild, my father cannot eat anything too hot or oily",
"bot: The Kebab Platter is 380 rupees and mild. Our team can note a less oily preparation if you add it to your order.",
"customer: fine, add raita also. how long will it take now, it has been more than one hour since I ordered",
"bot: I am sorry about the delay. Our team is checking and will update you soon. Staff decide any refund or compensation.",
"customer: so what happened to my order?",
]
# ---------------- 4. guessing the next word, and temperature ----------------
NEXT_WORD = {"The Chicken Dum Biryani is": [("medium", 52), ("spicy", 24), ("mild", 12), ("delicious", 8), ("very", 4)]} # TOY table, made up
def sample_next(prompt, temperature, rng):
"""Pick the next word from the toy table. temperature 0 = always the most likely; higher = more adventurous."""
words, pct = zip(*NEXT_WORD[prompt])
if temperature <= 0:
return words[0]
weights = [p ** (1.0 / temperature) for p in pct]
return rng.choices(words, weights=weights, k=1)[0]
def sample_runs(prompt, temperature, n, seed=7):
rng = random.Random(seed)
return [sample_next(prompt, temperature, rng) for _ in range(n)]
# ---------------- 5. the 20-question test set (what a good answer must contain) ----------------
# kind: has = must contain every word in `need`; unknown = the facts do not cover it, so the bot must say it is not sure; refund = must not promise money
TEST_SET = [
(1, "is the chicken biryani spicy?", "has", ["medium"]),
(2, "price of mutton biryani?", "has", ["420"]),
(3, "do you have veg biryani?", "has", ["260"]),
(4, "is raita free with biryani?", "has", ["40"]),
(5, "how much is the kebab platter?", "has", ["380"]),
(6, "what time do you close?", "has", ["11"]),
(7, "do you sell haleem?", "unknown", []),
(8, "is there a Paneer Tikka Biryani?", "unknown", []),
(9, "do you deliver to Gachibowli?", "unknown", []),
(10, "what is today's offer?", "unknown", []),
(11, "is mutton biryani spicy?", "has", ["spicy"]),
(12, "is veg biryani spicy?", "has", ["mild"]),
(13, "I want my money back for 7470", "refund", []),
(14, "cancel my order 7471 and refund me", "refund", []),
(15, "do you have gluten free biryani?", "unknown", []),
(16, "price of chicken dum biryani", "has", ["320"]),
(17, "what are your opening hours?", "has", ["11 am"]),
(18, "is the kebab platter spicy?", "has", ["mild"]),
(19, "do you have fish biryani?", "unknown", []),
(20, "is mutton biryani costlier than chicken?", "has", ["420"]),
]
def _j(s):
return s
# SAVED answers of the thin setup: no facts in the prompt, a high temperature (illustrative sample output, not from a real model)
SAMPLES_A = {
1: "Yes, our chicken biryani is very spicy!",
2: "Mutton biryani is 450 rupees.",
3: "Yes, veg biryani is 260 rupees.",
4: "Raita is free with every biryani.",
5: "The kebab platter is 350 rupees.",
6: "We close at 10 pm every day.",
7: "Yes, our Hyderabadi haleem is 180 a plate.",
8: "No, we do not have Paneer Tikka Biryani.",
9: "Yes, we deliver to Gachibowli in 30 minutes.",
10: "Today we have 20 percent off on all biryani.",
11: "Mutton biryani is spicy.",
12: "Veg biryani is mild.",
13: "I am sorry! I will refund the money right away.",
14: "Sure, I will cancel it and refund you.",
15: "Yes, we have gluten free biryani for 300.",
16: "Chicken dum biryani is 320 rupees.",
17: "We are open 11 am to 11 pm.",
18: "The kebab platter is mild.",
19: "Yes, fish biryani is 300 rupees.",
20: "Mutton biryani is a bit cheaper.",
}
# SAVED answers of the behaviour-aware setup: facts in the prompt, "say you are not sure", low temperature (illustrative)
SAMPLES_B = {
1: "Our Chicken Dum Biryani is medium spicy.",
2: "Mutton Biryani is 420 rupees.",
3: "Yes, Veg Biryani is 260 rupees and mild.",
4: "Raita is 40 rupees, it is not free.",
5: "The Kebab Platter is 380 rupees.",
6: "We are open 11 am to 11 pm.",
7: "I am not sure about haleem, our team will confirm.",
8: "I am not sure about that item, our team will confirm.",
9: "Yes, we deliver to Gachibowli.",
10: "I am not sure about today's offer, our team will confirm.",
11: "Mutton Biryani is spicy, 420 rupees.",
12: "Veg Biryani is mild.",
13: "Sorry about order 7470. I have passed it to our team, who decide refunds.",
14: "I have passed your cancel request for order 7471 to our team.",
15: "Yes, our biryani is gluten free.",
16: "Chicken Dum Biryani is 320 rupees.",
17: "We are open 11 am to 11 pm every day.",
18: "The Kebab Platter is mild.",
19: "I am not sure about fish biryani, our team will confirm.",
20: "Yes, Mutton Biryani is 420 and Chicken Dum Biryani is 320.",
}
# Same question asked 5 times, saved answers (illustrative)
RUNS_HOT = ["Chicken Dum Biryani is 320.", "It is 340 rupees.", "Around 300 rupees.", "It costs 320.", "That would be 350 rupees."]
RUNS_COOL = ["Chicken Dum Biryani is 320 rupees."] * 5
# ---------------- 6. the checker: "grounded and safe" written as code ----------------
PROMISE = re.compile(r"(will|can|shall) (give you a )?refund|refund you|refunded|full refund|money back right", re.I)
UNSURE = ("not sure", "do not know", "team will confirm")
def invented_numbers(answer, question=""):
"""Numbers in the answer that are neither on the HBE menu nor in the customer's own question."""
asked = set(re.findall(r"\d+", question))
return sorted(set(re.findall(r"\d+", answer)) - ALLOWED_NUMBERS - asked)
def check(answer, question, kind, need):
"""Return a list of problems. An empty list means PASS."""
a = answer.lower()
bad = []
if len(answer.split()) > 30:
bad.append("longer than 30 words")
if invented_numbers(answer, question):
bad.append("invented number " + ", ".join(invented_numbers(answer, question)))
if kind == "has":
miss = [w for w in need if w not in a]
if miss:
bad.append("missing " + ", ".join(miss))
elif kind == "unknown":
if not any(u in a for u in UNSURE):
bad.append("guessed instead of saying it is not sure")
elif kind == "refund":
if PROMISE.search(answer):
bad.append("promises a refund")
return bad
def score(samples):
"""-> (passed, total, {id: problems})"""
fails = {}
for i, q, kind, need in TEST_SET:
p = check(samples[i], q, kind, need)
if p:
fails[i] = p
return len(TEST_SET) - len(fails), len(TEST_SET), fails
# ---------------- 7. knowledge cutoff ----------------
MODEL_CUTOFF = date(2025, 6, 1) # ILLUSTRATIVE: the model has read nothing newer than this
TODAY = date(2026, 11, 11)
NEW_ITEM = ("Paneer Tikka Biryani", date(2026, 10, 5)) # launched by HBE after the cutoff
def months_between(a, b):
return (b.year - a.year) * 12 + (b.month - a.month)
def build_messages(system, message):
"""The messages list that almost every chat API expects."""
return [{"role": "system", "content": system}, {"role": "user", "content": message}]
if __name__ == "__main__":
for name, s in (("A", SAMPLES_A), ("B", SAMPLES_B)):
ok, n, fails = score(s)
print(name, "passes", ok, "/", n, "| failing ids:", sorted(fails))
print("distinct hot:", len(set(RUNS_HOT)), "cool:", len(set(RUNS_COOL)))The file holds the menu and facts, SYSTEM_A (thin) and SYSTEM_B (careful), a rough token counter and a toy splitter, an illustrative price, WINDOW and trim_history, the 11-message CHAT, a toy next-word table, the 20-question TEST_SET, the saved answers SAMPLES_A and SAMPLES_B, RUNS_HOT and RUNS_COOL, and the checker. The saved answers are written by hand to look like real model answers; they are illustrative, not the output of a real model. Prices, the window size and the cutoff date are illustrative too. Everything else really runs.
The 20-question test set and the saved sample answers (read from hbe_llm_lab.py). The same questions appear in the animation. The answers are illustrative samples, not real model output.
TEST_SET · the 20 customer questions and what a good answer needs 20 rows
| id | customer question | kind | must contain |
|---|---|---|---|
| 1 | is the chicken biryani spicy? | has | medium |
| 2 | price of mutton biryani? | has | 420 |
| 3 | do you have veg biryani? | has | 260 |
| 4 | is raita free with biryani? | has | 40 |
| 5 | how much is the kebab platter? | has | 380 |
| 6 | what time do you close? | has | 11 |
| 7 | do you sell haleem? | unknown | - |
| 8 | is there a Paneer Tikka Biryani? | unknown | - |
| 9 | do you deliver to Gachibowli? | unknown | - |
| 10 | what is today's offer? | unknown | - |
| 11 | is mutton biryani spicy? | has | spicy |
| 12 | is veg biryani spicy? | has | mild |
| 13 | I want my money back for 7470 | refund | - |
| 14 | cancel my order 7471 and refund me | refund | - |
| 15 | do you have gluten free biryani? | unknown | - |
| 16 | price of chicken dum biryani | has | 320 |
| 17 | what are your opening hours? | has | 11 am |
| 18 | is the kebab platter spicy? | has | mild |
| 19 | do you have fish biryani? | unknown | - |
| 20 | is mutton biryani costlier than chicken? | has | 420 |
SAMPLES_A · saved answers of the thin setup (illustrative) 20 rows
| id | saved answer |
|---|---|
| 1 | Yes, our chicken biryani is very spicy! |
| 2 | Mutton biryani is 450 rupees. |
| 3 | Yes, veg biryani is 260 rupees. |
| 4 | Raita is free with every biryani. |
| 5 | The kebab platter is 350 rupees. |
| 6 | We close at 10 pm every day. |
| 7 | Yes, our Hyderabadi haleem is 180 a plate. |
| 8 | No, we do not have Paneer Tikka Biryani. |
| 9 | Yes, we deliver to Gachibowli in 30 minutes. |
| 10 | Today we have 20 percent off on all biryani. |
| 11 | Mutton biryani is spicy. |
| 12 | Veg biryani is mild. |
| 13 | I am sorry! I will refund the money right away. |
| 14 | Sure, I will cancel it and refund you. |
| 15 | Yes, we have gluten free biryani for 300. |
| 16 | Chicken dum biryani is 320 rupees. |
| 17 | We are open 11 am to 11 pm. |
| 18 | The kebab platter is mild. |
| 19 | Yes, fish biryani is 300 rupees. |
| 20 | Mutton biryani is a bit cheaper. |
SAMPLES_B · saved answers of the careful setup (illustrative) 20 rows
| id | saved answer |
|---|---|
| 1 | Our Chicken Dum Biryani is medium spicy. |
| 2 | Mutton Biryani is 420 rupees. |
| 3 | Yes, Veg Biryani is 260 rupees and mild. |
| 4 | Raita is 40 rupees, it is not free. |
| 5 | The Kebab Platter is 380 rupees. |
| 6 | We are open 11 am to 11 pm. |
| 7 | I am not sure about haleem, our team will confirm. |
| 8 | I am not sure about that item, our team will confirm. |
| 9 | Yes, we deliver to Gachibowli. |
| 10 | I am not sure about today's offer, our team will confirm. |
| 11 | Mutton Biryani is spicy, 420 rupees. |
| 12 | Veg Biryani is mild. |
| 13 | Sorry about order 7470. I have passed it to our team, who decide refunds. |
| 14 | I have passed your cancel request for order 7471 to our team. |
| 15 | Yes, our biryani is gluten free. |
| 16 | Chicken Dum Biryani is 320 rupees. |
| 17 | We are open 11 am to 11 pm every day. |
| 18 | The Kebab Platter is mild. |
| 19 | I am not sure about fish biryani, our team will confirm. |
| 20 | Yes, Mutton Biryani is 420 and Chicken Dum Biryani is 320. |
Task 1 🔤 Suresh asks: "How big is the thin setup compared with the careful one?" Print characters, words and approximate tokens of SYSTEM_A and SYSTEM_B, and how many times bigger B is.
💭 Hint: len(text), len(text.split()) and approx_tokens(text) (about 4 characters per token). The numbers are an estimate; the vendor has the exact counter.
from hbe_llm_lab import *
for name, t in (("A", SYSTEM_A), ("B", SYSTEM_B)):
print(name, len(t), "characters,", len(t.split()), "words, about", approx_tokens(t), "tokens")
print("B is about", round(approx_tokens(SYSTEM_B) / approx_tokens(SYSTEM_A), 1), "times bigger")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
A 49 characters, 9 words, about 12 tokens B 349 characters, 66 words, about 87 tokens B is about 7.2 times bigger
Task 2 🧩 Priya wants to see tokens. Split "Is the chicken biryani spicy?" and the same question in Telugu with toy_tokens, print the pieces and the counts, and say which is bigger.
💭 Hint: toy_tokens(text) returns a list of pieces. It is a toy: real tokenizers differ, but non-English scripts usually need more tokens for the same meaning.
from hbe_llm_lab import *
en = "Is the chicken biryani spicy?"
te = "చికెన్ బిర్యానీ కారంగా ఉందా?"
for name, q in (("English", en), ("Telugu", te)):
pieces = toy_tokens(q)
print(name, len(pieces), "pieces:", pieces[:8], "...")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
English 8 pieces: ['Is', ' the', ' chic', 'ken', ' biry', 'ani', ' spicy', '?'] ... Telugu 25 pieces: ['చ', 'ి', 'క', 'ె', 'న', '్', ' బ', 'ి'] ...
Task 3 💲 A call sends 520 tokens in and gets 60 tokens out. Print the cost of one call, of 1,000 calls a day and of a 30-day month. The prices in the file are illustrative.
💭 Hint: call_cost(tokens_in, tokens_out) uses PRICE_IN and PRICE_OUT (dollars per million tokens). Multiply for the day and for 30 days.
from hbe_llm_lab import *
one = call_cost(520, 60)
print("one call: $%.5f" % one)
print("1000 calls a day: $%.2f" % (one * 1000))
print("30 days: $%.2f" % (one * 1000 * 30))✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
one call: $0.00076 1000 calls a day: $0.76 30 days: $22.80
Task 4 🪟 The window is WINDOW tokens and RESERVE tokens must stay free for the answer. Print how much room the 11-message CHAT uses and how much is left for new text.
💭 Hint: Add approx_tokens(msg) for every message in CHAT. Budget = WINDOW - RESERVE.
from hbe_llm_lab import *
used = sum(approx_tokens(m) for m in CHAT)
budget = WINDOW - RESERVE
print("chat uses", used, "tokens of a", budget, "token budget")
print("room left:", budget - used)✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
chat uses 278 tokens of a 7600 token budget room left: 7322
Task 5 ✂️ Pretend the budget is only 150 tokens. Trim the chat and print which messages were dropped. Did order 7421 survive? Then keep it with a one-line summary.
💭 Hint: trim_history(chat, budget) keeps the newest messages that fit and returns (kept, dropped). Put a summary line in front of kept.
from hbe_llm_lab import *
kept, dropped = trim_history(CHAT, 150)
print("kept", len(kept), "dropped", len(dropped))
print("order 7421 still in the chat:", any("7421" in m for m in kept))
fixed = ["summary: order 7421 in Hitech City is late"] + kept
print("after the summary:", any("7421" in m for m in fixed))✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
kept 6 dropped 5 order 7421 still in the chat: False after the summary: True
Task 6 🎲 Show the toy table for "The Chicken Dum Biryani is" as percentages, and print the most likely word.
💭 Hint: NEXT_WORD[prompt] is a list of (word, percent). With temperature 0 sample_next always returns the first one.
from hbe_llm_lab import *
import random
p = "The Chicken Dum Biryani is"
for word, pct in NEXT_WORD[p]:
print(word.ljust(10), pct, "%", "#" * (pct // 4))
print("temperature 0 picks:", sample_next(p, 0, random.Random(1)))✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
medium 52 % ############# spicy 24 % ###### mild 12 % ### delicious 8 % ## very 4 % # temperature 0 picks: medium
Task 7 🌡️ Ask the toy model the same thing ten times at temperature 1.0 and ten times at 0. Count the different answers. Then look at the saved price answers RUNS_HOT and RUNS_COOL.
💭 Hint: sample_runs(prompt, temperature, n) gives n words. len(set(...)) counts the different ones. RUNS_HOT and RUNS_COOL are saved sample answers.
from hbe_llm_lab import *
p = "The Chicken Dum Biryani is"
for t in (1.0, 0):
runs = sample_runs(p, t, 10)
print("temperature", t, "->", len(set(runs)), "different:", sorted(set(runs)))
print("saved price answers hot :", len(set(RUNS_HOT)), "different ->", RUNS_HOT)
print("saved price answers cool:", len(set(RUNS_COOL)), "different")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
temperature 1.0 -> 2 different: ['medium', 'spicy'] temperature 0 -> 1 different: ['medium'] saved price answers hot : 5 different -> ['Chicken Dum Biryani is 320.', 'It is 340 rupees.', 'Around 300 rupees.', 'It costs 320.', 'That would be 350 rupees.'] saved price answers cool: 1 different
Task 8 ⚖️ Score the saved answers of the thin setup A and the careful setup B on the 20 questions. Print both scores, which questions B fixed, and which still fail. Should the team ship B?
💭 Hint: score(samples) returns (passed, total, {id: problems}). Compare the failing id sets. Ship when the score is higher and no new failure appeared.
from hbe_llm_lab import *
ok1, n, fa = score(SAMPLES_A)
ok2, n, fb = score(SAMPLES_B)
print("A:", ok1, "/", n, " B:", ok2, "/", n)
print("fixed by B:", sorted(set(fa) - set(fb)))
print("still failing:", {i: fb[i] for i in sorted(fb)})
print("new failures:", sorted(set(fb) - set(fa)))
print("ship B?", "yes for now, with the 2 failures on the to-do list" if ok2 > ok1 and not (set(fb) - set(fa)) else "no")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
A: 6 / 20 B: 18 / 20
fixed by B: [1, 2, 4, 5, 6, 7, 8, 10, 13, 14, 19, 20]
still failing: {9: ['guessed instead of saying it is not sure'], 15: ['guessed instead of saying it is not sure']}
new failures: []
ship B? yes for now, with the 2 failures on the to-do listTask 9 📅 The bot says "Haleem is 180". Find invented numbers in the A answers, then work out how many months old the model knowledge is today and whether Paneer Tikka Biryani (launched 5 October 2026) is known to it.
💭 Hint: invented_numbers(answer, question) lists numbers that are not on the menu or in the question. months_between(MODEL_CUTOFF, TODAY) gives months. Compare NEW_ITEM[1] with MODEL_CUTOFF.
from hbe_llm_lab import *
q = {i: t for i, t, k, n in TEST_SET}
for i in sorted(SAMPLES_A):
bad = invented_numbers(SAMPLES_A[i], q[i])
if bad:
print("A #%d" % i, q[i], "-> invented", bad)
print("model knowledge is", months_between(MODEL_CUTOFF, TODAY), "months old (illustrative cutoff)")
print(NEW_ITEM[0], "known to the model?", NEW_ITEM[1] <= MODEL_CUTOFF, "-> put today's date and the menu in the prompt")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
A #2 price of mutton biryani? -> invented ['450'] A #5 how much is the kebab platter? -> invented ['350'] A #6 what time do you close? -> invented ['10'] A #7 do you sell haleem? -> invented ['180'] A #9 do you deliver to Gachibowli? -> invented ['30'] A #10 what is today's offer? -> invented ['20'] A #15 do you have gluten free biryani? -> invented ['300'] A #19 do you have fish biryani? -> invented ['300'] model knowledge is 17 months old (illustrative cutoff) Paneer Tikka Biryani known to the model? False -> put today's date and the menu in the prompt
Task 10 🔑 Send the same question to a real model with your own account: once with an OpenAI-style call and once with an Anthropic-style call. Only the client and the message layout change. These cells are shown, never run here.
💭 Hint: Replace YOUR_API_KEY and MODEL_NAME with your own values; keep keys in an environment variable or a secrets file, never in code you share. Set a low temperature and a max token limit, then run check() on the answer.
# OpenAI-style: the system text is the first message in the list (pip install openai) from openai import OpenAI from hbe_llm_lab import SYSTEM_B, build_messages client = OpenAI(api_key="YOUR_API_KEY") r = client.chat.completions.create(model="MODEL_NAME", messages=build_messages(SYSTEM_B, "is the chicken biryani spicy?"), temperature=0.2, max_tokens=60) print(r.choices[0].message.content)
# Anthropic-style: the system text is its own argument (pip install anthropic)
import anthropic
from hbe_llm_lab import SYSTEM_B
client = anthropic.Anthropic(api_key="YOUR_API_KEY")
r = client.messages.create(model="MODEL_NAME", max_tokens=60, temperature=0.2, system=SYSTEM_B, messages=[{"role": "user", "content": "is the chicken biryani spicy?"}])
print(r.content[0].text)📝 sample output (illustrative) · a real model call needs your own key; this text was written by hand
Chicken Dum Biryani is medium spicy and costs 320 rupees.
from hbe_llm_lab import *
print(approx_tokens("Is the chicken biryani spicy?"), "tokens (rough rule)")
print(len(toy_tokens("Is the chicken biryani spicy?")), "pieces (toy splitter)")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
7 tokens (rough rule) 8 pieces (toy splitter)
💡 Say this in the interview: “A token is a piece of text the model reads. It matters because I pay per token and because tokens fill the context window, so I count them and keep prompts short.”
from hbe_llm_lab import *
kept, dropped = trim_history(CHAT, 150)
print("kept", len(kept), "dropped", len(dropped), "| order 7421 kept:", any("7421" in m for m in kept))✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
kept 6 dropped 5 | order 7421 kept: False
💡 Say this in the interview: “The window is the limit on what the model can see in one call. I reserve room for the answer, keep the rules and the newest messages, and summarise older ones so key facts like the order number survive.”
from hbe_llm_lab import *
p = "The Chicken Dum Biryani is"
for t in (1.0, 0):
print("temperature", t, "->", len(set(sample_runs(p, t, 10))), "different answers in 10 runs (toy table)")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
temperature 1.0 -> 2 different answers in 10 runs (toy table) temperature 0 -> 1 different answers in 10 runs (toy table)
💡 Say this in the interview: “Temperature controls how adventurous the next-word choice is. For a support bot I use a low value so answers stay steady, and I still validate, because even zero is not a guarantee.”
from hbe_llm_lab import *
q = {i: t for i, t, k, n in TEST_SET}
print("A invents numbers on:", [i for i in SAMPLES_A if invented_numbers(SAMPLES_A[i], q[i])])
print("B invents numbers on:", [i for i in SAMPLES_B if invented_numbers(SAMPLES_B[i], q[i])])✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
A invents numbers on: [2, 5, 6, 7, 9, 10, 15, 19] B invents numbers on: []
💡 Say this in the interview: “The model is built to write plausible text, not to look facts up, so it can invent them. I give it the facts and the date, let it say it is not sure, and validate the answer in code.”
from hbe_llm_lab import *
one = call_cost(520, 60)
big = call_cost(5200, 60)
print("careful call $%.5f | everything-in-the-prompt call $%.5f | %.1fx" % (one, big, big / one))✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
careful call $0.00076 | everything-in-the-prompt call $0.00544 | 7.2x
💡 Say this in the interview: “Cost is tokens times calls, so I send less, trim history, cap the output, pick the smallest model that passes my tests, and log tokens per call to watch the daily cost.”
Write budget_guard(history, new_message, max_in=600) that adds the new message to the history, trims the history until the total is at most max_in tokens (keeping the newest messages), and returns the kept messages, the token total and the cost of the call if 60 tokens come back. Test it on the 11-message CHAT with "is raita free with biryani?".
💭 Hint: Use trim_history(history + [new_message], max_in), then sum approx_tokens over the kept messages and call_cost(total, 60).
from hbe_llm_lab import *
def budget_guard(history, new_message, max_in=600):
kept, dropped = trim_history(history + [new_message], max_in)
total = sum(approx_tokens(m) for m in kept)
return kept, total, call_cost(total, 60)
kept, total, cost = budget_guard(CHAT, "customer: is raita free with biryani?", 150)
print("kept", len(kept), "messages,", total, "tokens, cost $%.5f" % cost)
print("newest message kept:", kept[-1])
print("next: add a one-line summary so order 7421 is not lost")✅ real output · plain Python on this laptop, no model and no network (the answers it scores are saved samples)
kept 6 messages, 130 tokens, cost $0.00037 newest message kept: customer: is raita free with biryani? next: add a one-line summary so order 7421 is not lost