如何通过Managed Identity与RBAC角色在Azure Function App中连接Azure OpenAI
使用托管身份从Azure Function连接Azure OpenAI(Python实现)
前置依赖安装
在Azure Function的Python环境中安装必要的包:
pip install azure-identity openai
核心代码实现
以下是完整的Function代码示例,通过托管身份完成认证并调用Azure OpenAI模型:
import os from azure.identity import DefaultAzureCredential from openai import AzureOpenAI def main(req): # 从Function应用设置读取配置 endpoint = os.environ["AZURE_OPENAI_ENDPOINT"] api_version = os.environ["AZURE_OPENAI_API_VERSION"] deployment_name = os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] # 初始化默认凭证(自动使用Function App的托管身份) credential = DefaultAzureCredential() # 获取Azure OpenAI服务的访问令牌 access_token = credential.get_token("https://cognitiveservices.azure.com/.default").token # 初始化OpenAI客户端 client = AzureOpenAI( azure_endpoint=endpoint, api_version=api_version, azure_ad_token=access_token ) # 调用模型示例(可根据需求调整对话内容) chat_response = client.chat.completions.create( model=deployment_name, messages=[ {"role": "system", "content": "你是一个专业助手"}, {"role": "user", "content": "请解释Azure托管身份的作用"} ] ) return chat_response.choices[0].message.content
关键配置说明
- 环境变量配置:在Azure Function的「应用设置」中添加以下变量:
AZURE_OPENAI_ENDPOINT:你的Azure OpenAI资源端点(格式类似https://<resource-name>.openai.azure.com/)AZURE_OPENAI_API_VERSION:使用的API版本(例如2024-02-15-preview)AZURE_OPENAI_DEPLOYMENT_NAME:你部署的模型名称
- 角色生效确认:确保已为Function App的托管身份分配「Cognitive Services User」角色,角色分配通常需要1-5分钟生效,请等待足够时间后测试。
- 凭证逻辑:
DefaultAzureCredential会自动识别Function App的托管身份,无需手动传入密钥或认证信息。
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

