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:str | Callable[[], str]
Your OpenAI API key. Can be a string or a callable that returns a string (for dynamic key rotation).Environment variable:
OPENAI_API_KEYstr | None
default:"None"
Your organization ID for API requests.Environment variable:
OPENAI_ORG_IDstr | None
default:"None"
Your project ID for API requests.Environment variable:
OPENAI_PROJECT_IDstr | httpx.URL | None
default:"https://api.openai.com/v1"
Override the default API base URL.Environment variable:
OPENAI_BASE_URLfloat | Timeout | None
default:"600 seconds"
Request timeout in seconds. Can be a float or an
httpx.Timeout object for granular control.See Timeouts for detailed configuration.int
default:"2"
Maximum number of retry attempts for failed requests.See Retries for retry behavior details.
Mapping[str, str] | None
default:"None"
Additional headers to include with every request.
Mapping[str, object] | None
default:"None"
Additional query parameters to include with every request.
httpx.Client | httpx.AsyncClient | None
default:"None"
Custom HTTP client instance. Use
DefaultHttpxClient or DefaultAsyncHttpxClient to preserve SDK defaults.str | None
default:"None"
Secret for webhook signature verification.Environment variable:
OPENAI_WEBHOOK_SECRETstr | httpx.URL | None
default:"None"
Base 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