问题摘要:
在尝试访问 OpenAI API 时遇到带有错误代码 401 的 AuthenticationError。错误消息显示主体无权访问 API/操作。
预期结果:
根据分配的角色和权限,服务主体应有权访问指定的 API/操作。
实际结果:
收到以下错误消息:主体无权访问 API/操作。这阻止了服务主体按预期访问 API。
环境详情:
-
订阅 ID:已隐藏
-
分配的角色:贡献者、用户
-
应用程序 ID:已隐藏
-
API/操作:Microsoft.CognitiveServices/accounts/listKeys/action
-
Azure 资源:已隐藏
感谢对上述问题的任何支持
回答:
您需要拥有Cognitive Services OpenAI 用户或Cognitive Services OpenAI 贡献者或认知服务用户角色,才能访问用于推理的 OpenAI 资源。
接下来,请使用以下代码。
from azure.identity import get_bearer_token_provider, ClientSecretCredentialfrom openai import AzureOpenAIcred = ClientSecretCredential(client_id="<yourClientId>",tenant_id="YourTenantId",client_secret="<ClientSeceret>")token_provider = get_bearer_token_provider( cred, "https://cognitiveservices.azure.com/.default")client = AzureOpenAI( api_version="2024-02-15-preview", azure_endpoint="https://v-jgsopenai.openai.azure.com/", azure_ad_token_provider=token_provider)response = client.chat.completions.create( model="gpt35", # model = "deployment_name". messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Does Azure OpenAI support customer managed keys?"}, {"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."}, {"role": "user", "content": "Do other Azure AI services support this too?"} ])print(response.choices[0].message.content)
输出: