The OpenAI Python SDK requires authentication using an API key. This guide covers how to set up authentication for both OpenAI and Azure OpenAI.
OpenAI API Key
Environment Variable (Recommended)
The most secure way to provide your API key is through the OPENAI_API_KEY environment variable:
The client will automatically read this variable:
Using python-dotenv
For local development, use python-dotenv to load your API key from a .env file:
Create .env file
Create a .env file in your project root:Add .env to your .gitignore to avoid committing your API key to version control.
Load environment variables
Direct API Key (Not Recommended)
You can pass the API key directly, but this is not recommended for production:
Never hardcode API keys in your source code or commit them to version control.
Get an API Key
You can obtain an API key from the OpenAI Platform.
Azure OpenAI Authentication
Azure OpenAI supports two authentication methods: API keys and Azure Active Directory (Azure AD).
API Key Authentication
Use the AZURE_OPENAI_API_KEY environment variable:
Then create the client:
Azure Active Directory (Azure AD)
For enhanced security, use Azure AD tokens:
See the Azure OpenAI guide for more details on Azure authentication.
Organization and Project IDs
You can optionally specify organization and project IDs:
These can also be set via environment variables:
Callable API Keys
For advanced use cases where you need to refresh tokens, you can pass a callable that returns the API key:
The function will be called for each request to get the current API key.