使用AAD认证的Azure OpenAI#

本指南将向您展示如何使用Azure OpenAI客户端与Azure Active Directory (AAD)认证。

所使用的身份必须被分配Cognitive Services OpenAI User角色。

安装 Azure Identity 客户端#

Azure identity客户端用于与Azure Active Directory进行身份验证。

pip install azure-identity

使用模型客户端#

from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

# Create the token provider
token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)

client = AzureOpenAIChatCompletionClient(
    azure_deployment="{your-azure-deployment}",
    model="{model-name, such as gpt-4o}",
    api_version="2024-02-01",
    azure_endpoint="https://{your-custom-endpoint}.openai.azure.com/",
    azure_ad_token_provider=token_provider,
)

注意

查看这里了解如何直接使用Azure客户端或获取更多信息。