你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

快速入门:使用代理控制评估工具调用(预览版)

在本快速入门中,你将使用代理控制 REST API 通过 Azure 资源管理器 (ARM) 创建策略。 然后,使用 Unified Moderate 评估建议的工具调用。

该策略允许退款大于零且不超过 100。 提交退款 75 以查看允许的结果。 然后提交退款 150 以查看被拒绝的结果。

这些 API 调用评估拟议的退款。 他们不执行工具或进行退款。

有关策略和干预点的简介,请参阅 什么是代理控制?

如果您还没有 Azure 订阅,请免费创建一个。

Prerequisites

  • 一份 Azure 订阅。
  • 为代理控制预览版启用Azure AI 内容安全资源。 如果需要资源,请在启用了预览访问的区域 中创建内容安全资源 。 仅创建资源不会启用代理控制。
  • 在该帐户下创建策略和 Rego 资源的权限,例如帐户范围内的 Contributor。
  • 帐户上用于运行时调用的 Cognitive Services User 角色。 设置部分显示管理员如何授予此角色。 创建角色分配需要其他权限,例如基于角色的 访问控制 管理员。
  • Azure CLI、cURL 7.76 或更高版本和 PowerShell 7 或更高版本。

本演练使用Microsoft Entra身份验证和帐户的自定义子域终结点。 它不需要 SDK、Node.js或 OPA。

Note

此示例使用 ARM API 版本 2026-11-15-preview、Unified Moderate API 版本 2026-09-01-preview 和 ACS 清单版本 0.4.0-alpha.1。 帐户和区域必须支持这些版本。

设置资源和访问权限

在以下请求文件的工作目录中打开 PowerShell。 在同一会话中运行命令。

登录并选择包含内容安全资源的订阅:

$ErrorActionPreference = 'Stop'
$SubscriptionId = '<subscription-guid>'
$ResourceGroup = '<resource-group-name>'
$AccountName = '<content-safety-account-name>'

az login
if ($LASTEXITCODE -ne 0) { throw 'Azure sign-in failed.' }
az account set --subscription $SubscriptionId
if ($LASTEXITCODE -ne 0) { throw 'Unable to select the subscription.' }

$AccountJson = az cognitiveservices account show `
    --resource-group $ResourceGroup --name $AccountName --output json
if ($LASTEXITCODE -ne 0) { throw 'Unable to read the Content Safety resource.' }
$Account = ($AccountJson -join "`n") | ConvertFrom-Json
$AccountId = $Account.id
$Endpoint = $Account.properties.endpoint
if (-not $AccountId -or [string]::IsNullOrWhiteSpace($Endpoint)) {
    throw 'The resource did not return an ID and endpoint.'
}
$Endpoint = $Endpoint.TrimEnd('/')

$ArmApiVersion = '2026-11-15-preview'
$DataApiVersion = '2026-09-01-preview'
$RegoId = "$AccountId/raiRegos/refund-quickstart"
$PolicyId = "$AccountId/raiPolicies/refund-quickstart"

如果已登录用户在该帐户上尚未拥有 Cognitive Services User,则具有角色分配权限的管理员可以运行:

$CallerId = az ad signed-in-user show --query id --output tsv
if ($LASTEXITCODE -ne 0 -or -not $CallerId) {
    throw 'Unable to resolve the signed-in user.'
}
az role assignment create `
    --assignee-object-id $CallerId `
    --assignee-principal-type User `
    --role 'Cognitive Services User' `
    --scope $AccountId `
    --output none
if ($LASTEXITCODE -ne 0) { throw 'Unable to grant data-plane access.' }

分配适用于已登录用户。 分配对其他人的访问权限的管理员必须改用该人员的对象 ID。 等待角色分配传播完成。

获取用于创建资源的 ARM 访问令牌:

$ArmToken = az account get-access-token `
    --resource 'https://management.azure.com/' `
    --query accessToken --output tsv
if ($LASTEXITCODE -ne 0 -or -not $ArmToken) {
    throw 'Unable to obtain an ARM access token.'
}

ARM 和 Unified Moderate 使用不同的令牌受众。 在本演练的后面部分,你将获得运行时令牌。

创建 Rego 资源

Rego 定义退款规则。 将以下代码另存为 refund.rego:

package refund_guard

import rego.v1

default verdict := {"decision": "deny", "reason": "refund_not_permitted"}

verdict := {"decision": "allow"} if {
    input.intervention_point == "pre_tool_call"
    input.snapshot.tool_call.name == "refund_order"
    amount := input.policy_target.value.amount
    is_number(amount)
    amount > 0
    amount <= 100
}

此规则默认拒绝。 它只允许其数值金额在允许范围内的 refund_order 调用。

从源文件创建 ARM 请求正文:

$RegoBody = @{
    properties = @{
        encoding = 'None'
        rego = Get-Content -LiteralPath .\refund.rego -Raw
    }
}
$RegoBody | ConvertTo-Json -Depth 10 |
    Set-Content -LiteralPath .\rego-request.json -Encoding utf8

该 rego 属性包含源文本。 encoding: "None" 表示源不是 Base64 编码的。

使用 ARM PUT 请求上传它:

curl.exe --request PUT `
    --url "https://management.azure.com${RegoId}?api-version=$ArmApiVersion" `
    --header "Authorization: Bearer $ArmToken" `
    --header 'Content-Type: application/json' `
    --header 'If-None-Match: *' `
    --data-binary '@rego-request.json' `
    --include --fail-with-body --silent --show-error --max-time 60
if ($LASTEXITCODE -ne 0) {
    throw 'Rego creation failed. Check the preceding response.'
}

成功的 PUT 返回 HTTP 200 或 201,并返回一个 ETag。 If-None-Match: * 阻止此请求替换现有资源。 如果 refund-quickstart 已存在,请使用新的资源名称或遵循 策略更新指南。

创建策略

策略清单将 pre_tool_call 干预点连接到 Rego 规则,并选择用于评估的工具参数。

将此完整的 ARM 请求正文保存为 policy.json:

{
  "properties": {
    "format": "ACS",
    "acs": {
      "agent_control_specification_version": "0.4.0-alpha.1",
      "policies": {
        "refund-guard": {
          "type": "rego",
          "query": "data.refund_guard.verdict"
        }
      },
      "intervention_points": {
        "pre_tool_call": {
          "policy_target": "$snap.tool_call.args",
          "policy_target_kind": "tool_args",
          "tool_name_from": "$snap.tool_call.name",
          "policy": { "id": "refund-guard" }
        }
      },
      "tools": {
        "refund_order": {
          "type": "write",
          "description": "Issue a refund."
        }
      }
    },
    "acsRegos": [{ "regoName": "refund-quickstart" }]
  }
}
Property Purpose
format 选择 ACS 策略格式。
query 标识 verdict Rego 包中的 refund_guard 规则。
pre_tool_call 在主机调度工具调用之前应用规则。
policy_target 选择提交的工具参数。
tool_name_from 在清单的工具目录中选择该工具的条目。
acsRegos 加载在上一步中创建的 Rego 资源。

如果更改了 Rego 资源名称,请更新 acsRegos[0].regoName 使其与之匹配。

使用 ARM PUT 请求创建策略:

curl.exe --request PUT `
    --url "https://management.azure.com${PolicyId}?api-version=$ArmApiVersion" `
    --header "Authorization: Bearer $ArmToken" `
    --header 'Content-Type: application/json' `
    --header 'If-None-Match: *' `
    --data-binary '@policy.json' `
    --include --fail-with-body --silent --show-error --max-time 60
if ($LASTEXITCODE -ne 0) {
    throw 'Policy creation failed. Check the preceding response.'
}

成功的 PUT 返回 HTTP 200 或 201。 策略存储在内容安全帐户下,引用同一帐户中的 Rego。

评估建议的工具调用

获取内容安全访问令牌:

$DataToken = az account get-access-token `
    --scope 'https://cognitiveservices.azure.com/.default' `
    --query accessToken --output tsv
if ($LASTEXITCODE -ne 0 -or -not $DataToken) {
    throw 'Unable to obtain a Content Safety access token.'
}
$ModerateUrl = "$Endpoint/contentsafety/content:unifiedModerate"
$ModerateUrl += "?api-version=$DataApiVersion"

将以下请求另存为 tool-call.json:

{
  "policyId": "refund-quickstart",
  "source": "pre_tool_call",
  "toolName": "refund_order",
  "toolCallId": "refund-1",
  "content": "{\"order_id\":\"demo-001\",\"amount\":75}",
  "context": {
    "agentId": "support-agent",
    "sessionId": "refund-example",
    "sequence": 0
  }
}
领域 Purpose
policyId 按名称选择服务帐户下已发布的策略。
source 选择要评估的点。
toolName、toolCallId 确定建议的工具和调用。
content 包含 JSON 编码的对象字符串形式的工具参数。
context 标识代理、会话和事件序列,用于关联。 这些值不授予访问权限。

固定标识符使此示例易于重现。 在应用程序中,为实际事件构造它们。 保留 JSON 编码字符串中的参数类型,包括数值金额。 如果更改了策略资源名称,请更新 policyId 以与之匹配。

提交请求:

curl.exe --request POST `
    --url $ModerateUrl `
    --header "Authorization: Bearer $DataToken" `
    --header 'Content-Type: application/json' `
    --data-binary '@tool-call.json' `
    --fail-with-body --silent --show-error --max-time 30
if ($LASTEXITCODE -ne 0) {
    throw 'Policy evaluation failed. Check the preceding response.'
}

正文中的 policyId 选择通过 ARM 创建的策略。 不需要任何资源绑定。

解析响应

Unified Moderate 返回一个字符串 verdict 和 acsVerdict 中的决策详细信息。 对于退款 75,响应包括:

{
  "verdict": "allowed",
  "content": "{\"order_id\":\"demo-001\",\"amount\":75}",
  "acsVerdict": { "decision": "allow" }
}

响应可以包含其他成员。 其他适用的策略可能会影响最终决定。

响应字段 Meaning
verdict allowed 或 blocked。
acsVerdict.decision 这是主机必须强制执行的决定。 此规则返回 allow 或 deny。
acsVerdict.reason 规则提供的原因代码。
content 为允许的结果返回的许可的内容字符串。

HTTP 200 表示评估已完成。 检查verdict和acsVerdict.decision,以确定是否允许调用。

尝试超出限制的退款

将内部 content 金额更改为 150,然后提交新事件:

$Request = Get-Content -LiteralPath .\tool-call.json -Raw |
    ConvertFrom-Json -AsHashtable
$Arguments = $Request.content | ConvertFrom-Json -AsHashtable
$Arguments.amount = 150
$Request.content = $Arguments | ConvertTo-Json -Compress
$Request.toolCallId = 'refund-2'
$Request.context.sequence = 1
$Request | ConvertTo-Json -Depth 10 |
    Set-Content -LiteralPath .\tool-call.json -Encoding utf8

curl.exe --request POST `
    --url $ModerateUrl `
    --header "Authorization: Bearer $DataToken" `
    --header 'Content-Type: application/json' `
    --data-binary '@tool-call.json' `
    --fail-with-body --silent --show-error --max-time 30
if ($LASTEXITCODE -ne 0) {
    throw 'Policy evaluation failed. Check the preceding response.'
}

响应仍使用 HTTP 200,但规则返回此判决:

{
  "verdict": "blocked",
  "reason": "refund_not_permitted",
  "acsVerdict": {
    "decision": "deny",
    "reason": "refund_not_permitted"
  }
}

在应用程序中,主机在调度该工具之前检查判定结果。 被拒绝或评估失败会使调用保持阻止状态。

对于允许的调用,主机将执行经过求值的参数。 请参阅解释响应,了解响应验证和转换处理。

将评估连接到代理

在工具执行之前,在负责调度工具的代码中添加检查。 捕获一次建议的参数,并将相同的值用于评估和调度。 以下代码是伪代码,而不是提供的 SDK API:

arguments = captureProposedArguments(proposedCall)
request = { policyId, source: "pre_tool_call", toolName, toolCallId,
            content: json(arguments), context: { agentId, sessionId, sequence } }
response = evaluate(request, boundedDeadline)
validateResponse(response)

if response.verdict != "allowed" or response.acsVerdict.decision != "allow":
    block the call
else:
    validate the captured arguments against the tool's schema
    authorize the caller using trusted application state
    dispatch the registered tool with the captured arguments

评估或响应验证失败必须停止调度。 保留与确切挂起请求关联的响应。 主机必须实现其应用程序所需的每个干预点。

这个最小门控会阻止转换和带有审批信息的拒绝。 仅当主机实现其验证和审批合同时,才添加这些行为。 不要仅仅因为重试了评估,才重试非幂等工具操作。

对于生成的输出,请在发布之前评估完整内容。 如果模型流,请在应用程序限制内缓冲输出,提交已完成的输出以供评估,然后仅释放允许的内容。 在溢出或失败时停止。

在检查完成之前向用户发送令牌不能由以后的拒绝撤消。 此 REST 演练不实现每区块流式处理发布协议。

清理资源

完成后,删除 refund-quickstart 策略及其 Rego 资源(如果不再需要)。 若要使用 ETag 保护删除策略和 Rego 资源并处理异步操作,请参阅“删除策略及其 Rego 资源”。

仅当为此练习创建了该帐户,并且其他应用程序不需要该帐户时,才单独删除该帐户。

后续步骤