RuntimeError
RuntimeError: Cannot run the event loop while another loop is running
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
result = kernel.invoke_function("myAsyncFunc") # sync call to async function
File "semantic_kernel/kernel.py", line 123, in invoke_function
return asyncio.run(self._invoke_async_function(name))
File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run
raise RuntimeError("Cannot run the event loop while another loop is running")
RuntimeError: Cannot run the event loop while another loop is running Why it happens
Semantic Kernel async functions require an active event loop to run. Calling them synchronously with asyncio.run() inside an already running event loop (e.g., in Jupyter or async frameworks) causes this RuntimeError due to nested event loops being disallowed.
Detection
Detect this error by checking if your environment already has a running event loop before calling asyncio.run(), or by catching RuntimeError with the specific message about nested event loops.
Causes & fixes
Calling asyncio.run() inside an environment where an event loop is already running (e.g., Jupyter notebook or async web server).
Use 'await' to call async functions directly if inside an async context, or use nest_asyncio to patch the event loop in Jupyter environments.
Invoking Semantic Kernel async functions synchronously without awaiting them.
Refactor your code to be async and use 'await kernel.invoke_function_async(...)' instead of synchronous calls.
Using synchronous wrappers that internally call asyncio.run() multiple times in the same process.
Avoid multiple calls to asyncio.run() in the same process; instead, manage the event loop explicitly or use async entry points.
Code: broken vs fixed
from semantic_kernel import Kernel
kernel = Kernel()
result = kernel.invoke_function("myAsyncFunc") # This line causes RuntimeError
print(result) import os
import asyncio
from semantic_kernel import Kernel
os.environ["SEMANTIC_KERNEL_API_KEY"] = os.environ.get("SEMANTIC_KERNEL_API_KEY", "your_api_key_here")
kernel = Kernel()
async def main():
result = await kernel.invoke_function_async("myAsyncFunc") # Fixed: await async call
print(result)
asyncio.run(main()) # Proper async entry point Workaround
If you cannot refactor to async, use the 'nest_asyncio' package to patch the running event loop in environments like Jupyter: import nest_asyncio; nest_asyncio.apply() before calling asyncio.run().
Prevention
Design your application to be fully async when using Semantic Kernel async functions, avoiding synchronous wrappers that call asyncio.run() multiple times, and use async entry points consistently.