Lesson 2.2 · 2 of 6 · 6 min read · Reviewed 24 Nov 2026
Next-token prediction
By the end, you can
- Describe the predict, sample, append loop that produces output.
- Name the three ways generation stops and the stop_reason for each.
At its core, a language model does one thing: given a sequence of tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id., it produces a score for every token in its vocabulary saying how likely it is to come next. A softmax turns those scores into probabilities that add up to 1.
The generation loop
- Feed in the context (the prompt so far).
- Get a probability distribution over the next token.
- Sample one token from it.
- Append that token to the context and repeat.
That loop is why responses stream out word by word, and why output tokensOutput tokens: The tokens the model generates in its reply, including any tool calls and thinking. are slower and pricier than input tokensInput tokens: The tokens you send in a request: system prompt, tool definitions, conversation history and attached content.: every output token needs its own pass through the model, while the input can be processed in parallel.
When does it stop?
The loop ends when one of these happens:
- the model produces its end-of-turn token (
stop_reason: "end_turn") - the output matches one of your
stop_sequences(stop_reason: "stop_sequence") - it reaches your
max_tokenslimit (stop_reason: "max_tokens"), which can cut an answer mid-sentence
Prediction is not lookup
Nothing in this loop retrieves a stored fact. The model has learned patterns that make true continuations likely, which is why it is usually right and also why it can produce a fluent, confident and wrong answer. Chapter 7 covers how to ground answers in sources.
Key points
- A model outputs a probability for every possible next token.
- Generation is a loop of predict, sample, append.
- Generation stops at an end-of-turn token, a stop sequence or max_tokens.
Write the predict, sample, append loop
Generate text from a toy next-token table and stop it each of the three ways a real model stops.
You will have: A generate() function that returns text plus end_turn, max_tokens or stop_sequence.
Steps
- Look up the distribution for the last token and pick the most likely next token.
- Return end_turn when the end token is chosen.
- Append the token and repeat, stopping at max_tokens.
- Cut the text and return stop_sequence when a stop sequence appears.
Done when
- A long budget ends with stop_reason end_turn and a full sentence.
- A budget of 3 ends with max_tokens mid-sentence.
- The stop sequence " the" ends with stop_sequence and the text before it.
Open in the Playground No API key needed.
Starter code (Python)
NEXT = {
"<start>": {"The": 0.7, "A": 0.3},
"The": {" cat": 0.6, " dog": 0.4},
"A": {" cat": 0.5, " dog": 0.5},
" cat": {" sat": 0.8, " ran": 0.2},
" dog": {" ran": 0.7, " sat": 0.3},
" sat": {" on": 0.9, ".": 0.1},
" ran": {" home": 0.6, ".": 0.4},
" on": {" the": 1.0},
" the": {" mat": 0.7, " roof": 0.3},
" mat": {".": 0.9, " again": 0.1},
" roof": {".": 1.0},
" home": {".": 1.0},
".": {"<end>": 1.0},
}
def generate(max_tokens, stop_sequences=()):
context, out = ["<start>"], ""
# TODO: loop up to max_tokens times: look up NEXT[context[-1]], pick the most likely token
# TODO: return (out, "end_turn") on "<end>"; otherwise append the token to context and out
# TODO: if out contains a stop sequence, return the text before it and "stop_sequence"
return out, "max_tokens"
for max_tokens, stops in [(20, ()), (3, ()), (20, (" the",))]:
text, reason = generate(max_tokens, stops)
print(f"max_tokens={max_tokens:2} stops={list(stops)} -> {text!r} stop_reason: {reason}")
Show a solution
# A toy "model": for each last token, a probability for every possible next token.
NEXT = {
"<start>": {"The": 0.7, "A": 0.3},
"The": {" cat": 0.6, " dog": 0.4},
"A": {" cat": 0.5, " dog": 0.5},
" cat": {" sat": 0.8, " ran": 0.2},
" dog": {" ran": 0.7, " sat": 0.3},
" sat": {" on": 0.9, ".": 0.1},
" ran": {" home": 0.6, ".": 0.4},
" on": {" the": 1.0},
" the": {" mat": 0.7, " roof": 0.3},
" mat": {".": 0.9, " again": 0.1},
" roof": {".": 1.0},
" home": {".": 1.0},
".": {"<end>": 1.0},
}
def generate(max_tokens, stop_sequences=()):
context, out = ["<start>"], ""
for _ in range(max_tokens):
probs = NEXT[context[-1]] # 1-2. predict a distribution
token = max(probs, key=probs.get) # 3. pick (greedy, so the run is repeatable)
if token == "<end>":
return out, "end_turn"
context.append(token) # 4. append and repeat
out += token
for s in stop_sequences:
if s in out:
return out[: out.index(s)], "stop_sequence"
return out, "max_tokens"
for max_tokens, stops in [(20, ()), (3, ()), (20, (" the",))]:
text, reason = generate(max_tokens, stops)
print(f"max_tokens={max_tokens:2} stops={list(stops)} -> {text!r} stop_reason: {reason}")
Do it See a reply cut off at max_tokens in the Playground. No API key needed.