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.
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.
- Assemble the promptSystem prompt, tool definitions, and the conversation history are formatted into one long text sequence with role markers.
- TokenizeThe text is split into sub-word pieces (tokens), and each piece is mapped to an integer ID from a fixed vocabulary.
- EmbedEach token ID looks up a row in the embedding matrix and becomes a vector of thousands of numbers.
- Add positionPosition information is mixed in (e.g. RoPE), so the model knows token order.
- 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.
- Unembed → logitsThe final vector at the last position is projected to one score per vocabulary token.
- Softmax + samplingTemperature, top-k and top-p shape the probabilities, and one token is picked.
- Repeat (autoregression)The new token is appended and the model runs again for the next one. A KV cache avoids recomputing earlier tokens.
- StopGeneration ends on an end-of-turn token, a stop sequence,
max_tokens, or a tool call. That reason is the API'sstop_reason. - Detokenize & streamToken IDs are turned back into text and streamed to you, or parsed into structured blocks such as
tool_use.
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
- Tool definitions (name, description, JSON schema) are serialised into the prompt too. That's why tool descriptions use up tokens and strongly influence which tool is picked.
- The model is stateless. It has no memory between API calls. Every request resends the entire conversation, including earlier tool results. "Memory" features (CLAUDE.md, conversation history) work by putting text back into the prompt.
- Prefill: if you end with a partial assistant message, the model simply continues it. That's because generation is just "continue this sequence".
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):
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)
- Start with the 256 possible bytes (UTF-8), so any text, emoji, or language can be represented. Nothing is ever "unknown".
- Count the most frequent adjacent pair in a huge training corpus (e.g.
t+h) and merge it into a new tokenth. - Repeat tens of thousands of times:
th+e→the,␣+the→␣the… - 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
| Effect | Why |
|---|---|
| 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 strings | The model sees straw|berry as chunks, not individual characters |
| Arithmetic on long numbers can be shaky | Numbers are split into irregular chunks |
| Different models give different token counts for the same text | Each model family has its own tokenizer. Use the API's token-counting endpoint, or usage in responses, for exact counts. |
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.
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]
- "Embedding" and "vector" are the same thing here. An embedding is a vector (a list of numbers). "Tokens → embeddings → vectors" is really one step: tokens → embedding vectors.
- The values aren't hand-designed. They're learned in training, so tokens used in similar contexts end up with similar vectors (
" Paris"near" Lyon"," king"near" queen"). - Individual dimensions usually don't mean anything readable. Meaning is spread across many dimensions.
- At this point each vector knows only which token it is, not its position or context.
" bank"has the same starting vector in "river bank" and "bank account". The transformer layers fix that.
Real model sizes (public open models)
| Model | Vocab size | d_model (vector size) | Layers | Attention heads | Context |
|---|---|---|---|---|---|
| GPT-2 small | 50,257 | 768 | 12 | 12 | 1,024 |
| Llama 2 7B | 32,000 | 4,096 | 32 | 32 | 4,096 |
| Llama 3 8B | 128,256 | 4,096 | 32 | 32 (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.
- 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:
| Method | How | Used by |
|---|---|---|
| Sinusoidal (absolute) | Add a fixed sine/cosine pattern per position to each embedding | Original Transformer (2017) |
| Learned absolute | Add 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:
- Query
q = x·WQ: "what am I looking for?" - Key
k = x·WK: "what do I contain?" - Value
v = x·WV: "what will I hand over if you attend to me?"
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 |
|---|---|
The | 0.02 |
animal | 0.61 |
didn't cross | 0.08 |
the street | 0.14 |
because | 0.05 |
it (itself) | 0.10 |
- Causal mask: a token can't attend to future tokens. That's what makes the model a next-token predictor, and it's why generation goes left to right.
- Multi-head: the layer runs many attention "heads" in parallel (e.g. 32), each with its own WQ, WK, WV. Different heads learn different relationships: syntax, coreference, copying, and so on. Their outputs are concatenated and projected back to
d_model. - Cost: every token is compared with every earlier token, so attention compute grows quadratically with sequence length (O(n²)). Long contexts are expensive.
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.
7. Step 5b — The transformer block, stacked N times
- MLP (feed-forward network): applied to each token's vector independently. It expands to roughly 4× width, applies a non-linearity, and projects back. Most of a model's parameters, and much of its "factual knowledge", live here.
- Residual stream: each sub-layer adds its output to the running vector rather than replacing it. Think of the vector as a shared workspace that every layer reads from and writes to.
- Layer norm keeps the numbers in a stable range so deep stacks train well.
- Depth builds meaning: early layers handle syntax and local patterns; middle and late layers handle meaning, facts, and the plan for the next token. By the last layer, the vector at the final position encodes "what should come next".
- Mixture-of-Experts (MoE) variants replace the single MLP with many expert MLPs and a router that sends each token to a few of them. That gives more total parameters at similar compute per token.
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 token | Logit | Probability (T = 1) |
|---|---|---|
Paris | 9.0 | ≈ 0.87 |
a | 6.2 | ≈ 0.05 |
the | 5.8 | ≈ 0.04 |
located | 5.1 | ≈ 0.02 |
| … 128k others | low | tiny |
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
| Control | What it does | Effect |
|---|---|---|
| Temperature (T) | Divide logits by T before softmax | T < 1 sharpens toward the top token (focused, consistent). T > 1 flattens the distribution (diverse, riskier). T → 0 ≈ greedy (always the top token). |
| top-k | Keep only the k most likely tokens | Cuts off the long tail of unlikely tokens |
| top-p (nucleus) | Keep the smallest set whose cumulative probability ≥ p | Adapts to how confident the model is |
| Constrained decoding | Mask out tokens that would break a grammar or JSON schema | The basis of guaranteed-structure outputs |
The capital of France is. Example logits; greyed-out tokens are excluded by top-p.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
| Phase | What happens | Determines |
|---|---|---|
| Prefill | All input tokens are processed in parallel in one pass, and the KV cache is filled | Time to first token (TTFT). Grows with prompt length. |
| Decode | Output tokens are generated one at a time, sequentially | Tokens per second. Total time grows with output length. |
- This is why output tokens cost more than input tokens: each needs its own sequential pass.
- Prompt caching stores the processed state (KV cache) of a stable prefix (tools, system prompt, long documents). Later requests that start with the exact same prefix skip that prefill work, so they're faster and the cached tokens are billed at a much lower rate. Put static content first and changing content last.
- Extended thinking is the same loop: the model generates reasoning tokens before the answer. They're real output tokens, so they cost time and money and use up the token budget.
11. Step 9 — Stopping, and where stop_reason comes from
| What happened during generation | API stop_reason |
|---|---|
| The model sampled its special end-of-turn token | end_turn |
The generated text matched one of your stop_sequences | stop_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 turn | tool_use |
| The prompt plus output hit the model's context window | model_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).
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.
12. Step 10 — Detokenizing, streaming and tool calls
- Detokenization: token IDs are mapped back to their byte sequences and joined into text. Because a multi-byte character can be split across tokens, streaming clients buffer partial bytes.
- Streaming (server-sent events) sends each chunk as it's decoded. That's purely a delivery choice; the model computes the same way either way.
- Tool use: the model was trained to emit a special structured format when it wants a tool. The API parses that into a
tool_usecontent block (name,inputJSON,id). The model never runs anything. Your code (or Claude Code's harness) executes the tool, and the result goes back into the next prompt as atool_result, which is tokenized like any other text. - Structured output: a schema plus constrained decoding guarantees valid shape. Whether the values are correct still depends on the model, so validate the semantics.
13. End-to-end worked example
User asks: "What is the capital of France?"
| # | Stage | Data at this point |
|---|---|---|
| 1 | Chat template | One string: system text + <user>What is the capital of France?</user><assistant> |
| 2 | Tokenize | ~20 integer IDs, e.g. […, 2061, 318, 262, 3139, 286, 4881, 30, …] |
| 3 | Embed | Matrix [20 × d_model] of floats |
| 4 | + Position | Same shape, now order-aware (RoPE is applied inside attention) |
| 5 | N transformer layers | Same shape [20 × d_model], but each vector is now contextual. The last one "knows" an answer about France's capital is due. |
| 6 | Unembed | Logits [vocab_size] for the next token |
| 7 | Softmax + sample | "The" (p≈0.6) is chosen |
| 8 | Loop with KV cache | " capital" → " of" → " France" → " is" → " Paris" → "." |
| 9 | Stop | The end-of-turn token is sampled → stop_reason: "end_turn" |
| 10 | Detokenize / stream | "The capital of France is Paris." with usage: {input_tokens: ~20, output_tokens: 7} |
14. Where the weights come from (training, briefly)
- 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.
- 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.
- 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.
15. Common misconceptions, and how they connect to the exam
| Misconception | Reality | Practical consequence |
|---|---|---|
| "The model reads words or characters" | It reads sub-word tokens | Budget in tokens. Expect weak letter counting. |
| "It remembers our last chat" | Stateless: every call resends the full history | Persist 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 use | Put critical info at the start or end, summarise, trim tool output |
| "Embeddings and vectors are separate steps" | An embedding is a vector | Tokens → embedding vectors → transformer |
| "The LLM searches my vector DB" | Your code retrieves text; the LLM reads it as prompt tokens | Retrieval quality is a pipeline concern, not a model one |
| "The model runs my tools" | It emits a tool_use request; your harness runs it | Validate and authorise in code (hooks, permissions) |
| "Temperature 0 means perfectly deterministic" | Highly consistent, not guaranteed identical | Validate outputs, add retries |
| "A JSON schema guarantees correct data" | It guarantees structure only | Add semantic validation |
| "The model learns from my corrections" | Weights are frozen at inference | Put corrections in the prompt or persistent memory |
16. Self-check quiz
Score: 0 / 0 answered (of 8)
stop_reason: "max_tokens". What does that tell you?max_tokens stop condition before the end-of-turn token was sampled.