Seamlessly Integrate Azure OpenAI with EntraID: A Guide to Using Azure SDK and Azure APIM

Eray ALTILI
10 min readOct 18, 2024
A Guide to Using Azure SDK and Interactive Browser Credential with EntraID
import os
from azure.identity import InteractiveBrowserCredential, get_bearer_token_provider
from openai import AzureOpenAI

# Load environment variables (if using a .env file)
from dotenv import load_dotenv
load_dotenv()

# Retrieve environment variables
api_version = os.getenv("API_VERSION", "2024-07-01-preview")
endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")


# Set up token provider
token_provider = get_bearer_token_provider(
InteractiveBrowserCredential(),
"https://cognitiveservices.azure.com/.default"
)

# Initialize AzureOpenAI client
client = AzureOpenAI(
api_version=api_version,
azure_endpoint=endpoint,
azure_ad_token_provider=token_provider,
)

# Create a chat completion request
response = client.chat.completions.create(
model="gpt-4o", # model = "deployment_name".
messages=[
{"role": "system", "content": "Assistant is a large language model trained by OpenAI."},
{"role": "user", "content": "Who were the founders of Microsoft?"}
]
)

# Print the response
print(response.model_dump_json(indent=2))
print(response.choices.message.content)

Code Explanation

Importing Modules

import os
from azure.identity import InteractiveBrowserCredential, get_bearer_token_provider
from…

--

--

Eray ALTILI
Eray ALTILI

Written by Eray ALTILI

I am passionate about Technology, Cloud Computing, Machine Learning, Blockchain and Finance. All opinions are my own and do not express opinions of my employer.

No responses yet