Sub topic 8
Streaming tokens as they are generated
This chapter assumes you can already send a non-streaming chat completion to a local server with the OpenAI Python client (openai 1.x). It also assumes you know basic HTTP and JSON. The examples use Ollama on port 11434 with llama3.2 downloaded. Other OpenAI-compatible servers work the same way once you change the base URL and model name.
Why stream
A normal chat completion returns only after the model has generated the whole reply. On local hardware that can take many seconds. The user sees nothing during that time, and then all the text appears at once.
With streaming, the server sends the reply in small pieces as it generates them. Your program can display each piece immediately. The total generation time is about the same. What improves is the time to first visible text, and that is what makes a chat interface feel responsive.
Streaming is useful when:
- A person is watching the output, such as in a terminal or chat window.
- You want to stop generation early, for example when the user presses cancel.
- A reply is long enough that waiting for it would risk a timeout.
Streaming adds little when a program only needs the finished text, for example when it parses the reply as JSON. In that case a non-streaming call is simpler.
How streaming works on the wire
When you set stream=True, the client sends the same request with "stream": true in the JSON body. The server answers with a long-lived HTTP response whose content type is text/event-stream. This format is called server-sent events (SSE). Each event is a line that starts with data: followed by a JSON object. A blank line separates events. The stream ends with the literal line data: [DONE].
You can see this with curl. The -N flag turns off curl's output buffering so lines appear as they arrive.
curl -N http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "llama3.2", "stream": true, "messages": [{"role": "user", "content": "Say hello in one sentence."}]}'The output looks like this, shortened here:
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]The exact IDs and the number of chunks vary by server.
The chunk format
A streamed chunk differs from a normal response in three ways:
- The object type is
chat.completion.chunk, notchat.completion. - Each entry in
choiceshas adeltafield instead of amessagefield. The delta holds only the new part of the reply. finish_reasonisnulluntil the last content chunk. Then it holds a value such asstop(the model finished) orlength(themax_tokenslimit was reached).
The first chunk often carries delta.role and an empty content. The last content chunk often has an empty delta and a finish_reason. Some servers send a chunk with an empty choices list, typically to report usage. So the loop must not assume that choices[0] exists or that content is a string.
A "token" is the unit the model generates, and it is often a word fragment. One chunk usually holds one token, but servers may batch several tokens into a chunk. Do not rely on one chunk meaning one token.
Reading a stream in Python
With the OpenAI client, stream=True makes create return an iterator of chunk objects instead of a single response.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Write a haiku about servers."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()Three details matter:
chunk.choices and ...guards against chunks with an emptychoiceslist.delta.contentcan beNoneor an empty string, and the truthiness test skips both.end=""stopsprintfrom adding a newline after each fragment.flush=Trueforces Python to write the text to the terminal now. Without it, output may be buffered and appear in bursts, which defeats the purpose.
Collecting the full reply
Often you want to display fragments and also keep the complete text, for example to add it to the conversation history as an assistant message. Collect the pieces in a list and join them at the end. Also record the finish reason so you can tell whether the reply was cut off.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
messages = [{"role": "user", "content": "Explain what a context window is in two sentences."}]
parts = []
finish_reason = None
stream = client.chat.completions.create(
model="llama3.2",
messages=messages,
max_tokens=120,
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
if choice.delta.content:
parts.append(choice.delta.content)
print(choice.delta.content, end="", flush=True)
if choice.finish_reason:
finish_reason = choice.finish_reason
print()
reply = "".join(parts)
messages.append({"role": "assistant", "content": reply})
if finish_reason == "length":
print("Warning: the reply was cut off by max_tokens.")Use "".join(parts) rather than reply += fragment in a loop. Both work, but joining is the usual idiom and avoids repeated string copying on long replies.
Token usage in a stream
A non-streaming response includes a usage object with prompt and completion token counts. A stream does not include it by default. The OpenAI API lets you request it with stream_options. The final chunk then has a usage field and an empty choices list.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Name three planets."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if getattr(chunk, "usage", None):
print(f"\n[prompt={chunk.usage.prompt_tokens} completion={chunk.usage.completion_tokens}]")Support for stream_options varies. Some servers ignore it and some may reject it, so test it on your server before relying on it. This is one of the compatibility differences covered in a later chapter.
Stopping a stream early
The stream object is tied to an open HTTP connection. If you stop reading without closing it, the connection may stay open and the server may keep generating. Close the stream when you are done, including when you break out of the loop.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
limit = 40
seen = 0
with client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Count from 1 to 100, separated by commas."}],
stream=True,
) as stream:
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
text = chunk.choices[0].delta.content
print(text, end="", flush=True)
seen += len(text)
if seen >= limit:
break
print()The with block closes the connection on exit. Whether the server then stops generating immediately depends on the server. Most notice the closed connection and cancel the work, which frees the GPU or CPU for the next request. This matters on local hardware, where one model often serves one request at a time.
Timeouts and errors while streaming
The timeout setting on the client applies to individual network operations, such as waiting for the next bytes. It does not limit the total length of a stream. A long reply that keeps producing tokens will not hit a 60 second timeout, but a stall of 60 seconds between chunks will.
This has a practical consequence on local servers. Before the first token, the server must load the model if it is not already in memory, and process the whole prompt. With a large model or a long prompt, that delay can be longer than your timeout. If the first request after starting the server always fails but later ones succeed, raise the timeout or send a small warm-up request first.
Errors can also occur in the middle of a stream. The HTTP status was already 200 when streaming began, so a failure later shows up as a broken connection or an error event, not as a status code. Wrap the loop in a try block and decide what to do with partial text.
import openai
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="local",
timeout=120.0,
max_retries=2,
)
parts = []
try:
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Tell me a short story."}],
stream=True,
)
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)
except openai.APIConnectionError:
print("\nConnection lost. Partial reply kept.")
except openai.APITimeoutError:
print("\nTimed out waiting for the server.")
except openai.APIStatusError as e:
print(f"\nServer returned status {e.status_code}")
partial = "".join(parts)APITimeoutError is a subclass of APIConnectionError, so the order of the except clauses matters. Python uses the first clause that matches. In the code above, the connection clause comes first and catches timeouts too, so the timeout clause never runs. To handle timeouts separately, put APITimeoutError first.
The max_retries setting only applies to the request that opens the stream. The client does not resume a stream that breaks halfway. If you need that, your code must re-send the request, and the model will generate a fresh reply that may differ from the first.
Streaming in an async program
If your application uses asyncio, for example inside a web server, use AsyncOpenAI. The stream is then consumed with async for.
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="local")
async def main():
stream = await client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Write a haiku about rivers."}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
asyncio.run(main())Note the await on create. With the async client, create is a coroutine that returns the stream object.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| All text appears at once at the end | Output buffering, or a proxy buffering the response | Use `flush=True`; with `curl`, add `-N`; check any reverse proxy in between |
| `IndexError` on `chunk.choices[0]` | A chunk with an empty `choices` list | Test `chunk.choices` before indexing |
| `TypeError` when joining or concatenating | `delta.content` is `None` | Test that content is truthy before using it |
| Long pause, then a timeout, on the first request | Model loading or long prompt processing | Raise `timeout` or warm up the model |
| Reply ends mid-sentence | `finish_reason` is `length` | Raise `max_tokens` or check the context window |
| Server rejects the request when `stream_options` is set | The server does not support that option | Remove it and count tokens another way |
Summary of the pattern
- Pass
stream=Truetocreate. - Loop over the returned stream.
- For each chunk, check that
choicesis non-empty, then readdelta.contentand skip empty values. - Print with
flush=Trueand collect the fragments. - Record
finish_reason, and close the stream if you stop early. - Handle connection loss and timeouts around the whole loop.
Exercise
A streaming loop crashes with IndexError: list index out of range on chunk.choices[0] for the last chunk only. What is the cause, and what is the minimal fix?
Show answer
The server sent a final chunk (often one that carries usage data) with an empty choices list. Guard the access with if chunk.choices and chunk.choices[0].delta.content: or if not chunk.choices: continue before indexing.
Exercise
Your code catches openai.APIConnectionError first and openai.APITimeoutError second. Timeouts are always reported as "connection lost". Why, and how do you fix it?
Show answer
APITimeoutError is a subclass of APIConnectionError, so the first except clause matches timeouts as well. Put except openai.APITimeoutError before except openai.APIConnectionError.
Exercise
You set timeout=30.0 and stream a reply that takes five minutes in total, with tokens arriving steadily. Will the request time out? What if the model needs 45 seconds to load before the first token?
Show answer
The steady five-minute stream will not time out, because the timeout applies to waiting on each network operation, not to the total duration. The 45-second model load before the first token will time out, since no data arrives within 30 seconds. Raise the timeout or warm up the model first.