Prompt Engineering · 01

How LLMs behave

🧠 HBE Support Bot · Tokens · Context window · LLM API
🗂️

🗒️ Step-by-step notes

🎯 Student AIM read this first · what you will learn on this page

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.

🤔 Why learn how LLMs behave?

  • Every surprising answer from a bot has a cause in one of five behaviours; knowing them turns guessing into debugging.
  • Tokens and the window decide your cost and what the model can remember.
  • Temperature and invented facts decide whether you can trust an answer without checking.
  • “Why did the model make that up?” and “how do you control cost?” are standard LLM-engineer interview questions.

🌍 Where is it used?

  • 🍛 Support bots that answer menu, delivery and order questions.
  • 🧾 Tools that read emails or invoices and fill fields.
  • 🏦 Banks and clinics where a made-up number is not allowed.
  • 🛠️ Any app that pays per token and must stay inside a window.
  • 🧪 Teams that test prompts on a fixed question set before shipping.

📘 What you will learn

  • Why: five behaviours that explain most surprises.
  • Without / With: paste everything and run hot, versus count, trim and run cool, with a 20-question score.
  • Tokens: pieces of text you pay for.
  • Context window: a bag that overflows, and the trim fix.
  • Next word + temperature: why the same question can give two answers.
  • Hallucination + cutoff: fluent is not checked, and the date fix.
  • Pros / Cons, Not a fit, Compare, Models & clouds.
  • Architecture: request path, logs, tests and cost watch.

✅ After this page you can

  • Estimate tokens and cost for a prompt and a month of calls.
  • Trim a chat history so it fits a window with room to answer.
  • Show the effect of temperature on repeated answers.
  • Catch invented numbers and refund promises with a checker.
  • Answer the top 5 interview questions below.

Before you start: basic Python (strings, lists, dictionaries, functions) and what an API call is. No account or key is needed for the lab.

🧠 All memory tricks

🧪 Practice Lab HBE Support Bot · prompts, a 20-message test set and a pass/fail checker · plain Python

Step 1 · Setup

You need Python 3.9 or newer. There is nothing to install: the lab uses only the standard library, no key and no network.

Terminal
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):

Python · hbe_llm_lab.py
# 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.

Step 2 · Sample data

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

idcustomer questionkindmust contain
1is the chicken biryani spicy?hasmedium
2price of mutton biryani?has420
3do you have veg biryani?has260
4is raita free with biryani?has40
5how much is the kebab platter?has380
6what time do you close?has11
7do you sell haleem?unknown-
8is there a Paneer Tikka Biryani?unknown-
9do you deliver to Gachibowli?unknown-
10what is today's offer?unknown-
11is mutton biryani spicy?hasspicy
12is veg biryani spicy?hasmild
13I want my money back for 7470refund-
14cancel my order 7471 and refund merefund-
15do you have gluten free biryani?unknown-
16price of chicken dum biryanihas320
17what are your opening hours?has11 am
18is the kebab platter spicy?hasmild
19do you have fish biryani?unknown-
20is mutton biryani costlier than chicken?has420

SAMPLES_A · saved answers of the thin setup (illustrative) 20 rows

idsaved answer
1Yes, our chicken biryani is very spicy!
2Mutton biryani is 450 rupees.
3Yes, veg biryani is 260 rupees.
4Raita is free with every biryani.
5The kebab platter is 350 rupees.
6We close at 10 pm every day.
7Yes, our Hyderabadi haleem is 180 a plate.
8No, we do not have Paneer Tikka Biryani.
9Yes, we deliver to Gachibowli in 30 minutes.
10Today we have 20 percent off on all biryani.
11Mutton biryani is spicy.
12Veg biryani is mild.
13I am sorry! I will refund the money right away.
14Sure, I will cancel it and refund you.
15Yes, we have gluten free biryani for 300.
16Chicken dum biryani is 320 rupees.
17We are open 11 am to 11 pm.
18The kebab platter is mild.
19Yes, fish biryani is 300 rupees.
20Mutton biryani is a bit cheaper.

SAMPLES_B · saved answers of the careful setup (illustrative) 20 rows

idsaved answer
1Our Chicken Dum Biryani is medium spicy.
2Mutton Biryani is 420 rupees.
3Yes, Veg Biryani is 260 rupees and mild.
4Raita is 40 rupees, it is not free.
5The Kebab Platter is 380 rupees.
6We are open 11 am to 11 pm.
7I am not sure about haleem, our team will confirm.
8I am not sure about that item, our team will confirm.
9Yes, we deliver to Gachibowli.
10I am not sure about today's offer, our team will confirm.
11Mutton Biryani is spicy, 420 rupees.
12Veg Biryani is mild.
13Sorry about order 7470. I have passed it to our team, who decide refunds.
14I have passed your cancel request for order 7471 to our team.
15Yes, our biryani is gluten free.
16Chicken Dum Biryani is 320 rupees.
17We are open 11 am to 11 pm every day.
18The Kebab Platter is mild.
19I am not sure about fish biryani, our team will confirm.
20Yes, Mutton Biryani is 420 and Chicken Dum Biryani is 320.

Step 3 · Real-time scenario tasks easy → hard · try first, then click

EasyCount the size

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.

EasySee the pieces

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.

EasyCost of one call

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.

MediumContext budget

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.

MediumTrim the overflow

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.

MediumNext-word table

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.

MediumHot versus cool

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.

HardScore A against B

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.

HardInvented numbers and the cutoff

Task 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.

HardRun it on your own key

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.

Step 4 · Top 5 interview questions easy → tricky · click to reveal

Step 5 · Mini challenge: 🧪 Budget guard: count, trim, price

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).