RuntimeError
anthropic.RuntimeError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
response = await client.messages.create(model="claude-3", messages=messages)
File "/usr/local/lib/python3.10/site-packages/anthropic/client.py", line 210, in create
raise RuntimeError("Event loop is closed or invalid")
RuntimeError: Event loop is closed or invalid Why it happens
This error occurs when the Anthropic async client is used improperly in an environment where the asyncio event loop is closed, missing, or conflicting. It often happens if the client is called outside an async function or if the event loop is prematurely closed or reused incorrectly.
Detection
Detect this error by wrapping async Anthropic client calls in try/except RuntimeError and logging the event loop state or error message before retrying or fixing the async context.
Causes & fixes
Calling async Anthropic client methods outside an async function or without awaiting
Ensure all Anthropic async client calls are made inside async functions and are awaited properly.
Using the Anthropic async client in a synchronous context without an event loop
Run the async client calls inside an asyncio event loop using asyncio.run() or an equivalent async runner.
Prematurely closing or reusing the asyncio event loop causing it to be invalid
Avoid closing the event loop manually; let the runtime manage it or recreate a fresh event loop before client calls.
Code: broken vs fixed
from anthropic import Anthropic
client = Anthropic(api_key="sk-xxx")
messages = [{"role": "user", "content": "Hello"}]
# This line causes RuntimeError because it's called at top-level without async context
response = await client.messages.create(model="claude-3", messages=messages)
print(response) import os
import asyncio
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
messages = [{"role": "user", "content": "Hello"}]
async def main():
response = await client.messages.create(model="claude-3", messages=messages) # Fixed: inside async function
print(response)
asyncio.run(main()) # Fixed: runs async function with event loop Workaround
If you cannot refactor to async, run the async call synchronously by wrapping it with asyncio.run() or use an async-to-sync helper library to manage the event loop.
Prevention
Design your application to use async/await properly with the Anthropic client, avoid manual event loop management, and test async calls in isolated async contexts to prevent event loop errors.