How to beginner · 3 min read

How to use Claude with async python

Quick answer
Use the anthropic Python SDK with asyncio to call Claude models asynchronously. Instantiate Anthropic client with your API key, then use await client.messages.acreate() with the system prompt and messages array to get responses without blocking your event loop.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic>=0.20

Setup

Install the official anthropic Python SDK and set your API key as an environment variable.

bash
pip install anthropic>=0.20

Step by step

This example demonstrates a complete async Python script that calls Claude using the anthropic SDK's async method messages.acreate(). It sends a system prompt and a user message, then prints the AI's response.

python
import os
import asyncio
import anthropic

async def main():
    client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    response = await client.messages.acreate(
        model="claude-3-5-sonnet-20241022",
        max_tokens=500,
        system="You are a helpful assistant.",
        messages=[{"role": "user", "content": "Hello, how do I use Claude asynchronously in Python?"}]
    )
    print(response.content[0].text)

if __name__ == "__main__":
    asyncio.run(main())
output
Hello! To use Claude asynchronously in Python, you use the Anthropic SDK's async methods like messages.acreate() within an async function.

Common variations

  • Change model to other Claude versions like claude-3-5-haiku-20241022.
  • Adjust max_tokens for longer or shorter responses.
  • Use synchronous client.messages.create() if async is not needed.
  • Integrate with asyncio event loops in web frameworks like FastAPI or aiohttp.

Troubleshooting

  • If you get authentication errors, verify your ANTHROPIC_API_KEY environment variable is set correctly.
  • For timeout issues, increase your network timeout or check your internet connection.
  • If asyncio.run() raises errors in nested event loops (e.g., Jupyter), use alternative async runners like nest_asyncio.

Key Takeaways

  • Use the Anthropic SDK's async method messages.acreate() for non-blocking Claude calls.
  • Always set your API key in the environment variable ANTHROPIC_API_KEY for secure authentication.
  • Integrate async Claude calls smoothly into Python async frameworks like FastAPI or aiohttp.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-3-5-haiku-20241022
Verify ↗