Sub topic 5
Asking an LLM API to stream
This chapter assumes you can send a basic request to an LLM API, know what a token is, and are comfortable reading Python and JSON. You do not need to know the Server-Sent Events (SSE) format in detail yet. The previous chapter covered it, and the next chapter covers how to read the events that come back.
What changes in the request
Streaming is a request-level choice. The model generates the same text either way. What changes is when the server sends it. In a normal request the server waits for the whole completion and returns one JSON body. In a streamed request the server keeps the connection open and writes events as tokens are produced.
Most providers expose this as one extra field in the JSON body, usually named stream. Set it to true and the response changes shape.
| Aspect | Normal request | Streamed request |
|---|---|---|
| Body field | `stream` absent or `false` | `"stream": true` |
| Response `Content-Type` | `application/json` | `text/event-stream` |
| Response body | One JSON object | A series of SSE events |
| Where the text lives | `choices[0].message.content` | `choices[0].delta.content`, spread over many events |
| Token usage | In the single response | Not sent unless you ask for it (see below) |
| Failure before any output | HTTP error status | HTTP error status |
| Failure after output starts | Not possible, because you get nothing until the end | An error event or a dropped connection |
The last two rows matter. Problems with the request itself, such as a bad API key, an invalid model name, or a malformed body, are still reported as ordinary HTTP errors with a 4xx or 5xx status, before any stream starts. Check the status first. Only a 200 response has a stream to read.
Streaming with an SDK
An official SDK hides the HTTP details. With the OpenAI Python SDK, passing stream=True makes create return an iterator of chunk objects instead of a single completion.
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. Three details are worth noting:
- The guard
chunk.choices and ...is needed. Some chunks have an emptychoiceslist, and others havedelta.contentset toNone, for example the first chunk, which often carries only the role. flush=Truemakes the terminal show each piece immediately. Without it, Python may hold output in a buffer and the stream will look like it arrives all at once.full_textis built by joining the pieces. Printing is only for display. The accumulation step is covered in a later chapter.
Streaming over raw HTTP
You will sometimes call the API without an SDK, for example from a language that has no SDK, or to debug. The request is the same as before, plus the stream field. Here is a complete example using httpx that prints the raw lines of the response.
import json
import os
import httpx
URL = "https://api.openai.com/v1/chat/completions"
headers = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
"Accept": "text/event-stream",
}
body = {
"model": "MODEL_NAME",
"messages": [{"role": "user", "content": "Say hello."}],
"stream": True,
}
# No overall time limit, but fail if the server goes quiet for 60 seconds.
timeout = httpx.Timeout(10.0, read=60.0)
with httpx.stream("POST", URL, headers=headers, json=body, timeout=timeout) as response:
if response.status_code != 200:
response.read() # load the error body so we can print it
raise RuntimeError(f"{response.status_code}: {response.text}")
print(response.headers["content-type"])
for line in response.iter_lines():
print(repr(line))Running this prints text/event-stream and then lines such as 'data: {...}', empty strings between events, and a final 'data: [DONE]'. Turning those lines into text is the job of the parser in the next chapters.
A few points about this request:
Accept: text/event-streamis a hint. Many providers do not require it, but sending it is harmless and some gateways use it.- The
withblock closes the connection when it exits. Leaving a stream open wastes a connection and may keep the server generating tokens you will never read. - The timeout is different from a normal request. A single total timeout of, say, 30 seconds would cut off long answers that are working fine. Set a connect timeout and a read timeout, which limits the silence between chunks.
Asking for usage data
A non-streamed response includes a usage object with prompt and completion token counts. A stream does not include it by default, because the counts are only known at the end. With OpenAI-style chat completions, you ask for it with an extra option.
stream = client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
stream_options={"include_usage": True},
)The API then sends one additional chunk at the end. Its choices list is empty and its usage field holds the totals. This is the reason the chunk.choices and ... guard above is not optional. Without it, chunk.choices[0] raises IndexError on that last chunk.
Common errors
- Forgetting
stream=Trueon one code path. The request succeeds, but the user sees nothing until the full answer is ready. The bug is invisible in tests that only check the final text. - Treating the return value as a completion. With streaming on,
createreturns an iterator. Accessing.choices[0].messageon it fails. - Reading the iterator twice. A stream is consumed as you read it. Store the pieces if you need them again.
- Skipping the status check in raw HTTP code. If you parse an error body as if it were events, you get no output and no clear error.
- Using a short total timeout. Long answers are cut off partway through.
- Not closing the stream on early exit. If you break out of the loop, close the stream (or use a
withblock) so the connection is released.
Exercise
You set "stream": true, and the call returns a 401 status with a JSON error body. Does your stream-reading loop run? Separately, why does your total token count come out as zero when you stream without any extra options?
Show answer
The loop should not run. Request-level errors such as an invalid API key return a normal HTTP error status before any stream starts, so you must check the status code first and read the error body as JSON. The token count is zero (or missing) because streamed responses omit usage by default. With OpenAI-style APIs you add streamoptions={"includeusage": True}, and the usage then arrives in one final chunk whose choices list is empty.