Skip to main content

Overview

The AsyncOpenAI client enables asynchronous, non-blocking API calls using Python’s async/await syntax. This is ideal for:
  • Making concurrent API requests
  • Building async web applications (FastAPI, Sanic, etc.)
  • Handling high-throughput workloads
  • Avoiding blocking I/O in event loops

Basic Usage

The AsyncOpenAI client provides an identical API to OpenAI, with all methods returning awaitable coroutines.

Concurrent Requests

Make multiple API calls concurrently using asyncio.gather():

Streaming with Async

Stream responses asynchronously using async for:
See Streaming for more details on streaming responses.

Context Manager

Use async context managers for automatic resource cleanup:

Integration with Web Frameworks

FastAPI

Sanic

Using aiohttp Transport

For improved concurrency performance, use the aiohttp HTTP transport:
The aiohttp transport can provide better performance for high-concurrency workloads compared to the default httpx transport.

Error Handling

Handle errors in async code using try/except blocks:
See Error Handling for comprehensive error handling patterns.

Rate Limiting with Async

Implement rate limiting for concurrent requests:

Pagination with Async

Iterate through paginated results asynchronously:

Task Groups (Python 3.11+)

Use task groups for structured concurrency:

Best Practices

  • Always use await with async methods - forgetting it will return a coroutine object instead of the result
  • Use asyncio.gather() for concurrent requests, not sequential await calls
  • Close the client properly using context managers or explicit await client.close()
  • Be mindful of rate limits when making many concurrent requests