快速入门:为 Azure AI 服务创建多服务资源

使用本快速入门为 Azure AI 服务创建和管理多服务资源。 借助多服务资源,可以使用单个密钥和终结点访问多个 Azure AI 服务。 它还会合并所使用服务的计费。

可以通过两种不同的资源访问 Azure AI 服务:多服务资源或单一服务资源。

  • 多服务资源:
    • 通过单个密钥和终结点访问多个 Azure AI 服务。
    • 根据使用的服务合并计费。
  • 单服务资源:
    • 使用所创建的每个服务的唯一密钥和终结点访问单个 Azure AI 服务。
    • 大多数 Azure AI 服务提供免费层来试用。

Azure AI 服务由你在 Azure 订阅下创建的 Azure 资源表示。 创建资源后,可以使用生成的密钥和终结点对应用程序进行身份验证。

具有多服务资源的受支持服务

多服务资源支持通过单个密钥和终结点访问以下 Azure AI 服务。 使用以下链接查找快速入门文章和示例等内容,以开始使用你的资源。

服务 说明
Content Moderator icon内容审查器(已停用) 检测潜在的冒犯性内容或不需要的内容
Document Intelligence icon文档智能 仅需很少的时间和成本即可将文档转换为可用数据
Language icon语言 使用行业领先的自然语言理解功能构建应用
Speech icon语音 语音转文本、文本转语音、翻译和说话人辨识
Translator icon翻译器 翻译超过 100 种语言和方言
Vision icon视觉 分析图像和视频中的内容

先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。

创建新的多服务资源

多服务资源在门户中的“Azure AI 服务”>“Azure AI 服务多服务帐户”下列出。 要创建多服务资源,请按照以下说明操作:

  1. 选择此链接以创建多服务资源:https://portal.azure.cn/#create/Microsoft.CognitiveServicesAllInOne

  2. 在“创建”页中提供以下信息:

    项目详细信息 说明
    订阅 选择一个可用的 Azure 订阅。
    资源组 将包含 Azure AI 服务资源的 Azure 资源组。 可以创建新组或将其添加到预先存在的组。
    区域 Azure AI 服务实例的位置。 不同位置可能会导致延迟,但不会影响资源的运行时可用性。
    名称 Azure AI 服务资源的描述性名称。 例如,MyCognitiveServicesResource
    定价层 Azure AI 服务帐户的成本取决于你选择的选项和使用情况。 有关详细信息,请参阅 API 定价详细信息

    Multi-service resource creation screen

  3. 根据需要为资源配置其他设置,阅读并接受条件(如果适用),然后选择“查看 + 创建”。

提示

如果订阅不允许创建 Azure AI 服务资源,则可能需要使用 Azure 门户PowerShell 命令Azure CLI 命令启用 Azure 资源提供程序的特权。 如果你不是订阅所有者,可请求订阅所有者或具有管理员角色的人员帮助你完成注册,或请求向你的帐户授予 /register/action 特权。

获取资源的密钥

  1. 成功部署资源后,选择“后续步骤”>“转到资源”。

    Get resource keys screen

  2. 从打开的快速入门窗格中,可以访问资源终结点并管理密钥。

配置用于身份验证的环境变量

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 若要为资源密钥设置环境变量,请打开控制台窗口,按照操作系统和开发环境的说明进行操作。 若要设置 COGNITIVE_SERVICE_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。

对于生产环境,请使用安全的方式来存储和访问凭据,例如受密码保护的机密保管库。 对于测试环境,写入环境变量是标准做法,但请记住,环境变量将以明文形式存储在本地计算机上。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

PowerShell 包含一个可扩展的解决方案,即机密管理,它用于在机密存储Azure KeyVault 等平台中存储安全字符串。

若要设置机密存储以托管安全字符串,请参阅开始使用机密存储一文。 然后,使用以下示例存储 API 密钥。

Set-Secret -Name COGNITIVE_SERVICE_KEY -value your-key

对于测试环境,可以使用 PowerShell 的 $Env: 语法仅为当前会话设置环境变量,也可以使用 setx 命令在会话之间保留该变量。 请记住,这些值将以明文形式存储在 Windows 注册表项中。

$Env:COGNITIVE_SERVICE_KEY = your-key
setx COGNITIVE_SERVICE_KEY your-key

使用 setx 添加环境变量后,可能需要重启任何正在运行的控制台或需要读取环境变量的其他程序。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

若要为语音资源区域设置环境变量,请执行相同步骤。 将 COGNITIVE_SERVICE_REGION 设置为资源的区域。 例如 chinanorth2

清理资源

如果想要清理并移除 Azure AI 服务订阅,则可以删除资源或资源组。 删除资源组也会删除该组中包含的任何其他资源。

  1. 在 Azure 门户中展开左侧的菜单,打开服务菜单,然后选择“资源组”以显示资源组的列表。
  2. 找到包含要删除的资源的资源组。
  3. 如果要删除整个资源组,请选择资源组名称。 在下一页上,选择“删除资源组”并进行确认。
  4. 如果想要仅删除 Azure AI 服务资源,请选择资源组以查看其中包含的所有资源。 在下一页上,依次选择要删除的资源、该行的省略号菜单、“删除”。

使用本快速入门,以通过 Azure 命令行接口 (CLI) 命令创建 Azure AI 服务资源。 创建资源后,请使用生成的密钥和终结点对应用程序进行身份验证。

Azure AI 服务是基于云的人工智能 (AI) 服务,可帮助开发人员将认知智能内置于应用程序中,而无需具备直接的 AI 或数据科学技能或知识。 可采用常用开发语言通过 REST API 和客户端库 SDK 使用此类服务。 借助 Azure AI 服务,开发人员可以通过能够看、听、说和分析的认知解决方案,轻松地将认知功能添加到应用程序中。

先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • Azure CLI
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。
  • 必须从 Azure 门户创建第一个人脸、语言服务或 Azure AI 视觉资源,以审核和确认条款和条件。 可在此处执行此操作:人脸语言服务Azure AI 视觉。 在那之后,你可以使用任何部署工具(SDK、CLI 或 ARM 模板等)在同一 Azure 订阅下创建后续资源。

安装 Azure CLI 并登录

安装 Azure CLI。 若要登录到本地安装的 CLI,请运行 az login 命令:

az login

也可以使用绿色的“尝试”按钮在浏览器中运行这些命令。

创建新的 Azure AI 服务资源组

在创建 Azure AI 服务资源之前,必须具有 Azure 资源组才能包含该资源。 在创建新资源时,可以新建资源组,也可以使用现有资源组。 本文介绍如何创建新资源组。

选择资源组位置

若要创建资源,需要为订阅提供一个可用的 Azure 位置。 可以使用 az account list-locations 命令检索可用位置的列表。 可以从多个位置访问大部分 Azure AI 服务。 选择离你最近的位置,或查看哪些位置可供服务使用。

重要

  • 请记住 Azure 位置,因为在调用 Azure AI 服务资源时需要使用该位置。
  • 某些 Azure AI 服务的可用性因区域而异。 有关详细信息,请参阅 Azure 产品在各区域中的推出情况
az account list-locations --query "[].{Region:name}" --out table

选择 Azure 位置后,在 Azure CLI 中使用 az group create 命令创建新的资源组。 在以下示例中,请将 Azure 位置 chinanorth2 替换为你的订阅可用的某个 Azure 位置。

az group create --name ai-services-resource-group --location chinanorth2

创建 Azure AI 服务资源

选择服务和定价层

创建新资源时,需要知道要使用的服务的种类,以及所需的定价层(或 SKU)。 创建资源时,将此信息和其他信息用作参数。

请参阅下面的 SKU 和定价信息列表。

多服务

服务 种类
多个服务。 有关详细信息,请参阅定价页。 CognitiveServices

影像

服务 种类
Azure AI 视觉 ComputerVision
人脸 Face
文档智能 FormRecognizer

语音

服务 种类
语音服务 SpeechServices

语言

服务 种类
LUIS LUIS
语言服务 TextAnalytics
文本翻译 TextTranslation

决策

服务 种类
异常检测器 AnomalyDetector
内容审查器 ContentModerator

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义事务数的成本。 根据定价详细信息中为服务所指定的内容,超过此数字将导致额外费用。

注意

许多 Azure AI 服务都有一个免费层,供你试用该服务。 若要使用免费层,请使用 F0 作为资源的 SKU。

可以使用 az cognitiveservices account list-kinds 命令查找可用 Azure AI 服务“种类”的列表:

az cognitiveservices account list-kinds

将新资源添加到资源组

要创建并订阅新的 Azure AI 服务资源,请使用 az cognitiveservices account create 命令。 此命令会将新的可计费资源添加到前面创建的资源组。 创建新资源时,需要知道要使用的服务的种类,以及其定价层(或 SKU)和 Azure 位置:

可以使用以下命令创建名为 multi-service-resource 的标准 S0 多服务资源。

az cognitiveservices account create --name multi-service-resource --resource-group ai-services-resource-group  --kind CognitiveServices --sku F0 --location chinanorth2 --yes

提示

如果订阅不允许创建 Azure AI 服务资源,则可能需要使用 Azure 门户PowerShell 命令Azure CLI 命令启用 Azure 资源提供程序的特权。 如果你不是订阅所有者,可请求订阅所有者或具有管理员角色的人员帮助你完成注册,或请求向你的帐户授予 /register/action 特权。

获取资源的密钥

若要登录到本地安装的命令行接口 (CLI),请使用 az login 命令。

az cloud set -n AzureChinaCloud
az login

使用 az cognitiveservices account keys list 命令获取资源的密钥。

az cognitiveservices account keys list  --name multi-service-resource --resource-group ai-services-resource-group

配置用于身份验证的环境变量

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 若要为资源密钥设置环境变量,请打开控制台窗口,按照操作系统和开发环境的说明进行操作。 若要设置 COGNITIVE_SERVICE_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。

对于生产环境,请使用安全的方式来存储和访问凭据,例如受密码保护的机密保管库。 对于测试环境,写入环境变量是标准做法,但请记住,环境变量将以明文形式存储在本地计算机上。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

PowerShell 包含一个可扩展的解决方案,即机密管理,它用于在机密存储Azure KeyVault 等平台中存储安全字符串。

若要设置机密存储以托管安全字符串,请参阅开始使用机密存储一文。 然后,使用以下示例存储 API 密钥。

Set-Secret -Name COGNITIVE_SERVICE_KEY -value your-key

对于测试环境,可以使用 PowerShell 的 $Env: 语法仅为当前会话设置环境变量,也可以使用 setx 命令在会话之间保留该变量。 请记住,这些值将以明文形式存储在 Windows 注册表项中。

$Env:COGNITIVE_SERVICE_KEY = your-key
setx COGNITIVE_SERVICE_KEY your-key

使用 setx 添加环境变量后,可能需要重启任何正在运行的控制台或需要读取环境变量的其他程序。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

若要为语音资源区域设置环境变量,请执行相同步骤。 将 COGNITIVE_SERVICE_REGION 设置为资源的区域。 例如 chinanorth2

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义数目的事务的成本。 超过此金额将产生定价详细信息中为服务指定的额外费用。

获取资源的当前配额使用情况

使用 az cognitiveservices account list-usage 命令获取资源的使用情况。

az cognitiveservices account list-usage --name multi-service-resource --resource-group ai-services-resource-group --subscription subscription-name

清理资源

如果想要清理并移除 Azure AI 服务资源,可以删除它或资源组。 删除资源组也会删除该组中包含的任何其他资源。

若要删除资源组及其关联的资源,请使用 az group delete 命令。

az group delete --name ai-services-resource-group

使用本快速入门,以通过 Azure PowerShell 命令创建 Azure AI 服务资源。 创建资源后,请使用生成的密钥和终结点对应用程序进行身份验证。

Azure AI 服务是基于云的人工智能 (AI) 服务,可帮助开发人员将认知智能内置于应用程序中,而无需具备直接的 AI 或数据科学技能或知识。 可采用常用开发语言通过 REST API 和客户端库 SDK 使用此类服务。 借助 Azure AI 服务,开发人员可以通过能够看、听、说和分析的认知解决方案,轻松地将认知功能添加到应用程序中。

先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • Azure PowerShell
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。
  • 必须从 Azure 门户创建第一个人脸、语言服务或 Azure AI 视觉资源,以审核和确认条款和条件。 可在此处执行此操作:人脸语言服务Azure AI 视觉。 在那之后,你可以使用任何部署工具(SDK、CLI 或 ARM 模板等)在同一 Azure 订阅下创建后续资源。

安装 Azure PowerShell 并登录

安装 Azure PowerShell。 若要登录,请运行 Connect-AzAccount 命令:

Connect-AzAccount -Environment AzureChinaCloud

也可以使用绿色的“尝试”按钮在浏览器中运行这些命令。

创建新的 Azure AI 服务资源组

在创建 Azure AI 服务资源之前,必须具有 Azure 资源组才能包含该资源。 在创建新资源时,可以新建资源组,也可以使用现有资源组。 本文介绍如何创建新资源组。

选择资源组位置

若要创建资源,需要为订阅提供一个可用的 Azure 位置。 可以使用 Get-AzLocation 命令检索可用位置的列表。 可以从多个位置访问大部分 Azure AI 服务。 选择离你最近的位置,或查看哪些位置可供服务使用。

重要

  • 请记住 Azure 位置,因为在调用 Azure AI 服务资源时需要使用该位置。
  • 某些 Azure AI 服务的可用性因区域而异。 有关详细信息,请参阅 Azure 产品在各区域中的推出情况
Get-AzLocation | Select-Object -Property Location, DisplayName

获得 Azure 位置后,使用 New-AzResourceGroup 命令在 Azure PowerShell 创建新的资源组。 在以下示例中,请将 Azure 位置 chinanorth2 替换为你的订阅可用的某个 Azure 位置。

New-AzResourceGroup -Name ai-services-resource-group -Location chinanorth2

创建 Azure AI 服务资源

选择服务和定价层

创建新资源时,需要知道要使用的服务的种类,以及所需的定价层(或 SKU)。 创建资源时,将此信息和其他信息用作参数。

请参阅下面的 SKU 和定价信息列表。

多服务

服务 种类
多个服务。 有关详细信息,请参阅定价页。 CognitiveServices

影像

服务 种类
Azure AI 视觉 ComputerVision
人脸 Face
文档智能 FormRecognizer

语音

服务 种类
语音服务 SpeechServices

语言

服务 种类
LUIS LUIS
语言服务 TextAnalytics
文本翻译 TextTranslation

决策

服务 种类
异常检测器 AnomalyDetector
内容审查器 ContentModerator

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义事务数的成本。 根据定价详细信息中为服务所指定的内容,超过此数字将导致额外费用。

注意

许多 Azure AI 服务都有一个免费层,供你试用该服务。 若要使用免费层,请使用 F0 作为资源的 SKU。

可以使用 Get-AzCognitiveServicesAccountType 命令查找可用 Azure AI 服务“种类”的列表:

Get-AzCognitiveServicesAccountType

将新资源添加到资源组

若要创建并订阅新的 Azure AI 服务资源,请使用 New-AzCognitiveServicesAccount 命令。 此命令会将新的可计费资源添加到前面创建的资源组。 创建新资源时,需要知道要使用的服务的种类,以及其定价层(或 SKU)和 Azure 位置:

可以使用以下命令创建名为 multi-service-resource 的标准 S0 多服务资源。

New-AzCognitiveServicesAccount -ResourceGroupName ai-services-resource-group -Name multi-service-resource -Type CognitiveServices -SkuName F0 -Location chinanorth2

提示

如果订阅不允许创建 Azure AI 服务资源,则可能需要使用 Azure 门户Azure PowerShell 命令Azure CLI 命令启用 Azure 资源提供程序的特权。 如果你不是订阅所有者,可请求订阅所有者或具有管理员角色的人员帮助你完成注册,或请求向你的帐户授予 /register/action 特权。

获取资源的密钥

使用 Get-AzCognitiveServicesAccountKey 命令获取资源的密钥。

Get-AzCognitiveServicesAccountKey -Name multi-service-resource -ResourceGroupName ai-services-resource-group

配置用于身份验证的环境变量

必须对应用程序进行身份验证才能访问 Azure AI 服务资源。 若要为资源密钥设置环境变量,请打开控制台窗口,按照操作系统和开发环境的说明进行操作。 若要设置 COGNITIVE_SERVICE_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。

对于生产环境,请使用安全的方式来存储和访问凭据,例如受密码保护的机密保管库。 对于测试环境,写入环境变量是标准做法,但请记住,环境变量将以明文形式存储在本地计算机上。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

PowerShell 包含一个可扩展的解决方案,即机密管理,它用于在机密存储Azure KeyVault 等平台中存储安全字符串。

若要设置机密存储以托管安全字符串,请参阅开始使用机密存储一文。 然后,使用以下示例存储 API 密钥。

Set-Secret -Name COGNITIVE_SERVICE_KEY -value your-key

对于测试环境,可以使用 PowerShell 的 $Env: 语法仅为当前会话设置环境变量,也可以使用 setx 命令在会话之间保留该变量。 请记住,这些值将以明文形式存储在 Windows 注册表项中。

$Env:COGNITIVE_SERVICE_KEY = your-key
setx COGNITIVE_SERVICE_KEY your-key

使用 setx 添加环境变量后,可能需要重启任何正在运行的控制台或需要读取环境变量的其他程序。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

若要为语音资源区域设置环境变量,请执行相同步骤。 将 COGNITIVE_SERVICE_REGION 设置为资源的区域。 例如 chinanorth2

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义数目的事务的成本。 超过此金额将产生定价详细信息中为服务指定的额外费用。

获取资源的当前配额使用情况

使用 Get-AzCognitiveServicesAccountUsage 命令获取资源的使用情况。

Get-AzCognitiveServicesAccountUsage -ResourceGroupName ai-services-resource-group -Name multi-service-resource

清理资源

如果想要清理并移除 Azure AI 服务资源,可以删除它或资源组。 删除资源组也会删除该组中包含的任何其他资源。

若要删除资源组及其关联的资源,请使用 Remove-AzResourceGroup 命令。

Remove-AzResourceGroup -Name ai-services-resource-group

参考文档 | 库源代码 | 包 (NuGet) | 示例

C# 先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • .NET Core 的当前版本。
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。
  • 必须从 Azure 门户创建第一个人脸、语言服务或 Azure AI 视觉资源,以审核和确认条款和条件。 可在此处执行此操作:人脸语言服务Azure AI 视觉。 在那之后,你可以使用任何部署工具(SDK、CLI 或 ARM 模板等)在同一 Azure 订阅下创建后续资源。

创建 Azure 服务主体

若要使应用程序与 Azure 帐户交互,需要使用 Azure 服务主体来管理权限。 请按照创建 Azure 服务主体中的说明操作。

创建服务主体时,你会看到它有一个机密值、一个 ID 和一个应用程序 ID。 将应用程序 ID 和机密保存到某个临时位置,以供后续步骤使用。

创建资源组

在创建 Azure AI 服务资源之前,帐户必须具有 Azure 资源组才能包含该资源。 如果还没有资源组,请在 Azure 门户 中创建一个资源组,然后再继续。

新建 C# 应用程序

创建新的 .NET Core 应用程序。 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 azure-management-quickstart 的新控制台应用。 此命令将创建包含单个源文件的简单“Hello World”C# 项目:program.cs

dotnet new console -n azure-management-quickstart

将目录更改为新创建的应用文件夹。 可使用以下代码生成应用程序:

dotnet build

生成输出不应包含警告或错误。

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

安装客户端库

在应用程序目录中,使用以下命令安装适用于 .NET 的 Azure 管理客户端库:

dotnet add package Azure.ResourceManager.CognitiveServices
dotnet add package Microsoft.Azure.Management.Fluent
dotnet add package Microsoft.Azure.Management.ResourceManager.Fluent

如果你使用的是 Visual Studio IDE,客户端库可用作可下载的 NuGet 包。

导入库

打开“program.cs”并将以下 using 语句添加到文件顶部:

using System;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.CognitiveServices;
using Microsoft.Azure.Management.CognitiveServices.Models;

验证客户端

将以下字段添加到“program.cs”的根目录,并使用创建的服务主体和 Azure 帐户信息填写其值。

        const string  service_principal_application_id = "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE";
        const string  service_principal_secret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE";

        /* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
        const string  subscription_id = "PASTE_YOUR_SUBSCRIPTION_ID_HERE";

        /* The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory. */
        const string  tenant_id = "PASTE_YOUR_TENANT_ID_HERE";

        /* The name of the Azure resource group in which you want to create the resource.
        You can find resource groups in the Azure Dashboard under Home > Resource groups. */
        const string  resource_group_name = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE";

        /* The name of the custom subdomain to use when you create the resource. This is optional.
        For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
        your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.cn/.
        Note not all Cognitive Services allow custom subdomain names. */
        const string subdomain_name = "PASTE_YOUR_SUBDOMAIN_NAME_HERE";

然后,在 Main 方法中,使用这些值构造 CognitiveServicesManagementClient 对象。 所有 Azure 管理操作都需要此对象。

            var service_principal_credentials = new ServicePrincipalLoginInformation ();
            service_principal_credentials.ClientId = service_principal_application_id;
            service_principal_credentials.ClientSecret = service_principal_secret;

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(service_principal_application_id, service_principal_secret, tenant_id, AzureEnvironment.AzureGlobalCloud);
            var client = new CognitiveServicesManagementClient(credentials);
            client.SubscriptionId = subscription_id;

调用管理方法

将以下代码添加到 Main 方法中,以列出可用资源、创建示例资源、列出拥有的资源,然后删除示例资源。 你将在后续步骤中定义这些方法。

            // Uncomment to list all available resource kinds, SKUs, and locations for your Azure account:
            //list_available_kinds_skus_locations(client);
        
            // Create a resource with kind TextTranslation, F0 (free tier), location global.
            create_resource(client, "test_resource", "TextTranslation", "F0", "Global");

            // List all resources for your Azure account and resource group:
            list_resources(client);

            // Delete the resource.
            delete_resource(client, "test_resource");

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

创建 Azure AI 服务资源 (C#)

要创建并订阅新的 Azure AI 服务资源,请使用 Create 方法。 此方法向传入的资源组添加新的可计费资源。 创建新资源时,需要知道要使用的服务的种类,以及其定价层(或 SKU)和 Azure 位置。 下面的方法使用所有这些参数并创建资源。

        static void create_resource(CognitiveServicesManagementClient client, string resource_name, string kind, string account_tier, string location)
        {
            Console.WriteLine("Creating resource: " + resource_name + "...");
            /* NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
            property from CognitiveServicesAccountProperties. */
            CognitiveServicesAccount parameters = 
                new CognitiveServicesAccount(null, null, kind, location, resource_name, new CognitiveServicesAccountProperties(customSubDomainName : subdomain_name), new Sku(account_tier));
            var result = client.Accounts.Create(resource_group_name, resource_name, parameters);
            Console.WriteLine("Resource created.");
            Console.WriteLine("ID: " + result.Id);
            Console.WriteLine("Kind: " + result.Kind);
            Console.WriteLine();
        }

选择服务和定价层

创建新资源时,需要知道要使用的服务的种类,以及所需的定价层(或 SKU)。 创建资源时,将此信息和其他信息用作参数。 可以通过在脚本中调用以下方法来获取可用 Azure AI 服务“种类”的列表:

        static void list_available_kinds_skus_locations(CognitiveServicesManagementClient client)
        {

            Console.WriteLine("Available SKUs:");
            var result = client.ResourceSkus.List();
            Console.WriteLine("Kind\tSKU Name\tSKU Tier\tLocations");
            foreach (var x in result) {
                var locations = "";
                foreach (var region in x.Locations)
                {
                    locations += region;
                }
                Console.WriteLine(x.Kind + "\t" + x.Name + "\t" + x.Tier + "\t" + locations);
            };
        }

可以通过两种不同的资源来访问 Azure 认知服务:多服务资源或单一服务资源。

  • 多服务资源:
    • 通过单个密钥和终结点访问多个 Azure 认知服务。
    • 合并来自你使用的服务的计费。
  • 单服务资源:
    • 对于创建的每个服务,使用唯一密钥和终结点访问单个 Azure 认知服务。
    • 使用免费层试用服务。

请参阅下面的 SKU 和定价信息列表。

多服务

服务 种类
多个服务。 有关详细信息,请参阅定价页。 CognitiveServices

影像

服务 种类
Azure AI 视觉 ComputerVision
人脸 Face
文档智能 FormRecognizer

语音

服务 种类
语音服务 SpeechServices

语言

服务 种类
LUIS LUIS
语言服务 TextAnalytics
文本翻译 TextTranslation

决策

服务 种类
异常检测器 AnomalyDetector
内容审查器 ContentModerator

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义事务数的成本。 根据定价详细信息中为服务所指定的内容,超过此数字将导致额外费用。

注意

许多 Azure AI 服务都有一个免费层,供你试用该服务。 若要使用免费层,请使用 F0 作为资源的 SKU。

查看资源

若要查看 Azure 帐户下的所有资源(跨所有资源组),请使用以下方法:

        static void list_resources(CognitiveServicesManagementClient client)
        {
            Console.WriteLine("Resources in resource group: " + resource_group_name);
            var result = client.Accounts.ListByResourceGroup(resource_group_name);
            foreach (var x in result)
            {
                Console.WriteLine("ID: " + x.Id);
                Console.WriteLine("Name: " + x.Name);
                Console.WriteLine("Type: " + x.Type);
                Console.WriteLine("Kind: " + x.Kind);
                Console.WriteLine();
            }
        }

删除资源

下面的方法从给定的资源组中删除指定的资源。

        static void delete_resource(CognitiveServicesManagementClient client, string resource_name)
        {
            Console.WriteLine("Deleting resource: " + resource_name + "...");
            client.Accounts.Delete (resource_group_name, resource_name);

            Console.WriteLine("Resource deleted.");
            Console.WriteLine();
        }

运行应用程序

从应用程序目录使用 dotnet run 命令运行应用程序。

dotnet run

参考文档 | 库源代码 | 包 (Maven)

Java 先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • 最新版本的 Java 开发工具包 (JDK)
  • Gradle 生成工具,或其他依赖项管理器。
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。
  • 必须从 Azure 门户创建第一个人脸、语言服务或 Azure AI 视觉资源,以审核和确认条款和条件。 可在此处执行此操作:人脸语言服务Azure AI 视觉。 在那之后,你可以使用任何部署工具(SDK、CLI 或 ARM 模板等)在同一 Azure 订阅下创建后续资源。

创建 Azure 服务主体

若要使应用程序与 Azure 帐户交互,需要使用 Azure 服务主体来管理权限。 请按照创建 Azure 服务主体中的说明操作。

创建服务主体时,你会看到它有一个机密值、一个 ID 和一个应用程序 ID。 将应用程序 ID 和机密保存到某个临时位置,以供后续步骤使用。

创建资源组

在创建 Azure AI 服务资源之前,帐户必须具有 Azure 资源组才能包含该资源。 如果还没有资源组,请在 Azure 门户 中创建一个资源组,然后再继续。

创建新的 Java 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。

mkdir myapp && cd myapp

从工作目录运行 gradle init 命令。 此命令将创建 Gradle 的基本生成文件,包括 build.gradle.kts,在运行时将使用该文件创建并配置应用程序。

gradle init --type basic

当提示你选择一个 DSL 时,选择 Kotlin

在工作目录中运行以下命令:

mkdir -p src/main/java

安装客户端库

本快速入门使用 Gradle 依赖项管理器。 可以在 Maven 中央存储库中找到客户端库以及其他依赖项管理器的信息。

在项目的 build.gradle.kts 文件中,以 implementation 语句的形式包含客户端库及所需的插件和设置。

plugins {
    java
    application
}
application {
    mainClass.set("FormRecognizer")
}
repositories {
    mavenCentral()
}
dependencies {
    implementation(group = "com.microsoft.azure", name = "azure-mgmt-cognitiveservices", version = "1.10.0-beta")
}

导入库

导航到新的 src/main/java 文件夹,并创建名为 Management.java 的文件。 在喜好的编辑器或 IDE 中打开该文件并添加以下 import 语句:

import com.azure.core.management.*;
import com.azure.core.management.profile.*;
import com.azure.identity.*;
import com.azure.resourcemanager.cognitiveservices.*;
import com.azure.resourcemanager.cognitiveservices.implementation.*;
import com.azure.resourcemanager.cognitiveservices.models.*;

import java.io.*;
import java.lang.Object.*;
import java.util.*;
import java.net.*;

验证客户端

在 Management.java 中添加类,然后在其中添加以下字段及其值。 使用创建的服务主体和其他 Azure 帐户信息填写其值。

	/*
	Be sure to use the service pricipal application ID, not simply the ID. 
	*/
	
	private static String applicationId = "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE";
	private static String applicationSecret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE";

	/* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
	private static String subscriptionId = "PASTE_YOUR_SUBSCRIPTION_ID_HERE";

	/* The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory. */
	private static String tenantId = "PASTE_YOUR_TENANT_ID_HERE";

	/* The name of the Azure resource group in which you want to create the resource.
	You can find resource groups in the Azure Dashboard under Home > Resource groups. */
	private static String resourceGroupName = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE";

	/* The name of the custom subdomain to use when you create the resource. This is optional.
	For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
	your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.cn/.
	Note not all Cognitive Services allow custom subdomain names. */
	private static String subDomainName = "PASTE_YOUR_SUBDOMAIN_NAME_HERE";

然后,在 main 方法中,使用这些值构造 CognitiveServicesManager 对象 。 所有 Azure 管理操作都需要此对象。

		/* For more information see:
		https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md
		*/

		ClientSecretCredential credential = new ClientSecretCredentialBuilder()
			.clientId(applicationId)
			.clientSecret(applicationSecret)
			.tenantId(tenantId)
			.build();
		AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE);

		CognitiveServicesManager client = CognitiveServicesManager.authenticate(credential, profile);

调用管理方法

将以下代码添加到 Main 方法中,以列出可用资源、创建示例资源、列出拥有的资源,然后删除示例资源。 你将在后续步骤中定义这些方法。

		String resourceName = "test_resource";
		String resourceKind = "TextTranslation";
		String resourceSku = "F0";
		Region resourceRegion = Region.US_WEST;

		// Uncomment to list all available resource kinds, SKUs, and locations for your Azure account.
		// list_available_kinds_skus_locations (client);

		// Create a resource with kind Text Translation, SKU F0 (free tier), location US West.
		String resourceId = create_resource (client, resourceName, resourceGroupName, resourceKind, resourceSku, resourceRegion);

		// Uncomment this to list all resources for your Azure account.
		// list_resources (client, resourceGroupName);

		// Delete the resource.
		delete_resource (client, resourceId);

		/* NOTE: When you delete a resource, it is only soft-deleted. You must also purge it. Otherwise, if you try to create another
		resource with the same name or custom subdomain, you will receive an error stating that such a resource already exists. */
		purge_resource (client, resourceName, resourceGroupName, resourceRegion);

创建 Azure AI 服务资源 (Java)

要创建并订阅新的 Azure AI 服务资源,请使用 create 方法。 此方法向传入的资源组添加新的可计费资源。 创建新资源时,需要知道要使用的服务的种类,以及其定价层(或 SKU)和 Azure 位置。 下面的方法使用所有这些参数并创建资源。

	public static String create_resource (CognitiveServicesManager client, String resourceName, String resourceGroupName, String resourceKind, String resourceSku, Region resourceRegion) {
		System.out.println ("Creating resource: " + resourceName + "...");

		/* NOTE: If you do not want to use a custom subdomain name, remove the withCustomSubDomainName
		setter from the AccountProperties object. */
		Account result = client.accounts().define(resourceName)
			.withExistingResourceGroup(resourceGroupName)
			// Note: Do not call withRegion() first, as it does not exist on the Blank interface returned by define().
			.withRegion(resourceRegion)
			.withKind(resourceKind)
			.withSku(new Sku().withName(resourceSku))
			.withProperties(new AccountProperties().withCustomSubDomainName(subDomainName))
			.create();

		System.out.println ("Resource created.");
		System.out.println ("ID: " + result.id());
		System.out.println ("Provisioning state: " + result.properties().provisioningState().toString());
		System.out.println ();

		return result.id();
	}

选择服务和定价层

创建新资源时,需要知道要使用的服务的种类,以及所需的定价层(或 SKU)。 创建资源时,将此信息和其他信息用作参数。 可以通过调用以下方法来获取可用 Azure AI 服务“种类”的列表:

	public static void list_available_kinds_skus_locations (CognitiveServicesManager client) {
		System.out.println ("Available SKUs:");
		System.out.println("Kind\tSKU Name\tSKU Tier\tLocations");
		ResourceSkus skus = client.resourceSkus();
		for (ResourceSku sku : skus.list()) {
			String locations = String.join (",", sku.locations());
			System.out.println (sku.kind() + "\t" + sku.name() + "\t" + sku.tier() + "\t" + locations);
		}
	}

可以通过两种不同的资源来访问 Azure 认知服务:多服务资源或单一服务资源。

  • 多服务资源:
    • 通过单个密钥和终结点访问多个 Azure 认知服务。
    • 合并来自你使用的服务的计费。
  • 单服务资源:
    • 对于创建的每个服务,使用唯一密钥和终结点访问单个 Azure 认知服务。
    • 使用免费层试用服务。

请参阅下面的 SKU 和定价信息列表。

多服务

服务 种类
多个服务。 有关详细信息,请参阅定价页。 CognitiveServices

影像

服务 种类
Azure AI 视觉 ComputerVision
人脸 Face
文档智能 FormRecognizer

语音

服务 种类
语音服务 SpeechServices

语言

服务 种类
LUIS LUIS
语言服务 TextAnalytics
文本翻译 TextTranslation

决策

服务 种类
异常检测器 AnomalyDetector
内容审查器 ContentModerator

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义事务数的成本。 根据定价详细信息中为服务所指定的内容,超过此数字将导致额外费用。

注意

许多 Azure AI 服务都有一个免费层,供你试用该服务。 若要使用免费层,请使用 F0 作为资源的 SKU。

查看资源

若要查看 Azure 帐户下的所有资源(跨所有资源组),请使用以下方法:

	public static void list_resources (CognitiveServicesManager client, String resourceGroupName) {
		System.out.println ("Resources in resource group: " + resourceGroupName);
		// Note Azure resources are also sometimes referred to as accounts.
		Accounts accounts = client.accounts();
		for (Account account : accounts.listByResourceGroup(resourceGroupName)) {
			System.out.println ("ID: " + account.id());
			System.out.println ("Kind: " + account.kind ());
			System.out.println ("SKU Name: " + account.sku().name());
			System.out.println ("Custom subdomain name: " + account.properties().customSubDomainName());
			System.out.println ();
		}
	}

删除资源

下面的方法从给定的资源组中删除指定的资源。

	public static void delete_resource (CognitiveServicesManager client, String resourceId) {
		System.out.println ("Deleting resource: " + resourceId + "...");
		client.accounts().deleteById (resourceId);
		System.out.println ("Resource deleted.");
		System.out.println ();
	}

参考文档 | 库源代码 | 包 (npm) | 示例

JavaScript 先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • 最新版本的 Node.js
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。
  • 必须从 Azure 门户创建第一个人脸、语言服务或 Azure AI 视觉资源,以审核和确认条款和条件。 可在此处执行此操作:人脸语言服务Azure AI 视觉。 在那之后,你可以使用任何部署工具(SDK、CLI 或 ARM 模板等)在同一 Azure 订阅下创建后续资源。

创建 Azure 服务主体

若要使应用程序与 Azure 帐户交互,需要使用 Azure 服务主体来管理权限。 请按照创建 Azure 服务主体中的说明操作。

创建服务主体时,你会看到它有一个机密值、一个 ID 和一个应用程序 ID。 将应用程序 ID 和机密保存到某个临时位置,以供后续步骤使用。

创建资源组

在创建 Azure AI 服务资源之前,帐户必须具有 Azure 资源组才能包含该资源。 如果还没有资源组,请在 Azure 门户 中创建一个资源组,然后再继续。

创建新的 Node.js 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。

mkdir myapp && cd myapp

运行 init 命令以使用 package.json 文件创建一个 node 应用程序。

 init

继续之前,请先创建一个名为 index.js 的文件。

安装客户端库

安装以下 npm 包:

npm install @azure/arm-cognitiveservices
npm install @azure/identity

应用的 package.json 文件将使用依赖项进行更新。

导入库

打开 index.js 脚本并导入以下库。

"use strict";

/* To run this sample, install the following modules.
 * npm install @azure/arm-cognitiveservices @azure/identity
 */
var Arm = require("@azure/arm-cognitiveservices");
var Identity = require("@azure/identity");

验证客户端

将以下字段添加到脚本的根目录中,并使用所创建的服务主体和 Azure 帐户信息填写其值。

const service_principal_application_id =
  "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE";
const service_principal_secret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE";

/* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
const subscription_id = "PASTE_YOUR_SUBSCRIPTION_ID_HERE";

/* The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory. */
const tenant_id = "PASTE_YOUR_TENANT_ID_HERE";

/* The name of the Azure resource group in which you want to create the resource.
You can find resource groups in the Azure Dashboard under Home > Resource groups. */
const resource_group_name = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE";

/* The name of the custom subdomain to use when you create the resource. This is optional.
For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.cn/.
Note not all Cognitive Services allow custom subdomain names.
*/
const subdomain_name = "PASTE_YOUR_SUBDOMAIN_NAME_HERE";

接下来,添加以下 quickstart 函数来处理程序的主要工作。 第一个代码块使用你在上面输入的凭据变量构造一个 CognitiveServicesManagementClient 对象。 所有 Azure 管理操作都需要此对象。

async function quickstart() {
  /* For more information see:
https://www.npmjs.com/package/@azure/arm-cognitiveservices/v/6.0.0
https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-a-client-secret
*/
  const credentials = new Identity.ClientSecretCredential(
    tenant_id,
    service_principal_application_id,
    service_principal_secret
  );
  const client = new Arm.CognitiveServicesManagementClient(
    credentials,
    subscription_id
  );
  // Note Azure resources are also sometimes referred to as accounts.
  const accounts_client = client.accounts;
  const resource_skus_client = client.resourceSkus;
  const deleted_accounts_client = client.deletedAccounts;

调用管理函数

将以下代码添加到 quickstart 函数的末尾,以列出可用资源、创建示例资源、列出拥有的资源,然后删除示例资源。 你将在后续步骤中定义这些函数。

创建 Azure AI 服务资源 (Node.js)

要创建并订阅新的 Azure AI 服务资源,请使用 Create 函数。 此函数向传入的资源组添加新的可计费资源。 创建新资源时,需要知道要使用的服务的种类,以及其定价层(或 SKU)和 Azure 位置。 下面的函数使用所有这些参数并创建资源。

async function create_resource(
  client,
  resource_name,
  resource_kind,
  resource_sku,
  resource_region
) {
  console.log("Creating resource: " + resource_name + "...");
  /* NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
property from the properties object. */
  var parameters = {
    sku: { name: resource_sku },
    kind: resource_kind,
    location: resource_region,
    properties: { customSubDomainName: subdomain_name },
  };
  return client
    .beginCreateAndWait(resource_group_name, resource_name, parameters)
    .then((result) => {
      console.log("Resource created.");
      console.log();
      console.log("ID: " + result.id);
      console.log("Kind: " + result.kind);
      console.log();
    })
    .catch((err) => {
      console.log(err);
    });
}

选择服务和定价层

创建新资源时,需要知道要使用的服务的种类,以及所需的定价层(或 SKU)。 创建资源时,将此信息和其他信息用作参数。 以下函数列出了可用的 Azure AI 服务“种类”。

async function list_available_kinds_skus_locations(client) {
  console.log("Available SKUs:");
  var result = client.list();
  console.log("Kind\tSKU Name\tSKU Tier\tLocations");
  for await (let item of result) {
    var locations = item.locations.join(",");
    console.log(item.kind + "\t" + item.name + "\t" + item.tier + "\t" + locations);
  }
}

可以通过两种不同的资源来访问 Azure 认知服务:多服务资源或单一服务资源。

  • 多服务资源:
    • 通过单个密钥和终结点访问多个 Azure 认知服务。
    • 合并来自你使用的服务的计费。
  • 单服务资源:
    • 对于创建的每个服务,使用唯一密钥和终结点访问单个 Azure 认知服务。
    • 使用免费层试用服务。

请参阅下面的 SKU 和定价信息列表。

多服务

服务 种类
多个服务。 有关详细信息,请参阅定价页。 CognitiveServices

影像

服务 种类
Azure AI 视觉 ComputerVision
人脸 Face
文档智能 FormRecognizer

语音

服务 种类
语音服务 SpeechServices

语言

服务 种类
LUIS LUIS
语言服务 TextAnalytics
文本翻译 TextTranslation

决策

服务 种类
异常检测器 AnomalyDetector
内容审查器 ContentModerator

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义事务数的成本。 根据定价详细信息中为服务所指定的内容,超过此数字将导致额外费用。

注意

许多 Azure AI 服务都有一个免费层,供你试用该服务。 若要使用免费层,请使用 F0 作为资源的 SKU。

查看资源

若要查看 Azure 帐户下的所有资源(跨所有资源组),请使用以下函数:

async function list_resources(client) {
  console.log("Resources in resource group: " + resource_group_name);
  var result = client.listByResourceGroup(resource_group_name);
  for await (let item of result) {
    console.log(item);
    console.log();
  }
}

删除资源

下面的函数从给定的资源组中删除指定的资源。

async function delete_resource(client, resource_name) {
  console.log("Deleting resource: " + resource_name + "...");
  await client.beginDeleteAndWait(resource_group_name, resource_name);
  console.log("Resource deleted.");
  console.log();
}

如果需要恢复已删除的资源,请参阅恢复已删除的 Azure AI 服务资源

运行应用程序

将以下代码添加到脚本底部,以调用包含错误处理的主 quickstart 函数。

try {
  quickstart();
} catch (error) {
  console.log(error);
}

然后,在控制台窗口中,使用 node 命令运行应用程序。

node index.js

参考文档 | 库源代码 | 包 (PyPi) | 示例

Python 先决条件

  • 有效的 Azure 订阅 - 创建试用订阅
  • Python 3.x
  • 要同意负责任 AI 条款并创建资源,你的 Azure 帐户必须分配有 Cognitive Services Contributor 角色。 若要将此角色分配给你的帐户,请按照分配角色文档中的步骤进行操作,或与管理员联系。
  • 必须从 Azure 门户创建第一个人脸、语言服务或 Azure AI 视觉资源,以审核和确认条款和条件。 可在此处执行此操作:人脸语言服务Azure AI 视觉。 在那之后,你可以使用任何部署工具(SDK、CLI 或 ARM 模板等)在同一 Azure 订阅下创建后续资源。

创建 Azure 服务主体

若要使应用程序与 Azure 帐户交互,需要使用 Azure 服务主体来管理权限。 请按照创建 Azure 服务主体中的说明操作。

创建服务主体时,你会看到它有一个机密值、一个 ID 和一个应用程序 ID。 将应用程序 ID 和机密保存到某个临时位置,以供后续步骤使用。

创建资源组

在创建 Azure AI 服务资源之前,帐户必须具有 Azure 资源组才能包含该资源。 如果还没有资源组,请在 Azure 门户 中创建一个资源组,然后再继续。

创建新的 Python 应用程序

在首选编辑器或 IDE 中创建新的 Python 应用程序,并在控制台窗口中导航到你的项目。

安装客户端库

可使用以下方式安装客户端库:

pip install azure-mgmt-cognitiveservices

另外,请安装 Azure 标识库以支持 Microsoft Entra 令牌身份验证。

pip install azure-identity

导入库

打开 Python 脚本并导入以下库。

import time
from azure.identity import ClientSecretCredential
from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
from azure.mgmt.cognitiveservices.models import Account, Sku

验证客户端

将以下字段添加到脚本的根目录中,并使用所创建的服务主体和 Azure 帐户信息填写其值。

# Be sure to use the service pricipal application ID, not simply the ID. 
service_principal_application_id = "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE"
service_principal_secret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE"

# The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions.
subscription_id = "PASTE_YOUR_SUBSCRIPTION_ID_HERE"

# The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory.
tenant_id = "PASTE_YOUR_TENANT_ID_HERE"

# The name of the Azure resource group in which you want to create the resource.
# You can find resource groups in the Azure Dashboard under Home > Resource groups.
resource_group_name = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE"

# The name of the custom subdomain to use when you create the resource. This is optional.
# For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
# your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.cn/.
# Note not all Cognitive Services allow custom subdomain names.
subdomain_name = "PASTE_YOUR_SUBDOMAIN_NAME_HERE"

# How many seconds to wait between checking the status of an async operation.
wait_time = 10

然后添加以下代码来构造 CognitiveServicesManagementClient 对象。 所有 Azure 管理操作都需要此对象。

credential = ClientSecretCredential(tenant_id, service_principal_application_id, service_principal_secret)
client = CognitiveServicesManagementClient(credential, subscription_id)

创建 Azure AI 服务资源 (Python)

要创建并订阅新的 Azure AI 服务资源,请使用 Create 函数。 此函数向传入的资源组添加新的可计费资源。 创建新资源时,需要知道要使用的服务的种类,以及其定价层(或 SKU)和 Azure 位置。 下面的函数使用所有这些参数并创建资源。

def create_resource (resource_name, kind, sku_name, location) :
	print("Creating resource: " + resource_name + "...")

# NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
# property from the properties object.
	parameters = Account(sku=Sku(name=sku_name), kind=kind, location=location, properties={ 'custom_sub_domain_name' : subdomain_name })

	poller = client.accounts.begin_create(resource_group_name, resource_name, parameters)
	while (False == poller.done ()) :
		print ("Waiting {wait_time} seconds for operation to finish.".format (wait_time = wait_time))
		time.sleep (wait_time)
# This will raise an exception if the server responded with an error.
	result = poller.result ()

	print("Resource created.")
	print()
	print("ID: " + result.id)
	print("Name: " + result.name)
	print("Type: " + result.type)
	print()

选择服务和定价层

创建新资源时,需要知道要使用的服务的种类,以及所需的定价层(或 SKU)。 创建资源时,将此信息和其他信息用作参数。 以下函数列出了可用的 Azure AI 服务“种类”。

def list_available_kinds_skus_locations():
	print("Available SKUs:")
	result = client.resource_skus.list()
	print("Kind\tSKU Name\tSKU Tier\tLocations")
	for x in result:
		locations = ",".join(x.locations)
		print(x.kind + "\t" + x.name + "\t" + x.tier + "\t" + locations)

可以通过两种不同的资源来访问 Azure 认知服务:多服务资源或单一服务资源。

  • 多服务资源:
    • 通过单个密钥和终结点访问多个 Azure 认知服务。
    • 合并来自你使用的服务的计费。
  • 单服务资源:
    • 对于创建的每个服务,使用唯一密钥和终结点访问单个 Azure 认知服务。
    • 使用免费层试用服务。

请参阅下面的 SKU 和定价信息列表。

多服务

服务 种类
多个服务。 有关详细信息,请参阅定价页。 CognitiveServices

影像

服务 种类
Azure AI 视觉 ComputerVision
人脸 Face
文档智能 FormRecognizer

语音

服务 种类
语音服务 SpeechServices

语言

服务 种类
LUIS LUIS
语言服务 TextAnalytics
文本翻译 TextTranslation

决策

服务 种类
异常检测器 AnomalyDetector
内容审查器 ContentModerator

定价层和计费

定价层(以及你收到的账单金额)基于你使用身份验证信息发送的事务数。 每个定价层指定:

  • 每秒允许的最大事务数 (TPS)。
  • 在定价层中启用的服务功能。
  • 预定义事务数的成本。 根据定价详细信息中为服务所指定的内容,超过此数字将导致额外费用。

注意

许多 Azure AI 服务都有一个免费层,供你试用该服务。 若要使用免费层,请使用 F0 作为资源的 SKU。

查看资源

若要查看 Azure 帐户下的所有资源(跨所有资源组),请使用以下函数:

def list_resources():
	print("Resources in resource group: " + resource_group_name)
	result = client.accounts.list_by_resource_group(resource_group_name)
	for x in result:
		print(x.name)
		print(x)
		print()

删除资源

下面的函数从给定的资源组中删除指定的资源。

def delete_resource(resource_name) :
	print("Deleting resource: " + resource_name + "...")

	poller = client.accounts.begin_delete(resource_group_name, resource_name)
	while (False == poller.done ()) :
		print ("Waiting {wait_time} seconds for operation to finish.".format (wait_time = wait_time))
		time.sleep (wait_time)
# This will raise an exception if the server responded with an error.
	result = poller.result ()

	print("Resource deleted.")

如果需要恢复已删除的资源,请参阅恢复已删除的 Azure AI 服务资源

调用管理函数

将以下代码添加到脚本底部,以调用上述函数。 此代码列出可用资源、创建示例资源、列出拥有的资源,然后删除示例资源。

resource_name = "test_resource"
resource_kind = "TextTranslation"
resource_sku = "F0"
resource_location = "Global"

# Uncomment this to list all available resource kinds, SKUs, and locations for your Azure account.
#list_available_kinds_skus_locations ()

# Create a resource with kind Text Translation, SKU F0 (free tier), location global.
create_resource(resource_name, resource_kind, resource_sku, resource_location)

# Uncomment this to list all resources for your Azure account.
#list_resources()

# Delete the resource.
delete_resource(resource_name)

# NOTE: Deleting a resource only soft-deletes it. To delete it permanently, you must purge it.
# Otherwise, if you later try to create a resource with the same name, you will receive the following error:
# azure.core.exceptions.ResourceExistsError: (FlagMustBeSetForRestore) An existing resource with ID '<your resource ID>' has been soft-deleted. To restore the resource, you must specify 'restore' to be 'true' in the property. If you don't want to restore existing resource, please purge it first.
# Code: FlagMustBeSetForRestore

# Purge the resource.
purge_resource(resource_name, resource_location)

运行应用程序

在命令行中使用 python 命令运行应用程序。

python <your-script-name>.py

后续步骤