AI Engineering NotesRohit’s interview study guide
Chapter 01

How LLMs Work

What a model actually does with your prompt: tokens, next-token probabilities and the generation loop, sampling, attention and the KV cache, context windows, how training shapes behaviour, reasoning models, hallucination and choosing a model, with a real small model running the examples.

You can build good AI features without knowing the maths, but not without a correct picture of the machine. Almost every production surprise (a bill that grows with every chat turn, a JSON reply cut off halfway, a confident wrong answer, a model that can't count letters, two identical requests with different answers) is explained by one of the ideas in this chapter. Interviewers know that, which is why "explain what happens between my prompt and the reply" is such a common opening question.

The chapter keeps one real model on the bench the whole time: SmolLM2-135M-Instruct, a small open model from Hugging Face (135 million parameters, Apache 2.0 licence, trained on 2 trillion tokens and then instruction-tuned with SFT and DPO, according to its model card). It's far too small to be useful in a product, which is exactly why it's good for learning: it runs on a laptop CPU in a fraction of a second, and it lets you look at the things a hosted API hides, such as the probability of every possible next token. Claude works on the same principles at a vastly larger scale, and the Claude-specific facts (prices, thinking, effort, what the API accepts) come from Anthropic's documentation, checked in December 2026.

How these examples run. Every example is a Node 26 program that was run for this page, and the box under it is its real output. The local-model examples use transformers.js (@huggingface/transformers 4.3.2) with models cached on disk, so the probabilities, tokens and generated text you see are genuine model output, and they're deterministic on the machine that produced them. The Claude examples use the real Anthropic TypeScript SDK (@anthropic-ai/sdk 1.17.0) exactly as production code would, but there's no API key here: the replies at the top of each one, in the block marked "Scripted replies", are written in the exact shape the API returns, and the model's words and token counts in them were written for the example. To run one for real, delete that block and create the client with new Anthropic() and ANTHROPIC_API_KEY set (or after ant auth login).

10 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#What a large language model is

Added

A large language model is a function that takes a sequence of tokens and returns, for every token in its vocabulary, the probability that it comes next. That is the whole interface. Chat, answers, code, tool calls and agents all come from two things around that function: the text you put in front of it, and a loop that keeps asking "what comes next?" and appending the answer. "Large" means billions of learned numbers (parameters, or weights) trained on trillions of tokens of text.

The mental model that holds up best: an autocomplete that read a large part of the internet, books and code, and then went to finishing school. To predict the next word of millions of documents well, it had to pick up grammar, facts, styles, programming languages and patterns of reasoning, because all of those help prediction. That first stage produces a base model, which continues any text you give it but doesn't know it's supposed to be answering anyone. Finishing school comes next: instruction tuning shows it thousands of example conversations so it learns the chat format and to answer rather than ramble; preference tuning teaches it which answers people rate as better; and, for reasoning models, reinforcement learning on problems with checkable answers teaches it to work through a problem before answering. How models are trained goes through each stage.

Four facts follow straight from "a function from tokens to probabilities", and they shape every system you'll build:

  • It's stateless. The model remembers nothing between calls. A "conversation" is your code sending the whole history again every time, which is why chat costs grow with every turn (Context windows).
  • A chat is just text. Messages, roles and the system prompt are flattened into one string with special marker tokens (a chat template) before the model sees them. The example below prints one.
  • The randomness is outside the model. Given the same tokens, the network computes the same probabilities; variety comes from how the next token is picked (Sampling).
  • It only knows what's in its weights and its context. Anything after its training data, or private to your company, has to be put into the prompt, which is what RAG and tools are for.
Base modelInstruction-tuned (chat) modelReasoning (thinking) model
Trained bynext-token prediction on raw text+ supervised examples of conversations, preference tuning+ reinforcement learning on problems with checkable answers
Given "The capital of France is"continues the text like a web pageanswers the question in a turnmay think first, then answers
What you build with itrarely used directly in apps; the starting point for fine-tuningchat, extraction, classification, most featuresmaths, code, planning, multi-step agent work
Examplesmost open families publish a base and an instruct versionSmolLM2-135M-Instruct, every hosted chat modelClaude with adaptive thinking; other vendors' reasoning models

Current Claude models blur the last two columns: they're instruction-tuned models that can also think, and on Claude Opus 5.5 thinking is always available and the model decides how much to use (Reasoning models and thinking).

The example runs the same small model twice: once with a question wrapped in its chat template, once with bare text. Nothing else changes.

chat-is-text.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

// A real 135M-parameter instruction-tuned model, running locally on the CPU.
const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

// Greedy completion: keep appending the single most likely next token.
async function complete(text, maxNewTokens) {
  const inputs = tokenizer(text);
  const output = await model.generate({ ...inputs, max_new_tokens: maxNewTokens, do_sample: false });
  const newIds = Array.from(output[0].data, Number).slice(inputs.input_ids.dims[1]);
  return tokenizer.decode(newIds);
}

// 1. A chat is turned into one long string before the model sees it.
const messages = [{ role: "user", content: "What is the capital of France?" }];
const prompt = tokenizer.apply_chat_template(messages, { tokenize: false, add_generation_prompt: true });
console.log("--- what the model actually reads ---");
console.log(prompt + "▌");
console.log("--- what it writes next ---");
console.log(JSON.stringify(await complete(prompt, 20)));

// 2. The same model, given plain text with no chat format, just continues the text.
console.log("--- plain text, no chat template ---");
console.log(JSON.stringify("The capital of France is" + (await complete("The capital of France is", 12))));
Result
--- what the model actually reads ---
<|im_start|>system
You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
▌
--- what it writes next ---
"The capital of France is Paris.<|im_end|>"
--- plain text, no chat template ---
"The capital of France is the capital of the country.\n\nThe country is divided"
What’s happening
  1. from_pretrained loads the tokenizer and the 4-bit quantised weights (dtype: "q4") from the local cache. The model has 135 million parameters; generate will call it once per new token.
  2. apply_chat_template turns the messages array into one string. Each turn is wrapped in <|im_start|>role … <|im_end|>, and the template quietly added a default system prompt ("You are a helpful AI assistant named SmolLM…") that you never wrote: the template's authors put it there. add_generation_prompt: true appends <|im_start|>assistant and a newline, so the most likely continuation is the assistant's reply (the ▌ marks where the model starts writing).
  3. generate with do_sample: false is greedy decoding: at every step it takes the single most likely token. The model writes The capital of France is Paris. and then produces <|im_end|>, the token it learned to emit at the end of its turn. That token is the model's end-of-sequence token, so generation stops there.
  4. Given the bare text The capital of France is, the very same weights produce the capital of the country. and start a new paragraph. Nothing in that input says "someone asked a question", so the model does what pre-training taught it: continue the text the way a document would.
  5. So there's no separate "answer mode" inside a chat model: a chat API is a template, a generation loop and a stop token. Claude's API does the same on the server with its own format, which Anthropic doesn't publish; you send system and messages as JSON and never see the template.
AdvancedSmall models show mechanics, not quality
Does the model remember your last request?

A user chats with your support bot. Turn 1: "My order number is 4471." Turn 2: "When will it arrive?" Your code sends only the newest message to the API each time. What happens on turn 2, and why?

Show answer

The model has no idea which order the user means.

What’s happening
  1. A model call is a pure function of the tokens in that request. Nothing from turn 1 is stored inside the model; its weights don't change when you call it.
  2. On turn 2 the request contains only "When will it arrive?", so the order number simply isn't in the input. The model will ask for it, or worse, invent a plausible answer.
  3. Chat products feel stateful because the application resends the history: turn 2's request must contain turn 1's user message, the assistant's reply and the new question.
  4. That design choice is yours: you store conversations (chapter 8), decide how much history to resend, and pay for those tokens on every turn.

#Tokens and tokenizers

Added

Models don't read characters or words. They read tokens: integers that index a fixed vocabulary of text pieces, typically common words, word fragments, punctuation, and as a last resort single bytes. OpenAI's o200k_base tokenizer (GPT-4o's) has a vocabulary of 200,006 entries according to gpt-tokenizer; SmolLM2's has 49,152. A tokenizer is a deterministic program that runs before the model: text in, list of ids out, and back again for the reply.

Most modern tokenizers use byte-pair encoding (BPE), a compression trick that Sennrich, Haddow and Birch applied to neural machine translation in 2016 and that GPT-style models adopted. Training a BPE tokenizer is just counting: start with every text split into bytes, find the adjacent pair that occurs most often in a huge corpus, merge it into a new vocabulary entry, and repeat tens of thousands of times. Frequent chunks ( the, model, ing) become single tokens; rare words are spelled out of several pieces; and because single bytes are always in the vocabulary, any string can be encoded, including emoji and languages the tokenizer never saw much of. The mental model is a dictionary of abbreviations built by counting: whatever was common in the tokenizer's training text gets a short code, and everything else costs more codes.

Four consequences matter in practice:

  • Prices, limits and speed are counted in tokens, not characters or words. The same text costs different amounts on different models, and different languages cost very different amounts on the same model.
  • The model can't see letters inside a token. strawberry is a single id (101830 in o200k_base), so "how many r's?" asks the model about spelling it never directly observed. It has to have memorised the spelling from text, which is why letter counting, reversing words and character-level puzzles are weak spots.
  • Leading spaces are part of tokens. strawberry at the start of a string and strawberry after a space are different tokens, sometimes very differently split.
  • Token counts aren't portable between models. Claude's tokenizer isn't public, so counts from gpt-tokenizer or a Hugging Face tokenizer are only rough guides for Claude; Anthropic's own guidance says such counts undercount Claude tokens, and by more on code and non-English text. Even between Claude models the tokenizer changes: Anthropic's token counting documentation says Claude 4.7 and later models use a newer tokenizer that produces approximately 30% more tokens for the same text than earlier models. For real numbers, ask the API with count_tokens (below).
AI LabTokenizer

Type the same sentence in English and in Hindi (or paste a line of your own TypeScript) and compare the token counts. Then try strawberry with and without a leading space, and a long number such as 1234567.

The example runs two real tokenizers, o200k_base (through gpt-tokenizer) and SmolLM2's (through transformers.js), over English, code, Hindi, numbers and the famous strawberry question.

tokenize.mjs
import { encode, decode } from "gpt-tokenizer/encoding/o200k_base"; // OpenAI's o200k_base (GPT-4o's tokenizer)
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

const smol = await AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct");
const model = await AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct", { dtype: "q4" });
const tokenizers = {
  o200k: { ids: (s) => encode(s), piece: (id) => decode([id]) },
  smollm2: { ids: (s) => smol.encode(s, { add_special_tokens: false }), piece: (id) => smol.decode([id]) },
};

const samples = {
  english: "Tokenizers split text into pieces that the model has seen often.",
  code: "const total = items.reduce((sum, x) => sum + x.price, 0);",
  hindi: "मुझे कल सुबह दिल्ली जाना है।", // "I have to go to Delhi tomorrow morning."
  numbers: "Order 1234567 costs $89.99",
  strawberry: "How many r's are in the word strawberry?",
};

for (const [name, text] of Object.entries(samples)) {
  const words = text.split(/\s+/).length;
  console.log(`${name}: ${text.length} characters, ${Buffer.byteLength(text)} UTF-8 bytes, ${words} words`);
  for (const [tname, t] of Object.entries(tokenizers)) {
    const ids = t.ids(text);
    const pieces = ids.map((id) => t.piece(id).replaceAll("\uFFFD", "?")); // ? = part of a character's bytes
    console.log(`  ${tname.padEnd(8)}${String(ids.length).padStart(3)} tokens (${(ids.length / words).toFixed(1)} per word)  ${pieces.join("|")}`);
  }
}
console.log("\nids for ' strawberry':", encode(" strawberry"), "(o200k),", smol.encode(" strawberry", { add_special_tokens: false }), "(smollm2)");

// And what does the model say when asked the strawberry question?
const prompt = smol.apply_chat_template([{ role: "user", content: samples.strawberry }], { tokenize: false, add_generation_prompt: true });
const inputs = smol(prompt);
const out = await model.generate({ ...inputs, max_new_tokens: 20, do_sample: false });
console.log("SmolLM2's answer:", JSON.stringify(smol.decode(Array.from(out[0].data, Number).slice(inputs.input_ids.dims[1]), { skip_special_tokens: true })));
Result
english: 64 characters, 64 UTF-8 bytes, 11 words
  o200k    13 tokens (1.2 per word)  Token|izers| split| text| into| pieces| that| the| model| has| seen| often|.
  smollm2  13 tokens (1.2 per word)  Token|izers| split| text| into| pieces| that| the| model| has| seen| often|.
code: 57 characters, 57 UTF-8 bytes, 10 words
  o200k    19 tokens (1.9 per word)  const| total| =| items|.reduce|((|sum|,| x|)| =>| sum| +| x|.price|,| |0|);
  smollm2  21 tokens (2.1 per word)  const| total| =| items|.|reduce|((|sum|,| x|)| =>| sum| +| x|.|price|,| |0|);
hindi: 28 characters, 74 UTF-8 bytes, 6 words
  o200k     8 tokens (1.3 per word)  म|ुझे| कल| सुबह| दिल्ली| जाना| है|।
  smollm2  34 tokens (5.7 per word)  म|ु|?|?|े| क|?|?| स|ु|?|?|?|?| ?|?|ि|?|?|्|?|?|ी| ?|?|ा|न|ा| ?|?|?|?|?|?
numbers: 26 characters, 26 UTF-8 bytes, 4 words
  o200k    10 tokens (2.5 per word)  Order| |123|456|7| costs| $|89|.|99
  smollm2  16 tokens (4.0 per word)  Order| |1|2|3|4|5|6|7| costs| $|8|9|.|9|9
strawberry: 40 characters, 40 UTF-8 bytes, 8 words
  o200k    10 tokens (1.3 per word)  How| many| r|'s| are| in| the| word| strawberry|?
  smollm2  10 tokens (1.3 per word)  How| many| r|'s| are| in| the| word| strawberry|?

ids for ' strawberry': [ 101830 ] (o200k), [ 35199 ] (smollm2)
SmolLM2's answer: "The word strawberry has 2 r's."
What’s happening
  1. Each tokenizer turns the string into ids; decode([id]) turns one id back into its text piece so you can see the boundaries (|). A ? means the piece is only part of a character's UTF-8 bytes, so it isn't printable on its own.
  2. English is cheap on both: 13 tokens for 11 words (1.2 per word), and the splits are identical, because common English words are single tokens in any vocabulary trained mostly on English. Tokenizers is rare enough to need two pieces (Token|izers).
  3. Code costs more per "word" (1.9 and 2.1): operators and brackets are tokens of their own. o200k_base has .reduce and .price as single tokens, while SmolLM2 splits off the dot, so the same line is 19 tokens in one and 21 in the other.
  4. Hindi shows the biggest gap. The sentence is 28 characters but 74 UTF-8 bytes (most Devanagari characters take 3 bytes). o200k_base was trained on plenty of Hindi and needs 8 tokens; SmolLM2, whose model card says it mainly understands English, has few Devanagari merges and falls back to raw bytes: 34 tokens, 5.7 per word, with most pieces being fragments of a single character.
  5. Numbers are split by rule before BPE runs: o200k_base groups digits in threes (123|456|7), SmolLM2 gives every digit its own token (its pre-tokenizer setting individual_digits: true). Either way the model never sees "1234567" as one quantity, which is part of why arithmetic on long numbers is unreliable without a calculator tool.
  6. Strawberry: in the question the word is one token ( strawberry, id 101830 in o200k_base, 35199 in SmolLM2). The model receives a single number with no letters in it, and when the program asks SmolLM2 the question it answers The word strawberry has 2 r's. (there are 3). Frontier models usually get it right now, from memorised spelling or by thinking it through letter by letter, but the root cause of the classic failure is visible right here.
AdvancedBPE from scratch

Training a BPE tokenizer is short enough to write out. This version works on characters and a ten-word corpus instead of bytes and terabytes, but the algorithm is the same one that built the vocabularies above: count adjacent pairs, merge the most frequent, repeat, and remember the merges in order.

bpe.mjsPlayground ↗
// Byte-pair encoding, trained from scratch on a toy corpus (the classic example from Sennrich et al., 2016).
const corpus = "low low low low low lower lower newest newest newest newest newest newest widest widest widest";

// Start with every word as a list of single characters, plus an end-of-word marker.
const words = new Map();
for (const w of corpus.split(" ")) words.set(w, (words.get(w) ?? 0) + 1);
let vocab = [...words].map(([w, count]) => ({ symbols: [...w, "_"], count }));

function countPairs() {
  const pairs = new Map();
  for (const { symbols, count } of vocab)
    for (let i = 0; i < symbols.length - 1; i++) {
      const pair = symbols[i] + " " + symbols[i + 1];
      pairs.set(pair, (pairs.get(pair) ?? 0) + count);
    }
  return pairs;
}
function applyMerge(symbols, [a, b]) {
  const out = [];
  for (let i = 0; i < symbols.length; i++) {
    if (symbols[i] === a && symbols[i + 1] === b) { out.push(a + b); i++; }
    else out.push(symbols[i]);
  }
  return out;
}

// Training: repeatedly merge the most frequent adjacent pair. Each merge becomes a rule.
const merges = [];
for (let step = 1; step <= 8; step++) {
  const [best, freq] = [...countPairs()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))[0];
  const pair = best.split(" ");
  merges.push(pair);
  vocab = vocab.map((v) => ({ ...v, symbols: applyMerge(v.symbols, pair) }));
  console.log(`merge ${step}: ${pair.join(" + ").padEnd(10)} (seen ${freq}x) -> ${vocab.map((v) => v.symbols.join(" ")).join(" | ")}`);
}

// Encoding a word: replay the merges in the order they were learned.
const encodeWord = (w) => merges.reduce((symbols, pair) => applyMerge(symbols, pair), [...w, "_"]);
for (const w of ["lowest", "newer", "wider", "zebra"]) console.log(`${w.padEnd(7)} -> ${encodeWord(w).join(" | ")}`);
Result
merge 1: e + s      (seen 9x) -> l o w _ | l o w e r _ | n e w es t _ | w i d es t _
merge 2: es + t     (seen 9x) -> l o w _ | l o w e r _ | n e w est _ | w i d est _
merge 3: est + _    (seen 9x) -> l o w _ | l o w e r _ | n e w est_ | w i d est_
merge 4: l + o      (seen 7x) -> lo w _ | lo w e r _ | n e w est_ | w i d est_
merge 5: lo + w     (seen 7x) -> low _ | low e r _ | n e w est_ | w i d est_
merge 6: e + w      (seen 6x) -> low _ | low e r _ | n ew est_ | w i d est_
merge 7: ew + est_  (seen 6x) -> low _ | low e r _ | n ewest_ | w i d est_
merge 8: n + ewest_ (seen 6x) -> low _ | low e r _ | newest_ | w i d est_
lowest  -> low | est_
newer   -> n | ew | e | r | _
wider   -> w | i | d | e | r | _
zebra   -> z | e | b | r | a | _
What’s happening
  1. The corpus becomes a table of distinct words with counts (low ×5, lower ×2, newest ×6, widest ×3), each split into characters plus _ to mark the end of a word, so suffixes and prefixes can be told apart.
  2. countPairs counts every adjacent pair, weighted by how often the word occurs. e s appears in newest (6) and widest (3), 9 times in all, more than any other pair, so merge 1 creates the symbol es.
  3. Merges build on merges: es + t becomes est, then est + _ becomes est_, a token meaning "word ending in est". By merge 5, low is one symbol, and by merge 8 the frequent word newest_ is a single token. Ties are broken alphabetically so the run is deterministic.
  4. Encoding replays the merges in the order they were learned. lowest was never in the corpus, but it comes out as low | est_: two meaningful pieces. newer and wider only get partial merges, and zebra gets none, so it's spelled letter by letter: rare text costs more tokens.
  5. Real tokenizers do the same thing over bytes, on billions of words, for tens of thousands of merges, with a pre-tokenizer that first splits text on spaces, punctuation and digits. That's why o200k_base knows strawberry as one token and why a language that was rare in its training data costs several tokens per word.
AdvancedCounting Claude tokens with count_tokens

Because Claude's tokenizer isn't published, the count has to come from the API: POST /v1/messages/count_tokens takes the same model, system, messages and tools you'd send to create a message and returns input_tokens. According to Anthropic's token counting documentation (December 2026) it's free to use, with its own requests-per-minute limits separate from message creation, and the result is an estimate that can differ from the billed input by a small amount. That makes it the right tool for "will this fit?" checks and cost estimates before you send a big request. The example sends the request from Anthropic's documentation, so the scripted reply is the count the documentation shows for it.

count-tokens.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run") ---------------------------------------------
// The count is the one Anthropic's token counting documentation shows for this exact request.
const fetch = async (url, init) => {
  console.log(`POST ${new URL(url).pathname}`);
  console.log(`body: ${init.body}`);
  return Response.json({ input_tokens: 14 });
};
const client = new Anthropic({ apiKey: "sk-ant-test", fetch }); // for real: new Anthropic()
// ----------------------------------------------------------------------------------------------

const PRICE_PER_MTOK = { input: 4, output: 20 }; // Claude Opus 5.5, US dollars per million tokens

const request = {
  model: "claude-opus-5-5",
  system: "You are a scientist",
  messages: [{ role: "user", content: "Hello, Claude" }],
};
const { input_tokens } = await client.messages.countTokens(request);
const maxTokens = 1024; // the max_tokens you plan to send: the most output you can be billed for
const worstCase = (input_tokens * PRICE_PER_MTOK.input + maxTokens * PRICE_PER_MTOK.output) / 1e6;
console.log(`input tokens: ${input_tokens}; worst-case cost of the call: $${worstCase.toFixed(6)}`);
Result
POST /v1/messages/count_tokens
body: {"model":"claude-opus-5-5","system":"You are a scientist","messages":[{"role":"user","content":"Hello, Claude"}]}
input tokens: 14; worst-case cost of the call: $0.020536
What’s happening
  1. The scripted fetch prints what the SDK actually sends. client.messages.countTokens(request) posts to /v1/messages/count_tokens with the model, system prompt and messages as JSON, the same shape as a real messages.create call minus max_tokens.
  2. The reply is { input_tokens } (the SDK type is MessageTokensCount): 14 for this request, as in Anthropic's documentation. It's specific to the model you pass, and the documentation notes that it may include a few tokens Anthropic adds automatically, which you aren't billed for.
  3. The cost estimate multiplies by the price list: input at $4 and output at $20 per million tokens for Claude Opus 5.5. Output can't be counted in advance, so the worst case uses max_tokens, the most you can be billed for.
  4. The worst case is $0.020536, about two cents, nearly all of it the 1,024 possible output tokens. The habit worth building: decide max_tokens deliberately and estimate before sending anything large. Counting tokens and estimating cost builds a fuller calculator, including prompt-caching prices.
Leading spaces

How many tokens is strawberry at the start of a string, and how many is strawberry (with a space before it), in o200k_base?

Show answer

Three and one.

What’s happening
  1. BPE vocabularies store words together with the space in front of them, because that's how words appear in running text: strawberry is common, so it earned a single entry (id 101830).
  2. strawberry with no space is how the word appears only at the very start of a text or after punctuation such as a quote or a bracket. That form is rarer, so it never got its own merge and is built from pieces: st|raw|berry, 3 tokens (the example's output shows the same 3-piece split in SmolLM2's tokenizer).
  3. Strawberry with a capital splits differently again (Str|aw|berry in o200k_base). Case and spacing change tokens, which is one reason a prompt with odd formatting can behave slightly differently from a clean one.

#Next-token prediction and the generation loop

Added

One call of the model, a forward pass, reads the whole token sequence at once and produces, at every position, a score for every vocabulary entry: SmolLM2 produces 49,152 scores per position. These raw scores are called logits. Only the last position matters for generation, because it's the model's prediction of the token after everything so far. A softmax turns those scores into probabilities that add up to 1. Then the generation loop does three things, over and over: pick one token from the distribution, append it, run the model again.

The mental model is a typist who can only type one character at a time, and before each keystroke re-reads everything written so far. The prompt is read in one go (that phase is called prefill, and the GPU can process all its tokens in parallel), but the reply comes out strictly one token at a time (decode), because each token depends on the one before it. That single fact explains three things you'll meet in production:

  • Output tokens cost more than input tokens. Every Claude model's output price is five times its input price ($4 vs $20 per million tokens on Claude Opus 5.5, $0.10 vs $0.50 on Claude Haiku 5.5). Prefill is parallel work; decode is a sequential pass per token.
  • Latency has two parts. Time to first token is mostly prefill (it grows with prompt length), and then tokens per second is decode speed (it multiplies with output length). Streaming exists because the reply is produced left to right anyway, so you may as well show it as it comes (Streaming responses).
  • Something must stop the loop. Either the model emits its end-of-turn token (the API reports stop_reason: "end_turn"), or the reply reaches your max_tokens (stop_reason: "max_tokens", and the text is cut off mid-sentence), or it produces one of your stop_sequences.
stops at the end-of-turn token or at max_tokens Tokens so far prompt + reply so far [1, 9690, 198, …] Model one forward pass 30 layers, 135M weights Probabilities one per vocabulary entry " Paris" 0.886 Pick one token greedy: the top one sampling: weighted draw append the chosen token, run the model again pass 1 reads the whole prompt in parallel (prefill); every later pass adds one token (decode)
The generation loop: one forward pass per new token, until a stop token or max_tokens.

The example makes one forward pass over The capital of France is and prints the eight most likely next tokens with their raw scores and probabilities.

next-token.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

const inputs = tokenizer("The capital of France is");
const { logits } = await model(inputs); // one forward pass over the whole prompt
const [batch, positions, vocab] = logits.dims;
console.log(`logits shape: [${batch}, ${positions}, ${vocab}]  (1 prompt, ${positions} token positions, ${vocab} scores each)`);

// Only the last position predicts the *next* token. Turn its scores into probabilities (softmax).
const scores = Array.from(logits.data.subarray((positions - 1) * vocab, positions * vocab));
const max = Math.max(...scores);
const exps = scores.map((s) => Math.exp(s - max));
const total = exps.reduce((a, b) => a + b, 0);
const probs = exps.map((e) => e / total);

const ranked = [...probs.keys()].sort((a, b) => probs[b] - probs[a]);
let cumulative = 0;
console.log("rank  token         score   probability  cumulative");
for (const [rank, tokenId] of ranked.slice(0, 8).entries()) {
  cumulative += probs[tokenId];
  console.log(
    `${String(rank + 1).padStart(4)}  ${JSON.stringify(tokenizer.decode([tokenId])).padEnd(12)}${scores[tokenId].toFixed(2).padStart(7)}` +
      `${(probs[tokenId] * 100).toFixed(1).padStart(12)}%${(cumulative * 100).toFixed(1).padStart(11)}%`,
  );
}
const paris = tokenizer.encode(" Paris", { add_special_tokens: false })[0];
console.log(`" Paris" is token ${paris}; the other ${(ranked.length - 8).toLocaleString("en-GB")} tokens share the remaining ${((1 - cumulative) * 100).toFixed(1)}%`);
Result
logits shape: [1, 5, 49152]  (1 prompt, 5 token positions, 49152 scores each)
rank  token         score   probability  cumulative
   1  " the"        18.27        49.1%       49.1%
   2  " Paris"      17.75        29.2%       78.3%
   3  " located"    15.12         2.1%       80.5%
   4  " called"     14.74         1.4%       81.9%
   5  ","           14.43         1.1%       83.0%
   6  " a"          14.08         0.7%       83.7%
   7  " par"        14.08         0.7%       84.5%
   8  " not"        13.92         0.6%       85.1%
" Paris" is token 7042; the other 49,144 tokens share the remaining 14.9%
What’s happening
  1. model(inputs) is one forward pass. The output tensor has shape [1, 5, 49152]: one sequence, five token positions (The, capital, of, France, is), and a score for each of the 49,152 vocabulary entries at each position. Every position predicts its own next token; that's what makes training efficient, but for generation only the last row is used.
  2. The scores are unbounded numbers (18.27 for the). Softmax exponentiates them and divides by the sum, so they become probabilities; subtracting the maximum first (s - max) keeps Math.exp from overflowing without changing the result. Because of the exponent, a gap of about half a point in score (18.27 vs 17.75) already means 49.1% against 29.2%.
  3. The top answer isn't Paris but the (49.1%), with Paris second (29.2%). The model isn't answering a question; it's predicting how this text continues, and "The capital of France is the city of…" is a perfectly common sentence. With the chat template, the same model gives Paris 88.6% at the same point (the next example and Why models hallucinate show it).
  4. The top 8 tokens hold 85.1% of the probability; the other 49,144 tokens share the remaining 14.9%. That long tail is why the way you pick matters so much (Sampling).
  5. This list is what a model gives you at each step. Hosted APIs like Claude's don't return these probabilities (the Messages API response has no log-probability field); they pick for you and return text. Seeing them on a local model is the best way to build intuition.
AdvancedThe generation loop, step by step

Here is the loop written out by hand with greedy decoding, on the chat-formatted question. It deliberately does the simple, slow thing (re-reading the whole sequence on every step) so the logic is plain; Transformers and attention shows the KV cache that removes that waste.

generation-loop.mjs
import { AutoTokenizer, AutoModelForCausalLM, Tensor } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

const prompt = tokenizer.apply_chat_template(
  [{ role: "user", content: "What is the capital of France?" }],
  { tokenize: false, add_generation_prompt: true },
);
const ids = Array.from(tokenizer(prompt).input_ids.data, Number);
const promptLength = ids.length;
const stopId = tokenizer.eos_token_id; // <|im_end|>: the token the model emits to end its turn
const maxNewTokens = 20;
let forwardPasses = 0;

console.log(`prompt: ${promptLength} tokens; stop token: ${JSON.stringify(tokenizer.decode([stopId]))} (id ${stopId})`);
for (let step = 1; step <= maxNewTokens; step++) {
  const input_ids = new Tensor("int64", BigInt64Array.from(ids.map(BigInt)), [1, ids.length]);
  const attention_mask = new Tensor("int64", new BigInt64Array(ids.length).fill(1n), [1, ids.length]);
  const { logits } = await model({ input_ids, attention_mask }); // re-reads the whole sequence every step
  forwardPasses++;

  const V = logits.dims[2];
  const scores = logits.data.subarray((ids.length - 1) * V, ids.length * V);
  let best = 0;
  for (let i = 1; i < V; i++) if (scores[i] > scores[best]) best = i; // greedy: take the top score
  let total = 0;
  for (let i = 0; i < V; i++) total += Math.exp(scores[i] - scores[best]);

  console.log(`step ${String(step).padStart(2)}: ${JSON.stringify(tokenizer.decode([best])).padEnd(10)} p=${(1 / total).toFixed(3)}`);
  if (best === stopId) break;
  ids.push(best); // the new token becomes part of the input for the next step
}
console.log(`answer: ${JSON.stringify(tokenizer.decode(ids.slice(promptLength)))}`);
console.log(`forward passes: ${forwardPasses}, one per generated token (the prompt itself was read in parallel inside each pass)`);
Result
prompt: 37 tokens; stop token: "<|im_end|>" (id 2)
step  1: "The"      p=0.336
step  2: " capital" p=0.979
step  3: " of"      p=0.984
step  4: " France"  p=0.951
step  5: " is"      p=0.654
step  6: " Paris"   p=0.886
step  7: "."        p=0.762
step  8: "<|im_end|>" p=0.853
answer: "The capital of France is Paris."
forward passes: 8, one per generated token (the prompt itself was read in parallel inside each pass)
What’s happening
  1. The chat template turns the question into 37 tokens. tokenizer.eos_token_id is 2, the id of <|im_end|>: the model's way of saying "my turn is over", and the loop's stop condition.
  2. Each step builds the input tensors from the whole sequence so far and runs one forward pass. Then it scans the last position's 49,152 scores for the highest one (greedy) and computes that token's probability: 1 / total works because every term was taken relative to the best score, so the best token's own term is exp(0) = 1.
  3. The model writes The (only 33.6% sure: it could also have started with Paris or The capital), then capital, of, France at over 95% each, because once it has chosen to restate the question the words are predictable. Paris comes at step 6 with 88.6%.
  4. At step 8 the model emits <|im_end|> with 85.3%, and the loop breaks without appending it. The answer is exactly the 7 tokens before it: The capital of France is Paris.
  5. 8 forward passes for 7 tokens of answer: one per generated token, plus the one that produced the stop token. If you set maxNewTokens to 4, the loop would stop after France with no full stop, which is what stop_reason: "max_tokens" means in an API response: cut off, not finished.
Where does the time go?

A request sends 10,000 input tokens and gets 500 output tokens back. Which phase does the server run once, and which does it run 500 times?

Show answer

Prefill runs once; decode runs about 500 times.

What’s happening
  1. Prefill: one forward pass over all 10,000 prompt tokens. The work is large, but it's parallel, so it finishes in one go and produces the first output token.
  2. Decode: each of the remaining output tokens needs another forward pass that can't start until the previous token is known: roughly 500 sequential steps in total.
  3. That's why time to first token depends mostly on the prompt (and on queueing), while the time after that depends on how much the model writes.
  4. In an interview, the practical conclusion is the useful part: to make a feature feel faster, stream the reply and shorten the output; to make the first token come sooner, shorten or cache the prompt (Prompt caching).

#Sampling: temperature, top-p and top-k

Added

The model hands you a probability distribution; a decoding strategy decides which token to take from it. Greedy decoding always takes the most likely token. It's deterministic, but it tends to be bland and can get stuck repeating itself, because repeating a phrase makes the phrase itself more likely. Sampling instead makes a weighted random draw: a token with 24% probability is picked about a quarter of the time. That's where variety comes from, and it's why the same prompt can produce different answers.

Three knobs reshape the distribution before the draw. The mental model is a weighted die:

  • Temperature changes how lopsided the die is. Every score is divided by T before the softmax: below 1 the favourites get even more likely (towards greedy), above 1 the distribution flattens and long-shot tokens get a real chance (towards gibberish). T = 1 is the model's raw distribution.
  • Top-k removes all faces except the k most likely, then rescales the rest to add up to 1.
  • Top-p (nucleus sampling) keeps the smallest set of most likely tokens whose probabilities add up to at least p. Unlike top-k it adapts: when the model is confident, the set is tiny; when it's unsure, the set is large.

Open models and local servers take these settings. transformers.js's generate has do_sample, temperature, top_k and top_p; Ollama's documented defaults (checked December 2026) are temperature 0.8, top_k 40 and top_p 0.9, with a seed option for repeatable output.

Current Claude models don't. Anthropic's documentation says temperature, top_p and top_k aren't supported on Claude 4.7 and later models, and from API version 2026-10-21 a request that sends any of them gets a 400 error, even at the default value. The TypeScript SDK sends that version from 1.0.0 onwards (1.17.0, used here, sends anthropic-version: 2026-10-21), and its types no longer have the three fields. Requests sample with the defaults, temperature 1.0 included. What replaces the knobs is the rest of this course: effort for how hard the model thinks (Reasoning models and thinking), prompting for tone and creativity, structured outputs for format, and evals that run each case several times to measure consistency rather than assuming it.

AI LabNext token and sampling

Type a prompt such as My favourite programming language is and drag the temperature slider from 0.2 to 1.5: watch Python's share fall and the tail grow. Then set top-p to 0.9 and count how many tokens stay in play.

The example takes the real scores SmolLM2 gives the token after My favourite programming language is and applies each setting to them.

sampling.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

// The real scores (logits) for the token after the prompt: one per vocabulary entry.
const inputs = tokenizer("My favourite programming language is");
const { logits } = await model(inputs);
const [, n, V] = logits.dims;
const scores = Array.from(logits.data.subarray((n - 1) * V, n * V));

const softmax = (xs) => {
  const max = Math.max(...xs);
  const exps = xs.map((x) => Math.exp(x - max));
  const sum = exps.reduce((a, b) => a + b, 0);
  return exps.map((e) => e / sum);
};
const renormalise = (probs, keep) => {
  const kept = probs.map((p, i) => (keep.has(i) ? p : 0));
  const sum = kept.reduce((a, b) => a + b, 0);
  return kept.map((p) => p / sum);
};
const byProbability = (probs) => [...probs.keys()].sort((a, b) => probs[b] - probs[a]);

// Temperature divides every score before the softmax.
const withTemperature = (t) => softmax(scores.map((s) => s / t));
// Top-k keeps the k most likely tokens.
const topK = (probs, k) => renormalise(probs, new Set(byProbability(probs).slice(0, k)));
// Top-p keeps the smallest set of most likely tokens whose probabilities add up to at least p.
const topP = (probs, p) => {
  const keep = new Set();
  let mass = 0;
  for (const i of byProbability(probs)) {
    keep.add(i);
    mass += probs[i];
    if (mass >= p) break;
  }
  return renormalise(probs, keep);
};

const watch = byProbability(softmax(scores)).slice(0, 5);
const pct = (p) => `${(p * 100).toFixed(1).padStart(5)}%`;
const show = (label, probs) => {
  const shown = watch.reduce((s, i) => s + probs[i], 0);
  const candidates = probs.filter((p) => p > 0).length;
  const cells = watch.map((i) => `${tokenizer.decode([i]).trim().padEnd(8)}${pct(probs[i])}`).join("  ");
  console.log(`${label.padEnd(13)}${cells}  rest${pct(1 - shown)}  (${candidates.toLocaleString("en-GB")} candidates)`);
};

show("T = 0.5", withTemperature(0.5));
show("T = 1 (raw)", withTemperature(1));
show("T = 1.5", withTemperature(1.5));
show("top-k = 3", topK(withTemperature(1), 3));
show("top-p = 0.9", topP(withTemperature(1), 0.9));
show("T 0.5, p 0.9", topP(withTemperature(0.5), 0.9));
Result
T = 0.5      Python   69.4%  Java     16.1%  not       4.6%  probably  2.3%  to        2.1%  rest  5.5%  (49,152 candidates)
T = 1 (raw)  Python   24.0%  Java     11.5%  not       6.1%  probably  4.3%  to        4.2%  rest 49.8%  (49,152 candidates)
T = 1.5      Python    6.4%  Java      3.9%  not       2.6%  probably  2.1%  to        2.0%  rest 83.0%  (49,152 candidates)
top-k = 3    Python   57.5%  Java     27.7%  not      14.8%  probably  0.0%  to        0.0%  rest  0.0%  (3 candidates)
top-p = 0.9  Python   26.6%  Java     12.8%  not       6.8%  probably  4.8%  to        4.7%  rest 44.3%  (97 candidates)
T 0.5, p 0.9 Python   77.1%  Java     17.9%  not       5.1%  probably  0.0%  to        0.0%  rest  0.0%  (3 candidates)
What’s happening
  1. scores is the real last-position row of logits, 49,152 numbers. Every setting below works on these same numbers; only the picking rule changes. watch holds the five most likely tokens at T = 1, so each row shows the same columns.
  2. Temperature: at T = 1 (the raw distribution) Python has 24.0%, Java 11.5%, and 49.8% of the probability sits outside the top five. Dividing the scores by 0.5 doubles the gaps between them before exponentiating, so Python jumps to 69.4% and the tail shrinks to 5.5%. Dividing by 1.5 shrinks the gaps: Python falls to 6.4% and 83.0% of draws would land somewhere in the long tail of odd tokens.
  3. Top-k = 3 throws away everything but Python, Java and not, and rescales those three to add up to 100% (57.5%, 27.7%, 14.8%). It's a blunt tool: three candidates whether the model is sure or not.
  4. Top-p = 0.9 has to keep 97 tokens to reach 90% of the probability, because the top five only hold 50.2%. The visible five each get a little bigger (26.6% instead of 24.0%) because the 10% tail beyond those 97 tokens was cut and the rest rescaled. Had the model been confident, a couple of tokens would have reached 90%.
  5. Combining them is normal: T = 0.5 first sharpens the distribution so much that Python, Java and not alone pass 90%, so top-p leaves just 3 candidates. Ollama's defaults (T 0.8, top_k 40, top_p 0.9) are such a combination.
  6. Nothing here changed the model; the same forward pass serves every setting. That's why sampling settings are per request on open models, and why they're cheap to experiment with.
AdvancedGreedy loops and sampled variety

The real effect shows up over a whole reply. This example writes the same haiku request five ways: greedy, three samples at T = 0.7 with top-p 0.9, and one at T = 1.5. The random draws use a small seeded generator (mulberry32), so the output is reproducible; with a different seed you'd get different poems. For speed, the sampler ignores tokens with a probability below one in ten million, which changes nothing you could see. It uses the KV cache explained in Transformers and attention, so only the new token is fed in at each step.

sampling-runs.mjs
import { AutoTokenizer, AutoModelForCausalLM, Tensor, DynamicCache } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

function mulberry32(seed) { // small seeded PRNG, so every run prints the same samples
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function pick(scores, { temperature, topP, random }) {
  if (temperature === 0) return scores.indexOf(Math.max(...scores)); // greedy
  const max = Math.max(...scores);
  const exps = scores.map((s) => Math.exp((s - max) / temperature));
  const sum = exps.reduce((a, b) => a + b, 0);
  const order = [...exps.keys()].filter((i) => exps[i] / sum > 1e-7).sort((a, b) => exps[b] - exps[a]);
  const kept = [];
  let mass = 0;
  for (const i of order) { kept.push(i); mass += exps[i] / sum; if (mass >= topP) break; }
  let r = random() * mass;
  for (const i of kept) { r -= exps[i] / sum; if (r <= 0) return i; }
  return kept.at(-1);
}

const tensor = (ids) => new Tensor("int64", BigInt64Array.from(ids.map(BigInt)), [1, ids.length]);
const ones = (n) => new Tensor("int64", new BigInt64Array(n).fill(1n), [1, n]);

async function generate(prompt, settings, maxTokens = 32) {
  const ids = Array.from(tokenizer(prompt).input_ids.data, Number);
  let feed = ids.slice(), cache = null; const out = [];
  for (let step = 0; step < maxTokens; step++) {
    const res = await model({ input_ids: tensor(feed), attention_mask: ones(ids.length), ...(cache && { past_key_values: cache }) });
    const V = res.logits.dims[2];
    const scores = Array.from(res.logits.data.subarray((feed.length - 1) * V, feed.length * V));
    const next = pick(scores, settings);
    if (next === tokenizer.eos_token_id) break;
    out.push(next); ids.push(next); feed = [next];
    cache = new DynamicCache(Object.fromEntries(Object.entries(res).filter(([k]) => k.startsWith("present")).map(([k, v]) => [k.replace("present", "past_key_values"), v])));
  }
  return tokenizer.decode(out);
}

const prompt = tokenizer.apply_chat_template([{ role: "user", content: "Write a haiku about tokens." }], { tokenize: false, add_generation_prompt: true });
console.log("greedy      :", JSON.stringify(await generate(prompt, { temperature: 0 })));
for (const seed of [1, 2, 3]) console.log(`T 0.7 seed ${seed}:`, JSON.stringify(await generate(prompt, { temperature: 0.7, topP: 0.9, random: mulberry32(seed) })));
for (const seed of [1]) console.log(`T 1.5 seed ${seed}:`, JSON.stringify(await generate(prompt, { temperature: 1.5, topP: 1, random: mulberry32(seed) })));
Result
greedy      : "In the token world, a token is a token is a token is a token is a token is a token is a token is a token is a token is"
T 0.7 seed 1: "The token is like a thread,\nA few threads, a few strings, a few words,\nA token, a token, a token,\nA"
T 0.7 seed 2: "\"The token, the token's light,\nThe token's pulse, the token's rise,\nThe token's light, the token's light,\n"
T 0.7 seed 3: "\"The token is the light, the air, the sky, the flower. The token is the heart, the soul, the pain, the love. The"
T 1.5 seed 1: "as tokens bend revenceptions grasp snacks barcheswhelped expungenes epiphagic thecat recaphuman modeltriedead sacrificistetraphagsellan language"
What’s happening
  1. pick does the decoding. With temperature: 0 it returns the top score (greedy). Otherwise it applies the temperature inside the exponent, sorts the candidates, keeps the nucleus up to topP, and draws a random number to choose within it, exactly the procedure from the previous example.
  2. Greedy gets stuck: a token is a token is a token is… until the 32-token limit. Each repetition makes the next one more likely, and greedy never takes the less likely exit. This is a classic failure of pure greedy decoding on open-ended text, and small models show it vividly.
  3. T = 0.7, top-p 0.9 with seeds 1, 2 and 3 gives three different poems. Each draw follows the model's preferences most of the time but occasionally takes the second or third choice, which is enough to escape loops and vary the wording. They're not good haiku (it's a 135M model), but they're fluent.
  4. T = 1.5 flattens the distribution so much that rare tokens win constantly: the text falls apart into fragments and invented words within a few tokens.
  5. Run it twice and you get identical output, because the seed fixes the draws and the model's scores are deterministic on one machine. On a serving cluster even greedy output can vary between runs: Thinking Machines Lab showed in September 2025 that inference kernels whose results depend on how requests are batched together are a main cause. Design for variation rather than counting on determinism.
AdvancedWhat replaces temperature on Claude

People reach for temperature for three reasons. Each has a better tool on current Claude models:

You wantedOld habitWhat to do now
Consistent, factual answerstemperature: 0A clear system prompt, grounding in documents, structured outputs for fixed formats, and an eval that runs each case several times and reports how often it passes
More creative or varied texttemperature: 1 or higherAsk for it explicitly ("give five very different taglines"), give examples of the range you want, or generate several candidates and pick
Cheaper, shallower answerslow temperature on a big modelLower effort, or a smaller model, chosen with evals

If you need byte-identical answers for the same input (a cached FAQ answer, a test fixture), cache the response in your own system instead of hoping the model repeats itself (Caching responses).

Top-k = 1

On an open model you set top_k: 1 and sample with temperature: 1. What decoding strategy is that, and does the temperature matter?

Show answer

It's greedy decoding, and the temperature has no effect.

What’s happening
  1. Top-k keeps only the k most likely tokens; with k = 1 only the single most likely token survives.
  2. After rescaling, that token has probability 1, so the "random" draw always picks it: exactly what greedy does.
  3. Temperature divides all scores by the same number, which never changes their order, so the top token stays the top token whatever T is. It only changes how much probability the others get, and they've all been removed.
  4. The same reasoning shows why top-p with a very small p also tends towards greedy: the nucleus shrinks to the top token whenever that token alone holds more than p.

#Transformers and attention, just enough

Added

Between the token ids going in and the scores coming out is a transformer: a stack of identical layers that repeatedly refine a vector for every token. Three steps, in order:

  1. Embedding. Each token id is looked up in a table and becomes a vector of numbers (576 in SmolLM2, several thousand in large models). Similar tokens get similar vectors; chapter 5 uses the same idea for search (What embeddings are).
  2. Layers. Each layer has two parts. Attention lets every token gather information from the tokens before it: each token produces a query ("what am I looking for?"), every token offers a key ("what do I contain?") and a value ("what I'll pass on"), and a token's new vector is a weighted mix of earlier values, weighted by how well its query matches their keys. A causal mask stops a token from looking at anything after it, because at generation time the future doesn't exist yet. Then an MLP (a small feed-forward network) transforms each token's vector on its own; a lot of what the model "knows" is stored in these weights. SmolLM2 has 30 such layers and 9 attention heads per layer, each head free to look for something different.
  3. Output. The last position's final vector is multiplied by the vocabulary matrix to give one score per token: the logits from the previous topic.

The mental model is a meeting held thirty times over. Words sit in a row in order. In each round, every word may ask the words before it a question, listen mostly to the ones whose answers match, and update its own understanding; "he" learns who it refers to, "bank" learns whether it's about rivers or money. After thirty rounds, the last word's understanding is rich enough to predict what comes next.

Two practical consequences come straight out of attention, and they're the ones interviewers ask about:

  • Long context costs more. Every token attends to every earlier token, so the attention work for a prompt grows with the square of its length, and each newly generated token has to look back over the whole context. Providers price per token; you pay in latency and in quality as well (Context windows).
  • The KV cache. At decode time the keys and values of earlier tokens never change, so servers keep them in memory instead of recomputing them: a new token computes only its own query, key and value and reads the rest from the cache. That turns quadratic re-reading into one token's work per step, at the price of memory that grows with every token, for every layer. This cache, not the weights, is often what limits how many long conversations a GPU can serve at once.
The capital of France is Embedding each id becomes 576 numbers Layer 1 attention: look back at earlier tokens · MLP: transform each ⋮ 30 layers in SmolLM2 Layer 30 Output last position → 49,152 scores KV cache every layer keeps a key and a value for each token so far new a new token computes only its own query, key and value, reads the cached ones, then joins the cache memory grows with every token, in every layer
Token ids become vectors, 30 layers of attention and MLP refine them, and the last position becomes scores. The KV cache keeps earlier keys and values so each new token is cheap.

Attention is easier to believe once you've computed it. The example runs one attention head by hand on six tokens, with three-number vectors made up so you can read them (a real model learns its vectors and uses 64 numbers per head in SmolLM2).

attention.mjsPlayground ↗
// One attention head, by hand. Real models learn these vectors; these are hand-made so you can read them.
// Dimensions of the toy vectors: [is a person, is a thing, is an action]
const tokens = ["Rohit", "fixed", "the", "bug", "because", "he"];
const keys = [    // what each token offers to be found by ("I am a person", "I am a thing", ...)
  [3, 0, 0], [0, 0, 3], [0, 1, 0], [0, 3, 0], [0, 0, 1], [2, 0, 0],
];
const queries = [ // what each token is looking for
  [0, 0, 1], [3, 1, 0], [0, 2, 0], [0, 0, 2], [0, 0, 2], [3, 0, 0],
];
const values = keys; // keep it simple: what a token passes on is the same as what it offers

const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
const softmax = (xs) => {
  const m = Math.max(...xs);
  const e = xs.map((x) => Math.exp(x - m));
  const s = e.reduce((a, b) => a + b, 0);
  return e.map((x) => x / s);
};

const d = keys[0].length;
console.log("attention weights (row = token doing the looking, columns = earlier tokens it can see)");
console.log(" ".repeat(9) + tokens.map((t) => t.padStart(8)).join(""));
for (let i = 0; i < tokens.length; i++) {
  // Causal mask: token i may only look at tokens 0..i, never at the future.
  const scores = tokens.slice(0, i + 1).map((_, j) => dot(queries[i], keys[j]) / Math.sqrt(d));
  const weights = softmax(scores);
  const row = tokens.map((_, j) => (j <= i ? weights[j].toFixed(2) : "-").padStart(8)).join("");
  console.log(tokens[i].padEnd(9) + row);
  if (tokens[i] === "he") {
    const output = values[0].map((_, k) => weights.reduce((s, w, j) => s + w * values[j][k], 0));
    console.log(`\n"he" leaves the layer as ${JSON.stringify(output.map((x) => +x.toFixed(2)))}: mostly "person", mostly from "Rohit"`);
  }
}
Result
attention weights (row = token doing the looking, columns = earlier tokens it can see)
            Rohit   fixed     the     bug because      he
Rohit        1.00       -       -       -       -       -
fixed        0.99    0.01       -       -       -       -
the          0.19    0.19    0.61       -       -       -
bug          0.03    0.91    0.03    0.03       -       -
because      0.03    0.84    0.03    0.03    0.08       -
he           0.83    0.00    0.00    0.00    0.00    0.15

"he" leaves the layer as [2.8,0.02,0.02]: mostly "person", mostly from "Rohit"
What’s happening
  1. Each token has a key (what it offers), a query (what it's looking for) and a value (what it passes on), with three made-up dimensions: person, thing, action. Rohit's key says "person" strongly ([3, 0, 0]), bug's says "thing", fixed's says "action". he looks for a person ([3, 0, 0]).
  2. For token i, the score against each earlier token j is the dot product of i's query with j's key, divided by √3 (the square root of the vector size, which keeps scores from growing with dimension). Only j ≤ i is computed: that's the causal mask, and it's why the table is a triangle.
  3. Softmax turns each row of scores into weights that add up to 1. he's query matches Rohit's key (3 × 3 = 9, scaled to 5.2) far better than anything else, so he puts 0.83 of its attention on Rohit and 0.15 on itself (its own key also says "person"). bug looks for an action and attends 0.91 to fixed.
  4. The output for he is the weighted sum of the values: [2.8, 0.02, 0.02], almost purely "person, from Rohit". After this layer, the vector at he's position carries information that came from four tokens back: that's how the model resolves references.
  5. A real layer does this with 9 heads in parallel (SmolLM2), each with its own learned query, key and value weights, then mixes the heads and runs the MLP; 30 layers stack it. Notice that fixed can only attend to Rohit (0.99): it can't see bug yet, because during generation that word hasn't been written.
AdvancedModel size and KV cache from the config

How big is the model, and how big is its cache?

A model's config.json tells you most of what you need to reason about memory. This example reads SmolLM2's real config, counts its parameters from the layer shapes, and computes KV cache sizes, for SmolLM2 and for a 72-billion-parameter model using the shape in Qwen2.5-72B-Instruct's published config (80 layers, 8 key-value heads of size 128).

model-size.mjs
import { AutoConfig } from "@huggingface/transformers";

// The real config.json of the model this chapter runs.
const c = await AutoConfig.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct");
const headDim = c.hidden_size / c.num_attention_heads;
console.log(`layers ${c.num_hidden_layers}, width ${c.hidden_size}, heads ${c.num_attention_heads} (KV heads ${c.num_key_value_heads}), ` +
  `head size ${headDim}, vocabulary ${c.vocab_size}, max context ${c.max_position_embeddings}`);

// Count the weights a Llama-style decoder has, from the config alone.
const h = c.hidden_size, kv = c.num_key_value_heads * headDim;
const embeddings = c.vocab_size * h;                     // one vector per token id (shared with the output layer here)
const attention = h * h + h * kv + h * kv + h * h;        // Q, K, V and output projections
const mlp = 3 * h * c.intermediate_size;                  // gate, up and down projections
const norms = 2 * h;                                      // two RMSNorm weight vectors per layer
const perLayer = attention + mlp + norms;
const total = embeddings + c.num_hidden_layers * perLayer + h;
const M = (x, digits = 1) => (x / 1e6).toFixed(digits) + "M";
console.log(`embeddings ${M(embeddings)} + ${c.num_hidden_layers} layers x ${M(perLayer, 2)} (attention ${M(attention, 2)}, MLP ${M(mlp, 2)}) = ${M(total)} parameters`);

// The KV cache: every layer keeps one key and one value vector per KV head, for every token so far.
function kvBytesPerToken({ layers, kvHeads, headDim, bytes }) {
  return 2 * layers * kvHeads * headDim * bytes;
}
const smol = kvBytesPerToken({ layers: c.num_hidden_layers, kvHeads: c.num_key_value_heads, headDim, bytes: 4 });
console.log(`SmolLM2 KV cache: ${(smol / 1024).toFixed(1)} KiB per token (float32), ${((smol * c.max_position_embeddings) / 2 ** 20).toFixed(0)} MiB at its full ${c.max_position_embeddings}-token context`);

// Qwen2.5-72B-Instruct's published config.json: 80 layers, 8 KV heads, head size 8192 / 64 = 128, served in 16-bit.
const big = kvBytesPerToken({ layers: 80, kvHeads: 8, headDim: 128, bytes: 2 });
for (const ctx of [8_192, 32_768, 131_072])
  console.log(`72B model, ${String(ctx).padStart(7)} tokens: ${((big * ctx) / 2 ** 30).toFixed(1).padStart(5)} GiB of KV cache per conversation`);
Result
layers 30, width 576, heads 9 (KV heads 3), head size 64, vocabulary 49152, max context 8192
embeddings 28.3M + 30 layers x 3.54M (attention 0.88M, MLP 2.65M) = 134.5M parameters
SmolLM2 KV cache: 45.0 KiB per token (float32), 360 MiB at its full 8192-token context
72B model,    8192 tokens:   2.5 GiB of KV cache per conversation
72B model,   32768 tokens:  10.0 GiB of KV cache per conversation
72B model,  131072 tokens:  40.0 GiB of KV cache per conversation
What’s happening
  1. AutoConfig.from_pretrained reads the cached config.json: 30 layers, a width (hidden size) of 576, 9 query heads but only 3 key-value heads, so each head has 576 / 9 = 64 numbers. Sharing one key and value head between three query heads is called grouped-query attention, and it exists to shrink the KV cache.
  2. The parameter count comes from the matrix shapes: the embedding table is 49,152 × 576 = 28.3M numbers (SmolLM2 reuses it as the output layer, tie_word_embeddings: true), and each layer has 0.88M attention weights and 2.65M MLP weights (plus two small normalisation vectors), 3.54M in all. 28.3M + 30 × 3.54M gives 134.5M, which is the "135M" in the model's name. The MLPs hold most of the weights.
  3. The KV cache stores, per token, a key and a value (×2) in each of 30 layers, for 3 heads of 64 numbers, at 4 bytes each in float32: 45 KiB per token, or 360 MiB if you fill the model's 8,192-token context.
  4. For a 72B model of Qwen2.5's shape, served in 16-bit numbers, each token costs 320 KiB of cache: 2.5 GiB for an 8K-token conversation and 40 GiB at 131,072 tokens, which is half an 80 GB accelerator for a single conversation. That's why long contexts are expensive to serve, and why providers invest in cache-saving tricks.
  5. The same arithmetic tells you what local hardware can run (chapter 12): weights plus KV cache for your context length must fit in memory.
AdvancedThe KV cache, measured

The earlier generation loop fed the whole sequence back in at every step. Here the same greedy generation runs twice, once that way and once passing the model's own keys and values back in, so only the new token is fed.

kv-cache.mjs
import { AutoTokenizer, AutoModelForCausalLM, Tensor, DynamicCache } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

const tensor = (ids) => new Tensor("int64", BigInt64Array.from(ids.map(BigInt)), [1, ids.length]);
const ones = (n) => new Tensor("int64", new BigInt64Array(n).fill(1n), [1, n]);
const argmaxLast = (logits) => {
  const [, n, V] = logits.dims;
  const row = logits.data.subarray((n - 1) * V, n * V);
  let best = 0;
  for (let i = 1; i < V; i++) if (row[i] > row[best]) best = i;
  return best;
};
// The model returns this step's keys and values as "present.*"; the next call takes them as "past_key_values.*".
const toCache = (out) => new DynamicCache(Object.fromEntries(
  Object.entries(out).filter(([k]) => k.startsWith("present")).map(([k, v]) => [k.replace("present", "past_key_values"), v]),
));

async function generate(prompt, steps, useCache) {
  const ids = Array.from(tokenizer(prompt).input_ids.data, Number);
  let feed = ids.slice(), cache = null, positionsProcessed = 0;
  const out = [];
  for (let s = 0; s < steps; s++) {
    const res = await model({ input_ids: tensor(feed), attention_mask: ones(ids.length), ...(cache && { past_key_values: cache }) });
    positionsProcessed += feed.length;
    const next = argmaxLast(res.logits);
    out.push(next);
    ids.push(next);
    if (useCache) {
      cache = toCache(res);
      feed = [next]; // only the new token goes in; earlier keys and values come from the cache
      if (s === 0 || s === steps - 1) console.log(`  after step ${s + 1}: layer 0 key cache has shape [${cache["past_key_values.0.key"].dims}]`);
    } else {
      feed = ids.slice(); // no cache: feed the whole sequence again
    }
  }
  return { text: tokenizer.decode(out), positionsProcessed };
}

const prompt = "The capital of France is";
console.log("with the KV cache:");
const cached = await generate(prompt, 8, true);
const plain = await generate(prompt, 8, false);
console.log(`without cache: ${JSON.stringify(plain.text)}  token positions computed: ${plain.positionsProcessed}`);
console.log(`with cache:    ${JSON.stringify(cached.text)}  token positions computed: ${cached.positionsProcessed}`);
Result
with the KV cache:
  after step 1: layer 0 key cache has shape [1,3,5,64]
  after step 8: layer 0 key cache has shape [1,3,12,64]
without cache: " the capital of the country.\n\n"  token positions computed: 68
with cache:    " the capital of the country.\n\n"  token positions computed: 12
What’s happening
  1. Each forward pass returns present.0.key, present.0.value … present.29.value: every layer's keys and values for the tokens it just processed. toCache renames them to the past_key_values.* names the model takes as input next time and wraps them in transformers.js's DynamicCache.
  2. With the cache, the first pass reads the 5 prompt tokens and the layer-0 key cache has shape [1, 3, 5, 64]: one sequence, 3 key-value heads, 5 tokens, 64 numbers each. After 8 steps it's [1, 3, 12, 64]: one more token per step, in every one of the 30 layers.
  3. Both runs produce the same text, the capital of the country. and a blank line, because the cached keys and values are exactly what a full re-read would recompute. The cache is a pure speed optimisation.
  4. The work is very different: without the cache the model computes 68 token positions (5 + 6 + … + 12); with it, 12 (the 5-token prompt once, then 1 per step). For a 2,000-token reply the gap becomes millions of positions, which is why every serving stack uses a KV cache.
  5. Prompt caching in the Claude API applies the same principle across requests: the provider keeps the processed form of a prompt prefix it has seen recently, so a request that starts with the same tokens doesn't pay to process them again. Anthropic doesn't describe its internals, but the effect on your bill and latency is what Prompt caching measures.
What grouped-query attention saves

SmolLM2 has 9 query heads but only 3 key-value heads, and its KV cache is 45 KiB per token. How big would the cache be per token if every query head had its own key and value head?

Show answer

135 KiB per token, three times as much.

What’s happening
  1. The cache stores keys and values only, so its size per token is 2 × layers × key-value heads × head size × bytes per number.
  2. Today: 2 × 30 × 3 × 64 × 4 bytes = 46,080 bytes = 45 KiB.
  3. With 9 key-value heads, only that one factor changes: 2 × 30 × 9 × 64 × 4 = 138,240 bytes = 135 KiB.
  4. The weights would grow a little too (bigger K and V projections), but the cache is the part that grows with every token of every conversation, so cutting it by two-thirds is a large saving at serving time, which is why most recent open models use grouped-query attention.

#Context windows

Added

The context window is the maximum number of tokens one request can involve: everything the model reads plus everything it writes. All current Claude models have a 1M-token window and up to 128K output tokens (the older Claude Haiku 4.5 has 200K), according to Anthropic's model overview; SmolLM2's is 8,192. What counts against it is everything in the request:

  • the system prompt and the definitions of any tools (their names, descriptions and schemas are tokens too);
  • the whole message history you resend, including earlier assistant replies, tool calls and tool results;
  • documents, retrieved chunks, images and PDFs you attach;
  • and the reply itself, thinking included, up to max_tokens.

A big window is room, not a recommendation. Three costs grow with it. Money: every input token is billed on every call that sends it. Latency: more tokens to prefill and attend over. Quality: models don't use all positions equally. The well-known study is "Lost in the Middle" (Liu et al., Transactions of the ACL, 2024): with 20 retrieved documents, GPT-3.5-Turbo answered 75.8% of questions correctly when the relevant document came first, 63.2% when it came last, and only 53.8% when it sat in the middle, which was worse than its 56.1% with no documents at all. Newer models are much better at long contexts, but Anthropic's own guidance on context engineering still treats context as a finite attention budget: the goal is the smallest set of high-signal tokens that gets the job done.

That's why context engineering, deciding what goes into the window on each call, is the real skill behind most AI features: retrieve the few relevant chunks instead of the whole manual (chapter 6), summarise or drop old turns and bulky tool results (chapter 7), put long documents first and the question last (chapter 3), and cache the stable prefix (chapter 3).

The mental model is a desk, not a filing cabinet. Whatever is on the desk the model can see and use, but the desk is cleared after every call, everything on it costs money each time you set it out, and a desk piled high is harder to work at than a tidy one.

all of it must fit in the context window (1M tokens on current Claude models) System prompt Tools definitions Documents retrieved chunks History grows every turn New message Output thinking + reply input tokens input price, resent on every call output tokens up to max_tokens, output price (5×) the API is stateless: last turn's reply is this turn's history
What one request puts in the window. Everything left of the output is resent and billed again on every turn.

The example follows a 40-turn support chat and prints what each request contains. The sizes are assumptions for the sketch: a 2,500-token system prompt, 4,000 tokens of tool definitions and 4,800 tokens of retrieved documents sent with every request, a 120-token user message and a 350-token reply per turn, and 16,000 tokens reserved for output.

context-budget.mjsPlayground ↗
// What fills a context window over a long chat. Token sizes are assumptions for the sketch (stated in the prose).
const WINDOW = 1_000_000;                 // current Claude models
const PRICE = { input: 4, output: 20 };    // Claude Opus 5.5, US dollars per million tokens
const fixed = { system: 2_500, tools: 4_000, documents: 4_800 }; // sent with every request
const perTurn = { user: 120, assistant: 350 };
const maxTokens = 16_000;                  // reserved for the reply (thinking included)

let history = 0, billedInput = 0, billedOutput = 0;
console.log("turn  input tokens  of which history  room left in window");
for (let turn = 1; turn <= 40; turn++) {
  const input = fixed.system + fixed.tools + fixed.documents + history + perTurn.user;
  billedInput += input;
  billedOutput += perTurn.assistant;
  if ([1, 5, 10, 20, 40].includes(turn)) {
    const room = WINDOW - input - maxTokens;
    console.log(`${String(turn).padStart(4)}${String(input).padStart(14)}${String(history).padStart(18)}${String(room).padStart(21)}`);
  }
  history += perTurn.user + perTurn.assistant; // the API is stateless: this turn is resent next time
}
const cost = (billedInput * PRICE.input + billedOutput * PRICE.output) / 1e6;
console.log(`40 turns: ${billedInput.toLocaleString("en-GB")} input tokens billed, ${billedOutput.toLocaleString("en-GB")} output tokens, $${cost.toFixed(2)}`);
console.log(`input share of the bill: ${((billedInput * PRICE.input) / 1e6 / cost * 100).toFixed(0)}%`);
Result
turn  input tokens  of which history  room left in window
   1         11420                 0               972580
   5         13300              1880               970700
  10         15650              4230               968350
  20         20350              8930               963650
  40         29750             18330               954250
40 turns: 823,400 input tokens billed, 14,000 output tokens, $3.57
input share of the bill: 92%
What’s happening
  1. Each request's input is the fixed part (2,500 + 4,000 + 4,800 = 11,300 tokens), plus the history, plus the new 120-token message: 11,420 tokens on turn 1.
  2. After each turn, the user message and the reply (470 tokens) join the history, because the API is stateless and the next request has to carry them. By turn 40 the history is 18,330 tokens and the request is 29,750.
  3. The window is nowhere near full: 954,250 tokens of room are left even on turn 40. With a 1M window, running out of space is rarely the first problem.
  4. The bill is. Summing every request gives 823,400 input tokens for 40 turns, against 14,000 output tokens: $3.57 at Claude Opus 5.5 prices, 92% of it input. Per-request input grows linearly, so the total grows with the square of the number of turns.
  5. Every lever on that bill is a context-engineering decision: cache the 11,300-token fixed prefix (Prompt caching), send fewer tools or documents, and trim or summarise old turns (Memory and context management).
AdvancedWhen the window really does overflow

Long agent runs are where windows fill up: each tool result (a file, a web page, a query result) is appended and resent, and a few hundred steps can reach a million tokens. When a request is larger than the window, the API rejects it with an error rather than silently dropping text, so your code has to decide what to cut. The options, from simplest:

  • Trim: drop the oldest turns (keep the system prompt and the most recent exchanges). Cheap, but the model forgets early facts.
  • Clear bulky tool results: old tool outputs are usually the largest and least needed part. Anthropic offers context editing (beta) that clears old tool results or thinking blocks server-side.
  • Summarise: replace old turns with a summary. Anthropic's server-side compaction (beta) does this automatically when input reaches a trigger (150K tokens by default), and you pass the returned compaction block back on later requests.
  • Retrieve instead of keep: store facts outside the conversation (a memory store or database) and fetch them when needed.

Chapter 7 builds these into an agent. Local runtimes behave differently: Ollama's documented default context (num_ctx) was 2,048 tokens as of December 2026, so a long prompt sent to a local model can be cut without an error unless you raise it.

Linear per request, quadratic in total

In the 40-turn example, the request on turn n has 11,420 + 470 × (n − 1) input tokens. How many input tokens do all 40 requests add up to, and what would 80 turns cost in input tokens?

Show answer

823,400 for 40 turns; 2,398,800 for 80 turns: 2.9 times as many for twice the turns.

What’s happening
  1. Sum over turns: 40 × 11,420 for the fixed part and first message, plus 470 × (0 + 1 + … + 39) for the history.
  2. 0 + 1 + … + 39 = 39 × 40 / 2 = 780, so the history adds 470 × 780 = 366,600, and the total is 456,800 + 366,600 = 823,400, matching the program.
  3. For 80 turns: 80 × 11,420 = 913,600, and 0 + 1 + … + 79 = 79 × 80 / 2 = 3,160, so the history adds 470 × 3,160 = 1,485,200, and the total is 2,398,800.
  4. Doubling the conversation length multiplies the input tokens by 2.9, because the history term grows with the square of the turn count. Long chats need a history strategy (trim, summarise, cache) or their cost runs away.

#How models are trained: pre-training, fine-tuning and RL

Added

A modern chat model is built in stages, and each stage leaves fingerprints on the behaviour you see in production. Knowing which stage causes which behaviour is what lets you predict failures instead of being surprised by them.

  1. Pre-training. The model starts with random weights and learns to predict the next token of an enormous amount of text: web pages, books, code, papers. The loss is simply how surprised the model was by each real next token (the negative log-probability it gave that token), averaged over trillions of tokens; SmolLM2-135M saw 2 trillion. This is where knowledge, language and coding ability come from, and also where the knowledge cut-off comes from: nothing after the training data exists for the model.
  2. Supervised fine-tuning (SFT). The same next-token loss, now on curated example conversations written or checked by people, laid out in the chat template. Usually only the assistant's tokens count towards the loss. This teaches the format, following instructions, and when to stop.
  3. Preference tuning. People compare two answers and pick the better one. In RLHF (reinforcement learning from human feedback) a reward model is trained on those choices and the chat model is optimised against it; OpenAI's InstructGPT paper (Ouyang et al., 2022) found that people preferred the outputs of a 1.3B-parameter model trained this way over the 175B GPT-3. Anthropic's Constitutional AI (Bai et al., 2022) replaces many human labels with AI feedback guided by a written set of principles (RLAIF). DPO (direct preference optimisation) learns from the same preference pairs without a separate reward model; SmolLM2-Instruct's model card says it used DPO.
  4. Reinforcement learning on checkable tasks. For reasoning models, the model attempts problems whose answers can be checked automatically (maths with known answers, code with tests) and is rewarded for correct results. DeepSeek's R1 paper (January 2025) reported that reasoning abilities can be incentivised through pure reinforcement learning, with self-reflection and verification emerging on their own. This is what makes models think step by step before answering.

The mental model: pre-training is reading everything; SFT is an apprenticeship; preference tuning is customer feedback; RL is practice exams with an answer key. Each one teaches what it rewards, nothing more:

Behaviour you'll seeWhere it comes from
Knows a lot, but nothing recentpre-training data and its cut-off date
Fluent, confident, sometimes wrongpre-training rewards plausible text; nothing rewarded "I don't know"
Follows formats, answers in turns, stopsSFT on example conversations
Polite, thorough, sometimes agrees too readily or pads answerspreference tuning: raters tend to like agreeable, complete-looking answers
Declines some requestssafety training in SFT and preference tuning
Thinks for a long time on hard problemsRL on checkable tasks
Pre-training trillions of tokens: web, books, code next-token loss knowledge, language, code → a base model Fine-tuning (SFT) example conversations in the chat template same loss chat format, following instructions Preference tuning answer pairs ranked by people or a guided model RLHF · RLAIF · DPO helpful tone, refusals; also sycophancy RL on checkable tasks maths with answers, code with tests reward = correct step-by-step reasoning, self-checking each stage teaches exactly what it rewards, and nothing more
The stages behind a chat model, and the behaviour each one leaves behind.

The example computes the pre-training loss on a real sentence with SmolLM2, then shows what that objective rewards: whatever text usually says.

pretraining-objective.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });

// log-probabilities of the whole vocabulary at one position (a log-softmax over the scores)
function logProbs(logits, position) {
  const V = logits.dims[2];
  const row = logits.data.subarray(position * V, (position + 1) * V);
  let max = -Infinity;
  for (const x of row) if (x > max) max = x;
  let sum = 0;
  for (const x of row) sum += Math.exp(x - max);
  return (tokenId) => row[tokenId] - max - Math.log(sum);
}

// 1. The pre-training loss: for every position, how surprised was the model by the token that really came next?
const text = "The Eiffel Tower is in Paris.";
const inputs = tokenizer(text);
const ids = Array.from(inputs.input_ids.data, Number);
const { logits } = await model(inputs);
let loss = 0;
const parts = [];
for (let t = 0; t < ids.length - 1; t++) {
  const nll = -logProbs(logits, t)(ids[t + 1]); // negative log-likelihood of the real next token
  loss += nll;
  parts.push(`${JSON.stringify(tokenizer.decode([ids[t + 1]]))} ${nll.toFixed(2)}`);
}
console.log(`${JSON.stringify(text)}\n  per-token loss: ${parts.join(", ")}\n  mean loss: ${(loss / (ids.length - 1)).toFixed(2)}`);

// 2. The objective rewards what text usually says, which is not always what is true.
async function nextWord(prefix, options) {
  const inp = tokenizer(prefix);
  const { logits: l } = await model(inp);
  const lp = logProbs(l, inp.input_ids.dims[1] - 1);
  const row = options.map((w) => `${w.trim()} ${(Math.exp(lp(tokenizer.encode(w, { add_special_tokens: false })[0])) * 100).toFixed(1)}%`);
  console.log(`${JSON.stringify(prefix + " …")}  ${row.join(", ")}`);
}
await nextWord("The Eiffel Tower is in", [" Paris", " Rome", " Berlin"]);
await nextWord("Lightning never strikes the same place", [" twice", " again"]);
await nextWord("Bulls get angry when they see the colour", [" red", " blue"]);
Result
"The Eiffel Tower is in Paris."
  per-token loss: " E" 9.42, "iffel" 5.89, " Tower" 1.20, " is" 2.74, " in" 4.82, " Paris" 2.48, "." 1.15
  mean loss: 3.96
"The Eiffel Tower is in …"  Paris 8.4%, Rome 0.3%, Berlin 0.1%
"Lightning never strikes the same place …"  twice 60.3%, again 5.9%
"Bulls get angry when they see the colour …"  red 24.8%, blue 8.2%
What’s happening
  1. logProbs is a log-softmax over one position's scores: it returns a function giving the log-probability of any token there. The loss for one position is the negative of that for the token that really came next.
  2. Position by position through The Eiffel Tower is in Paris.: E after The costs 9.42 (lots of words could follow "The"), iffel after The E 5.89, then Tower only 1.20 because "Eiffel" almost forces it, and Paris 2.48. The first token, The, has no loss: nothing came before it to predict it from.
  3. The mean loss, 3.96, is the number pre-training pushes down, averaged over trillions of tokens instead of seven. Lower loss means the model would have been less surprised by real text. There is no other signal in pre-training: no "true" or "false", only "likely" or "unlikely".
  4. That objective happens to favour truth when the truth is what text says: after The Eiffel Tower is in, Paris gets 8.4% against 0.3% for Rome and 0.1% for Berlin.
  5. But it favours common sayings just as happily. After Lightning never strikes the same place the model gives twice 60.3% (lightning does strike the same place repeatedly; tall buildings are hit many times a year), and after Bulls get angry when they see the colour it gives red 24.8% (bulls react to the cape's movement, not its colour). The model isn't lying: it's predicting the text it read.
  6. Later stages push against this (preference tuning rewards accurate answers, RL rewards correct ones), but the pre-training habit of producing the plausible continuation never disappears entirely. That's the root of hallucination, the next-but-one topic.
AdvancedWhy preference tuning breeds sycophancy

Why preference tuning can make models agree too readily

Preference tuning optimises for what raters prefer, and people tend to prefer answers that agree with them and sound complete. Anthropic's research on sycophancy (Sharma et al., "Towards Understanding Sycophancy in Language Models", 2023) found that models trained with human feedback often tell users what they want to hear, and that human preference data itself rewards this sometimes. In an application that shows up as a model that backs down when the user pushes ("are you sure?") or praises a flawed plan. Two practical defences: don't treat "are you sure?" as verification (check against a source or a tool instead), and in evaluation, include cases where the user is confidently wrong and check that the model holds its ground.

Is the model wrong about lightning?

SmolLM2 gives twice a 60.3% probability after "Lightning never strikes the same place". As a pre-trained language model, is it making an error?

Show answer

No: by its own objective it's doing exactly its job; the error only appears when you treat its output as a factual claim.

What’s happening
  1. Pre-training scores the model on one thing: how well it predicts the next token of real text. The saying "lightning never strikes the same place twice" is extremely common, so twice really is the most likely continuation.
  2. Factually, lightning does strike the same place repeatedly, but the training signal never says "true" or "false", only "likely" or "unlikely".
  3. An instruction-tuned and preference-tuned model asked "Does lightning strike the same place twice?" is far more likely to answer correctly, because those stages rewarded accurate answers to questions. The pre-training prior is still underneath.
  4. The lesson for engineering: a model's fluency tells you what's common, not what's true. Treat factual output as a claim to be grounded or checked.

#Reasoning models and thinking

Added

A reasoning model writes out intermediate reasoning, as thinking tokens, before its answer, and was trained (with reinforcement learning on checkable problems) to make that reasoning useful. Each token is one more forward pass, so thinking is a way to spend more computation on harder questions: break the problem down, try an approach, notice a mistake, try again. The visible answer then comes after the thinking.

On current Claude models this is adaptive thinking: the model decides whether to think at all and for how long, based on how hard the request looks, and you steer the overall depth with effort. The facts that matter, from Anthropic's documentation:

  • Request shape. thinking: { type: "adaptive" } turns it on (on Claude Opus 5.5 it's on even if you omit it), and output_config: { effort: "low" | "medium" | "high" | "xhigh" | "max" } sets the depth. The default effort is medium on Claude Opus 5.5 and Claude Haiku 5.5 and high on most other current models, so set it explicitly.
  • No fixed budgets. The old thinking: { type: "enabled", budget_tokens: N } returns a 400 error on current models (Opus 5.5, Sonnet 5.5, Fable 5.2 and others), and on Claude Opus 5.5 thinking can't be disabled at all: lower the effort instead.
  • What you see. The response contains thinking blocks before the text block. With the default display: "omitted" on current models, the thinking text is empty and only an opaque signature comes back; display: "summarized" returns a readable summary. The raw chain of thought is never returned.
  • What you pay. Thinking tokens are billed as output tokens and count towards max_tokens, so a one-line answer can carry hundreds of output tokens.
  • Multi-turn. Send assistant content back unchanged, thinking blocks and signatures included (with tools it's required).

The mental model is asking someone to show their working, then grading only the final line. Showing working makes people better at long sums and no better at recalling a phone number. The same holds for models: thinking helps multi-step maths and logic, planning, debugging, and agents that must decide which tool to call next; it adds cost and delay for classification, extraction, short factual lookups and casual chat. Effort is how you choose, per route, and an eval is how you know which level is enough.

The example sends a question that rewards a moment's care (whether the stop is extra time) with summarised adaptive thinking at high effort, and reads the blocks that come back.

thinking.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run") ---------------------------------------------
// The reply follows the shape of Anthropic's documented responses; its words and numbers were written for the example.
const reply = {
  id: "msg_01JxWq8n3VtLkR5sYb2Pc9Hd",
  type: "message",
  role: "assistant",
  content: [
    {
      type: "thinking",
      thinking:
        "The train leaves at 14:35. Travel time is 2 h 50 min, and the 25-minute stop is part of the journey, " +
        "not extra, because the timetable time already includes stops. So 14:35 + 2:50 = 17:25.",
      signature: "EqQBCkgIBRABGAIiQL4mY2Vp7zR0yFh0wq9c1kUeT3...",
    },
    { type: "text", text: "It arrives at 17:25. The 25-minute stop is already included in the 2 h 50 min journey time." },
  ],
  model: "claude-opus-5-5",
  stop_reason: "end_turn",
  stop_sequence: null,
  usage: { input_tokens: 61, output_tokens: 412 },
};
const fetch = async (url, init) => {
  const body = JSON.parse(init.body);
  console.log(`sent: thinking=${JSON.stringify(body.thinking)} output_config=${JSON.stringify(body.output_config)}`);
  return Response.json(reply);
};
const client = new Anthropic({ apiKey: "sk-ant-test", fetch }); // for real: new Anthropic()
// ----------------------------------------------------------------------------------------------

const message = await client.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000, // thinking tokens count towards max_tokens, so leave room
  thinking: { type: "adaptive", display: "summarized" }, // default display on this model is "omitted" (empty text)
  output_config: { effort: "high" }, // low | medium | high | xhigh | max; this model's default is medium
  messages: [
    {
      role: "user",
      content: "A train leaves at 14:35. The journey takes 2 h 50 min, including a 25-minute stop. When does it arrive?",
    },
  ],
});

for (const block of message.content) {
  if (block.type === "thinking") console.log(`[thinking summary] ${block.thinking}`);
  else if (block.type === "text") console.log(`[answer] ${block.text}`);
}

// Thinking is billed as output tokens, at the output price.
const { input_tokens, output_tokens } = message.usage;
const cost = (input_tokens * 4 + output_tokens * 20) / 1e6; // Opus 5.5: $4 in, $20 out per million tokens
console.log(`usage: ${input_tokens} in, ${output_tokens} out (thinking included) -> $${cost.toFixed(5)}`);

// Next turn: send the assistant content back unchanged, thinking block and signature included.
const history = [
  { role: "user", content: "A train leaves at 14:35. …" },
  { role: "assistant", content: message.content },
  { role: "user", content: "And if it leaves 10 minutes late?" },
];
console.log(`next request carries ${history.length} messages; assistant blocks: ${history[1].content.map((b) => b.type).join(", ")}`);
Result
sent: thinking={"type":"adaptive","display":"summarized"} output_config={"effort":"high"}
[thinking summary] The train leaves at 14:35. Travel time is 2 h 50 min, and the 25-minute stop is part of the journey, not extra, because the timetable time already includes stops. So 14:35 + 2:50 = 17:25.
[answer] It arrives at 17:25. The 25-minute stop is already included in the 2 h 50 min journey time.
usage: 61 in, 412 out (thinking included) -> $0.00848
next request carries 3 messages; assistant blocks: thinking, text
What’s happening
  1. The scripted fetch prints the two settings the SDK put in the request body: thinking: {"type":"adaptive","display":"summarized"} and output_config: {"effort":"high"}. Everything else is a normal messages.create call; max_tokens is 16,000 because thinking shares that limit with the answer.
  2. The response's content holds two blocks in order: a thinking block (here with summarised text, because display: "summarized" was requested; by default it would be an empty string) and a text block with the answer. The loop picks them out by type, never by position, because the number of thinking blocks varies.
  3. The thinking summary shows why the extra step helps: the trap is adding the 25-minute stop on top of the journey time (which would give 17:50) when the stop is already included. The answer is 17:25.
  4. usage.output_tokens is 412 although the answer is about 25 words: the thinking is billed as output. At Claude Opus 5.5 prices (these token numbers are scripted) the call costs about $0.0085, nearly all of it output.
  5. For the next turn, message.content goes back into the history as the assistant's content, unchanged: the thinking block with its signature and the text block. Stripping or editing the thinking can make the API reject or ignore those blocks on later turns.
AdvancedChoosing an effort level

Effort is a quality-versus-cost dial within one model: lower effort means less thinking, fewer and more consolidated tool calls and terser replies; higher effort means deeper reasoning and more tokens. Anthropic's guidance, summarised:

EffortGood for
lowhigh-volume or latency-sensitive routes: classification, routing, simple chat, subagents doing narrow jobs
mediuma cost-saving step down where quality holds; the default on Claude Opus 5.5 and Claude Haiku 5.5
highthe minimum for intelligence-sensitive work; often the best balance
xhighcoding and long agentic tasks, where it's recommended on several models
maxwhen correctness matters far more than time and tokens

Two habits keep this honest. Tune effort per route, not globally: a chat route and a code-review route want different settings. And measure on real requests before raising a default, judging cost per completed task: a cheaper setting that needs more retries isn't cheaper. Anthropic also suggests trying the most capable model at a lower effort before building a cascade of different models, because one model at lower effort often matches an older model at high effort.

AdvancedWhat changed from budget_tokens

Earlier Claude models used extended thinking with a fixed budget: thinking: { type: "enabled", budget_tokens: 4096 }, where the budget had to be at least 1,024 and less than max_tokens. You'll still see it in tutorials and older code. On current models that request returns a 400 error; adaptive thinking replaces it, with effort as the depth control. Code that set a budget "to keep thinking short" should move to a lower effort, and code that disabled thinking on Claude Opus 5.5 must stop sending { type: "disabled" }, which that model rejects at every effort level. Thinking and effort in requests covers the request details, streaming thinking, and the per-model differences.

Why 412 output tokens for a short answer?

The answer text in the example is about 25 words, roughly 30 tokens. Why does usage.output_tokens say 412, and what would you change to reduce it on a route where answers are simple?

Show answer

The rest is thinking, which is billed as output; lower the effort (or use a smaller model) on that route.

What’s happening
  1. With adaptive thinking, the model generated thinking tokens before the answer. They're produced by the same generation loop as the answer, so they're output tokens and are billed at the output price.
  2. display only controls what you see: with "omitted" the thinking text comes back empty, but it was still generated and billed.
  3. On a route where questions are simple, output_config: { effort: "low" } makes the model think less or not at all, cutting output tokens and latency. On Claude Opus 5.5 you can't switch thinking off, so effort is the lever.
  4. Verify with your eval that quality holds at the lower effort, and compare cost per correct answer, not cost per call.

#Why models hallucinate

Added

A hallucination is an answer that is fluent and confident but false or unsupported: an invented policy, a citation to a paper that doesn't exist, an API method that was never in the library. It isn't a malfunction. It's the generation loop doing what it does when the knowledge isn't there.

Four causes stack up:

  • The objective is plausibility. Pre-training rewards likely text, not true text. For facts that appear often, likely and true coincide; for rare facts there's no pattern to predict from. OpenAI's paper "Why Language Models Hallucinate" (Kalai et al., September 2025) uses the example of a person's birthday: an arbitrary, rarely written fact that can't be inferred, so the model can only guess.
  • Guessing is rewarded. The same paper argues that training and evaluation reward guessing over admitting uncertainty: on an accuracy-only test a blank scores zero and a guess sometimes scores, so models learn to always answer.
  • The loop commits. Once the reply starts "The capital of Zubrowka is", the next token has to be something, and the most plausible-looking something gets written.
  • No sources by default. Unless you put documents or tools in the context, the model answers from compressed memory with a training cut-off.

The mental model is a student in an exam who gets marks for any answer and none for leaving a blank, writing in a confident hand whether they know or not. The confidence of the prose tells you nothing; on a local model you can see the hidden uncertainty in the probabilities, as the example shows, but the Claude API doesn't return token probabilities, so in production you need other defences: grounding, citations, permission to say "I don't know", and verification.

The example asks SmolLM2 about a real capital, a fictional country (Zubrowka, from a film) and a prize that hasn't been awarded yet, and measures how sure it was at the moment it named the capital.

hallucination.mjs
import { AutoTokenizer, AutoModelForCausalLM } from "@huggingface/transformers";

const id = "HuggingFaceTB/SmolLM2-135M-Instruct";
const tokenizer = await AutoTokenizer.from_pretrained(id);
const model = await AutoModelForCausalLM.from_pretrained(id, { dtype: "q4" });
const chat = (q) => tokenizer.apply_chat_template([{ role: "user", content: q }], { tokenize: false, add_generation_prompt: true });

async function answer(question) {
  const inputs = tokenizer(chat(question));
  const out = await model.generate({ ...inputs, max_new_tokens: 40, do_sample: false });
  return tokenizer.decode(Array.from(out[0].data, Number).slice(inputs.input_ids.dims[1]), { skip_special_tokens: true });
}

// How sure is the model about the word that follows? Look at the distribution, not the text.
async function confidence(text) {
  const inputs = tokenizer(text);
  const { logits } = await model(inputs);
  const [, n, V] = logits.dims;
  const row = logits.data.subarray((n - 1) * V, n * V);
  let max = -Infinity;
  for (const x of row) if (x > max) max = x;
  const probs = Array.from(row, (x) => Math.exp(x - max));
  const sum = probs.reduce((a, b) => a + b, 0);
  let entropy = 0, best = 0;
  probs.forEach((p, i) => {
    const q = p / sum;
    if (q > 0) entropy -= q * Math.log2(q);
    if (p > probs[best]) best = i;
  });
  return `top token ${JSON.stringify(tokenizer.decode([best]))} at ${((probs[best] / sum) * 100).toFixed(1)}%, entropy ${entropy.toFixed(2)} bits`;
}

for (const place of ["France", "Zubrowka"]) {
  const q = `What is the capital of ${place}?`;
  console.log(`Q: ${q}\nA: ${await answer(q)}`);
  console.log(`   after "The capital of ${place} is": ${await confidence(chat(q) + `The capital of ${place} is`)}`);
}
const q = "Who won the 2031 Nobel Prize in Physics?";
console.log(`Q: ${q}\nA: ${JSON.stringify(await answer(q))}`);
Result
Q: What is the capital of France?
A: The capital of France is Paris.
   after "The capital of France is": top token " Paris" at 88.6%, entropy 1.03 bits
Q: What is the capital of Zubrowka?
A: The capital of Zubrowka is Zubowka.
   after "The capital of Zubrowka is": top token " Z" at 29.5%, entropy 6.22 bits
Q: Who won the 2031 Nobel Prize in Physics?
A: "The 2031 Nobel Prize in Physics was awarded to:\n\n1. Niels Bohr\n2. Erwin Schrödinger\n3. Werner Heisenberg\n4"
What’s happening
  1. answer runs greedy generation with the chat template, so you see what the model would actually say. confidence looks at the distribution for the word right after "The capital of X is" in the assistant's turn, and reports the top token's probability and the entropy of the whole distribution (in bits: 0 means certain, higher means more spread out).
  2. France: the answer is The capital of France is Paris., and at the decisive point Paris has 88.6% with entropy 1.03 bits. The model is sure, and right.
  3. Zubrowka: the answer is The capital of Zubrowka is Zubowka., written in exactly the same tone. But the distribution at that point is spread out (entropy 6.22 bits) and its top choice, the fragment Z, has only 29.5%. The model was guessing, built a name out of the country's own letters, and nothing in the text shows it.
  4. The 2031 Nobel Prize: the model lists Niels Bohr, Erwin Schrödinger and Werner Heisenberg, physicists who died decades ago, for a prize that hasn't happened. A plausible shape ("awarded to: 1., 2., 3.") filled with famous physics names: pure pattern completion.
  5. What it demonstrates: hallucinations look identical to correct answers from the outside. You can't fix them by asking the model to "be accurate"; you fix them by changing what's in the context (sources), what the model is allowed to say ("I don't know"), and what your code checks before showing the answer.
AdvancedGrounding, abstaining and verifying in code

The defences work best together. This example combines three: the answer must come from a document in the prompt (grounding), the schema lets the model answer null (abstaining is a legitimate output, not a failure), and the code checks that the supporting quote really appears in the document before trusting the answer (verification). It uses structured outputs (output_config.format) so the reply is guaranteed to be JSON matching the schema; chapter 4 covers them in depth.

grounded.mjsPlayground ↗
import Anthropic from "@anthropic-ai/sdk";

// Scripted replies (see "How these examples run") ---------------------------------------------
// Two replies in the documented response shape; the model's words were written for the example.
const text = (t) => ({
  id: "msg_01Fq2ZbXc8RkT4mWnP7sVy3L",
  type: "message",
  role: "assistant",
  content: [{ type: "text", text: t }],
  model: "claude-opus-5-5",
  stop_reason: "end_turn",
  stop_sequence: null,
  usage: { input_tokens: 240, output_tokens: 38 },
});
const replies = [
  text('{"answer":"Returns are accepted within 30 days with a receipt.","quote":"You can return any item within 30 days of purchase if you have the receipt."}'),
  text('{"answer":null,"quote":null}'),
];
const fetch = async () => Response.json(replies.shift());
const client = new Anthropic({ apiKey: "sk-ant-test", fetch }); // for real: new Anthropic()
// ----------------------------------------------------------------------------------------------

const policy = `Returns policy (Bikes & Bits, updated March 2026)
You can return any item within 30 days of purchase if you have the receipt.
Electric bikes must be returned with the battery charged above 50%.
Gift cards cannot be refunded.`;

const schema = {
  type: "object",
  properties: {
    answer: { anyOf: [{ type: "string" }, { type: "null" }], description: "null if the policy does not say" },
    quote: { anyOf: [{ type: "string" }, { type: "null" }], description: "the exact policy sentence that supports the answer" },
  },
  required: ["answer", "quote"],
  additionalProperties: false,
};

async function ask(question) {
  const message = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    system:
      "Answer only from the policy in <policy> tags. Copy the supporting sentence exactly into quote. " +
      "If the policy doesn't answer the question, set both fields to null; never guess.",
    output_config: { format: { type: "json_schema", schema } },
    messages: [{ role: "user", content: `<policy>\n${policy}\n</policy>\n\nQuestion: ${question}` }],
  });
  if (message.stop_reason !== "end_turn") return `stopped early (${message.stop_reason})`;
  const { answer, quote } = JSON.parse(message.content.find((b) => b.type === "text").text);
  if (answer === null) return "I don't know: the policy doesn't say.";
  if (!policy.includes(quote)) return "rejected: the quote is not in the policy";
  return `${answer}  [source: "${quote}"]`;
}

console.log(await ask("Can I return a helmet I bought three weeks ago?"));
console.log(await ask("Do you price-match other shops?"));
Result
Returns are accepted within 30 days with a receipt.  [source: "You can return any item within 30 days of purchase if you have the receipt."]
I don't know: the policy doesn't say.
What’s happening
  1. The policy goes inside <policy> tags in the user message, and the system prompt says to answer only from it, copy the supporting sentence exactly, and use null when the policy doesn't say. Making abstention part of the instructions and the schema is what makes "I don't know" a normal output.
  2. output_config: { format: { type: "json_schema", schema } } constrains the reply to that JSON shape: answer and quote are each a string or null (anyOf), both required, and additionalProperties: false (required on every object in structured outputs).
  3. ask checks stop_reason first: anything other than end_turn (a cut-off at max_tokens, or a refusal) means the JSON may be incomplete, so it isn't parsed.
  4. For the helmet question the (scripted) reply answers and quotes "You can return any item within 30 days of purchase if you have the receipt." The code confirms that exact sentence is in the policy with policy.includes(quote), so the answer is shown with its source.
  5. For price matching, which the policy never mentions, the reply is {"answer":null,"quote":null} and the code turns it into an honest "I don't know". If a reply ever quoted a sentence that isn't in the policy, the check would reject it instead of showing a confident invention. Claude's citations feature (chapter 2) does the quote-tracking for you on document blocks, and chapter 6 builds the full retrieval version.
A confident invented policy

Your support bot tells a customer "Yes, we price-match any competitor within 14 days." No such policy exists. List three changes, in the order you'd make them.

Show answer

Ground it, let it abstain, and verify before showing.

What’s happening
  1. Ground: retrieve the relevant policy documents for each question and instruct the model to answer only from them. Without sources, it filled the gap with the most typical-sounding retail policy.
  2. Abstain: make "I don't know, let me connect you to a person" an explicit, acceptable answer in the prompt and the output schema, and add unanswerable questions like this one to your eval set so you can see whether the model uses it.
  3. Verify: require a quote or citation for every policy claim and check in code that it appears in the retrieved text; if it doesn't, don't show the answer.
  4. Then keep the failure as an eval case so the fix stays fixed when you change the prompt or the model (The improvement loop).

#The model landscape and choosing a model

Added

There are two broad kinds of model you can build on. Hosted frontier models are called through a vendor's API: Anthropic's Claude family, OpenAI's GPT models and Google's Gemini models are the best known. You get the strongest models with no infrastructure, and you accept the vendor's prices, rate limits and data terms. Open-weight models publish their weights so you can run them yourself or through a hosting provider: well-known families include Qwen, DeepSeek, Llama, Gemma, Mistral and OpenAI's gpt-oss, in sizes from SmolLM2's 135 million parameters to hundreds of billions (many large ones are mixture-of-experts models that use only part of their weights per token). You get control, privacy and possibly lower cost at scale, and you take on serving, scaling and quality work yourself (chapter 12).

This field changes monthly, so treat any list as a snapshot. In December 2026: Anthropic's current models are Claude Fable 5.2 (the most capable widely released model), Claude Opus 5.5 (the default for most hard work), Claude Sonnet 5.5 and Claude Haiku 5.5; OpenAI's pricing page lists GPT-6-series models in several tiers alongside earlier GPT-5 models; and Google's November 2026 update announced the Gemini 4 family. Check each vendor's documentation for what's current when you build.

The Claude line-up, from Anthropic's model overview and price list:

ModelAPI idInput / output price per million tokensContextNotes
Claude Fable 5.2claude-fable-5-2$8 / $401Mmost capable; thinking always on; requires 30-day data retention
Claude Opus 5.5claude-opus-5-5$4 / $201Mthe default for complex and agentic work; effort defaults to medium
Claude Sonnet 5.5claude-sonnet-5-5$2 / $101Mspeed and capability for everyday coding and agent work
Claude Haiku 5.5claude-haiku-5-5$0.10 / $0.50 (prompts up to 100K tokens; $0.50 / $2.50 above)1Mfast and cheap: classification, routing, extraction, subagents

How to choose, in the order that usually decides it:

  1. Quality on your task, measured with your own eval set, not a leaderboard. Public benchmarks test someone else's task and may have leaked into training data.
  2. Latency: time to first token and tokens per second, at your prompt sizes, including thinking at the effort you'd use.
  3. Price: input, output, cache reads and batch discounts, multiplied by your real token counts and volume.
  4. Context and modalities: window size, images, PDFs, structured outputs, tool use, prompt caching.
  5. Data and deployment rules: retention (zero data retention eligibility), the region where inference runs, and which clouds offer it (Claude is also on Amazon Bedrock, Google Cloud Vertex AI and Microsoft Foundry).
  6. Operational fit: rate limits, SDK quality, model deprecation schedules, and whether you need to fine-tune or self-host.

The mental model is hiring for a role: you don't hire the most impressive CV for every job, you define the job, run a work sample (the eval), and pick the cheapest candidate who passes, then re-run the work sample when new candidates appear.

The example prices one feature on each Claude model and then picks the cheapest model that clears a quality bar on an eval. The workload is an assumption for the sketch: 20,000 requests a day, 3,000 input tokens and 400 output tokens each, 30 days a month. The pass rates are illustrative numbers standing in for your own eval results, not published benchmark scores.

choose-model.mjsPlayground ↗
// Monthly cost of one feature on each current Claude model, then "the cheapest model that passes your eval".
// Prices: Anthropic's price list (US dollars per million tokens), checked December 2026.
const models = [
  { id: "claude-haiku-5-5", input: 0.1, output: 0.5 }, // prompts up to 100K tokens
  { id: "claude-sonnet-5-5", input: 2, output: 10 },
  { id: "claude-opus-5-5", input: 4, output: 20 },
  { id: "claude-fable-5-2", input: 8, output: 40 },
];
// The workload (assumptions): a support assistant.
const requestsPerDay = 20_000;
const inputTokens = 3_000; // system prompt + retrieved help articles + question
const outputTokens = 400; // answer, thinking included

const monthly = (m) => ((inputTokens * m.input + outputTokens * m.output) / 1e6) * requestsPerDay * 30;
for (const m of models) console.log(`${m.id.padEnd(18)} $${Math.round(monthly(m)).toLocaleString("en-GB").padStart(6)} a month`);

// Pass rates on YOUR eval set (200 real questions graded against reference answers).
// Illustrative numbers for the sketch, not published benchmark results.
const passRate = { "claude-haiku-5-5": 0.81, "claude-sonnet-5-5": 0.93, "claude-opus-5-5": 0.95, "claude-fable-5-2": 0.96 };
const target = 0.92;
const choice = models.filter((m) => passRate[m.id] >= target).sort((a, b) => monthly(a) - monthly(b))[0];
console.log(`target ${target * 100}% -> ${choice.id} (${passRate[choice.id] * 100}%, $${Math.round(monthly(choice)).toLocaleString("en-GB")} a month)`);
Result
claude-haiku-5-5   $   300 a month
claude-sonnet-5-5  $ 6,000 a month
claude-opus-5-5    $12,000 a month
claude-fable-5-2   $24,000 a month
target 92% -> claude-sonnet-5-5 (93%, $6,000 a month)
What’s happening
  1. monthly multiplies each request's cost (input tokens × input price + output tokens × output price, divided by a million) by 20,000 requests a day for 30 days.
  2. The spread is a factor of 80: $300 a month on Claude Haiku 5.5 against $24,000 on Claude Fable 5.2 for the same traffic. Model choice is usually the single biggest cost decision in an AI feature.
  3. passRate stands in for the results of running your own eval set (say 200 real support questions graded against reference answers) on each model. With a target of 92%, Haiku's 81% rules it out.
  4. Among the models that pass, the code picks the cheapest: Claude Sonnet 5.5 at 93% and $6,000 a month. Opus 5.5 and Fable 5.2 score a little higher but cost two and four times as much for gains the target doesn't need.
  5. The decision is only as good as the eval: if the 200 questions don't reflect real traffic, the "cheapest passing model" is a guess. Re-run it when prices change or new models ship, and before switching, check latency and effort too (Opus 5.5 at low effort might beat Sonnet at high effort on both cost and quality for some tasks).
AdvancedOpen weights or an API?
Hosted API (Claude, GPT, Gemini)Open-weight model you serve
Qualitythe strongest models availablestrong and improving; the best open models are large and need serious hardware
Cost shapepay per token, nothing when idlepay for hardware whether busy or idle; can be cheaper at high, steady volume
Datasent to the vendor under its terms (retention options vary)stays in your infrastructure
Controlvendor decides versions, deprecations, limitsyou pin weights forever, can fine-tune freely
Work for youan SDK callserving, scaling, monitoring, safety, upgrades
Sampling settingsremoved on current Claude modelsfull control (temperature, top-p, seeds)

Many teams use both: a hosted frontier model for the hard, user-facing work, and a small open model for cheap, private or offline tasks (embedding, classification, PII detection in the browser). This site's AI Lab runs small open models in your browser for exactly that reason (Small models in the browser).

Two options, one budget

Option A: Claude Opus 5.5 at low effort. Option B: Claude Sonnet 5.5 at high effort. Both cost about the same per request on your traffic. What do you do?

Show answer

Run both on your eval and pick on quality, then latency; don't decide from the model names.

What’s happening
  1. Price per request is similar, so it doesn't separate them. Quality on your task does, and only your eval can measure it.
  2. Effort changes behaviour a lot: a more capable model at low effort can match or beat a smaller model working harder, and Anthropic suggests measuring exactly this before building multi-model setups.
  3. Compare latency too: high effort means more thinking tokens, so a longer wait before the answer.
  4. Check the cost per completed task, including retries and fallbacks, not just per call, then pin the winner's model id and effort in config so the choice is visible and easy to revisit.

Written fresh for AI engineering interviews (there was no Google Doc for this one). Examples were run on Node 26 with @anthropic-ai/sdk 1.17.0, the AI SDK 7.1 and transformers.js 4.3; API facts were checked against Anthropic’s documentation in December 2026.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.