How an LLM Generates Text

Updated · 5 min read
mediumPython 3.13aillmnext-token-predictiongenerationbeginnersinterview

Does a chat assistant plan its whole answer before writing? Navika watches a reply appear on her screen in Dallas, a few words at a time, and wonders whether the assistant already "knows" the end of the sentence. It doesn't. It writes one small piece at a time, choosing each piece based on everything written so far.

This lesson shows that loop, called next-token prediction, step by step.

One Token at a Time

An LLM generates text in a loop:

  1. Read the text so far: your prompt, plus anything already generated.
  2. Score every possible next token and turn the scores into probabilities.
  3. Choose one token, often the most likely one, or a likely one picked with some randomness.
  4. Add it to the text, and go back to step 1.
  5. Stop when the model produces an end token or reaches a length limit.
Predict, add, repeat, stop

The Loop in Python

This toy "model" is a table of likely next tokens. Real models calculate these probabilities with billions of parameters; the loop around them is the same:

Python
# A toy "model": for each text so far, the likely next tokens and their probabilities
next_token = {
    "The capital of France is": {" Paris": 0.92, " a": 0.05, " Lyon": 0.03},
    "The capital of France is Paris": {".": 0.88, ",": 0.10, " and": 0.02},
    "The capital of France is Paris.": {"<end>": 0.97, " It": 0.03},
}
 
text = "The capital of France is"
while True:
    choices = next_token[text]
    best = max(choices, key=choices.get)  # pick the most likely next token
    print(f"{text!r} -> {best!r} ({choices[best]:.0%})")
    if best == "<end>":
        break
    text += best
Output
'The capital of France is' -> ' Paris' (92%)
'The capital of France is Paris' -> '.' (88%)
'The capital of France is Paris.' -> '<end>' (97%)

Notice the spaces: the token is " Paris", with a leading space. Tokens are pieces of text, not words, as "Tokens" explains. Real models are far more complex: they choose among about 200,000 possible tokens, consider the whole conversation, and calculate fresh probabilities at every step.

Why This Explains a Lot

What you noticeWhy
Replies appear word by wordThe app shows each token as soon as it is generated
The same question gets different answersTokens are often picked with some randomness, as "Temperature and Randomness" shows
A wrong start can lead to a wrong answerEach token builds on the earlier ones, so an early mistake carries forward
Confident but false answersThe model picks tokens that fit, not facts it has checked; see "Why LLMs Hallucinate"

Common Mistakes

Thinking the model writes whole sentences at once. It produces one token at a time.

Thinking "most likely" means "true". The most likely next token is the one that best fits patterns, which is usually but not always correct.

Thinking the model looks back and edits its answer. In the basic loop, once a token is generated, it stays; reasoning models may revise their thinking before the final answer.

Interview Corner

How does an LLM generate text?

By next-token prediction: it reads the text so far, calculates probabilities for every possible next token, chooses one, appends it, and repeats until an end token or a length limit.

Why can an LLM give a confident wrong answer?

Each token is chosen because it fits the patterns, not because it was checked against facts. A fluent, likely-sounding continuation can still be false.

Practice

Exercise: extend the toy model. Add a new starting text, "The capital of Japan is", with its own likely next tokens, and the entries needed to finish the sentence. Run the loop from your new text. Then change one probability so a different token wins, and see how the whole sentence changes.

Check your understanding:

  1. List the five steps of the generation loop.
  2. Why does each token depend on the ones before it?
  3. When does generation stop?

Quick check: how LLMs generate text

4 questions
1How does an LLM produce a reply?
2What does the model use to choose the next token?
3When does generation stop?
4Why can an early mistake spoil an answer?

Key Takeaways

Quick reference

TermMeaning
Next-token predictionChoosing the next piece of text from the text so far
ProbabilityHow likely the model thinks each next token is
End tokenA special token that tells the model to stop

Was this tutorial helpful?

Lesson 28 of 186