Sub topic 1
How a Model Produces Text One Token at a Time
This chapter covers the first idea in the streaming plan: a language model generates its answer one token at a time. Every later chapter builds on that fact, including why streaming exists, how events are shaped, and why tool-call JSON arrives in fragments.
Prerequisites
This chapter assumes you have:
- A basic idea of what a token is (a chunk of text, often a word piece, that the model reads and writes).
- Experience calling an LLM API at least once and reading its JSON response.
- Comfort reading short Python snippets.
You do not need to know how neural networks work internally. The chapter treats the model as a function that returns a probability for each possible next token.
The core idea: predict the next token
A large language model does not write a sentence in one step. It reads the text so far (the prompt plus anything it has already written) and produces a score for every token in its vocabulary. These scores become probabilities. One token is chosen, appended to the text, and the process repeats.
This loop is called autoregressive generation. "Auto" means self and "regressive" means each step depends on earlier ones. The model's own output becomes part of its next input.
Two consequences matter for the rest of the tutorial:
- The model cannot know the full answer before it starts writing. Token 50 does not exist until token 49 has been chosen.
- Because tokens are produced in order, each one can be sent to the client the moment it exists. Nothing in the algorithm forces the server to wait for the end.
A runnable toy model
The following program imitates the loop with a hand-written table of next-token probabilities. It is not a real model, but the control flow matches: look up probabilities, sample, append, check for a stop token.
import random
# For each previous token, the possible next tokens and their weights.
NEXT = {
"<start>": [("Streaming", 1.0)],
"Streaming": [(" is", 0.7), (" lets", 0.3)],
" is": [(" incremental", 0.6), (" useful", 0.4)],
" lets": [(" users", 1.0)],
" users": [(" read", 1.0)],
" read": [(" early", 1.0)],
" incremental": [(".", 1.0)],
" useful": [(".", 1.0)],
" early": [(".", 1.0)],
".": [("<end>", 1.0)],
}
def generate(seed=None, max_tokens=20):
"""Yield one token at a time, like a model decoding loop."""
rng = random.Random(seed)
current = "<start>"
for _ in range(max_tokens):
choices, weights = zip(*NEXT[current])
current = rng.choices(choices, weights=weights)[0]
if current == "<end>":
return
yield current
tokens = list(generate(seed=1))
print(tokens)
print("".join(tokens))Because generate is a Python generator, it already behaves like a stream. A caller can print each token as it arrives or collect them all first. The generator does the same work either way. Only the caller's behavior changes.
Where the time goes
Each pass through the loop runs the model's computation once. This pass is the expensive part, and it happens once per output token. Generation time therefore grows roughly in line with the number of tokens produced.
Providers describe the timing of a request with a few common measures:
| Measure | Meaning | What drives it |
|---|---|---|
| Time to first token (TTFT) | Delay from sending the request to receiving the first output token | Queueing, network, and processing the whole prompt |
| Inter-token latency | Gap between consecutive output tokens | Model size, hardware, load, and batching |
| Total generation time | Time until the last token | TTFT plus output length times inter-token latency |
A rough model is:
total_time ≈ TTFT + (output_tokens - 1) × inter_token_latencyWith a TTFT of 0.6 s, an inter-token latency of 25 ms, and a 400-token answer, the total is about 0.6 + 399 × 0.025, or roughly 10.6 s. A non-streaming client shows nothing for those 10.6 s. A streaming client shows the first words after 0.6 s.
Why the prompt is handled differently
The prompt is processed in one parallel pass. The model sees all prompt tokens at once, so a long prompt delays the first token but does not add a pass per prompt token. The output tokens cannot be parallelized in the same way, because each depends on the one before. This is why TTFT grows with prompt length, while the per-token gap stays roughly steady.
Many serving systems also keep a cache of intermediate values (often called a KV cache) so each new token does not recompute the whole history. You do not control this directly, but it explains why the per-token gap stays small even as the text grows.
Sampling: why the same prompt can give different text
Choosing "one token from the probabilities" is a decision with settings you can often change through the API.
- Temperature rescales the probabilities. Low values make the top token dominate. High values flatten the distribution so unlikely tokens are chosen more often.
- Top-p (nucleus sampling) limits the choice to the smallest group of tokens whose combined probability reaches p.
- A seed, where the provider supports one, makes sampling repeatable, though not always perfectly.
Each token is chosen once and then fixed. A client that has received "Hello" will never be told that the model "changed its mind" and meant "Help". Streamed text is append-only. This property makes the client simple: you can add each delta to the end of a buffer without handling edits.
Stopping: how the loop ends
The loop ends for one of a few reasons, and the API reports which one as a finish reason:
- The model emitted a special end-of-sequence token. This is a normal, complete finish.
- The output reached the maximum token limit you set. The text may stop mid-sentence.
- A stop sequence you supplied appeared in the output.
- The model chose to call a tool, so the turn ends with a tool request.
- A safety system stopped the output.
Exact names and values differ between providers, and a later chapter covers them. For now, remember that a stream can end without the answer being finished. The stop reason tells you which case you are in.
Tokens are not words
Streaming delivers tokens, and tokens do not line up with words or characters.
- A token may be a whole word, part of a word, punctuation, or whitespace.
- Leading spaces are usually part of the token, as in
" is"in the toy model above. - A single character can be split across several tokens. This happens with some emoji and non-Latin scripts, where one character is several bytes.
# The same character expressed as bytes. A tokenizer may split these bytes
# across tokens, so a partial token is not always valid text on its own.
emoji = "👍"
raw = emoji.encode("utf-8")
print(len(emoji), len(raw)) # 1 4
print(raw[:2].decode("utf-8", errors="replace")) # a replacement characterProviders normally merge pieces so that each text delta you receive is valid text. Still, do not assume one event equals one word, and never trim whitespace from deltas. Trimming " is" to "is" produces "Streamingis".
Common errors at this stage
- Believing streaming makes generation faster. The model produces tokens at the same rate either way. Streaming changes when you see them, not how fast they are made. Total time is about the same, and can be slightly longer because of per-event overhead.
- Expecting a steady rhythm. Tokens can arrive in bursts, because of batching on the server or buffering along the network path. Do not build logic that depends on regular timing.
- Treating each delta as a word. Join deltas by plain concatenation, with no added spaces.
- Assuming the answer is complete when the stream ends. Check the finish reason. A length cutoff looks like a clean end if you ignore it.
- Ignoring prompt cost. A very long prompt delays the first token, so streaming helps less when the wait is spent before any output begins.
What comes next
The following chapter uses this loop to explain why perceived latency matters, then later chapters follow each token across HTTP, Server-Sent Events, parsing, and the browser.
Exercise
A model has a TTFT of 0.8 s and an inter-token latency of 20 ms. It writes a 300-token answer. Roughly how long does a non-streaming client wait before seeing anything, and how long does a streaming client wait before seeing the first text? Does streaming change the total generation time?
Show answer
The non-streaming client waits for the whole answer: about 0.8 + 299 × 0.02 = 6.78 s, so roughly 6.8 s. The streaming client sees the first text after about 0.8 s. Streaming does not shorten generation. The last token is still produced at about 6.8 s either way. It only lets the user read while the rest is being produced.
Exercise
Why can a streaming client safely append each text delta to the end of a buffer without ever editing earlier text? And why is trimming whitespace from each delta a bug?
Show answer
Generation is autoregressive. Each token is sampled once and then becomes fixed input for later steps, so earlier text is never revised and the stream is append-only. Whitespace is often part of a token (for example " is"), so trimming it joins words together, producing text like "Streamingis".