Sub topic 3
Async generators as the source of a stream
This chapter covers the Python feature that produces a stream: the async generator. You will see how it behaves on its own before it is connected to FastAPI. The next chapter connects it to StreamingResponse. It assumes you know basic async/await, can run a script with asyncio.run, and know what a normal (synchronous) generator and yield do.
Why a generator fits a stream
A streamed response is a body that is produced over time. The server does not build the whole body and then send it. It sends a piece, waits for the next piece, sends that, and so on. Two properties make this hard with ordinary functions:
- A normal function returns once. It cannot hand back a first piece and then keep working.
- Waiting for the next piece, such as a token from a model, should not block the rest of the server.
An async generator has both properties. It can produce many values over time with yield, and it can await between them. While one stream waits, the event loop is free to serve other requests.
Defining and consuming one
A function becomes an async generator when it is declared with async def and contains yield. Here is a small one that matches the example in the plan:
import asyncio
async def count(n: int):
for i in range(n):
yield f"chunk {i}\n"
await asyncio.sleep(0.5)
async def main():
async for piece in count(3):
print(piece, end="", flush=True)
asyncio.run(main())Running this prints chunk 0, chunk 1 and chunk 2, one every half second. The consumer uses async for, which only works inside an async def. Each loop step asks the generator for its next value and waits for it.
Three behaviors are worth knowing before you build on this:
- Calling the function runs no code.
count(3)returns an async generator object. The body starts running when the first value is requested. Any exception in the body therefore appears at the consumer's firstasync forstep, not at the call site. - A generator object is single-use. Once it finishes, iterating it again yields nothing. Create a new one for each response.
returncannot carry a value. In an async generator a barereturnends the stream, butreturn valueis a syntax error. Send final information with a lastyieldinstead.
What the consumer sees
The consumer and the generator take turns. The generator runs until it hits yield, then pauses with its local variables intact. The consumer handles the value, then asks for the next one, and the generator resumes right after the yield.
In a FastAPI app the consumer is StreamingResponse. It loops over your generator and writes each chunk to the network. Your code only has to yield.
Chaining generators
An async generator can consume another one. This is how a stream is built in stages. In the full endpoint, one stage reads chunks from the model and another turns each chunk into an SSE message.
import asyncio
async def words():
for w in ["streaming", "is", "useful"]:
yield w
await asyncio.sleep(0.2)
async def shout(source):
async for item in source:
yield item.upper() + "\n"
async def main():
async for line in shout(words()):
print(line, end="")
asyncio.run(main())Each stage is small and testable. Values flow through one at a time, so nothing is collected into a list. The first line reaches the consumer as soon as words() produces its first item, even though the last item is still 0.4 seconds away.
Cleanup when the stream stops early
A stream does not always run to the end. A client can close the tab halfway through a response. When that happens the generator is left suspended at a yield. If the body holds something that must be released, such as an open connection to the model provider, put the release in finally.
import asyncio
async def count(n: int):
try:
for i in range(n):
yield i
await asyncio.sleep(0.1)
finally:
print("cleanup ran")
async def main():
gen = count(10)
async for i in gen:
print(i)
if i == 2:
break
await gen.aclose()
asyncio.run(main())The output is 0, 1, 2, then cleanup ran. The details matter:
- A
breakleaves the generator suspended. It does not close it. aclose()raisesGeneratorExitat the pausedyield. That runs yourfinallyblock and ends the generator.- If the garbage collector finalizes an unclosed async generator, the event loop schedules that cleanup later. You cannot predict when, so do not rely on it.
- In Python 3.10 and later,
contextlib.aclosingcloses the generator for you:
from contextlib import aclosing
async with aclosing(count(10)) as gen:
async for i in gen:
if i == 2:
breakInside an async with aclosing(...) block, cleanup runs when the block exits, whether by break, by an exception, or by normal completion.
A cancelled task has a similar effect. If the surrounding task is cancelled while the generator is awaiting, asyncio.CancelledError is raised at that await. The finally block still runs. Do not catch CancelledError and continue, or the stream will not stop. Later chapters build on this when handling client disconnects.
Do not block the event loop
An async generator is only as cooperative as its await points. Compare these two bodies:
import asyncio
import time
async def good():
for i in range(3):
yield i
await asyncio.sleep(1)
async def bad():
for i in range(3):
yield i
time.sleep(1)bad() yields the same values, but time.sleep(1) blocks the whole event loop for a second each time. No other request can be served during that time, and other open streams stall too. The same applies to any blocking call: synchronous HTTP clients, requests, file reads of large files, or CPU-heavy loops.
If you must call blocking code, either use an async library for the same job, or run the blocking call in a worker thread with await asyncio.to_thread(func, ...). For an LLM feature, use the provider's async client, which the plan covers in a later chapter.
Synchronous generators also work, with a cost
FastAPI's StreamingResponse accepts a plain generator too. Starlette runs a synchronous iterator in a thread pool so it does not block the loop. That is convenient for legacy code, but each step costs a thread hand-off. The thread pool also has a limited size, so many slow concurrent streams can exhaust it. An async generator uses no thread while it waits, so it is the better choice for long-lived streams such as model output.
| Property | Async generator | Sync generator |
|---|---|---|
| Declared with | `async def` plus `yield` | `def` plus `yield` |
| Consumed with | `async for` | `for` |
| Waiting between values | `await`, no thread held | Blocks a pool thread |
| Fit for slow, long streams | Good | Limited by thread pool size |
Common errors
- Forgetting to call the function.
StreamingResponse(count)passes the function, not a generator. Passcount(). - Using
awaiton a generator.await count()fails because an async generator is not awaitable. Iterate it withasync for. - Using
yieldin a plainasync defhelper and expecting a value. Anyyieldin the body makes the whole function a generator, soawait helper()raises aTypeError. - Reusing a finished generator. Build a new one per request.
- Building a list first. Collecting all chunks and then yielding them gives the client nothing until the slowest step is done. Yield as soon as each piece exists.
What comes next
You now have the source of a stream: an object that produces pieces over time and cleans up after itself. The next chapter hands it to StreamingResponse, which does the iteration and the network writes.
Exercise
A teammate writes async def tokens(): ... with yield inside. In the handler they write return StreamingResponse(await tokens()) and get a TypeError. What is wrong, and what is the fix? Also, the generator opens a provider connection at its start. Where should that connection be closed so it is released even when the client leaves early?
Show answer
An async generator is not awaitable, so await tokens() fails. Calling tokens() already returns the generator object, so the fix is StreamingResponse(tokens()). The connection should be closed in a finally block inside the generator (or by an async with around it). aclose() or task cancellation then triggers that block when the client leaves early.
Exercise
This generator is meant to send three messages one second apart, but other requests to the server freeze while it runs. Why, and how do you fix it? async def slow(): for i in range(3): yield f"msg {i}\n" time.sleep(1)
Show answer
time.sleep(1) is a blocking call, so it stops the whole event loop for each second. Replace it with await asyncio.sleep(1), which suspends only this generator and lets the loop serve other work.