Fix Azure OpenAI authentication error
Quick answer
Azure OpenAI authentication errors occur when using the standard
OpenAI client instead of the AzureOpenAI client or when missing the azure_endpoint parameter. Use AzureOpenAI with api_key and azure_endpoint set from environment variables to authenticate correctly. ERROR TYPE
config_error ⚡ QUICK FIX
Use the
AzureOpenAI client with both api_key and azure_endpoint parameters set from environment variables.Why this happens
Developers often encounter authentication errors when they use the standard OpenAI client to call Azure OpenAI services. This happens because Azure OpenAI requires specifying the azure_endpoint URL along with the API key, which the standard OpenAI client does not support. The error message typically indicates invalid credentials or missing endpoint configuration.
Example of incorrect code causing the error:
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["AZURE_OPENAI_API_KEY"])
response = client.chat.completions.create(
model=os.environ["AZURE_OPENAI_DEPLOYMENT"],
messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content) output
openai.error.AuthenticationError: Invalid API key or missing Azure endpoint
The fix
Use the AzureOpenAI client from the openai package, providing both the api_key and azure_endpoint parameters. This client is designed specifically for Azure OpenAI and handles the authentication flow correctly.
Corrected code example:
from openai import AzureOpenAI
import os
client = AzureOpenAI(
api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_version="2024-02-01"
)
response = client.chat.completions.create(
model=os.environ["AZURE_OPENAI_DEPLOYMENT"],
messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content) output
Hello
Preventing it in production
- Always use the
AzureOpenAIclient for Azure OpenAI API calls instead of the genericOpenAIclient. - Set and validate environment variables
AZURE_OPENAI_API_KEY,AZURE_OPENAI_ENDPOINT, andAZURE_OPENAI_DEPLOYMENTbefore runtime. - Implement retry logic with exponential backoff to handle transient authentication or network errors gracefully.
- Use managed identity authentication if running in Azure environments to avoid manual API key management.
Key Takeaways
- Use
AzureOpenAIclient withapi_keyandazure_endpointfor Azure OpenAI authentication. - Always set
AZURE_OPENAI_API_KEY,AZURE_OPENAI_ENDPOINT, andAZURE_OPENAI_DEPLOYMENTenvironment variables. - Implement retries and validate environment configuration to avoid runtime authentication failures.