SanitizeUserPrompt policy

This pageapplies toApigee andApigee hybrid.

View Apigee Edge documentation.

The SanitizeUserPrompt policy protects AI applications from harmful content by sanitizing user prompts sent to generative AI models. The policy usesModel Armor to evaluate user prompts for harmful content, enabling native protection for AI workloads using Apigee.Model Armor is a Google Cloud service offering AI security and safety measures to mitigate the risks associated with large language models (LLMs).

This policy works in conjunction with theSanitizeModelResponse policy.

This policy is anExtensible policy and use of this policy might have cost or utilization implications, depending on your Apigee license. For information on policy types and usage implications, seePolicy types.

Before you begin

Before you use the SanitizeUserPrompt policy, complete the following tasks:

  • Create a Model Armor template. Complete this step before you create a SanitizeUserPrompt policy.
  • Set the API endpoint for the Model Armor service.
  • Create a SanitizeModelResponse policy. Complete this task before you deploy the SanitizeUserPrompt policy.

Required roles

To get the permissions that you need to apply and use the SanitizeUserPrompt policy, ask your administrator to grant you the following IAM roles on the service account you use to deploy Apigee proxies:

For more information about granting roles, seeManage access to projects, folders, and organizations.

You might also be able to get the required permissions throughcustom roles or otherpredefined roles.

Enable APIs

Enable the Model Armor API.

Roles required to enable APIs

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

Enable the API

<SanitizeUserPrompt> element

Defines a SanitizeUserPrompt policy.

Default ValueSeeDefault Policy tab, below
Required?Required
TypeComplex object
Parent Element N/A
Child Elements<DisplayName>
<IgnoreUnresolvedVariables>
<TemplateName>
<UserPromptSource>

The<SanitizeUserPrompt> element uses the following syntax:

Syntax

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

Default Policy

The following example shows the default settings when you add a SanitizeUserPrompt policy to your request flow in the Apigee UI:

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

When you insert a new SanitizeUserPrompt policy using the Apigee UI, the template contains stubs for all possible operations. See below for information on required elements.

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

AttributeDefaultRequired?Description
nameN/ARequired

The internal name of the policy. The value of thename 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.

continueOnErrorfalseOptionalSet tofalse to return an error when a policy fails. This is expected behavior for most policies. Set totrue to have flow execution continue even after a policy fails. See also:
enabledtrueOptionalSet totrue to enforce the policy. Set tofalse toturn off the policy. The policy will not be enforced even if it remains attached to a flow.
async  falseDeprecatedThis attribute is deprecated.

The following table provides a high level description of the child elements of<SanitizeUserPrompt>:

Child ElementRequired?Description
<DisplayName>OptionalThe name of the policy.

<IgnoreUnresolvedVariables>OptionalSpecifies whether processing stops if the variable used for the template name or Model Armor payload is unresolved.
<ModelArmor>RequiredContains the required information for specifying the Model Armor template.
<UserPromptSource>OptionalThe location of the payload for the user prompt text to be extracted. Only string text values are supported.

This field supports Apigee message template syntax, including the use of variables orJSON Path functions.

For example:

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

Example

This section provides an example using the<SanitizeUserPrompt>.

This example uses all default values for model detection and prompt extraction:

<SanitizeUserPrompt async="false" continueOnError="false" enabled="true" name="sanitize-text">  <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>  <DisplayName>Sanitize-Text-sample</DisplayName>  <ModelArmor>    <TemplateName>projects/{project}/locations/{location}/templates/{template-name}</TemplateName>  </ModelArmor></SanitizeUserPrompt>

Child element reference

This section describes the child elements of<SanitizeUserPrompt>.

<DisplayName>

Use in addition to thename 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 ValueN/A
Required?Optional. If you omit<DisplayName>, the value of the policy'sname attribute is used.
TypeString
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>

Determines whether processing stops when a variable is unresolved. Set totrue to ignore unresolved variables and continue processing.

Default ValueFalse
Required?Optional
TypeBoolean
Parent Element<SanitizeUserPrompt>
Child Elements None

<ModelArmor>

Contains the required information for specifying the Model Armor template.

Default ValueN/A
Required?Required
TypeString
Parent Element
Child Elements<TemplateName>

The<ModelArmor> element uses the following syntax:

Syntax

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

Example

This example uses Apigee flow variables to populate the required information.

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

The following table provides a high-level description of the child elements of<ModelArmor>.

Child ElementRequired?Description
<TemplateName>RequiredString

The Model Armor template used to sanitize the user prompt.

This value can be templated using the following Apigee flow variables:

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

<UserPromptSource>

The location of the payload for the user prompt text to be extracted. This field supports Apigee message template syntax, including the use of variables orJSON Path functions. For example:

{jsonpath('$.input.prompt.text',request.content,false)}
Default Value{jsonPath('$.contents[-1].parts[-1].text',request.content,true)}
Required?Optional
TypeString
Parent Element<SanitizeUserPrompt>
Child Elements None

Flow variables

Flow variables configure dynamic runtime behavior for policies and flows, basedon HTTP headers or message content, or the context available in the Flow. For more informationabout flow variables, seeFlow variables reference.

This policy provides the following set ofread-only flow variables during execution. You can use these flow variables with theDataCapture policy to create custom analytics reports. For more information, seeCollecting customer data with the Data Capture policy.

Variable nameDescription
SanitizeUserPrompt.POLICY_NAME.templateUsedSpecifies which model armor template is used. For example:projects/myproject/locations/us-west1/templates/mytemplate
SanitizeUserPrompt.POLICY_NAME.userPromptSpecifies the prompt content used for the call to Model Armor to sanitize the content.
SanitizeUserPrompt.POLICY_NAME.modelResponseSpecifies the LLM response content used for the call to Model Armor to sanitize the content.
SanitizeUserPrompt.POLICY_NAME.responseFromModelArmorSpecifies the json response from Model Armor.
SanitizeUserPrompt.POLICY_NAME.filterMatchStateSpecifies whether the filter matched. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.invocationResultA field indicating the outcome of the invocation, irrespective of match status. It can have the following:
  • SUCCESS: All filters executed successfully.
  • PARTIAL: Some filters were skipped or failed execution.
  • FAILURE: All filters were skipped or failed execution.
SanitizeUserPrompt.POLICY_NAME.raiFilterResult.executionStateRai filter execution result. Valid values includeEXECUTION_SUCCESS andEXECUTION_SKIPPED.
SanitizeUserPrompt.POLICY_NAME.raiFilterResult.matchStateRai filter match state. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.sdpFilterResult.inspectResult.executionStateSdp filter inspect result execution state. Valid values includeEXECUTION_SUCCESS andEXECUTION_SKIPPED.
SanitizeUserPrompt.POLICY_NAME.sdpFilterResult.inspectResult.matchStateSdp filter inspect result match state. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.sdpFilterResult.deidentifyResult.executionStateSdp filter de identify result execution state. Valid values includeEXECUTION_SUCCESS andEXECUTION_SKIPPED.
SanitizeUserPrompt.POLICY_NAME.sdpFilterResult.deidentifyResult.matchStateSdp filter de identify result match state. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.piAndJailbreakFilterResult.executionStatePrompt injection and Jailbreak filter results execution state. Valid values includeEXECUTION_SUCCESS andEXECUTION_SKIPPED.
SanitizeUserPrompt.POLICY_NAME.piAndJailbreakFilterResult.matchStatePrompt injection and Jailbreak filter results match state. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.csamFilterFilterResult.executionStateCSAM filter execution state. Valid values includeEXECUTION_SUCCESS andEXECUTION_SKIPPED.
SanitizeUserPrompt.POLICY_NAME.csamFilterFilterResult.matchStateCSAM filter match state. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.maliciousUriFilterResult.executionStateMalicious URI filter execution state. Valid values includeEXECUTION_SUCCESS andEXECUTION_SKIPPED.
SanitizeUserPrompt.POLICY_NAME.maliciousUriFilterResult.matchStateMalicious URI filter match state. Valid values includeMATCH_FOUND andNO_MATCH_FOUND.
SanitizeUserPrompt.POLICY_NAME.sanitizationMetadata.errorCodeCustom overridden Error code if present in Model Armor response.
SanitizeUserPrompt.POLICY_NAME.sanitizationMetadata.errorMessageCustom overridden Error code if present in Model Armor response.
SanitizeUserPrompt.POLICY_NAME.csamFilterMatchedBoolean value indicating whether the CSAM filter matched.
SanitizeUserPrompt.POLICY_NAME.maliciousURIsAppended list of malicious URIs detected by the malicious URI filter.
SanitizeUserPrompt.POLICY_NAME.maliciousURIsDetectedBoolean value indicating whether the malicious URI filter matched.
SanitizeUserPrompt.POLICY_NAME.matchesFoundBoolean value indicating whether any of the filters matched.
SanitizeUserPrompt.POLICY_NAME.promptInjectionDetectedBoolean value indicating whether the prompt injection filter matched.
SanitizeUserPrompt.POLICY_NAME.promptInjectionConfidenceConfidence level of prompt injection detection.
SanitizeUserPrompt.POLICY_NAME.raiMatchesFoundBoolean value indicating whether the RAI filter matched.
SanitizeUserPrompt.POLICY_NAME.requestSentToModelArmorBoolean value indicating whether a request was sent to Model Armor.
SanitizeUserPrompt.POLICY_NAME.sanitizeOperationSpecifies the operation performed by the policy. Valid values includeSANITIZE_USER_PROMPT andSANITIZE_MODEL_RESPONSE.

Error reference

This section describes the fault codes and error messages that Apigee returns and the fault variables that Apigee sets for the SanitizeUserPrompt policy. This information is important to know if you are developing fault rules tohandle faults. To learn more, seeWhat you need to knowabout policy errors andHandlingfaults.

Runtime errors

These errors can occur when the policy executes.

Fault codeHTTP statusCause
steps.sanitize.user.prompt.response.FilterMatched400This error occurs if the user prompt does not pass the Model Armor template check.
steps.sanitize.user.prompt.SanitizationResponseParsingFailed500This error occurs if the Model Armor response cannot be parsed.
steps.sanitize.user.prompt.FailedToExtractUserPrompt500This error occurs if the automatic user prompt extraction for the default value failed.
steps.sanitize.user.prompt.InternalError500This error occurs if there is an internal server error.
steps.sanitize.modelarmor.ModelArmorTemplateNameExtractionFailed500This error occurs if the template name cannot be resolved.
steps.sanitize.modelarmor.AuthenticationFailure500This error occurs if the service account does not have permission to call the Model Armor API.
steps.sanitize.modelarmor.ModelArmorAPIFailed500This error occurs if the Model Armor API throws an error.
steps.sanitize.modelarmor.ModelArmorCalloutError500This error occurs if the Model Armor API call fails.
steps.sanitize.modelarmor.ServiceUnavailable500This error occurs if the Model Armor service is unavailable.

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error nameCause
The ModelArmor/TemplateName element is required.Occurs if the <TemplateName> element in <ModelArmor> is not present.
The TemplateName element value is required.Occurs if the <TemplateName> value is empty.

Fault variables

This policy sets these variables when it triggers an error at runtime. For more information, seeWhat you need to know about policy errors.

VariablesWhereExample
fault.name="FAULT_NAME"FAULT_NAME is the name of the fault, as listed in theRuntime errors table above. The fault name is the last part of the fault code.fault.name Matches "UnresolvedVariable"
SanitizeUserPrompt.POLICY_NAME.failedPOLICY_NAME is the user-specified name of the policy that threw the fault.SanitizeUserPrompt.sanitize-prompt.failed = true

Example error response

Note: For error handling, the best practice is to trap theerrorcode part of the error response. Do not rely on the text in thefaultstring, because it could change.
{"fault":{"faultstring":"SanitizeUserPrompt[sanitize-prompt]: unable to resolve variable [variable_name]","detail":{"errorcode":"steps.sanitizeuserprompt.UnresolvedVariable"}}}

Example fault rule

<FaultRule name="SanitizeUserPrompt Faults">    <Step>        <Name>SUP-CustomSetVariableErrorResponse</Name>        <Condition>(fault.name = "SetVariableFailed")</Condition>    </Step>    <Condition>(sanitizeuserprompt.failed = true)</Condition></FaultRule>

Model Armor template error code and error messages

The Model Armor template supports overriding error codes and error messages thrown by the SanitizeUserPrompt policy's API requests. If the user sets the overrides, then the Model Armor error codes and error messages populate the flow variables.

For example, a response with Model Armor error codes and messages could look like the following:

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

Schemas

Each policy type is defined by an XML schema (.xsd). For reference,policy schemas are available on GitHub.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.