stream=True turns the response into an asynchronous stream.
That means:
• It implements __aiter__, not__iter__.
• You must iterate with async for …, never plain for ….
• The loop has to live inside an async def (and you’ll need await or asyncio.run() to start it).
If you try a synchronous for loop, Python raises
TypeError: 'AsyncStream' object is not iterable
because a sync loop looks for __iter__, cannot find it, and complains.
Minimal working example
python
import asyncio
from asyncopenai import AsyncOpenAI # pip install async-openai>=1.0.0
client = AsyncOpenAI(api_key="sk-...")
async def main():
# request, but ask for a *stream* of chunks
stream = await client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello!"}],
stream=True, # <- important
)
# ------------- asynchronous iteration -------------
async for chunk in stream: # <-- async for!
delta = chunk.choices[0].delta.content or "" # delta may be None
print(delta, end="", flush=True)
# (you’ll get “Hello! How can I help you today? …” piece-by-piece)
# --------------------------------------------------
# kick off the async function from sync code
asyncio.run(main())
Typical “gotchas”
Forgot the word async in the loop header
python
for chunk in stream: # ❌ raises TypeError
Tried to run the loop at top level in a notebook or script without
being inside an async def.
Wrap it in an async function and call await/asyncio.run.
Converted the stream to a list (list(stream), [c async for c in stream])
inside non-async code.
If you really need synchronous code
You can consume the stream chunk-by-chunk:
python
import asyncio, contextlib
async def get_full_response():
stream = await client.chat.completions.create(..., stream=True)
parts = [chunk async for chunk in stream]
return "".join(c.choices[0].delta.content or "" for c in parts)
full_text = asyncio.run(get_full_response())
print(full_text)
But if your environment supports async (FastAPI, Quart, discord.py, etc.) stick to async for; you’ll gain true streaming and lower latency.
That’s all—you only needed to switch from a synchronous for to an async for loop!
User
The issue is that the function is recursive and has yield from in it.
Assistant
yield from only works with synchronous iterables. asyncopenai gives you an AsyncStream, which is asynchronous, so the moment your generator hits
python
yield from stream
Python tries to treat stream as a sync iterable → can’t find __iter__ → raises the
TypeError you’re seeing.
There are two ways out:
────────────────────────────────────────
Make your generator asynchronous
────────────────────────────────────────
If you can switch the whole call-chain to async, this is the clean (and fastest) fix.
python
import asyncio
from asyncopenai import AsyncOpenAI
client = AsyncOpenAI(api_key="sk-…")
async def recursive_stream(messages, depth=0, max_depth=3):
# 1️⃣ call OpenAI and get an AsyncStream
stream = await client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
stream=True,
)
# 2️⃣ forward every chunk to our caller
async for chunk in stream:
yield chunk # <-- NO "yield from"
# 3️⃣ (optional) recurse
if depth < max_depth:
messages.append({"role": "assistant",
"content": ''.join(
(chunk.choices[0].delta.content or '') async for chunk in stream)
})
async for chunk in recursive_stream(messages, depth+1, max_depth):
yield chunk
async def main():
async for piece in recursive_stream([{"role": "user", "content": "Hi!"}]):
print(piece.choices[0].delta.content or '', end='', flush=True)
asyncio.run(main())
Key points
• creates an .
• There is in async land; instead use
.
async def … yield …
asynchronous generator
no
yield from
async for x in other(): yield x
If somewhere up the stack you need the whole text at once:
python
async def gather_full_response(*args, **kw):
return ''.join(
chunk.choices[0].delta.content or ''
async for chunk in recursive_stream(*args, **kw)
)
────────────────────────────────────────
2. Keep the function synchronous (wrap the async stream)
────────────────────────────────────────
If you must stay sync (e.g., you’re in Flask 1.x or a plain script), wrap the
AsyncStream in a helper that blocks the event loop behind the scenes:
python
import asyncio
def sync_wrap(async_iter):
"""
Turn an async iterator into a blocking, synchronous iterator.
WARNING: blocks the event loop → use only in fully-sync code.
"""
loop = asyncio.new_event_loop()
try:
asyncio.set_event_loop(loop)
async def collect():
async for item in async_iter:
yield item
agen = collect()
while True:
try:
yield loop.run_until_complete(agen.__anext__())
except StopAsyncIteration:
break
finally:
loop.close()
asyncio.set_event_loop(None)
def recursive_stream_sync(messages, depth=0, max_depth=3):
stream = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
stream=True,
)
yield from sync_wrap(stream) # <- now 'stream' looks synchronous
if depth < max_depth:
# collect response synchronously
full_text = ''.join(chunk.choices[0].delta.content or ''
for chunk in sync_wrap(stream))
messages.append({"role": "assistant", "content": full_text})
yield from recursive_stream_sync(messages, depth+1, max_depth)
Downsides: extra latency, no true concurrency, and more complexity.
Whenever possible, prefer solution #1 and embrace async.
────────────────────────────────────────
Cheat-sheet: converting yield from → async world
────────────────────────────────────────
Sync code
python
def gen():
yield 1
yield from other() # flatten sub-iterable
Async equivalent
python
async def agen():
yield 1
async for item in other(): # 👈 replace ‘yield from’
yield item
That single transformation—yield from X → async for x in X: yield x—will let
your recursive generator work with the AsyncStream returned by
asyncopenai.