Two small utility classes to streamline connecting to Azure OpenAI:
- AzureIdentityUtil: sets up Microsoft Entra ID (Azure AD) credentials using
AZURE_CLIENT_ID,AZURE_TENANT_ID, andAZURE_CLIENT_SECRET, and exposes a bearer token provider for the Cognitive Services scope. - AzureOpenAIClientFactory: builds an
AzureOpenAIclient from the OpenAI Python library using either Entra ID token provider or API key.
python-sample-code/
├─ src/
│ └─ common/
│ ├─ __init__.py
│ ├─ azure_identity.py
│ └─ azure_openai_factory.py
├─ examples/
│ ├─ demo_chat.py
│ └─ demo_responses.py
├─ requirements.txt
└─ .env.example
- Python 3.10+
- An Azure OpenAI resource and a deployment (e.g.
gpt-4o) in your Azure subscription - One of:
- Microsoft Entra ID service principal with the
Cognitive Services OpenAI Userrole on the Azure OpenAI resource - Azure OpenAI API key
- Microsoft Entra ID service principal with the
openai(Azure OpenAI support viaAzureOpenAIclient)azure-identity(for Entra ID credentials and token provider)python-dotenv(optional, used in examples to read.env)
Install them:
pip install -r requirements.txt
Copy .env.example to .env and fill in:
AZURE_CLIENT_ID=<your-service-principal-client-id>
AZURE_TENANT_ID=<your-tenant-id>
AZURE_CLIENT_SECRET=<your-service-principal-secret>
AZURE_OPENAI_ENDPOINT=https://<your-resource-name>.openai.azure.com/
AZURE_OPENAI_API_VERSION=2024-10-21
# If using API key auth instead of Entra ID
AZURE_OPENAI_API_KEY=<your-azure-openai-key>
# Deployment name of the model to use (e.g., gpt-4o)
AZURE_OPENAI_DEPLOYMENT=<your-deployment-name>
Notes:
AZURE_OPENAI_API_VERSIONshould match a supported version for the features you use. Microsoft lists the latest GA/preview versions here: https://learn.microsoft.com/en-us/azure/ai-foundry/openai/api-version-lifecycle- In Azure, the
modelparameter is your deployment name (not a raw model ID).
import os
from dotenv import load_dotenv
from src.common.azure_identity import AzureIdentityUtil
from src.common.azure_openai_factory import AzureOpenAIClientFactory
load_dotenv()
deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT")
# Prefer Entra ID if SP creds are present; otherwise fall back to API key
has_sp = all(os.getenv(v) for v in ["AZURE_CLIENT_ID", "AZURE_TENANT_ID", "AZURE_CLIENT_SECRET"])
if has_sp:
token_provider = AzureIdentityUtil.from_env().get_token_provider()
factory = AzureOpenAIClientFactory.from_env_with_identity(token_provider)
else:
factory = AzureOpenAIClientFactory.from_env_with_api_key()
client = factory.create_client()
response = client.chat.completions.create(
model=deployment,
messages=[{"role": "user", "content": "Say hello from Azure OpenAI!"}],
)
print(response.choices[0].message.content)import os
from dotenv import load_dotenv
from src.common.azure_identity import AzureIdentityUtil
from src.common.azure_openai_factory import AzureOpenAIClientFactory
load_dotenv()
deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT")
- Add chat utility in `src/common/chat_util.py` providing:
- `ChatSession` for stateful conversations with history and optional system prompt
- `ChatUtil.quick_chat(...)` for one-shot prompts using the factory
has_sp = all(os.getenv(v) for v in ["AZURE_CLIENT_ID", "AZURE_TENANT_ID", "AZURE_CLIENT_SECRET"])
if has_sp:
token_provider = AzureIdentityUtil.from_env().get_token_provider()
factory = AzureOpenAIClientFactory.from_env_with_identity(token_provider)
else:
factory = AzureOpenAIClientFactory.from_env_with_api_key()
## Deprecations
- `AzureOpenAIClientFactory.quick_chat(...)` and `quick_response(...)` are deprecated.
- Prefer `src.common.chat_util.ChatUtil.quick_chat(...)` for one-shot calls.
- Prefer `src.common.chat_util.ChatSession` for stateful conversations with history.
- For advanced flows, use `client.chat.completions.create(...)` or `client.responses.create(...)` directly from the factory-built client.
# One-shot
text = ChatUtil(factory).quick_chat(os.getenv("AZURE_OPENAI_DEPLOYMENT"), "Hello!")
print(text)
# Stateful session
session = ChatSession(factory, deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT"), system_prompt="You are helpful.")
print(session.send("Hello"))
print(session.send("Give me a short tip about Azure."))from src.common.chat_util import ChatSession, ChatUtil
from src.common.azure_openai_factory import AzureOpenAIClientFactory
from src.common.azure_identity import AzureIdentityUtil
# Choose auth method (Service Principal preferred if available)
has_sp = all(os.getenv(v) for v in ["AZURE_CLIENT_ID", "AZURE_TENANT_ID", "AZURE_CLIENT_SECRET"])
if has_sp:
token_provider = AzureIdentityUtil.from_env().get_token_provider()
factory = AzureOpenAIClientFactory.from_env_with_identity(token_provider)
else:
factory = AzureOpenAIClientFactory.from_env_with_api_key()
# One-shot
text = ChatUtil(factory).quick_chat(os.getenv("AZURE_OPENAI_DEPLOYMENT"), "Hello!")
print(text)
# Stateful session
session = ChatSession(factory, deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT"), system_prompt="You are helpful.")
print(session.send("Hello"))
print(session.send("Give me a short tip about Azure."))- Entra ID auth: This uses
azure.identity.ClientSecretCredentialandget_bearer_token_providerfor thehttps://cognitiveservices.azure.com/.defaultscope. Pass the token provider to theAzureOpenAIclient viaazure_ad_token_provider. - API key auth: Provide
AZURE_OPENAI_API_KEYand the endpoint; the factory constructsAzureOpenAIwithapi_key. - API version: Keep this configurable (
AZURE_OPENAI_API_VERSION). Use the latest GA that supports the endpoints you need.
- OpenAI Cookbook – Azure examples (AAD token provider):
- Chat Completions: https://cookbook.openai.com/examples/azure/chat
- Embeddings: https://cookbook.openai.com/examples/azure/embeddings
- Microsoft Learn – Azure OpenAI API version lifecycle: https://learn.microsoft.com/en-us/azure/ai-foundry/openai/api-version-lifecycle
- AAD token provider in
AzureOpenAI(community/guide):