Sub topic 1
How a Model Produces Text One Token at a Time
Prerequisites
Assume you understand basic HTTP requests, JSON, Python or JavaScript, asynchronous code, and the idea of an LLM token. A token is a small piece of text, such as a word, part of a word, or punctuation mark.
From Tokens to Visible Text
An autoregressive language model generates output repeatedly:
- It reads the prompt and the tokens already generated.
- It calculates probabilities for the next token.
- It selects a token according to the decoding settings.
- It adds that token to the context and repeats.
A normal API response waits for this loop to finish. A streamed response sends each available piece during the loop.
flowchart TD
A[Prompt] --> B[Predict next token]
B --> C[Send token delta]
C --> D[Add token to context]
D --> B
B --> E[Finish generation]Why Streaming Improves Perceived Latency
Streaming does not usually reduce the total generation time. The model still performs the same generation work. It reduces time to first token, which is the delay before the user sees evidence of progress.
Users can read the beginning while the model produces the rest. This makes an interactive system feel faster and lets a user stop an unhelpful answer early.
HTTP Responses in Pieces
HTTP can deliver a response body incrementally instead of waiting for one complete body. With a streaming response, the server writes bytes as they become available, and the client reads them from a response stream.
Network reads do not preserve application boundaries. One read might contain half an event, several events, or an event plus part of the next one. The client must buffer incomplete data before parsing it.
The Server-Sent Events Format
Server-Sent Events (SSE) is a text format for server-to-client event streams. Each event ends with a blank line. A data: field carries the payload, while a line beginning with : is a comment or keep-alive.
data: {"delta":"Hel"}
data: {"delta":"lo"}
data: [DONE]
An LLM API commonly places a JSON delta in each event. The client joins the deltas to reconstruct the message. [DONE] is a provider-specific sentinel, not ordinary model text.
Asking an LLM API to Stream
Many SDKs enable streaming with a request option such as stream=True.
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": "Explain streaming in one sentence."}],
stream=True,
)
parts = []
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
parts.append(piece)
print(piece, end="", flush=True)
full_text = "".join(parts)Each chunk can contain metadata instead of text, so check whether the content field exists before appending it.
Exercise
Does streaming make the model generate tokens faster?
Show answer
Usually no. It lowers perceived latency by delivering the first available tokens before the complete response exists.