How LLMs actually work (without the maths panic)
Tokens, context windows, the prediction loop, temperature, statelessness and why models hallucinate.
A large language model is a next-token predictor. You give it a sequence of tokens and it returns a probability distribution over what token comes next. Everything else (chat, coding, reasoning) is built on top of that one trick repeated thousands of times.
You have already used a tiny version of this. The suggestion strip above your phone keyboard guesses your next word from the last few you typed. An LLM does the same job with a far larger neural network (a transformer), trained on a huge amount of text, looking at thousands of tokens of context instead of two or three words. Same idea, very different scale.
Swipe to see the full diagram →
One prediction step. Chat apps repeat this until the model stops.
Tokens, not words
Models do not read letters or words. They read tokens: chunks of roughly 3–4 English characters. Common words such as "the" or "good" are usually one token. Rarer words are cut into pieces, so "Bengaluru" might be 3 tokens. Names, code, numbers and text in Hindi, Tamil or Kannada script usually take more tokens than plain English of the same length.
Tokens matter for two practical reasons. You are billed per token, both for what you send and for what the model writes back. And every limit you will meet (context window, maximum output length, rate limits) is counted in tokens, not words. A rough rule for English: 100 tokens is about 75 words. When it matters, do not guess; count. Install the tokenizer library with pip install tiktoken and run this. No API key needed.
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # the tokenizer used by the gpt-4o family
samples = [
"good",
"Bengaluru",
"Is Bengaluru good for freshers?",
"def binary_search(arr, target):",
]
for text in samples:
ids = enc.encode(text)
pieces = [enc.decode([i]) for i in ids]
print(f"{len(ids):>2} tokens | {text} -> {pieces}")Different models use different tokenizers, so the exact count changes a little from one provider to another. The habit is what matters: before you paste a long document into a prompt, count it.
The context window is the model's desk
Every model has a maximum context window, for example 128k tokens. Think of it as a desk: the model can only work with the pages that are on the desk right now. Your instructions, the conversation so far, any document you paste and the answer being written all share that one desk.
- If it is not in the context window, the model cannot see it. It does not know your college, your resume or yesterday's chat unless that text is sent again.
- Input and output share the window. A huge prompt leaves less room for the answer.
- When a conversation outgrows the window, the app has to drop or summarise older messages. That is why very long chats start "forgetting" early details.
One prediction, then a loop
Here is one step. The model reads every token so far and gives a score to every token in its vocabulary (tens of thousands of candidates, or more). The scores become probabilities. One token is picked and added to the end. Then the whole, slightly longer text goes back in and the step runs again.
This loop explains three things you have already seen. Answers stream in piece by piece because they are produced piece by piece. Long answers take longer and cost more because every output token is one more trip through the model. And the model cannot go back and edit: once a token is written, everything after it is built on top of it.
Temperature: how adventurous the pick is
Temperature changes how the pick is made. At 0 the model takes the most likely token every time, so the same prompt gives (almost) the same answer. Around 0.7, less likely tokens sometimes win, so two runs give two different answers. The toy sampler below uses made-up scores for the first token of a reply, so you can watch the probabilities move. Run it a few times.
import math
import random
# Made-up scores for the first token of a reply to "Is Bengaluru good for freshers?"
scores = {"Many": 2.1, "It": 1.4, "Yes": 1.2, "Bengaluru": 0.4, "The": 0.0}
def probabilities(scores, temperature):
scaled = {tok: s / temperature for tok, s in scores.items()}
total = sum(math.exp(s) for s in scaled.values())
return {tok: math.exp(s) / total for tok, s in scaled.items()}
def pick(scores, temperature):
if temperature == 0: # greedy: always the top token
return max(scores, key=scores.get)
probs = probabilities(scores, temperature)
return random.choices(list(probs), weights=list(probs.values()))[0]
for t in (0.2, 0.7, 1.5):
probs = probabilities(scores, t)
print(f"temperature {t}:", {tok: round(p, 2) for tok, p in probs.items()})
print("temperature 0 :", [pick(scores, 0) for _ in range(6)])
print("temperature 0.7:", [pick(scores, 0.7) for _ in range(6)])- Use 0 to 0.3 for extraction, classification, grading, code and anything a program will parse.
- Use 0.7 to 1.0 for brainstorming, naming, rewriting and creative drafts.
- Hosted models can still vary slightly at temperature 0, so never write logic that depends on getting the exact same text twice.
Stateless: why chat apps resend everything
The model has no memory between calls. Each request is answered from scratch, using only the tokens in that request. So how does a chatbot know what "there" means in "What about salaries there?" The app keeps the conversation in a list and sends the whole list again with every new message.
That has a cost. Message 1 sends one question. Message 10 sends all nine earlier questions and answers plus the new one. The script below counts how the input grows turn by turn. The replies are hard-coded, so it runs without an API key.
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
history = [] # the app's "memory" is just a Python list
def send(user_text: str, reply: str) -> int:
"""Pretend to call the model. Returns how many tokens the request carried."""
history.append({"role": "user", "content": user_text})
sent = sum(len(enc.encode(m["content"])) for m in history) # the WHOLE list goes out
history.append({"role": "assistant", "content": reply})
return sent
turns = [
("Is Bengaluru good for freshers?", "Many freshers start there. It depends on your field."),
("What about salaries there?", "They vary a lot by company, role and skills."),
("Which skills should I build first?", "Strong DSA, one backend stack and a deployed project."),
]
for n, (question, reply) in enumerate(turns, start=1):
print(f"request {n}: about {send(question, reply)} input tokens")
# Real APIs add a few tokens of overhead per message, so treat these as approximate.When a product says it has "memory", that is application code: it saves notes or past chats in a database and pastes the relevant parts back into the prompt. The chat loop in the next lesson and the retrieval work in Module 3 are both versions of this idea.
Why models hallucinate
A model is trained to continue text in a plausible way, not to check facts. Ask it for your college's highest package last year and it has two options: say it does not know, or write a sentence that looks like the many placement articles it was trained on. Without help it often does the second, fluently and confidently. Its training data also stops at a cutoff date, so recent events are simply missing.
- Put the facts in the prompt. Paste the document, or retrieve it automatically (that is RAG, Module 3).
- Tell the model it may answer "I don't know" or "not in the document".
- Ask it to quote the line it used, so a person or a program can check it.
- Validate anything that matters (numbers, dates, names) before it reaches a user.
Temperature 0 does not fix this. It makes the answer repeatable, not true: a wrong answer will simply be wrong every time.
Common mistakes
- Estimating cost or limits in words or characters instead of counting tokens.
- Expecting a new API call to remember the previous one. It will not, unless you resend the history.
- Thinking temperature 0 means "accurate". It means "repeatable".
- Trusting a confident tone. Fluency is what the model is trained for; correctness has to be checked.
- Pasting a huge document with a one-line question, then being surprised by the bill. Every token on the desk is paid for on every call.
- Forgetting that output tokens count too, for both the limit and the cost.
How this shows up in interviews
- Q: In one line, what does an LLM do? A: Given the tokens so far, it outputs a probability for every possible next token. Generation is that step in a loop: pick a token, append it, run again.
- Q: The model is stateless, so how does a chatbot remember the conversation? A: The application stores the messages and resends them inside the context window on every call. When the history gets too long, the app trims or summarises it.
- Q: What is temperature, and what would you set it to? A: It controls how random the token pick is. Near 0 for extraction, classification and code, where I want repeatable output; around 0.7 or higher for creative work.
- Q: Why do LLMs hallucinate, and what do you do about it? A: They generate plausible text, not verified facts, and they only know their training data plus the prompt. I ground the answer in supplied documents, allow "I don't know", ask for quotes and validate the output.
Interview gold: "An LLM is stateless; memory is an application-level concern." Say this and you already sound like an engineer, not a user.
When a chatbot gives you a wrong answer, ask one question before blaming the model: was the correct information anywhere in its context window? Most real-world fixes start there.
Make a file called tokens-notes.md. (1) Run the token counter on your own resume summary and on the same lines written in your mother tongue, and record both counts. (2) Run the temperature sampler and paste the picks at 0 and at 0.7. (3) In three lines, explain why the two runs differ. (4) In one sentence, explain how a chatbot "remembers" earlier messages.
Stuck? That's normal. Ask in the community Discord or email hello@beyondplaced.com. No question is too basic.