What Is stream=true? Streaming Output and Python Chunk Printing (2026)
Streaming means the model sends back each piece of its answer as it is generated, instead of waiting until the whole answer is finished. In most APIs you turn it on by setting the request parameter stream to true. It does not make the model compute faster, and total time stays roughly the same, but the first word appears much sooner. That is what produces the "typewriter effect" in web chat.
If this is your first time working with an AI API and you want to understand endpoints, keys, and addresses first, start with What Is an AI API? A One-Page Primer for Beginners. The rest of this article assumes you can already send a normal request.
What is the difference between streaming and non-streaming?
Non-streaming (stream=false, the default in most APIs): you send a request, the server waits until the model has generated the full answer, then returns one complete JSON response. The longer the answer, the longer you wait, and nothing appears on screen in the meantime.
Streaming (stream=true): the server keeps the connection open and pushes a small chunk of data every time the model generates a few tokens. The client displays each chunk as it arrives. For what a token is and why billing is based on it, see What Is a Token in LLMs? Why Pricing Is Per Token.
| Comparison | stream=false | stream=true |
|---|---|---|
| How the response arrives | One complete JSON response | Multiple chunks, continuously |
| Time to first word | Same as the time to generate the whole answer | Usually very fast; equals "time to first token" |
| Total time | Roughly the same | Roughly the same, with a little extra overhead |
| Code complexity | Low; just read the result | Slightly higher; you loop over each chunk |
| Good for | Batch jobs, scripts, cases needing the full JSON | Chat interfaces, long answers, command-line tools |
"Time to first token" is the time from sending the request to receiving the first piece of content. It is what mostly determines whether something feels fast to a user.
How is a stream sent over the network?
The mainstream OpenAI-compatible APIs use SSE (Server-Sent Events). The response header is text/event-stream, and the body is plain text, line by line. Each event starts with data: . It looks roughly like this (fields are trimmed for illustration only):
data: {"choices":[{"delta":{"content":"你"}}]}
data: {"choices":[{"delta":{"content":"好"}}]}
data: [DONE]
Three key points:
- Each chunk carries a
delta(an increment), not the full content. You have to concatenate the pieces yourself. contentin a delta can be empty (for example, the first chunk may carry only role information and the last only the finish reason), so check for that in your code.- When the stream ends, OpenAI-compatible APIs send
data: [DONE]. Anthropic's API uses different event types, split into named events. For a field-by-field comparison, see Anthropic API vs. OpenAI API: A Field Comparison Table. Refer to the official documentation for the exact events.
How do I print chunks as they arrive in Python?
The example below uses the official OpenAI Python SDK. It also works with most services that follow the OpenAI format; you only need to swap the address and key. For what the endpoint address means, see What Is a Base URL?. For why compatibility works, see What Does "OpenAI-Compatible API" Mean?.
Install first:
pip install openai
Then run it (replace YOUR_BASE_URL and YOUR_MODEL with the values your service provides, and keep the key in an environment variable rather than in code; see What Is an API Key?):
import os
from openai import OpenAI
client = OpenAI(
base_url="YOUR_BASE_URL",
api_key=os.environ["API_KEY"],
)
stream = client.chat.completions.create(
model="YOUR_MODEL",
messages=[{"role": "user", "content": "用三句话解释什么是流式输出"}],
stream=True,
)
full_text = ""
for chunk in stream:
if not chunk.choices:
continue
piece = chunk.choices[0].delta.content
if piece:
print(piece, end="", flush=True)
full_text += piece
print()
A few things to note:
end=""makes each chunk continue on the same line instead of starting a new one.flush=Trueforces output immediately. Without it, the terminal may buffer for a while, and it will not look like streaming.if not chunk.choicesandif pieceare defensive checks, because some services send chunks with no content.full_textholds the assembled answer. You will need it later when saving to message history or logs.
To see how the messages array is written, see What Is Chat Completions?.
What are the common pitfalls with streaming?
In rough order of how often they occur, check these one by one:
- Output appears all at once: first confirm the request really uses
stream=True, then check forflush, and finally check whether a proxy or gateway in between is buffering the response (common with self-hosted reverse proxies, where you need to turn off response buffering; see your software's documentation for the exact setting). - The first word is slow: streaming only shortens the wait to see the first word. If the connection itself is slow, the first word cannot arrive quickly either. To tell whether the delay is in DNS, the TLS handshake, or model queueing, use cdnping's online speed test to look at "first connection" and "round trip" separately. For background, see Where API Latency from China Comes From.
- The answer cuts off midway: long-lived connections are vulnerable to network fluctuation and gateway timeouts. Set reasonable client timeouts and handle exceptions, and do not discard the
full_textyou have already received. - Token usage does not add up: with streaming, the final chunk does not necessarily include token usage. Whether it is supported, and the parameter name, depends on your service's official documentation.
- Incomplete arguments in tool calls: when streaming, function arguments also arrive in pieces. Concatenate them fully before parsing the JSON. For the concept, see What Is Function Calling?.
- A browser front end receives nothing: the native
EventSourcein browsers supports only GET requests, while chat APIs are usually POST. You generally need to read the response stream withfetch, or have your own backend forward it.
When should you not use streaming?
- Batch scripts that write results straight to a file or database, with nobody watching a screen: use non-streaming. The code is simpler and error handling is more direct.
- Cases where you must validate the complete output before using it, such as requiring valid JSON: streaming works, but you have to assemble everything before validating, so the benefit is small.
- Very short call chains where the answer is only a sentence or two: you will barely notice the experience benefit of streaming.
What should you watch for with relays or aggregators?
Whether streaming works depends on whether the server supports it and whether anything in between buffers it. If you use an aggregation gateway, the same code only needs a different base_url and key.
A note on the relationship: AGI Plan is a commercial partner of cdnping. AGI Plan is a multi-provider LLM aggregation gateway with a monthly subscription, paid in RMB, with no overseas credit card required. It is compatible with both the OpenAI and Anthropic API formats, so tools such as Claude Code and Codex work by changing just one endpoint address. The site states clearly that it is not an officially authorized channel, and some models are marked "overseas only"; see the models page for specifics. For setup steps, see the AGI Plan getting-started page. Whether streaming works on this kind of service, and with which parameters, depends on its documentation.
What should you do next?
- Get the code above running and compare how
stream=Falseandstream=Truefeel. - In a terminal, use
timeor Python timing to record the arrival time of the first chunk and the time to full completion. - To keep learning, read What Is an AI Agent?. Agent-style tools rely heavily on streaming and tool calls.