你当前正在访问 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-10-15-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-10-15-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。
评估建议的工具调用
获取内容安全访问令牌和 URL 编码策略资源 ID:
$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.'
}
$EncodedPolicyId = [Uri]::EscapeDataString($PolicyId)
$ModerateUrl = "$Endpoint/contentsafety/content:unifiedModerate"
$ModerateUrl += "?api-version=$DataApiVersion"
$ModerateUrl += "&policyId=$EncodedPolicyId"
将以下请求另存为 tool-call.json:
{
"spec": "agent-hooks/0.1",
"interception_point": "pre_tool_call",
"timestamp": "2026-11-06T12:00:00Z",
"sequence": 0,
"agent": { "id": "support-agent", "framework": "custom" },
"session": { "id": "refund-example" },
"tool_call": {
"id": "refund-1",
"name": "refund_order",
"args": { "order_id": "demo-001", "amount": 75 }
},
"target": { "order_id": "demo-001", "amount": 75 }
}
| 领域 | Purpose |
|---|---|
spec |
标识代理挂钩上下文格式。 |
interception_point |
选择要评估的生命周期点。 |
timestamp、sequence |
记录会话中的事件时间和顺序。 |
agent、session |
识别该代理并运行以进行相关性分析。 他们不会授予访问权限。 |
tool_call |
描述建议的工具名称和参数。 |
target |
包含为评估选择的参数。 此时它必须相等 tool_call.args。 |
固定时间戳和标识符使此示例易于重现。 在应用程序中,为实际事件构造它们。 将参数保留为原生 JSON,包括数值金额。
提交请求:
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 创建的策略。 正文描述建议的工具调用。 它不包含策略选择器。
解析响应
统一中等返回verdict和receipt。 对于金额为 75 的退款,规则的判定结果是:
{
"decision": "allow"
}
这是 verdict 响应的一部分,而不是完整的响应。 其他适用的策略可能会影响最终决策。
| 响应字段 | Meaning |
|---|---|
verdict.decision |
这是主机必须强制执行的决定。 此规则返回 allow 或 deny。 |
verdict.reason |
规则提供的原因代码。 |
receipt.evaluationId |
标识此评估以与应用程序记录关联。 |
receipt.evaluatedInterventionPoint |
此处评估的 pre_tool_call 点。 |
receipt.evaluatedPolicyLayers |
标识评估的策略和版本。 |
receipt.requestBinding |
将回执绑定到请求和策略选择器。 |
HTTP 200 表示评估已完成。 检查 verdict.decision 以确定是否允许该调用。
尝试超出限制的退款
将两处金额都更改为 150,然后提交一个新事件:
$Request = Get-Content -LiteralPath .\tool-call.json -Raw |
ConvertFrom-Json -AsHashtable
$Request.tool_call.args.amount = 150
$Request.target.amount = 150
$Request.tool_call.id = 'refund-2'
$Request.sequence = 1
$Request.timestamp = [DateTime]::UtcNow.ToString('o')
$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,但规则返回此判决:
{
"decision": "deny",
"reason": "refund_not_permitted"
}
在应用程序中,主机在调度该工具之前检查判定结果和回执。 被拒绝或评估失败会使调用保持阻止状态。
对于允许的调用,主机将执行经过求值的参数。 请参阅解读响应,了解回执检查和转换处理。
将评估连接到代理
在工具执行之前,在负责调度工具的代码中添加检查。 捕获一次建议的参数,并将相同的值用于评估和调度。 以下代码是伪代码,而不是提供的 SDK API:
context = capturePreToolContext(proposedCall)
response = evaluate(policyId, context, boundedDeadline)
validateResponseAndReceipt(response, context, policyId, servingAccountId)
if response.verdict.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 资源”。
仅当为此练习创建了该帐户,并且其他应用程序不需要该帐户时,才单独删除该帐户。
后续步骤
- 编写策略 以添加自己的规则和内容安全分类器。
- 配置 LLM 法官 以根据书面标准评估内容。
- 为其他方案选择策略模板。
- 在生产环境中使用托管标识 ,而不是交互式开发人员标识。
- 有关帮助将评估和回执检查集成到应用程序中的可选客户端示例,请参阅 HTTP 客户端示例。