Overview
The OpenAI Python SDK provides two client classes for interacting with the API:OpenAI- Synchronous client for blocking operationsAsyncOpenAI- Asynchronous client for concurrent operations
Basic Initialization
Synchronous Client
OPENAI_API_KEY environment variable. You can also pass the API key explicitly:
Asynchronous Client
The
AsyncOpenAI client provides the same initialization options as OpenAI. All API methods return awaitable coroutines.Configuration Options
The client accepts several configuration parameters to customize behavior:Your OpenAI API key. Can be a string or a callable that returns a string (for dynamic key rotation).Environment variable:
OPENAI_API_KEYYour organization ID for API requests.Environment variable:
OPENAI_ORG_IDYour project ID for API requests.Environment variable:
OPENAI_PROJECT_IDOverride the default API base URL.Environment variable:
OPENAI_BASE_URLRequest timeout in seconds. Can be a float or an
httpx.Timeout object for granular control.See Timeouts for detailed configuration.Maximum number of retry attempts for failed requests.See Retries for retry behavior details.
Additional headers to include with every request.
Additional query parameters to include with every request.
Custom HTTP client instance. Use
DefaultHttpxClient or DefaultAsyncHttpxClient to preserve SDK defaults.Secret for webhook signature verification.Environment variable:
OPENAI_WEBHOOK_SECRETBase URL for WebSocket connections. If not specified, the default base URL is used with ‘wss://’ scheme.
Advanced Configuration
Custom Headers and Query Parameters
Organization and Project IDs
Organization and Project IDs are sent as
OpenAI-Organization and OpenAI-Project headers with each request.Dynamic API Keys
For scenarios requiring API key rotation, you can provide a callable:Custom HTTP Client
Customize the underlying HTTP client for advanced use cases like proxies or custom transports:Context Manager Usage
Both clients support context managers for automatic resource cleanup:Per-Request Configuration
Override client settings for individual requests usingwith_options():
Client Lifecycle
Manual Cleanup
If not using a context manager, manually close the client when done:The client automatically closes when garbage collected, but explicit cleanup is recommended for long-running applications.
Related
- Async Operations - Using AsyncOpenAI for concurrent requests
- Timeouts - Configuring request timeouts
- Retries - Understanding retry behavior
- Error Handling - Handling API errors