Sub topic 5
Asking an LLM API to stream
This chapter assumes you can call an LLM API, read JSON, and write basic Python. You should also know that HTTP responses normally arrive as one complete body. The previous chapters covered why streaming helps and how Server-Sent Events (SSE) frame data. Here you turn streaming on and read the first results.
The one switch: `stream`
Most LLM providers use the same pattern. You send the usual request and add a flag, typically "stream": true. The server then keeps the connection open and sends events as the model produces tokens. It does not wait to send one final JSON body.
The request body changes by one field:
{
"model": "MODEL_NAME",
"messages": [{"role": "user", "content": "Explain streaming in one sentence."}],
"stream": true
}The response changes more. The Content-Type is text/event-stream, and the body is a series of SSE events instead of a single JSON object.
Using an SDK
An official SDK hides the SSE parsing. With the OpenAI Python SDK, stream=True makes the call return an iterator of chunks.
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)Replace MODEL_NAME with a model you can use. Four details matter in this loop:
- Each
chunkholds adelta, which is the new piece of text, not the whole message so far. chunk.choicescan be empty. Some chunks, such as a final usage chunk, carry no choices, so the code checks before indexing.delta.contentcan beNone. The first chunk often carries only the role, and the last carries only a finish reason.flush=Truepushes each piece to the terminal immediately. Without it, Python may buffer output and hide the streaming effect.
What happens on the wire
The SDK is doing the work you will do by hand in later chapters. It sends the request, reads the open connection, splits it into SSE events, and decodes each data: line as JSON.
Common errors
- Forgetting to iterate. With
stream=True, the call returns before the model finishes. If you print the returned object, you see an iterator, not text. - Assuming a status of 200 means success. The status line is sent before generation starts. Failures later in the stream arrive as events or as a dropped connection. A later chapter covers this.
- Reading
messageinstead ofdelta. Streamed chunks usedelta. Non-streamed responses usemessage. - Provider differences. Field names and event types vary. Some providers use named SSE events instead of one chunk shape, so check your provider's documentation.
Exercise
Your streaming loop crashes with a TypeError when it runs chunk.choices[0] on the last chunk. What is the likely cause, and how do you fix it?
Show answer
The last chunk can have an empty choices list, for example when it carries only usage data. Check chunk.choices before indexing, as in if chunk.choices and chunk.choices[0].delta.content:.