Sub topic 8
Streaming tokens as they are generated
This chapter assumes you can already send a basic chat completion to your local server with the OpenAI Python client. You should know the base URL and placeholder key setup, and you should be comfortable reading the choices[0].message.content field of a normal response.
Why stream
A normal request waits until the model has produced the whole reply. A local model on modest hardware may take many seconds to finish a long answer, and the user sees nothing during that time.
With streaming, the server sends the reply in small pieces as the model generates them. The first words appear quickly, and the total time stays about the same. Streaming improves perceived speed, and it lets you stop early if the output is going the wrong way.
Turning streaming on
Add stream=True to the request. The call then returns an iterator of chunks instead of one response object.
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()The loop prints each fragment without a newline. flush=True forces Python to write the text to the terminal immediately. Without it, output may be buffered and appear in bursts.
How the chunks arrive
Over the wire, the server uses Server-Sent Events (SSE). SSE is a format where the server keeps one HTTP response open and writes lines that start with data: . Each line holds a JSON object. The stream ends with the line data: [DONE]. The OpenAI client parses these lines for you and hands you Python objects.
The chunk format
A streamed chunk looks like a normal response, with one change. The message field is replaced by delta, which holds only the new part.
| Chunk position | What `delta` contains | What `finish_reason` is |
|---|---|---|
| First | `role` set to `assistant`, often empty `content` | `None` |
| Middle | A short `content` string, a word or part of a word | `None` |
| Last content chunk | Usually empty | `stop` or `length` |
This is why the code checks delta.content before printing. Some chunks carry no text, and content is then None or an empty string. Printing None would show the word "None" in your output.
Also check chunk.choices before indexing it. Some servers send a final chunk with an empty choices list, for example one that reports token usage.
Collecting the full reply
Often you want to display text live and also keep the complete answer, for example to append it to the conversation history as an assistant message. Build it up as you go.
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 uses of a local model."}],
stream=True,
)
parts = []
finish_reason = None
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()
full_text = "".join(parts)
print(f"[{len(full_text)} characters, finish_reason={finish_reason}]")If finish_reason is length, the reply stopped because it hit max_tokens or the context limit, not because the model was done.
Common errors
- Reading
messageinstead ofdelta. In a stream,chunk.choices[0].messagedoes not exist. Usedelta. - Printing without checking for
None. Guard ondelta.content. - Output appears all at once. Check that
flush=Trueis set. Also check that a proxy between you and the server is not buffering the response. Some servers ignorestreamand return one block, so test your server. - Connection drops mid-stream. The client raises an error part way through the loop. The text you already received is kept in your
partslist, but the request is not resumed. Wrap the loop in atryblock if partial output is useful.
Exercise
Exercise
A streaming loop prints the word "None" several times in the middle of the reply. What is the cause, and how do you fix it?
Show answer
Some chunks, such as the first chunk that only sets the role, have delta.content equal to None. The code prints it without checking. Fix it by printing only when chunk.choices is non-empty and chunk.choices[0].delta.content is truthy.
Exercise
You collect streamed text into a list and the final chunk reports finish_reason of length. What does that tell you?
Show answer
The reply was cut off because it reached the max_tokens cap or the context limit. The model did not finish naturally. Raise max_tokens or shorten the prompt if you need the full answer.