Overview
TheAsyncOpenAI 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 usingasyncio.gather():
Streaming with Async
Stream responses asynchronously usingasync for:
Context Manager
Use async context managers for automatic resource cleanup:Integration with Web Frameworks
FastAPI
Sanic
Using aiohttp Transport
For improved concurrency performance, use theaiohttp 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: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
Related
- Client Initialization - AsyncOpenAI configuration options
- Streaming - Async streaming responses
- Error Handling - Handling errors in async code
- Retries - Automatic retry behavior