SanitizeModelResponse 政策

本页面适用于 Apigee 和 Apigee Hybrid。

查看 Apigee Edge 文档。

SanitizeModelResponse 政策通过净化生成式 AI 模型的响应,保护 AI 客户端免受有害或冒犯性内容影响。该政策使用 Model Armor 评估模型回答是否存在有害或冒犯性内容,从而为使用 Apigee 的 AI 客户端和工作负载提供原生保护。Model Armor 是一项 Google Cloud 服务,可提供 AI 安防和安全措施,以降低与大语言模型 (LLM) 关联的风险。

此政策与 SanitizeModelResponse 政策结合使用。

此政策是一项可扩展政策,使用此政策可能会影响费用或使用情况,具体取决于您的 Apigee 许可。如需了解政策类型和使用情况影响,请参阅政策类型。

准备工作

在使用 SanitizeModelResponse政策之前,您必须完成以下任务:

  • 创建 Model Armor 模板。您必须先完成此步骤,然后才能创建 SanitizeModelResponse政策。
  • 为 Model Armor 服务设置 API 端点。

所需的角色

如需获得应用和使用 SanitizeModelResponse政策所需的权限,请让管理员为您授予用于部署 Apigee 代理的服务账号的以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

启用 API

Enable the Model Armor APIs.

Roles required to enable APIs

To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

Enable the APIs

<SanitizeModelResponse> 元素

定义 SanitizeModelResponse 政策。

默认值 请参阅下面的默认政策标签页
是否必需? 需要
类型 复杂对象
父元素 不适用
子元素 <DisplayName>
<IgnoreUnresolvedVariables>
<TemplateName>
<UserPromptSource>
<LLMResponseSource>

<SanitizeModelResponse> 元素使用以下语法:

语法

<SanitizeModelResponse async="false" continueOnError="false" enabled="true" name="sanitize-response">
  <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
  <DisplayName>sanitize-response-sample</DisplayName>
  <ModelArmor>
    <TemplateName>projects/{project}/locations/{location}/templates/{template-name}</TemplateName>
  </ModelArmor>
  <UserPromptSource>{jsonPath('$.contents[-1].parts[-1].text',request.content,true)}</UserPromptSource>
  <LLMResponseSource>{jsonPath('$.candidates[-1].content.parts',response.content,true)}</LLMResponseSource>
</SanitizeModelResponse>

默认政策

以下示例展示了在 Apigee 界面中将 SanitizeModelResponse 政策添加到请求流时的默认设置:

<SanitizeModelResponse async="false" continueOnError="false" enabled="true" name="sanitize-response">
  <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
  <DisplayName>sanitize-response-sample</DisplayName>
  <ModelArmor>
    <TemplateName>projects/{project}/locations/{location}/templates/{template-name}</TemplateName>
  </ModelArmor>
  <UserPromptSource>{jsonPath('$.contents[-1].parts[-1].text',request.content,true)}</UserPromptSource>
  <LLMResponseSource>{jsonPath('$.candidates[-1].content.parts',response.content,true)}</LLMResponseSource>
</SanitizeModelResponse>

当您使用 Apigee 界面插入新的 SanitizeModelResponse政策时,模板包含所有可能操作的桩。如需了解所需的元素,请参阅下文。

This element has the following attributes that are common to all policies:

Attribute Default Required? Description
name N/A Required

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

continueOnError false Optional Set to false to return an error when a policy fails. This is expected behavior for most policies. Set to true to have flow execution continue even after a policy fails. See also:
enabled true Optional Set to true to enforce the policy. Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.
async   false Deprecated This attribute is deprecated.

下表提供了 <SanitizeModelResponse> 的子元素的简要说明:

子元素 是否必需? 说明
<DisplayName> 可选 政策的名称。

<IgnoreUnresolvedVariables> 可选 指定在用于模板名称或 Model Armor 载荷的变量未解析时是否停止处理。
<TemplateName> 需要 用于清理 LLM 回答的 Model Armor 模板。

您可以使用以下 Apigee 流变量为此值创建模板:

projects/{organization.name}/locations/{system.region.name}/templates/{id}

<UserPromptSource> 需要 要提取的用户提示文本的载荷位置。仅支持字符串文本值。

此字段支持 Apigee 消息模板语法,包括使用变量或 JSON Path 函数。

例如:

{jsonpath('$.contents[-1].parts[-1].text',request.content,false)}
<LLMResponseSource> 需要 要提取的 LLM 回答文本的载荷位置。仅支持字符串文本值。

此字段支持 Apigee 消息模板语法,包括使用变量或 JSON 路径函数。

例如:

{jsonpath('$.input.prompt.text',request.content,false)}

子元素参考

本部分介绍 <SanitizeModelResponse> 的子元素。

<DisplayName>

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, more natural-sounding name.

The <DisplayName> element is common to all policies.

Default Value N/A
Required? Optional. If you omit <DisplayName>, the value of the policy's name attribute is used.
Type String
Parent Element <PolicyElement>
Child Elements None

The <DisplayName> element uses the following syntax:

Syntax

<PolicyElement>
  <DisplayName>POLICY_DISPLAY_NAME</DisplayName>
  ...
</PolicyElement>

Example

<PolicyElement>
  <DisplayName>My Validation Policy</DisplayName>
</PolicyElement>

The <DisplayName> element has no attributes or child elements.

<IgnoreUnresolvedVariables>

确定在变量无法解析时处理是否停止。设置为 true 可忽略无法解析的变量并继续处理。

默认值 错误
是否必需? 可选
类型 布尔值
父元素 <SanitizeModelResponse>
子元素 无

<TemplateName>

Model Armor 模板。

默认值 不适用
是否必需? 需要
类型 字符串
父元素 <SanitizeModelResponse>
子元素 无

<TemplateName> 元素使用以下语法:

语法

<ModelArmor>
  <TemplateName>projects/{project}/locations/{location}/templates/{template-name}</TemplateName>
</ModelArmor>

示例

此示例使用 Apigee 流变量来填充所需信息。

<ModelArmor>
  <TemplateName>projects/{organization.name}/locations/{system.region.name}/templates/{id}</TemplateName>
</ModelArmor>

<UserPromptSource>

要提取的用户提示文本的载荷位置。仅支持字符串文本值。

此字段支持 Apigee 消息模板语法,包括使用变量或 JSON 路径函数。 例如:

{jsonpath('$.input.prompt.text',request.content,false)}
默认值 {jsonPath('$.contents[-1].parts[-1].text',request.content,true)}
是否必需? 需要
类型 字符串
父元素 <SanitizeModelResponse>
子元素 无

<LLMResponseSource>

要提取的 LLM 回答的载荷位置。仅支持字符串文本值。

此字段支持 Apigee 消息模板语法,包括使用变量或 JSON 路径函数。 例如:

{jsonpath('$.input.prompt.text',request.content,false)}
默认值 {jsonPath($.candidates[-1].content.parts,response.content,true)}
是否必需? 需要
类型 字符串
父元素 <SanitizeModelResponse>
子元素 无

流变量

流变量可用于配置基于 HTTP 标头或消息内容或者流中可用的上下文的政策和流的动态运行时行为。如需详细了解流变量,请参阅流变量参考。

此政策在执行期间提供以下只读流变量集。您可以将这些流变量与 DataCapture 政策搭配使用,以创建自定义分析报告。如需了解详情,请参阅使用 Data Capture 政策收集客户数据。

变量名称 说明
SanitizeModelResponse.POLICY_NAME.templateUsed 指定要使用的 Model Armor 模板。例如:projects/myproject/locations/us-west1/templates/mytemplate
SanitizeModelResponse.POLICY_NAME.userPrompt 指定用于调用 Model Armor 以清理内容的提示内容。
SanitizeModelResponse.POLICY_NAME.modelResponse 指定用于调用 Model Armor 以清理内容的 LLM 响应内容。
SanitizeModelResponse.POLICY_NAME.responseFromModelArmor 指定来自 Model Armor 的 JSON 响应。 Model Armor。
SanitizeModelResponse.POLICY_NAME.filterMatchState 指定是否匹配过滤条件。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.invocationResult 一个字段,用于指示调用的结果,无论匹配状态如何。它可以具有以下值:
  • SUCCESS:所有过滤条件都已成功执行。
  • PARTIAL:部分过滤条件已跳过或执行失败。
  • FAILURE:所有过滤条件都已跳过或执行失败。
SanitizeModelResponse.POLICY_NAME.raiFilterResult.executionState RAI 过滤条件执行结果。有效值包括 EXECUTION_SUCCESS 和 EXECUTION_SKIPPED。
SanitizeModelResponse.POLICY_NAME.raiFilterResult.matchState RAI 过滤条件匹配状态。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.sdpFilterResult.inspectResult.executionState SDP 过滤条件检查结果执行状态。有效值包括 EXECUTION_SUCCESS 和 EXECUTION_SKIPPED。
SanitizeModelResponse.POLICY_NAME.sdpFilterResult.inspectResult.matchState SDP 过滤条件检查结果匹配状态。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.sdpFilterResult.deidentifyResult.executionState SDP 过滤条件对结果执行状态进行去标识化处理。有效值包括 EXECUTION_SUCCESS 和 EXECUTION_SKIPPED。
SanitizeModelResponse.POLICY_NAME.sdpFilterResult.deidentifyResult.matchState SDP 过滤条件对结果匹配状态进行去标识化处理。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.piAndJailbreakFilterResult.executionState 提示注入和越狱过滤条件结果执行状态。有效值包括 EXECUTION_SUCCESS 和 EXECUTION_SKIPPED。
SanitizeModelResponse.POLICY_NAME.piAndJailbreakFilterResult.matchState 提示注入和越狱过滤条件结果匹配状态。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.csamFilterFilterResult.executionState CSAM 过滤条件执行状态。有效值包括 EXECUTION_SUCCESS 和 EXECUTION_SKIPPED。
SanitizeModelResponse.POLICY_NAME.csamFilterFilterResult.matchState CSAM 过滤条件匹配状态。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.maliciousUriFilterResult.executionState 恶意 URI 过滤条件执行状态。有效值包括 EXECUTION_SUCCESS 和 EXECUTION_SKIPPED。
SanitizeModelResponse.POLICY_NAME.maliciousUriFilterResult.matchState 恶意 URI 过滤条件匹配状态。有效值包括 MATCH_FOUND 和 NO_MATCH_FOUND。
SanitizeModelResponse.POLICY_NAME.sanitizationMetadata.errorCode 自定义覆盖的错误代码(如果在 Model Armor 响应中存在)。
SanitizeModelResponse.POLICY_NAME.sanitizationMetadata.errorMessage 自定义覆盖的错误代码(如果在 Model Armor 响应中存在)。
SanitizeModelResponse.POLICY_NAME.csamFilterMatched 布尔值,指示 CSAM 过滤条件是否匹配。
SanitizeModelResponse.POLICY_NAME.maliciousURIs 恶意 URI 过滤条件检测到的恶意 URI 的附加列表。
SanitizeModelResponse.POLICY_NAME.maliciousURIsDetected 布尔值,指示恶意 URI 过滤条件是否匹配。
SanitizeModelResponse.POLICY_NAME.matchesFound 布尔值,指示是否有任何过滤条件匹配。
SanitizeModelResponse.POLICY_NAME.promptInjectionDetected 布尔值,指示提示注入过滤条件是否匹配。
SanitizeModelResponse.POLICY_NAME.promptInjectionConfidence 提示注入检测的置信度。
SanitizeModelResponse.POLICY_NAME.raiMatchesFound 布尔值,指示 RAI 过滤条件是否匹配。
SanitizeModelResponse.POLICY_NAME.requestSentToModelArmor 布尔值,指示是否向 Model Armor 发送了请求。
SanitizeModelResponse.POLICY_NAME.sanitizeOperation 指定政策执行的操作。有效值包括 SANITIZE_USER_PROMPT 和 SANITIZE_MODEL_RESPONSE。

错误参考信息

本部分介绍了 Apigee 针对 <SanitizeModelResponse> 政策返回的故障代码和错误消息以及设置的故障变量。在开发故障规则以处理故障时,请务必了解此信息。如需了解详情,请参阅您需要了解的有关政策错误的信息和处理故障。

运行时错误

故障代码 HTTP 状态 原因
steps.sanitize.model.response.FilterMatched 400 如果用户提示未通过 Model Armor 模板检查,就会发生此错误。
steps.sanitize.model.response.SanitizationResponseParsingFailed 500 如果无法解析 Model Armor 响应,就会发生此错误。
steps.sanitize.model.response.FailedToExtractUserPrompt 500 如果对默认值的自动用户提示提取失败,就会发生此错误。
steps.sanitize.model.response.FailedToExtractLLMResponse 500 如果对默认值的自动模型回答提取失败,就会发生此错误。
steps.sanitize.model.response.InternalError 500 如果发生内部服务器错误,就会发生此错误。
steps.sanitize.model.response.ModelArmorTemplateNameExtractionFailed 500 如果无法解析模板名称,就会发生此错误。
steps.sanitize.model.response.AuthenticationFailure 500 如果服务账号无权调用 Model Armor API,就会发生此错误。
steps.sanitize.model.response.ModelArmorAPIFailed 500 如果 Model Armor API 抛出错误,就会发生此错误。
steps.sanitize.model.response.ModelArmorCalloutError 500 如果 Model Armor API 调用失败,就会发生此错误。
steps.sanitize.modelarmor.ServiceUnavailable 500 如果 Model Armor 服务不可用,就会发生此错误。

部署错误

在您部署包含此政策的代理时,可能会发生这些错误。

错误名称 原因
The ModelArmor/TemplateName element is required. 如果 <ModelArmor> 中不存在 <TemplateName> 元素,就会发生此错误。
The TemplateName element value is required. 如果 <TemplateName> 值为空,则会发生此错误。

故障变量

当此政策在运行时触发错误时,将设置这些变量。如需了解详情,请参阅您需要了解的有关政策错误的信息。

变量 其中 示例
fault.name="FAULT_NAME" FAULT_NAME 是故障名称,如上面的运行时错误表中所列。故障名称是故障代码的最后一部分。 fault.name Matches "UnresolvedVariable"
SanitizeModelResponse.POLICY_NAME.failed POLICY_NAME 是抛出故障的政策的用户指定名称。 SanitizeModelResponse.sanitize-response.failed = true

错误响应示例

{
  "fault": {
    "faultstring": "SanitizeModelResponse[sanitize-response]: unable to resolve variable [variable_name]",
    "detail": {
      "errorcode": "steps.sanitizemodelresponse.UnresolvedVariable"
    }
  }
}

故障规则示例

<FaultRule name="SanitizeModelResponse Faults">
    <Step>
        <Name>SMR-CustomSetVariableErrorResponse</Name>
        <Condition>(fault.name = "SetVariableFailed")</Condition>
    </Step>
    <Condition>(sanitizemodelresponse.failed = true)</Condition>
</FaultRule>

Model Armor 模板错误代码和错误消息

Model Armor 模板支持替换 SanitizeModelResponse政策的 API 请求抛出的错误代码和错误消息。如果用户设置了替换项,则 Model Armor 错误代码和错误消息将填充流变量。

例如,包含 Model Armor 错误代码和消息的响应可能如下所示:

{
"sanitizationResult": {
  "filterMatchState": "MATCH_FOUND",
  "filterResults": {...},
  "sanitizationMetadata": {
    "errorCode": "890",
    "errorMessage": "get out"
  },
  "invocationResult": "SUCCESS"
  }
}

架构

每种政策类型均由 XML 架构 (.xsd) 定义。GitHub 提供了政策架构作为参考。