在本快速入門中,您將使用 Agent Controls REST API,透過 Azure Resource Manager (ARM) 建立原則。 接著你用 Unified Moderate 評估一個擬議的工具呼叫。
該政策允許退款金額大於零,且不得超過 100。 提交 75 的退款申請,即可看到獲准的結果。 然後提交一筆 150 的退款申請,以查看遭拒的結果。
這些 API 呼叫用來評估擬議的退款。 這些 API 呼叫不會執行工具呼叫或發放退款。
關於政策與介入點的介紹,請參閱《什麼是代理控制?》
如果您沒有 Azure 訂用帳戶,請建立免費帳戶。
Prerequisites
- Azure 訂用帳戶。
- 已啟用代理控制預覽的 Azure AI 內容安全 資源。 如果您需要資源,請在已啟用您預覽存取權的區域建立一個 Content Safety 資源。 僅建立資源並不會啟用 Agent Controls。
- 在該帳戶範圍內建立政策和 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、統一中等 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。
評估擬議的工具呼叫
取得內容安全存取權杖並將政策資源 ID 進行 URL 編碼:
$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 }
}
| Field | 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 建立的原則。 本文描述提出的工具呼叫。 它不包含原則選擇器。
解讀回應
Unified Moderate 會回傳 a verdict 和 a 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 用戶端範例。