Artificial Intelligence Fundamentals / Inside Generative AI

Generate text one token at a time

Lesson 20 of 26. Open to read. No account needed.

The Generation Loop

A language model is trained for one task: given the text so far, predict the next token. To produce a whole answer, that single step runs in a loop. The model looks at the prompt, chooses a next token, appends it, and then predicts again from the longer text, including its own output, until it reaches a length limit or a token that means "stop".

At each step the model does not produce a single answer. It produces a probability for every token in its vocabulary: how likely each one is to come next. How the next token is then chosen from those probabilities has a large effect on the result.

The generation loop: the text so far goes into the model, which produces next-token probabilities. One token is chosen, either the most likely or a weighted random choice. The chosen token is appended to the text, and the loop repeats until a length limit or a stop token.

Follow the loop round. The only way out is the stop condition at the bottom; everything else feeds the growing text back in. The model never plans the whole answer: each token depends on everything before it.

Choosing the Next Token

  • Greedy choice always takes the most likely token. It is predictable, but in longer texts it tends to repeat itself, because the same context keeps leading to the same choice.
  • Sampling makes a random choice, weighted by the probabilities: a token with probability 0.7 is chosen about 70% of the time, one with 0.1 about 10% of the time. Output varies from run to run and repeats less.

The Hugging Face Transformers library, for example, uses greedy choice by default and switches to sampling when asked. Chat assistants usually sample, which is why asking the same question twice can give two different answers.

Temperature adjusts sampling. It reshapes the probabilities before the choice: a temperature below 1 makes likely tokens even more likely, so output becomes more predictable; above 1 it flattens the differences, so output becomes more varied and more often odd. At exactly 1, the probabilities are used as they are; in Transformers, 1.0 is the default when a model sets no other value.

Random choices on a computer come from a generator that can be seeded. The same seed gives the same sequence of choices, so the same output, which is useful for testing; a different seed gives a different output.

A Toy Model You Can Read

A real language model computes its probabilities with billions of learned weights. The exercise below uses a much simpler stand-in that you can read completely: it counts, in a short text, which character follows which. If a is followed by t 7 times and by w twice, the toy model's next-character probabilities after a are 7/9 for t and 2/9 for w.

This is an illustration, not a small language model. It looks only at the last character, has no understanding of words and learns nothing beyond the counts. What it does share with real models is the loop: probabilities, a choice, append, repeat.

Exercise: Generate Text With a Toy Model

You will count next characters in a course-written text, then generate text greedily, by sampling with different seeds, and at a lower temperature.

Starting state: the course environment, active in your terminal. The script uses only plain Python.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/toy-generator
    cd ~/ai-practice/toy-generator
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\toy-generator
    cd $HOME\ai-practice\toy-generator
    

    Save this as toy_generator.py in that folder:

    """Generate text one character at a time from next-character counts."""
    import random
    from collections import Counter, defaultdict
    
    text = (
        "the cat sat on the mat. the dog sat on the log. "
        "the cat saw the dog. the dog saw the cat on the mat. "
    )
    
    # Count which character follows each character in the text.
    follows = defaultdict(Counter)
    for current, following in zip(text, text[1:]):
        follows[current][following] += 1
    
    print("After 'a':", dict(follows["a"].most_common()))
    
    
    def generate(start, length, rng=None, temperature=1.0):
        result = start
        for _ in range(length):
            counts = follows[result[-1]]
            if rng is None:  # greedy: always take the most frequent next character
                result += counts.most_common(1)[0][0]
            else:  # sampling: a random choice, weighted by the counts
                weights = [count ** (1 / temperature) for count in counts.values()]
                result += rng.choices(list(counts), weights=weights)[0]
        return result
    
    
    print("Greedy:         ", generate("t", 40))
    print("Seed 1:         ", generate("t", 40, random.Random(1)))
    print("Seed 2:         ", generate("t", 40, random.Random(2)))
    print("Seed 1 again:   ", generate("t", 40, random.Random(1)))
    print("Seed 1, temp 0.3:", generate("t", 40, random.Random(1), temperature=0.3))
    
  2. Before running it, predict what the greedy line will look like. Then run the script:

    python toy_generator.py
    

    Output, which should match exactly:

    After 'a': {'t': 7, 'w': 2}
    Greedy:          the the the the the the the the the the t
    Seed 1:          the sat mat t cathe cat. sathe sathe dog 
    Seed 2:          t. caw the the t. the cathe the saw saw d
    Seed 1 again:    the sat mat t cathe cat. sathe sathe dog 
    Seed 1, temp 0.3: the the the the the cat the the the cathe
    

How the Script Works

Counting. follows maps each character to a Counter of the characters that come after it. zip(text, text[1:]) pairs every character with the next one, and each pair adds one to a count. The first line of output shows the counts after a.

generate. Starting from start, the loop adds length characters. Each time, it looks up the counts for the last character so far, result[-1]:

  • With no random generator, rng=None, it takes the most frequent next character: greedy choice.
  • Otherwise it calls rng.choices, which picks one character at random, weighted by weights. Each count is raised to the power 1 / temperature. With temperature 1 the weights are the counts themselves; with 0.3 the power is about 3.3, so frequent characters gain weight far faster than rare ones: after a, the share of t rises from 0.78 to about 0.98.

random.Random(1) creates a random generator with seed 1.

What the results show. Greedy choice falls straight into a loop: after e the most frequent character is a space, after a space t, after t h, after h e, and round again. Sampling escapes the loop and produces varied, word-like text. Seeds 1 and 2 give different text; seed 1 used twice gives the same text exactly. At temperature 0.3, sampling with seed 1 behaves almost like greedy choice, with only occasional variation.

Notice also what the samples contain: "cathe" and "sathe", which are not words and never appear in the text. The model produced them because each pair of neighbouring characters is common. Fluent-looking output built from local patterns is the subject of the next lesson.

Success: the output matches; you can explain why greedy choice loops, why seed 1 repeats, and what temperature 0.3 did.

If something differs:

What you seeLikely causeNext step
The sampled lines differ from the listingThe text or a seed was changedRestore the text and seeds exactly; the counts must match
IndexError: list index out of rangeThe start character never appears in the text, so it has no counts to choose fromStart with a character that is followed by something in the text, such as t
ZeroDivisionErrortemperature=0 was used; dividing by zero is impossibleUse a small positive temperature such as 0.1
The lines are not alignedOnly spacing in the labels differsCompare the generated text, not the spaces
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf toy-generator
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse toy-generator
    ls
    

    Check that the first ls shows toy-generator before removing it. Do the independent task first.

Independent task: replace the two text lines with one line of your own, "a red fox ran to a big box. a big fox hid in a red box. ", change the start character in every generate call from "t" to "a", and change the counts line to show what follows o. Predict what the greedy line will do, then run the script.

Check Your Understanding

  1. A chat assistant gives two different answers to the same question. Name the step in the generation loop that explains this.
  2. A team wants the most consistent, predictable answers from an assistant. Should they raise or lower the temperature, and what do they give up?
  3. Does the toy model "know" that "cathe" is not a word? Why does it produce it?

Answer and Reasoning

Independent task

The script now prints counts after o, {'x': 4, ' ': 1}, and the greedy line becomes a big big big big big big big big big big. Greedy choice again falls into a loop, this time "big": after g comes a space, after a space b, after b i, after i g. The sampled lines mix pieces such as "red", "fox" and "box" in new orders. The same code produces different text from a different training text, because everything it "knows" comes from the counts.

Understanding check

  1. The choice of the next token. Assistants usually sample from the probabilities, so each run can choose differently, and each different choice changes everything that follows.
  2. Lower it. Likely tokens then dominate and answers repeat more, at the cost of less variety and, as greedy choice shows, a tendency to repeat themselves.
  3. No. It knows only how often each character follows another. "ca", "at", "th" and "he" are all common pairs, so chaining them is likely, whether or not the result is a word. Likelihood is not correctness.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy