AI · Topic 2 · Foundations

How LLMs work: from your text to the model's reply

Follow a single prompt through the whole pipeline: text becomes tokens, tokens become vectors, vectors pass through dozens of transformer layers, and a probability distribution produces the next token. That step repeats until the model stops. Once you see the pipeline, things like token limits, temperature, prompt caching, stop_reason and "lost in the middle" make sense.

Why it matters explains cost, latency, limits & failure modes ≈ 45–60 min read

1. The journey at a glance

Every request to Claude (or any decoder-only LLM) goes through these stages. The rest of the page explains each one.

  1. Assemble the promptSystem prompt, tool definitions, and the conversation history are formatted into one long text sequence with role markers.
  2. TokenizeThe text is split into sub-word pieces (tokens), and each piece is mapped to an integer ID from a fixed vocabulary.
  3. EmbedEach token ID looks up a row in the embedding matrix and becomes a vector of thousands of numbers.
  4. Add positionPosition information is mixed in (e.g. RoPE), so the model knows token order.
  5. Transformer layers (×N)Each layer runs self-attention (tokens exchange information) and then an MLP (per-token processing), with residual connections. The vectors become richer at each layer.
  6. Unembed → logitsThe final vector at the last position is projected to one score per vocabulary token.
  7. Softmax + samplingTemperature, top-k and top-p shape the probabilities, and one token is picked.
  8. Repeat (autoregression)The new token is appended and the model runs again for the next one. A KV cache avoids recomputing earlier tokens.
  9. StopGeneration ends on an end-of-turn token, a stop sequence, max_tokens, or a tool call. That reason is the API's stop_reason.
  10. Detokenize & streamToken IDs are turned back into text and streamed to you, or parsed into structured blocks such as tool_use.
One sentence to rememberAn LLM is a function that takes a sequence of tokens and returns a probability distribution over the next token. Everything else (chat, tool use, reasoning) comes from calling that function repeatedly.

2. Step 1 — Assembling the prompt (chat template)

The model doesn't receive "a message". It receives one flat sequence. The API turns your structured request (system prompt, tools, messages[]) into that sequence using a chat template: special marker tokens that separate roles and turns.

# What you send (Messages API)
system: "You are a concise geography tutor."
messages: [ {role: "user", content: "What is the capital of France?"} ]

# Conceptually, what the model sees (marker names are illustrative)
<system>You are a concise geography tutor.</system>
<user>What is the capital of France?</user>
<assistant>          ← the model continues writing from here
🎯 Why this mattersLong conversations get more expensive and slower every turn, because the whole history is reprocessed. Hence context management, compaction, and prompt caching.

3. Step 2 — Tokenization: text → token IDs

Neural networks process numbers, not characters. A tokenizer splits text into tokens (frequent sub-word chunks) and maps each one to an integer token ID in a fixed vocabulary.

Worked example

The text The capital of France is through the public GPT-2 tokenizer (Claude uses its own tokenizer with different IDs, but the idea is identical):

The464 capital3139 of286 France4881 is318

Notice the leading space is part of the token (" capital"), and common words are a single token. Rare words get split: something like "tokenization" might become "token" + "ization", and an unusual name might become several fragments.

How the vocabulary is built: Byte-Pair Encoding (BPE)

  1. Start with the 256 possible bytes (UTF-8), so any text, emoji, or language can be represented. Nothing is ever "unknown".
  2. Count the most frequent adjacent pair in a huge training corpus (e.g. t + h) and merge it into a new token th.
  3. Repeat tens of thousands of times: th+e → the, ␣+the → ␣the …
  4. Stop at the target vocabulary size (typically ~32k–200k tokens). At inference time, the same merges are applied to your text.

Consequences you can observe

EffectWhy
English ≈ 3–4 characters per token. Code, JSON, and many non-English languages use more tokens per word.The vocabulary was built mostly from frequent English patterns
Limits and pricing are in tokens (context window, max_tokens, $ per million tokens)The token is the model's unit of work
Models can struggle to count letters ("how many r's in strawberry?") or reverse stringsThe model sees straw|berry as chunks, not individual characters
Arithmetic on long numbers can be shakyNumbers are split into irregular chunks
Different models give different token counts for the same textEach model family has its own tokenizer. Use the API's token-counting endpoint, or usage in responses, for exact counts.
Game · Tokenization

Build a tokenizer

Everyday picture: texting shorthand. People who type “the” and “ing” all day start treating them as single units. Byte-pair encoding does that automatically: it keeps merging the most frequent neighbouring pair of symbols into a new symbol, and the list of merges becomes the vocabulary.

Your mission: below is a tiny training corpus (the number shows how often each word appears). Every word starts as single characters. Choose 5 merges to shrink the corpus to as few tokens as possible.

Merges used 0 / 5 · Corpus size 79 tokens

Most frequent neighbouring pairs. Click one to merge it:

Your vocabulary (learned merges, in order):

4. Step 3 — Embeddings: token IDs → vectors

A token ID like 4881 is just an index. The model's first layer is an embedding matrix of shape [vocab_size × d_model]. Each token ID selects one row, and that row is the token's embedding vector.

vocab_size = 50,257   d_model = 768          # GPT-2 small (public numbers)
E = embedding matrix, shape [50257 × 768]   # learned during training

" France" → id 4881 → E[4881] = [ 0.021, -0.113, 0.487, …, 0.064 ]   # 768 numbers

Prompt of 5 tokens → matrix X of shape [5 × 768]

Real model sizes (public open models)

ModelVocab sized_model (vector size)LayersAttention headsContext
GPT-2 small50,25776812121,024
Llama 2 7B32,0004,09632324,096
Llama 3 8B128,2564,0963232 (8 KV heads)8,192

Anthropic doesn't publish Claude's architecture details. Frontier models are far larger, with context windows of hundreds of thousands of tokens or more, but the pipeline is the same.

⚠️ Don't confuse the two kinds of "embeddings"
  • Token embeddings (this step): internal to the LLM, one vector per token, the input to the transformer.
  • Text embeddings for search/RAG: a separate embedding model (e.g. Voyage AI) turns a whole sentence or document into one vector. Similar meaning gives a high cosine similarity. These vectors go in a vector database for retrieval. The LLM never sees them; it only sees the retrieved text placed into the prompt.

5. Step 4 — Adding position

Attention (next step) is order-blind on its own. "dog bites man" and "man bites dog" would look identical. Models inject position information:

MethodHowUsed by
Sinusoidal (absolute)Add a fixed sine/cosine pattern per position to each embeddingOriginal Transformer (2017)
Learned absoluteAdd a learned vector per position (position 0, 1, 2 …)GPT-2
RoPE (rotary)Rotate the query and key vectors by an angle proportional to position. Attention then depends on relative distance.Llama and most modern LLMs

How position is encoded also limits how long a context the model handles well. Extending context windows mostly comes down to positional-encoding tricks plus training on long documents.

6. Step 5a — Self-attention: tokens share information

Self-attention lets every token look at earlier tokens and pull in relevant information. It's how " it" in "The animal didn't cross the street because it was too tired" picks up meaning from " animal".

Query, Key, Value

From each token's vector x, the layer computes three new vectors using learned weight matrices:

Attention(Q, K, V) = softmax( Q·Kᵀ / √d_k  +  causal_mask ) · V

1. Score:     each query · every key        → how relevant is token j to token i?
2. Scale:     ÷ √d_k                        → keeps softmax from saturating
3. Mask:      −∞ for future positions       → token i may only see tokens ≤ i  (causal)
4. Softmax:   scores → weights summing to 1
5. Mix:       weighted sum of value vectors → the new information for token i
Attention weights for " it" (illustrative)Weight
The0.02
animal0.61
didn't cross0.08
the street0.14
because0.05
it (itself)0.10
💡 Connects to "lost in the middle"Attention is a learned, soft weighting, not perfect lookup. In very long prompts, models tend to use information at the start and end more reliably than in the middle. That's why you put key instructions and facts at the beginning or end, under clear headers.
Game · Self-attention

What does it refer to?

Everyday picture: reading with a highlighter. When you reach a word like “it” or “tired”, your eyes jump back to the word it's about. Attention is a learned, soft version of that glance back, and it can only look backwards: later words are hidden by the causal mask.

Sentence 1 / 6 · Score 0

7. Step 5b — The transformer block, stacked N times

Input vectors [n × d] LayerNorm Multi-head self-attention tokens exchange information + LayerNorm MLP (feed-forward) per-token "thinking" / stored knowledge + Output vectors → next block residual residual × N layers
A pre-norm transformer block. Real models stack dozens of these, each with its own weights.

8. Step 6 — Final vector → logits → probabilities

After the last layer, take the vector at the last position (the token right before the one being predicted). Multiply it by the unembedding matrix [d_model × vocab_size] to get one raw score, or logit, per vocabulary token.

h_last            shape [4096]
logits = h_last · W_U          shape [vocab_size]   e.g. 128,256 scores
probs  = softmax(logits / T)   all positive, sum to 1

For "The capital of France is", the top of the distribution might look like this:

Next tokenLogitProbability (T = 1)
Paris9.0≈ 0.87
a6.2≈ 0.05
the5.8≈ 0.04
located5.1≈ 0.02
… 128k otherslowtiny

The model doesn't output an answer. It outputs a distribution. Picking from it is a separate step.

9. Step 7 — Sampling: choosing the token

ControlWhat it doesEffect
Temperature (T)Divide logits by T before softmaxT < 1 sharpens toward the top token (focused, consistent). T > 1 flattens the distribution (diverse, riskier). T → 0 ≈ greedy (always the top token).
top-kKeep only the k most likely tokensCuts off the long tail of unlikely tokens
top-p (nucleus)Keep the smallest set whose cumulative probability ≥ pAdapts to how confident the model is
Constrained decodingMask out tokens that would break a grammar or JSON schemaThe basis of guaranteed-structure outputs
Prompt: The capital of France is. Example logits; greyed-out tokens are excluded by top-p.
Click "Sample" a few times, then lower or raise the temperature.
Determinism caveatLow temperature makes outputs much more consistent, but even temperature 0 isn't strictly guaranteed to be bit-for-bit identical across calls on large-scale serving infrastructure. For reliability, design for validation and retries rather than assuming identical outputs.
Game · Sampling

The creativity thermostat

Everyday picture: a thermostat for creativity. Turn it down when you need an accountant: precise, consistent, predictable. Turn it up for a brainstorming session. But some problems aren't about temperature at all, and no setting will fix them.

For each task, choose the setting that fits best, or spot when the fix is something else entirely.

10. Step 8 — The generation loop, KV cache, prefill vs decode

One forward pass produces one token. To write a reply, the model loops:

tokens = tokenize(prompt)
while True:
    probs = model(tokens)[-1]          # distribution for the next position
    nxt   = sample(probs, T, top_p)
    if nxt == END_OF_TURN or hit_stop_sequence or len(out) == max_tokens: break
    tokens.append(nxt); out.append(nxt)
    stream(detokenize(nxt))            # this is why responses stream word by word

KV cache

The keys and values for earlier tokens don't change when a new token is added, because of the causal mask. The server caches them, so each new step only computes Q, K, and V for the single new token and attends over the cache. Without it, every step would reprocess the whole sequence.

Two phases with very different performance

PhaseWhat happensDetermines
PrefillAll input tokens are processed in parallel in one pass, and the KV cache is filledTime to first token (TTFT). Grows with prompt length.
DecodeOutput tokens are generated one at a time, sequentiallyTokens per second. Total time grows with output length.

11. Step 9 — Stopping, and where stop_reason comes from

What happened during generationAPI stop_reason
The model sampled its special end-of-turn tokenend_turn
The generated text matched one of your stop_sequencesstop_sequence
Output reached the max_tokens limit you set (text cut mid-thought)max_tokens
The model emitted a complete tool-call block and ended its turntool_use
The prompt plus output hit the model's context windowmodel_context_window_exceeded

So stop_reason isn't something the model "decides to say". It's the server reporting which stop condition fired. Your agent loop branches on it (see the agentic loop).

Game · Generation loop

Be the LLM

Everyday picture: your phone's autocomplete. It suggests the next word, you tap one, and it suggests again. An LLM does exactly that, one token at a time, until something tells it to stop. What that “something” was is the stop_reason the API returns.

UserWhat's the capital of France? Put the answer in <answer> tags.
max_tokens6
stop_sequences["</answer>"]
Tokens generated 0 / 6 · Endings found

12. Step 10 — Detokenizing, streaming and tool calls

13. End-to-end worked example

User asks: "What is the capital of France?"

#StageData at this point
1Chat templateOne string: system text + <user>What is the capital of France?</user><assistant>
2Tokenize~20 integer IDs, e.g. […, 2061, 318, 262, 3139, 286, 4881, 30, …]
3EmbedMatrix [20 × d_model] of floats
4+ PositionSame shape, now order-aware (RoPE is applied inside attention)
5N transformer layersSame shape [20 × d_model], but each vector is now contextual. The last one "knows" an answer about France's capital is due.
6UnembedLogits [vocab_size] for the next token
7Softmax + sample"The" (p≈0.6) is chosen
8Loop with KV cache" capital" → " of" → " France" → " is" → " Paris" → "."
9StopThe end-of-turn token is sampled → stop_reason: "end_turn"
10Detokenize / stream"The capital of France is Paris." with usage: {input_tokens: ~20, output_tokens: 7}

14. Where the weights come from (training, briefly)

  1. Pre-training: the model reads trillions of tokens and learns to predict the next token. The error (cross-entropy loss) is pushed back through the network (backpropagation), nudging every weight: embeddings, attention matrices, MLPs, unembedding. This is where language, facts, and reasoning patterns come from.
  2. Post-training: supervised fine-tuning on high-quality conversations, then reinforcement learning from human and AI feedback (Anthropic uses techniques such as Constitutional AI). This turns a text predictor into a helpful, honest, harmless assistant that follows the chat format, uses tools, and knows when to stop.
  3. Inference (your API call): weights are frozen. Nothing in your prompt changes the model. "Learning" from examples in the prompt (in-context learning, few-shot) happens only within that context window and is gone on the next call.
Knowledge cutoffThe model only "knows" what was in its training data up to a cutoff date. Anything newer, or private, must come in through the prompt: retrieval (RAG), tool calls, MCP, or documents you attach.

15. Common misconceptions, and how they connect to the exam

MisconceptionRealityPractical consequence
"The model reads words or characters"It reads sub-word tokensBudget in tokens. Expect weak letter counting.
"It remembers our last chat"Stateless: every call resends the full historyPersist key facts (CLAUDE.md, notes files, case-facts blocks)
"A bigger context means it uses everything equally"Attention is soft; the middle gets less reliable usePut critical info at the start or end, summarise, trim tool output
"Embeddings and vectors are separate steps"An embedding is a vectorTokens → embedding vectors → transformer
"The LLM searches my vector DB"Your code retrieves text; the LLM reads it as prompt tokensRetrieval quality is a pipeline concern, not a model one
"The model runs my tools"It emits a tool_use request; your harness runs itValidate and authorise in code (hooks, permissions)
"Temperature 0 means perfectly deterministic"Highly consistent, not guaranteed identicalValidate outputs, add retries
"A JSON schema guarantees correct data"It guarantees structure onlyAdd semantic validation
"The model learns from my corrections"Weights are frozen at inferencePut corrections in the prompt or persistent memory

16. Self-check quiz

Score: 0 / 0 answered (of 8)

1 · What is a token embedding?
B. The ID is just an index (A). C describes text embeddings used for RAG, which are a separate model. D describes the output distribution.
2 · Why does a long conversation get slower and more expensive with every turn, even when your new message is short?
D. Every request resends the full conversation as input tokens. Prompt caching and compaction exist to reduce this cost.
3 · In self-attention, what does the causal mask do?
A. Future positions are set to −∞ before the softmax, which makes the model a left-to-right next-token predictor. C describes top-k/top-p.
4 · You set temperature very low. What happens?
C. Temperature only reshapes the softmax. The computation and the model's knowledge are unchanged, so correctness isn't guaranteed.
5 · A response ends with stop_reason: "max_tokens". What does that tell you?
B. The decode loop hit the max_tokens stop condition before the end-of-turn token was sampled.
6 · Why does prompt caching require the cached content to be at the start of the prompt?
D. Because of causal attention, changing an early token changes the state of every later token. An identical prefix gives identical KV state that can be reused.
7 · Why are output tokens slower and pricier than input tokens?
A. Decode is sequential, with one forward pass per token, while prefill handles the whole prompt at once.
8 · In a RAG system, how does the LLM use the vector database?
C. Retrieval happens outside the model. The LLM only sees the retrieved text, tokenized like the rest of the prompt.
📚 Further reading"Attention Is All You Need" (Vaswani et al., 2017); Anthropic's docs on tokens, prompt caching, streaming and extended thinking; Anthropic's interpretability research on how features are represented inside models.