How LLMs Work (AI Engg #2)
Type "The capital of France is" into any LLM and it says "Paris". Type it a hundred times and you might get "Paris" ninety-nine times and "the city of light" once. Nothing inside the model “knows” France. There is a stack of matrix multiplications that, for the last token, produces a probability for every word in a 100,000-token vocabulary — and the word Paris happens to sit at the top.
This chapter opens the black box just far enough to be useful at work. You will learn what a token really is, how the next-token loop runs, why temperature/top-k/top-p change behavior, what the context window gates, and where fine-tuning ends and RAG begins. Everything in the later chapters (prompts, context, agents) rests on this machine.
From text to numbers: tokenization
Computers cannot multiply letters. The first step of every LLM call is tokenization: splitting text into units from a fixed vocabulary, then replacing each unit with an integer ID.
You can watch this yourself. In Python:
import tiktoken # OpenAI's tokenizer
enc = tiktoken.encoding_for_model("gpt-4o-mini")
for text in ["cats love fish", "unhappiness", "def f(x): return x**2", "こんにちは"]:
ids = enc.encode(text)
print(repr(text), "->", ids, "->", [enc.decode([i]) for i in ids])
Typical output: "cats love fish" becomes [86093, 3021, 4728] — one token per word here because all three are common. "unhappiness" becomes ["un", "happi", "ness"]. Code and non-English text often take one token per character or per byte.
Three facts follow, and each one costs teams money or quality when ignored:
- Tokens ≠ words. In English, ~1 token ≈ 4 characters ≈ ¾ of a word. In Hindi, Japanese, or minified JavaScript, it can be 1–3 tokens per character. A prompt that fits in 8K tokens in English can blow past 30K in another script.
- Pricing is per token, both directions. Input tokens (your prompt + context) and output tokens (the answer) are billed separately, with output usually 2–4× the price. A bloated system prompt is a recurring cost on every single request.
- The window is measured in tokens. When people say “128K context,” they mean 128,000 tokens total across system + user + assistant + retrieved documents + tool schemas + the answer being generated.
\begin{tikzpicture}[font=\rmfamily,
t/.style={draw, thick, rounded corners=2pt, minimum height=0.75cm, font=\rmfamily\small, inner sep=4pt},
a/.style={->, thick}]
\node[t, fill=blue!10] (w1) at (0,0) {cats};
\node[t, fill=blue!10] (w2) at (1.6,0) {love};
\node[t, fill=blue!10] (w3) at (3.2,0) {fish};
\node[font=\rmfamily\small] at (1.6,-0.9) {text: 3 words};
\node[t, fill=orange!20] (i1) at (0,-2.0) {86093};
\node[t, fill=orange!20] (i2) at (1.6,-2.0) {3021};
\node[t, fill=orange!20] (i3) at (3.2,-2.0) {4728};
\node[font=\rmfamily\small] at (1.6,-2.9) {tokens: integer IDs};
\draw[a] (1.6,-0.7) -- (1.6,-1.5);
\node[font=\rmfamily\small, text=black!60, align=left, anchor=west] at (4.6,-1.0) {annoying $\to$ ["an","noy","ing"]\\$1 \to 3$ tokens, more \$};
\end{tikzpicture}
(Rule of thumb for budgeting: estimate tokens as characters / 4 for English prose, characters / 2 for code, and measure with the real tokenizer before shipping a cost model.)
Inference: the next-token loop
At its core every chat model does one thing: given a sequence, output a probability distribution over the next token.
\[ P(x_{t+1} \mid x_1, x_2, \dots, x_t) \]
Then it samples one token from that distribution, appends it, and repeats. Chat is an illusion built on top: the “assistant” reply is generated token by token, each new token conditioned on the entire conversation so far.
A single forward pass looks like this, from the inside out:
- Tokens → embedding vectors (each ID looks up a learned vector).
- Position information is added (the model otherwise has no order sense).
- Dozens of Transformer blocks: self-attention lets every token look at every earlier token and decide what matters; a feed-forward network transforms each position.
- The final vector for the last position is projected onto the vocabulary, producing logits — one raw score per possible next token.
- Softmax turns logits into probabilities. Sampling picks one. Append. Go to 1.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=4.6cm, minimum height=0.62cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=gray!10] (t) at (0,0) {tokens: [86093, 3021, 4728, ...]};
\node[b, fill=blue!10] (e) at (0,-0.95) {embed + position};
\node[b, fill=orange!15] (b1) at (0,-1.9) {Transformer block $\times N$ (attention + FFN)};
\node[b, fill=green!10] (l) at (0,-2.85) {logits over vocabulary};
\node[b, fill=yellow!25] (s) at (0,-3.8) {softmax $\to$ sample one token};
\draw[a] (t) -- (e); \draw[a] (e) -- (b1); \draw[a] (b1) -- (l); \draw[a] (l) -- (s);
\draw[a, dashed] (s.east) to[out=0,in=0] (t.east);
\node[font=\rmfamily\small, text=black!60, anchor=west] at (2.7,-3.8) {append \& repeat};
\end{tikzpicture}
Two engineering consequences you must internalize:
- Generation is sequential, so it is slow. Each token depends on the previous one — you cannot compute token 50 before token 49. This is why streaming exists (
stream=Truegives you tokens as they are born) and why output length dominates latency and cost. - The model has no memory between calls. Everything it “remembers” must be resent in the prompt. Memory, RAG, and context engineering exist because of this single sentence. There is no hidden state you can leave behind.
Sampling controls: temperature, top-k, top-p
The softmax gives probabilities. How you choose from them is your first real knob.
Let the logits be \(z_i\) for each vocabulary token \(i\), and temperature \(T>0\):
\[ P_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)} \]
- \(T \to 0\): the largest logit dominates; output becomes nearly deterministic. Use for extraction, classification, SQL, grading.
- \(T = 1\): the model’s native distribution. Good default for chat.
- \(T > 1\): flattens the distribution; unlikely tokens get a chance. Use for brainstorming, names, ideas — and expect more fact errors.
Top-k keeps only the \(k\) highest-probability tokens before sampling; top-p (nucleus) keeps the smallest set whose cumulative probability reaches \(p\). Both cut off the long tail of nonsense. Common settings: temperature=0.2, top_p=0.9 for factual work; temperature=0.9, top_p=0.95 for creative.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
bar/.style={draw, thick, fill=cyan!35},
a/.style={->, thick}]
\foreach \x/\h in {0/1.9, 0.7/1.2, 1.4/0.7, 2.1/0.35, 2.8/0.18, 3.5/0.1} {
\fill[cyan!35] (\x,0) rectangle ++(0.5,\h);
\draw[thick] (\x,0) rectangle ++(0.5,\h);
}
\draw[thick] (0,0) -- (4.2,0);
\node[font=\small, anchor=north] at (0.25,-0.1) {Paris};
\node[font=\small, anchor=north] at (0.95,-0.1) {the};
\node[font=\small, anchor=north] at (1.65,-0.1) {a};
\node[font=\small, anchor=north] at (2.35,-0.1) {Lyon};
\node[font=\small, anchor=north] at (3.05,-0.1) {home};
\node[font=\small, anchor=north] at (3.75,-0.1) {banana};
\draw[a, red!70!black] (2.25,0) -- (2.25,2.3) node[above, font=\small, text=red!70!black] {top-k cutoff};
\node[font=\small, text=black!60, anchor=north] at (2.1,-0.85) {tail tokens (Lyon, home, banana) unreachable};
\end{tikzpicture}
One subtlety that trips people up: temperature 0 is not a guarantee. Batch sizes, GPU nondeterminism, and provider-side model updates can still change output. If you need true reproducibility, use exact-match evals with tolerances, not blind trust in temperature=0.
The context window: what fits, what forgets
The context window is the maximum number of tokens the model can attend to in one call — today 128K to 1M for frontier models, 8K–32K for small local ones. It is a hard wall: exceed it and the request errors or gets truncated.
Inside that budget you must fit, in priority order:
- System instructions (your rules).
- Tool/function schemas (each costs tokens, often hundreds).
- Retrieved context (RAG chunks, memory).
- Conversation history.
- The current user message.
- Room for the output (set
max_tokensso the answer is not cut off).
A larger window does not mean perfect recall. The “lost in the middle” effect — long documented and still visible in 2026 models — shows that information buried in the middle of a huge context is used less reliably than information at the start or end. Practical guidance from Anthropic’s context-engineering work: prefer the smallest set of high-signal tokens; compact or summarize when you approach the budget rather than dumping everything.
That is the entire motivation for Chapter 4. For now, remember the failure modes: context rot (attention degrades over long inputs), context poisoning (an untrusted document injects instructions), and context distraction (irrelevant but authoritative-looking text steers the answer).
Training vs inference vs fine-tuning vs RAG
These four words get blurred together in meetings. Separate them for good.
| Term | What happens | Cost | Changes knowledge? |
|---|---|---|---|
| Pre-training | Learn all weights from trillions of tokens | $10M–$1B+ | Yes — this is the knowledge |
| Inference | Run the frozen weights on your prompt | fractions of a cent | No |
| Fine-tuning | Small continued training on your examples | $10s–$1000s | Style/format yes; facts poorly |
| RAG | Retrieve documents into the prompt at runtime | vector DB + tokens | Yes — facts, freshly, with citations |
The decision rule that saves teams months: fine-tune for behavior, retrieve for facts. If the model must answer questions about your changing documents, RAG (Chapter 10). If it must consistently speak in a brand voice or emit a weird legacy format, a small fine-tune can beat endless prompt tweaks. Most production systems use frozen models + RAG, and reserve fine-tuning for narrow style or latency wins on small models.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.5cm, minimum height=0.75cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=red!10] (p) at (-3.1,0) {pre-train\\\$millions};
\node[b, fill=orange!15] (f) at (0,0) {fine-tune\\style, format};
\node[b, fill=green!12] (r) at (3.1,0) {RAG\\facts, freshness};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.9) {runtime inference uses the frozen base model + (optional fine-tune) + retrieved context};
\draw[a] (p) -- (f); \draw[a] (f) -- (r);
\end{tikzpicture}
Putting knobs to work
A concrete, runnable comparison. Same prompt, two temperatures:
from openai import OpenAI
client = OpenAI()
def sample(temp, n=3):
out = []
for _ in range(n):
r = client.chat.completions.create(
model="gpt-4o-mini",
temperature=temp,
max_tokens=25,
messages=[{"role": "user",
"content": "Name one startup idea for dog dentists. One line."}],
)
out.append(r.choices[0].message.content.strip())
return out
print("T=0.0 ->", sample(0.0))
print("T=1.2 ->", sample(1.2))
At T=0.0 you will usually see one repeated idea; at T=1.2 you get variety, some of it nonsensical. That spread is the sampling distribution, made visible.
For a token/cost sense, log usage:
r = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Summarize: " + long_text}],
)
u = r.usage
print(u.prompt_tokens, "in /", u.completion_tokens, "out")
# cost ≈ in/1e6 * in_price + out/1e6 * out_price ; compare models in Chapter 5
Why this matters downstream
Every later chapter is a consequence of this one:
- Prompt engineering (Chapter 3) controls the input distribution so the sampled output is shaped correctly.
- Context engineering (Chapter 4) decides which tokens occupy the window, because attention is finite and noise hurts.
- Models (Chapter 5) is about picking the right frozen weights for your price/latency/quality point.
- RAG (Chapter 10) injects fresh facts because training froze months or years ago.
- Agents (Chapter 11) just call this next-token loop in a loop with tools.
If you understand sampling and the window, none of the rest feels magical.
Pitfalls
- Budgeting by words. A “500-word” system prompt can be 900 tokens in another language. Count with a tokenizer; leave headroom for output.
- Temperature as a quality dial. Turning it up never makes a model “smarter”; it makes it more random. For factual work, keep it low and verify.
- Assuming memory. The model remembers nothing between calls unless you resend it. Stateless by design — design accordingly.
- Fine-tuning for facts. It memorizes unreliably, goes stale, and cannot cite. Use RAG, keep fine-tuning for behavior.
Why is the final answer’s first token slow but streaming fast? What does the context window actually bound?
ASolution
The first token requires a full forward pass over the whole prompt (no output yet), so it feels slow. After that, each token is generated sequentially but arrives as it is produced, so the user sees a stream. The window bounds the sum of all tokens the model can attend to in one call — system, context, history, user message, tool schemas, and the generated answer — and exceeding it truncates or errors.
Next: Prompt Engineering (AI Engg #3) — turning raw next-token output into controlled, structured behavior.