Sub topic 6
Streaming chunks from an async LLM client
This chapter assumes you know Python async/await, have seen an async generator, and know what a chat completions API is. You will read a streamed model response chunk by chunk and turn it into an async generator of plain text. The next chapters connect that generator to FastAPI.
What stream=True changes
Without streaming, create() returns one finished response object after the model has produced every token. With stream=True, the call returns an object you iterate over. Each item is a chunk, a small piece of the answer.
With the openai package's async client, two awaits are involved:
await client.chat.completions.create(..., stream=True)opens the request and returns the stream.async for chunk in streamwaits for each chunk as the server sends it.
Reading the chunks
A chunk holds a list called choices. For a normal chat request there is one choice, and its delta field holds the new text. This is different from a non-streaming response, where the text sits in message.content.
import asyncio
import os
from openai import AsyncOpenAI
async def main():
client = AsyncOpenAI()
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": "Name three colors."}],
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())Set OPENAI_API_KEY in your environment before running this. The if line guards against two cases that otherwise cause errors or noise:
chunk.choicescan be empty. Some providers send a final chunk with usage statistics and no choices, so indexing[0]without a check raisesIndexError.delta.contentcan beNoneor an empty string. The first chunk usually carries only the role, and the last chunk carries a finish reason. PrintingNonewould put the word "None" in your output.
Wrapping the stream in an async generator
The endpoint needs text, not provider chunk objects. Put the extraction in an async generator so the rest of the code never sees the provider's format.
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="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.contentThis keeps the work lazy. The request starts when the first chunk is requested, and each piece is passed on as soon as it arrives. Consume it with async for piece in stream_text(client, "hi"):.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: 'coroutine' object is not iterable` or an async-iteration error | Forgot `await` on `create()` | Write `stream = await client.chat.completions.create(...)` |
| `IndexError: list index out of range` | Indexed `choices[0]` on a chunk with no choices | Check `chunk.choices` first |
| The word `None` appears in output | Printed `delta.content` without checking it | Test that the content is truthy |
| Everything arrives at once | Used the sync client or omitted `stream=True` | Use `AsyncOpenAI` and pass `stream=True` |
Use the async client inside an async def endpoint. A sync client blocks the event loop while it waits, which stalls every other request on that worker.
Exercise
Why does the code check chunk.choices and chunk.choices[0].delta.content before using the text, and what would go wrong if you removed the check?
Show answer
Some chunks have an empty choices list, and others have delta.content set to None or an empty string (for example the role-only first chunk and the finish chunk). Without the check, indexing choices[0] can raise IndexError, and passing None along can cause a TypeError when you format it or send it to the client.