What an LLM actually does
Next-token prediction, and why that produces useful behavior.
Why it matters
You can already send a request to a model and read the reply. To build something reliable on that call, you need a picture of what happens in between. Most prompting advice in Phase 1 follows from one fact, and so do most of the ways LLM apps fail. The model writes its reply by predicting the next token, over and over. Once that clicks, you'll know when to trust a model, when to check it, and when to hand the job to ordinary code.
What you'll be able to do
- Describe how a model writes a reply one token at a time
- Explain where a model's knowledge comes from, and why it can sound sure and still be wrong
- Spot tasks that need checking or plain code instead: counting, recent facts, exact math
- Simulate the generation loop in Python with a toy probability table
What it covers
- Autocomplete, run in a loop
- The top choice doesn't always win
- Where the probabilities come from
- Why models get some things wrong
- Worked example: let code do the math
Autocomplete, run in a loop
Your phone's keyboard suggests the next word as you type. A large language model (LLM) does the same job at an enormous scale. You give it some text. It works out how likely each possible next piece of text is.
Those pieces are called tokens. As in your first LLM call, a token is a word or a piece of a word. The model reads tokens, which are chunks of characters, so individual letters aren't directly visible to it: that's why it can miscount the letters in a word. The full list of tokens a model knows is its vocabulary. The model gives every token in its vocabulary a probability. That's a number from 0 to 1 saying how likely the token is to come next. A probability of 0.31 means "about 31 times in 100".
Take the text Our spring sale ends. A model might score the candidates like this (numbers invented for illustration):
| Next token | Probability |
|---|---|
Sunday | 0.31 |
soon | 0.22 |
tomorrow | 0.18 |
March | 0.09 |
| thousands of others | the remaining 0.20 |
Notice the space before Sunday in the table. Tokens often include the space in front of a word. The probabilities across the whole vocabulary add up to 1, the same way the slices of a pie add up to the whole pie.
In plain words: the model looks at your text and asks "what usually comes next?" Its answer is a list of options, each with a score for how likely it is.
Show the answer
A probability for every possible next token
It scores every token it knows, and one gets picked. Then it does the same again on the longer text.
The model picks one token and adds it to the end of the text. Then it runs again on the longer text to score the token after that. That's the whole generation process:
- Read all the text so far: your prompt plus everything generated already.
- Give every possible next token a probability.
- Pick one token and add it to the end.
- Repeat. Stop when the model picks a special end-of-reply token, or when the reply reaches
max_tokens(the length limit you set in your request).
A 300-word reply is a few hundred trips around that loop. The model doesn't write the whole answer in private first and then type it out. It chooses each token in light of the ones before it.
The step-through below runs the same loop on a toy "model". The toy is a Python dictionary. For each word, it lists the words that can follow and their probabilities. The loop always takes the most likely option. That's called greedy picking, because it grabs the biggest number every time.
Watch the text grow by one word per pass. Each pass looks up the options for the last word, keeps the one with the highest probability and adds it to the end. It stops when "<end>" wins.
"sale": {"ends": 0.3, "<end>": 0.7},
Show the answer
our spring sale
After "sale", greedy picking now takes "<end>", because 0.7 beats 0.3. The loop stops and prints the three words it has. One changed probability changed the whole reply.
A real model differs from this toy in two big ways:
- It looks at all the text so far, not only the last word. So "sale ends" after "Black Friday" gets different scores than "sale ends" after "spring".
- Its probabilities come from billions of learned numbers, not a hand-written table.
The loop has the same shape.
The top choice doesn't always win
If a model always took the most likely token, the same prompt would give the same reply every time. Chat models usually sample instead. Sampling means picking at random, but weighted by the probabilities. Think of a raffle where Sunday holds 31 tickets out of every 100 and soon holds 22. So Sunday wins about 31% of the time and soon about 22%.
One different pick early on changes everything after it. That's why asking twice can get you two different subject lines.
Python's random.choices makes the same kind of weighted pick:
import random options = ["Sunday", "soon", "tomorrow", "March"] weights = [0.31, 0.22, 0.18, 0.09] for attempt in range(5): pick = random.choices(options, weights=weights)[0] print("Our spring sale ends", pick)
random.choices can pick several items at once, so it returns a list. [0] takes the single pick out of that list. Run the cell a few times. The likely words show up most often, but not every time. (The weights here don't add up to 1. random.choices only cares how big they are compared with each other.)
Note: Earlier versions of the API let you tune how adventurous the picking is with a setting called
temperature. The current version (2026-10-21) doesn't accept it. Phase 5 explains how sampling works inside a model.
Go deeper How often does sampling write the greedy sentence?
Go back to the toy model in the step-through. Suppose it sampled instead of picking greedily. How often would it write "our spring sale ends sunday"?
Each step has to go the greedy way. After "our", "spring" wins 6 times in 10 (0.6). After "spring", "sale" wins 0.7 of the time. Then "ends" wins 0.6, "sunday" wins 0.7, and "<end>" is certain at 1.0.
To get the chance that every step goes that way, you multiply the chances together: 0.6 × 0.7 × 0.6 × 0.7 × 1.0 = 0.1764.
chance = 0.6 * 0.7 * 0.6 * 0.7 * 1.0 print(round(chance, 4))
So a sampling version of the toy writes the greedy sentence only about 18 times in 100. A real reply can have hundreds of tokens, so two long sampled replies rarely match word for word.
Show the answer
Each token is sampled at random, weighted by probability, so the two replies took different paths
Sampling means a less likely token sometimes wins, and every later token builds on that choice. The model itself doesn't change between requests.
Where the probabilities come from
The probabilities come from training. Training happens in two broad stages.
Pretraining. The model reads a huge amount of text: web pages, books, articles and code. At each spot in the text, it guesses the next token. Then it compares its guess with the real next token. It nudges its internal numbers so it would guess a little better next time. Those numbers are called parameters, or weights, and a large model has billions of them.
Repeat that over trillions of tokens and the model picks up grammar, facts, writing styles and patterns of reasoning. It learns all of those because they all help predict text.
Go deeper What "nudging the numbers" means
Say the real next token is Sunday and the model gave it a probability of 0.2. Training changes the parameters by a tiny amount. Afterwards, on the same text, Sunday gets a bit more than 0.2. The total still has to be 1, so the other tokens' shares shrink a little, overall, to make room.
Each change is small. Billions of them, over trillions of tokens, add up to a model that writes well. Phase 3 shows the method behind the nudging, called gradient descent. This is a simplification, but it's the right picture.
Show the answer
It predicts the next token, and each miss nudges its numbers a little
There's no rulebook inside. Trillions of small corrections are what produce a model that writes well.
Post-training. A pretrained model continues text. It doesn't reliably follow instructions. Give it "Write a subject line for our spring sale" and it might carry on with more lines that look like a list of homework prompts. So it gets more training on example conversations, plus feedback on which replies are better. That turns it into an assistant. It answers the request, follows a system prompt, declines harmful tasks and stops when it's done. Phase 6 covers both stages in depth.
Three practical consequences follow:
- Knowledge has a cutoff. The model knows what was in its training data, up to the date that data was collected. It doesn't know this week's news, yesterday's campaign results or anything in your company's files. It only sees those if you put them in the request.
- It doesn't look things up. By default, nothing gets searched or checked. A model uses a search engine, a database or your documents only when the app around it provides them. That happens through tools or retrieval, both covered later in Phase 1.
- It doesn't learn from your requests. Every request runs on the same fixed model. Your conversations don't change it.
Reasoning models such as Claude Opus 5.5 fit the same picture. The thinking block you saw in your first call is text the model generates, token by token, before its answer. Writing out the steps in between gives the later tokens more to build on. That's why thinking helps on hard problems. Those thinking tokens are billed as output.
Show the answer
No. Every request runs on the same fixed model, and it only sees what's in that request
Requests don't change the model. If Tuesday's reply needs the slogan, put the slogan in Tuesday's request.
Why models get some things wrong
Next-token prediction explains most of the odd behavior you'll run into. The best known is a hallucination: a confident, specific answer that's false.
| What you see | Why it happens | What to do |
|---|---|---|
| A confident, specific, false answer (a hallucination) | Training rewards likely text, and a plausible-sounding claim is likely whether or not it's true | Give the model the facts to work from, allow "I don't know", and check claims that matter |
| Wrong about recent events | The training data has a cutoff date | Put current information in the prompt |
| Miscounts letters or words | It sees tokens, not individual letters | Count with code: len() |
| Slips on long exact arithmetic | Numbers are split into tokens too; thinking helps, but code is exact | Calculate in Python, then have the model explain the results |
| A different answer each time | Sampling | Check the structure of replies, not their exact wording |
| Mirrors the style of your prompt | The prompt is the text it's continuing, so it shapes every prediction | Write clear prompts and show examples (the next few lessons) |
Tip: Use the model for language work: explaining, rewriting, classifying and summarizing. Use code for anything that must be exact.
Worked example: let code do the math
Two campaigns' raw numbers need a short explanation for your manager. Two rates matter here:
- CTR (click-through rate) is the share of people who saw an ad and clicked it. If an ad is shown 200 times and gets 5 clicks, the CTR is 5 ÷ 200 × 100 = 2.5%.
- Conversion rate is the share of clickers who went on to do what you wanted, such as buy.
"Impressions" means the number of times the ad was shown. Python calculates both rates. Then the model gets the finished numbers and explains them.
import requests campaigns = [ {"name": "Spring Sale", "impressions": 182000, "clicks": 5470, "conversions": 301}, {"name": "Brand Video", "impressions": 410000, "clicks": 3800, "conversions": 41}, ] lines = [] for c in campaigns: ctr = c["clicks"] / c["impressions"] * 100 conversion_rate = c["conversions"] / c["clicks"] * 100 lines.append(f"{c['name']}: CTR {ctr:.2f}%, conversion rate {conversion_rate:.2f}%") facts = "\n".join(lines) prompt = f"""Here are last week's campaign results, already calculated: {facts} In two sentences, explain to a busy manager which campaign performed better and why.""" response = requests.post( "https://api.anthropic.com/v1/messages", headers={"x-api-key": "added-by-the-academy-server", "anthropic-version": "2026-10-21"}, json={ "model": "claude-opus-5-5", "max_tokens": 1000, "messages": [{"role": "user", "content": prompt}], }, timeout=60, ) response.raise_for_status() print(facts) print() for block in response.json()["content"]: if block["type"] == "text": print(block["text"])
The division happens in Python, where it's exact every time. For Spring Sale, 5,470 clicks ÷ 182,000 impressions × 100 gives a CTR of 3.01%. The model receives numbers it can't miscalculate. It does the part it's good at: turning them into a clear, readable explanation.
You could paste the raw counts and ask the model for the rates instead. It would usually get them right. But "usually" isn't good enough for a report your manager forwards.
Show the answer
Rewriting a product description in a friendlier tone
Counting, totaling and date comparisons must be exact, and code does them perfectly. Rewriting in a different tone is a language task, which is what models are good at.
Practice what you just read
- 3 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 5 review cards for spaced repetition
Try a quiz question
A model has generated the token Sunday partway through a reply. What happens next?