Sub topic 6
Streaming chunks from an async LLM client
This chapter covers the part of the endpoint that talks to the model: calling a chat API with streaming turned on and turning its chunks into a plain stream of text. It assumes you can read async/await code and know what an async generator is. It also assumes you have a FastAPI route with a Pydantic model and know roughly what a chat completion API is. The examples use the official openai Python package (version 1 or later) and an OPENAI_API_KEY environment variable.
What `stream=True` changes
A normal chat completion call waits until the model has finished, then returns one object with the full answer. With stream=True, the provider sends the answer in pieces as the model produces them. This is the property that makes streaming improve perceived latency. The user sees the first words after a fraction of a second instead of waiting for the whole answer.
With AsyncOpenAI, create is a coroutine. You await it to get a stream object, and then you iterate over that object with async for:
stream = await client.chat.completions.create(..., stream=True)
async for chunk in stream:
...A common mistake is to write async for chunk in client.chat.completions.create(...) and skip the await. That fails with a TypeError, because a coroutine is not an async iterable. The await finishes when the response headers arrive. The async for then reads the body piece by piece.
The shape of a chunk
Each item is a ChatCompletionChunk. The text lives in chunk.choices[0].delta.content. A delta is the new piece since the previous chunk, not the text so far. You must accumulate it yourself if you need the full answer.
Not every chunk carries text, so reading delta.content without checking will sometimes fail or yield None:
| Chunk | What it contains |
|---|---|
| First | `delta.role` is `"assistant"`. `content` is empty or `None`. |
| Middle | `delta.content` holds a few characters or a word fragment. |
| Last content chunk | `delta` is empty and `finish_reason` is set, for example `"stop"` or `"length"`. |
| Usage chunk | Only sent if you request it. `choices` is an empty list and `usage` holds token counts. |
This is why the endpoint in this tutorial guards with chunk.choices and chunk.choices[0].delta.content. The first check protects against the usage chunk, where choices is empty and indexing it raises IndexError. The second skips chunks with None or an empty string.
Tokens are not words. A delta can be part of a word, a space, or a newline. Never assume a delta is a complete word, and never strip or trim it. Removing a leading space glues words together on the client.
A first runnable script
Before putting this behind HTTP, run it in a terminal. Fewer moving parts means fewer places to look when it fails.
import asyncio
from openai import AsyncOpenAI
async def main() -> None:
client = AsyncOpenAI()
stream = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Name three uses of streaming."}],
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())The flush=True matters. Without it, Python's stdout buffer can hold the text back, and the output looks like it arrived all at once even though the chunks came in gradually. The same kind of buffering shows up later, in the proxy layer, and has the same symptom.
Turning chunks into a stream of text
The endpoint should not know what a ChatCompletionChunk is. Wrap the client call in an async generator that yields only strings. Everything downstream, including the SSE framing from the previous chapter, then works with plain text.
import asyncio
import os
from collections.abc import AsyncIterator
from openai import AsyncOpenAI
async def stream_text(client: AsyncOpenAI, prompt: str) -> AsyncIterator[str]:
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async with stream:
async for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content
if delta:
yield delta
async def main() -> None:
client = AsyncOpenAI()
async for text in stream_text(client, "Say hello in French."):
print(text, end="", flush=True)
print()
asyncio.run(main())This function has three properties worth keeping:
- It takes the client as an argument. The endpoint can pass in a shared client, and a test can pass in a fake. The dependency injection chapter builds on this.
- It yields one string per useful chunk. The generator skips empty chunks, so the caller never emits empty SSE events.
- It wraps the loop in
async with stream. The stream holds an open HTTP connection. The context manager closes that connection when the loop finishes, when an exception occurs, or when the generator itself is closed early.
Closing early matters
If a browser tab closes in the middle of an answer, the server stops iterating your generator. Python then closes the generator, which raises GeneratorExit at the yield. Because the yield sits inside async with stream, the stream's __aexit__ runs and the provider connection is released. Without it, the connection can stay open until garbage collection, and the provider may keep generating (and billing for) tokens nobody reads. The disconnect chapter returns to this. For now, keep the async with in place.
Capturing the finish reason and usage
Two values are worth recording when the stream ends. finish_reason tells you why the model stopped. "length" means the answer was cut off by the token limit. Usage gives token counts for cost tracking. Providers only send usage if you ask with stream_options:
import logging
import os
from collections.abc import AsyncIterator
from openai import AsyncOpenAI
logger = logging.getLogger("llm")
async def stream_with_stats(client: AsyncOpenAI, prompt: str) -> AsyncIterator[str]:
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
stream=True,
stream_options={"include_usage": True},
)
finish_reason = None
usage = None
async with stream:
async for chunk in stream:
if chunk.usage is not None:
usage = chunk.usage
if not chunk.choices:
continue
choice = chunk.choices[0]
if choice.delta.content:
yield choice.delta.content
if choice.finish_reason:
finish_reason = choice.finish_reason
logger.info("finish_reason=%s usage=%s", finish_reason, usage)The usage chunk arrives after the last content chunk, so the log line must come after the loop, not inside it. If the client disconnects early, the generator is closed at a yield and the log line never runs. Logging in a finally block covers that case, and the production chapter does so.
Where failures happen
Errors from the client fall into two groups, and they need different handling:
- Before the first chunk. The
await client.chat.completions.create(...)call raises, for exampleopenai.AuthenticationError,openai.RateLimitError, oropenai.APIConnectionError. No bytes have gone to your own client yet, so in principle you could still return an HTTP error status. In the endpoint built later, the generator runs after FastAPI has already sent the status line, so these errors also have to be reported inside the stream. - After some chunks. The provider connection drops or the provider reports an error part-way through the answer. The
async forraises. The text already yielded cannot be taken back.
The SDK retries some failures automatically (max_retries defaults to 2), but those retries apply to establishing the request. A stream that breaks half-way is not resumed. If you need that, you must start a new request and decide yourself what to do with the partial text.
The SDK timeout is an httpx timeout. Its read part applies to waiting for the next piece of data, not to the whole response. A long answer is fine as long as chunks keep arriving, but a provider that goes silent will raise openai.APITimeoutError. You can set it when you build the client, for example AsyncOpenAI(timeout=30.0).
Common errors
- Missing
awaitoncreate. GivesTypeError: 'async for' requires an object with __aiter__ method, got coroutine. - Indexing
choices[0]without checking. RaisesIndexErroron the usage chunk. - Yielding
Noneor empty strings. Produces blank events on the wire and confuses clients. - Stripping deltas. Removes the spaces that separate words.
- Creating a new client per request. Opens a new connection pool each time. Share one client, as the next chapter shows.
Exercise
Your generator contains text = chunk.choices[0].delta.content followed by yield text. It works in testing, but in production it sometimes raises an error at the very end of a response and sometimes sends null to clients. What two causes explain this, and what is the fix?
Show answer
The final usage chunk (when include_usage is on) has an empty choices list, so choices[0] raises IndexError. The first chunk, and the chunk carrying finish_reason, have delta.content set to None or an empty string, so yield text sends null or a blank value. The fix is to guard both: if not chunk.choices: continue, then delta = chunk.choices[0].delta.content, and if delta: yield delta.
Exercise
Why is the loop in stream_text wrapped in async with stream, and what could go wrong in production if you remove it?
Show answer
The stream owns an open HTTP connection to the provider. When the consumer stops early, for example because the browser tab closed, Python closes the generator at the yield. The async with then runs the stream's cleanup and releases the connection. Without it, the connection can stay open until garbage collection, so the provider may keep generating tokens that nobody reads, and you may pay for them.