RuntimeError
RuntimeError: This event loop is already running
Stack trace
RuntimeError: This event loop is already running
File "<ipython-input-1>", line 10, in <module>
response = asyncio.run(client.chat.completions.create(...))
File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run
raise RuntimeError('This event loop is already running') Why it happens
The OpenAI async client uses asyncio to run asynchronous calls. If you call asyncio.run() inside an environment where an event loop is already running (like Jupyter notebooks or some web frameworks), Python raises this RuntimeError because nested event loops are not allowed.
Detection
Detect this error by checking if your code calls asyncio.run() inside an environment that already has an active event loop, such as Jupyter or an async web server.
Causes & fixes
Calling asyncio.run() inside an already running event loop (e.g., Jupyter notebook or async framework).
Use 'await' directly in an async function or use nest_asyncio to patch the event loop in Jupyter environments instead of asyncio.run().
Mixing synchronous and asynchronous OpenAI client calls improperly.
Ensure you use the async client methods only inside async functions and await them properly without wrapping in asyncio.run() if the event loop is active.
Running async OpenAI client code in synchronous scripts without proper event loop management.
Use asyncio.run() only in standalone scripts where no event loop is running, or refactor code to async functions and run with an event loop manager.
Code: broken vs fixed
import os
import asyncio
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# This line causes RuntimeError if run in Jupyter or an active event loop
response = asyncio.run(client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}]))
print(response) import os
import asyncio
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
async def main():
response = await client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response)
# In Jupyter or async environment, just await main()
# In standalone script, use asyncio.run(main())
# Example for Jupyter:
# await main()
# Example for script:
# asyncio.run(main()) Workaround
In Jupyter notebooks, install and import nest_asyncio and call nest_asyncio.apply() once before running async OpenAI client code to allow nested event loops.
Prevention
Design your application to use async OpenAI client calls only inside async functions and avoid calling asyncio.run() if an event loop is already running; use environment detection or event loop patching as needed.