You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure中通过Python使用端点密钥部署微调GPT模型

用服务主体凭据替代短期Azure AD令牌部署微调GPT模型

Azure资源管理(ARM)API不支持直接使用认知服务的端点密钥进行认证,因此你需要改用**服务主体(Service Principal)**来获取持久化的认证凭据,替代az account get-access-token生成的短期用户令牌。以下是具体实现步骤:

1. 创建并配置服务主体

首先在Azure中创建服务主体,并为其分配部署认知服务模型所需的权限:

  • 使用Azure CLI执行命令:
az ad sp create-for-rbac --name <你的服务主体名称> --role "Cognitive Services Contributor" --scopes /subscriptions/<你的订阅ID>/resourceGroups/<你的资源组>/providers/Microsoft.CognitiveServices/accounts/<你的认知服务账户名>
  • 记录命令返回的appId(客户端ID)、password(客户端密钥)、tenant(租户ID),后续代码会用到这些信息。

2. 修改Python部署代码

使用Azure Identity SDK通过服务主体获取令牌,替换原有的短期令牌认证方式:

import json
import requests
from azure.identity import ClientSecretCredential

# 替换为你的服务主体信息
tenant_id = "[你的租户ID]"
client_id = "[你的客户端ID]"
client_secret = "[你的客户端密钥]"

# 原有部署参数
subscription = '[redacted]'
resource_group = "[redacted]"
resource_name = "[redacted]"
model_deployment_name = "gpt-4o-mini-2024-07-18-ft"

# 通过服务主体获取ARM API令牌
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
token = credential.get_token("https://management.azure.com/.default").token

deploy_params = {'api-version': "2023-05-01"}
deploy_headers = {'Authorization': 'Bearer {}'.format(token), 'Content-Type': 'application/json'}

deploy_data = {
    "sku": {"name": "standard", "capacity": 1},
    "properties": {
        "model": {
            "format": "OpenAI",
            "name": "gpt-4o-mini-2024-07-18.ft-[redacted]",
            "version": "1"
        }
    }
}
deploy_data = json.dumps(deploy_data)

request_url = f'https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.CognitiveServices/accounts/{resource_name}/deployments/{model_deployment_name}'

print('Creating a new deployment...')

r = requests.put(request_url, params=deploy_params, headers=deploy_headers, data=deploy_data)

print(r)
print(r.reason)
print(r.json())

补充说明

  • 先安装依赖包:执行pip install azure-identity
  • 服务主体的客户端密钥可设置最长2年的有效期,到期后可重新生成,适合自动化部署场景
  • 如果代码运行在Azure虚拟机、函数应用等服务中,可改用托管标识(Managed Identity),无需手动管理密钥,安全性更高

内容的提问来源于stack exchange,提问作者Franck Dernoncourt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:22:12