Enable Google Cloud APIs

Check my progress

/ 15

Create a service account

Check my progress

/ 15

Create a Model Armor template

Check my progress

/ 15

Create an API proxy

Check my progress

/ 15

Test the API proxy

Check my progress

/ 15

Update the API proxy error response for user prompts

Check my progress

/ 15

Test the updated error responses from the proxy endpoint

Check my progress

/ 10

This lab may incorporate AI tools to support your learning.
This content is not yet optimized for mobile devices.
For the best experience, please visit us on a desktop computer using a link sent by email.

GSP1367

Google Cloud self-paced labs

Overview

Apigee is a platform for developing and managing APIs. Apigee can help you leverage Google Cloud services like Gemini Enterprise Agent Platform, Pub/Sub, Cloud Logging, or any other cloud service providing a REST API.

In this lab, you develop an Apigee API proxy to sanitize a user prompt to a Gemini model and sanitize the model's response.

Note: The last two tasks in this lab are optional and include hints for additional support. Challenge yourself by expanding the hints progressively (or not!), as you complete the tasks.

Objectives

In this lab, you learn how to perform the following tasks:

  • Enable required Google Cloud APIs and configure a service account.
  • Create a Model Armor template with AI safety filters.
  • Develop an Apigee API proxy with policies to sanitize prompts and responses.
  • Test the API proxy and customize error responses for sanitized content.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method. On the right is the Lab setup and access panel with the following:

    • The Open Google Cloud console button
    • The temporary credentials (username and password) that you must use for this lab
    • Other information, if needed, to step through this lab

    Note that the lab timer is located near the top of the page, showing the remaining time.

  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab setup and access panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab setup and access panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field. Navigation menu icon and Search field

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

  2. Click through the following windows:

    • Continue through the Cloud Shell information window.
    • Authorize Cloud Shell to use your credentials to make Google Cloud API calls.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Enable Google Cloud APIs

In this task, you enable the APIs that will be used by the Apigee API proxy using the gcloud command.

  1. In Cloud Shell, set the environment variables:

    PROJECT_ID={{{project_0.project_id | "PROJECT_ID"}}} REGION={{{project_0.default_region | "REGION"}}} PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
  2. Enable the required APIs:

    gcloud services enable modelarmor.googleapis.com aiplatform.googleapis.com --project=$PROJECT_ID

    Model Armor will be used to screen LLM prompts and responses, and ensure responsible AI practices.

    Gemini Enterprise Agent Platform will be used to access a Gemini model for AI inferencing.

Click Check my progress to verify the objective. Enable Google Cloud APIs

Task 2. Configure a service account

In this task, you configure a service account to be used by the Apigee proxy.

Note: To maintain least-privilege security, the apigee-gc-service-access service account and its project-level roles (roles/modelarmor.user, roles/modelarmor.viewer, and roles/aiplatform.user) have been pre-provisioned during lab startup.
  1. Verify that the service account is created:

    gcloud iam service-accounts describe apigee-gc-service-access@${PROJECT_ID}.iam.gserviceaccount.com
  2. Verify that the service account has the Model Armor User, Model Armor Viewer, and Agent Platform User roles:

    gcloud projects get-iam-policy $PROJECT_ID \ --filter="bindings.members:apigee-gc-service-access@${PROJECT_ID}.iam.gserviceaccount.com"
  3. To enable the Apigee API proxy to authenticate with services on Google Cloud using Google access tokens, grant the Service Account Token Creator (roles/iam.serviceAccountTokenCreator) role to the Apigee Service Agent on the apigee-gc-service-access service account:

    gcloud iam service-accounts add-iam-policy-binding \ apigee-gc-service-access@{{{project_0.project_id | "PROJECT_ID"}}}.iam.gserviceaccount.com \ --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-apigee.iam.gserviceaccount.com" \ --role="roles/iam.serviceAccountTokenCreator"

Click Check my progress to verify the objective. Create a service account

Task 3. Create a Model Armor template

You use Model Armor templates to configure the screening of prompts and responses for your AI applications. A template provides customized filters and thresholds for multiple safety and security categories. For more information, see Model Armor templates.

  1. In Cloud Shell, set an environment variable for the template ID:

    TEMPLATE_ID=apigee-modelarmor-template
  2. Set the Model Armor API endpoint for your region:

    gcloud config set api_endpoint_overrides/modelarmor "https://modelarmor.${REGION}.rep.googleapis.com/" The Model Armor API endpoint is a specific network address that serves as the gateway for interacting with the Google Cloud Model Armor service. It's the destination where your requests to Model Armor are sent.
  3. Create the template:

    gcloud model-armor templates create -q --location $REGION "$TEMPLATE_ID" --project="$PROJECT_ID" --rai-settings-filters='[{ "filterType": "HATE_SPEECH", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "HARASSMENT", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "DANGEROUS", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "SEXUALLY_EXPLICIT", "confidenceLevel": "MEDIUM_AND_ABOVE" }]' --basic-config-filter-enforcement=enabled --pi-and-jailbreak-filter-settings-enforcement=enabled --pi-and-jailbreak-filter-settings-confidence-level=LOW_AND_ABOVE --malicious-uri-filter-settings-enforcement=enabled

    A Model Armor template is a reusable configuration that specifies how Model Armor should protect your AI models by filtering user prompts and AI-generated responses against various risks. This command creates a template with filters along with confidence levels that determines how aggressively Model Armor will block content that contains the type specified.

    The template enables filters to detect:

Click Check my progress to verify the objective. Create a Model Armor template

Task 4. Create an API proxy

In this task, you create the Apigee API proxy using the Apigee Model Armor proxy template.

Open the Apigee console

To open the Apigee console:

  • In the Google Cloud console, type Apigee into the Search bar, then select Apigee from the Products & pages results.

The Apigee console will open, where you can manage APIs, environments, proxies, and deployments.

Create the Apigee API proxy

  1. In the navigation menu, select Proxy development > API proxies.

  2. To create a new proxy using the proxy wizard, click Create.

  3. For Proxy template, select AI template > Proxy with Model Armor.

    The proxy will enforce safe AI interactions with policies that sanitize user prompts and model responses.

  4. For the Proxy details, specify the following:

    Property Value
    Proxy name promptllm-v1
    Base path /promptllm/v1
    Target (Existing API)
    Note: Confirm that you are using /promptllm/v1 for the base path, not /promptllm-v1.
  5. Click Next.

  6. Leave the Deploy (optional) settings at their defaults, and click Create.

    Note: The SanitizeUserPrompt policy is automatically added to the default proxy endpoint request preflow, and the SanitizeModelResponse policy is automatically added to the default target endpoint response preflow in the API proxy.

    The Apigee API proxy is created.

Update the SanitizeUserPrompt policy

To use the SanitizeUserPrompt policy in the proxy, you must provide it the location of the content in the API request.

  1. To update the default policy, click the Develop tab in the Proxy Editor.

  2. In the navigation menu in the Apigee UI, select Policies > Sanitize User Prompt.

  3. In the SUP-Sanitize-User-Prompt.xml file, replace the entire <SanitizeUserPrompt> element with:

    <SanitizeUserPrompt async="false" continueOnError="false" enabled="true" name="SUP-Sanitize-User-Prompt"> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <DisplayName>Sanitize User Prompt</DisplayName> <ModelArmor> <TemplateName>projects/{{{project_0.project_id | "PROJECT_ID"}}}/locations/{{{project_0.default_region | "REGION"}}}/templates/apigee-modelarmor-template</TemplateName> </ModelArmor> <UserPromptSource>{jsonPath('$.contents[*].parts[*].text',request.content,false)}</UserPromptSource> </SanitizeUserPrompt>

    The updated policy provides the location of the Model Armor template that you created earlier in the lab and provides the location of the content in the request (the prompt) that will be evaluated.

    jsonPath() is a function in Apigee that is used to select or extract data from a JSON message payload or JSON variable. In this case, it returns the value of the text field in all the elements of the parts[] array within each element of the contents[] array from the request message sent to the API proxy. This JSON structure is required to send the input prompt to the Gemini model.
  4. To save the changes to the policy, click Save.

Update the SanitizeModelResponse policy

The SanitizeModelResponse policy is used in conjunction with the SanitizeUserPrompt policy. The policy uses Model Armor to evaluate model responses for harmful or offensive content and protects AI clients and workloads using the Apigee API proxy.

Note that although the SanitizeUserPrompt policy is added to the API proxy endpoint request, the SanitizeModelResponse policy is added to the API target endpoint response. To use the policy, you must provide it the location of the content in the target response and the Model Armor template.

  1. To update the default policy, click the Develop tab in the Proxy Editor.

  2. In the navigation menu in the Apigee UI, select Policies > Sanitize Model Response.

  3. In the SMR-Sanitize-Model-Response.xml file, replace the entire <SanitizeModelResponse> element with:

    <SanitizeModelResponse async="false" continueOnError="false" enabled="true" name="SMR-Sanitize-Model-Response"> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <DisplayName>Sanitize Model Response</DisplayName> <ModelArmor> <TemplateName>projects/{{{project_0.project_id | "PROJECT_ID"}}}/locations/{{{project_0.default_region | "REGION"}}}/templates/apigee-modelarmor-template</TemplateName> </ModelArmor> <UserPromptSource>{jsonPath('$.contents[*].parts[*].text',request.content,false)}</UserPromptSource> <LLMResponseSource>{jsonPath('$.candidates[0].content.parts[*].text',response.content,false)}</LLMResponseSource> </SanitizeModelResponse>

    The updated policy provides the location of the Model Armor template that you created earlier in the lab, the location of the prompt content in the request, and the location of the response content returned by the model.

  4. To save the changes to the policy, click Save.

Modify the target endpoint to use authentication

The <HTTPTargetConnection>/<Authentication> element in the API proxy TargetEndpoint is used to make authenticated calls to the model endpoint running on Google Cloud. Apigee uses the service account you created earlier in the lab to generate the necessary token required to securely call the endpoint.

  1. Click the Develop tab in the Proxy Editor.

  2. In the Navigator menu for the proxy, in the Target endpoints section, click default > PreFlow.

  3. In the default.xml file, find the following code (your URL will be slightly different):

    <HTTPTargetConnection> <Properties/> <URL>{{{project_0.startup_script.proxyTargetUrl|"TARGET"}}}</URL> </HTTPTargetConnection> Note: If you do not see the <HTTPTargetConnection> section, confirm that you clicked PreFlow in the Target endpoints section, and not in the Proxy endpoints section.
  4. Above the <URL> element, add this <Authentication> element:

    <Authentication> <GoogleAccessToken> <Scopes> <Scope>https://www.googleapis.com/auth/cloud-platform</Scope> </Scopes> </GoogleAccessToken> </Authentication>

    Your TargetEndpoint code should now look similar to this:

    <TargetEndpoint name="default"> <Description/> <FaultRules/> <PreFlow name="PreFlow"> <Request/> <Response> <Step> <Name>SMR-Sanitize-Model-Response</Name> </Step> </Response> </PreFlow> <PostFlow name="PostFlow"> <Request/> <Response/> </PostFlow> <Flows/> <HTTPTargetConnection> <Properties/> <Authentication> <GoogleAccessToken> <Scopes> <Scope>https://www.googleapis.com/auth/cloud-platform</Scope> </Scopes> </GoogleAccessToken> </Authentication> <URL>{{{project_0.startup_script.proxyTargetUrl|"TARGET"}}}</URL> </HTTPTargetConnection> </TargetEndpoint>
  5. Click Save.

Click Check my progress to verify the objective. Create an API proxy

Task 5. Test the API proxy

Confirm that the runtime instance is available

  • In Cloud Shell, paste and run the following command:

    export INSTANCE_NAME=eval-instance; export ENV_NAME=eval; export PREV_INSTANCE_STATE=; echo "waiting for runtime instance ${INSTANCE_NAME} to be active"; while : ; do export INSTANCE_STATE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${GOOGLE_CLOUD_PROJECT}/instances/${INSTANCE_NAME}" | jq "select(.state != null) | .state" --raw-output); [[ "${INSTANCE_STATE}" == "${PREV_INSTANCE_STATE}" ]] || (echo; echo "INSTANCE_STATE=${INSTANCE_STATE}"); export PREV_INSTANCE_STATE=${INSTANCE_STATE}; [[ "${INSTANCE_STATE}" != "ACTIVE" ]] || break; echo -n "."; sleep 5; done; echo; echo "instance created, waiting for environment ${ENV_NAME} to be attached to instance"; while : ; do export ATTACHMENT_DONE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${GOOGLE_CLOUD_PROJECT}/instances/${INSTANCE_NAME}/attachments" | jq "select(.attachments != null) | .attachments[] | select(.environment == \"${ENV_NAME}\") | .environment" --join-output); [[ "${ATTACHMENT_DONE}" != "${ENV_NAME}" ]] || break; echo -n "."; sleep 5; done; echo "***ORG IS READY TO USE***";

    This series of commands uses the Apigee API to determine when the Apigee runtime instance has been created and the eval environment has been attached.

Wait until the instance is ready.

When the text ***ORG IS READY TO USE*** is displayed, the instance is ready. The Apigee organization (org) may have been created before you started the lab, so you might not have to wait for the instance to be created.

If you are waiting for the org to be ready, you can explore the AI products and services on Google Cloud.

Deploy the API

  1. Return to the promptllm-v1 API proxy in the Apigee UI, and click the Develop tab.

  2. Click Deploy.

  3. For Environment, select eval.

  4. For Service Account, specify the service account's email address:

    apigee-gc-service-access@{{{ project_0.project_id | "PROJECT_ID" }}}.iam.gserviceaccount.com
  5. Click Deploy.

  6. In the confirmation dialog, click Confirm.

  7. Click the Overview tab, and wait until the eval deployment status indicates that the proxy is deployed.

Test the API

The eval environment in the Apigee organization can be called using the hostname eval.example.com. The DNS entry for this hostname has been created within your project, and it resolves to the IP address of the Apigee runtime instance. This DNS entry has been created in a private zone, which means it is only visible on the internal network.

Cloud Shell does not reside on the internal network, so Cloud Shell commands cannot resolve this DNS entry. A virtual machine (VM) within your project can access the private zone DNS. A virtual machine named apigeex-test-vm was automatically created. You can use this machine to call the API proxy.

  1. In Cloud Shell, open an SSH connection to your test VM:

    TEST_VM_ZONE=$(gcloud compute instances list --filter="name=('apigeex-test-vm')" --format "value(zone)") gcloud compute ssh apigeex-test-vm --zone=${TEST_VM_ZONE} --force-key-file-overwrite

    If asked Do you want to continue (Y/n)?, type Y.

  2. For each question asked in Cloud Shell, press ENTER to specify the default input.

    Your logged in identity is the owner of the project, so SSH to this machine is allowed.

    Your Cloud Shell session is now running inside the VM.

  3. Call the deployed promptllm-v1 API proxy in the eval environment:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/promptllm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Can you describe this link? https://testsafebrowsing.appspot.com/s/malware.html"}]}],"generationConfig":{"candidateCount":1}}' The request payload contains the conversation from a user to a language model. The contents array contains the conversation or prompt in the text field of the parts array, and the generationConfig element requests that the model return only one generated response or candidate.

    The response from the API looks like this:

    {"fault":{"faultstring":"Model armor template filter matched. Policy caught the offending text. filter matched: RAIMatchesFound: false, SDPMatchesFound: false, PIMatchesFound: false, CSAMMatchesFound: false, URIMatchesFound: true","detail":{"errorcode":"steps.sanitize.user.prompt.FilterMatched"}}}

    The fault error message contains the URIMatchesFound: true filter match that correctly indicates the presence of a malicious URL in the input prompt.

  4. Send another prompt without any malicious content to the API:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/promptllm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Where is the Taj Mahal located?"}]}],"generationConfig":{"candidateCount":1}}'

    The request to the model is not blocked, and the model response should resemble this:

    { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "The Taj Mahal is located in **Agra, Uttar Pradesh, India**.\n" } ] }, "finishReason": "STOP", "avgLogprobs": -0.0084939042727152515 } ], "usageMetadata": { "promptTokenCount": 7, "candidatesTokenCount": 15, "totalTokenCount": 22, "trafficType": "ON_DEMAND", "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 7 } ], "candidatesTokensDetails": [ { "modality": "TEXT", "tokenCount": 15 } ] }, "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}", "createTime": "2025-12-02T06:35:18.968821Z", "responseId": "poguafWQO_K7u7APluz6oAs" }
  5. Type exit and press ENTER to leave the SSH session and return to Cloud Shell.

Click Check my progress to verify the objective. Test the API proxy

Task 6. Update the API proxy error response for user prompts

While testing the API proxy with malicious input in the request prompt, the proxy responds with the default fault error message that was generated when the Model Armor template filter matched the offending text.

In this task, you update the API proxy to return custom error responses when a bad user prompt is detected. The error response format is made consistent with the response returned from the model in the success scenario when no harmful text is detected in the user prompt.

Create a RaiseFault policy for the malicious URL detection filter

The Apigee RaiseFault policy lets you define a custom response that is returned to the requesting app when a specific error condition arises.

You'll create a RaiseFault policy for the malicious URL filter match condition configured for the Model Armor template.

  1. In the Apigee UI, navigate to the Develop tab, and click Policies > Add Policy.

  2. For Select Policy, to filter the policies, type Raise Fault.

  3. Select Mediation > Raise Fault.

  4. In the Details section, for Name, type:

    RF-MaliciousURL-Detected
  5. For Display name, type the same value RF-MaliciousURL-Detected.

    If present, remove the duplicate RF- prefix in the policy name and display name. Apigee policies use different prefixes in their names that indicate the type of policy.
  6. Click Create.

  7. In the RF-MaliciousURL-Detected.xml file, replace the entire <RaiseFault> element with:

    <RaiseFault continueOnError="false" enabled="true" name="RF-MaliciousURL-Detected"> <DisplayName>RF-MaliciousURL-Detected</DisplayName> <Properties/> <FaultResponse> <Set> <Payload contentType="application/json">{ "candidates": [ { "content": { "role": "model", "parts": [ { "text": "Your prompt has a malicious URL in it. Please review and try again." } ] }, "finishReason": "STOP" } ], "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}" } </Payload> <StatusCode>200</StatusCode> <ReasonPhrase>OK</ReasonPhrase> </Set> </FaultResponse> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> </RaiseFault>

    This RaiseFault policy alters the default error response payload content and status code that is returned if a malicious URL is detected in the input request.

    You could also create additional RaiseFault policies to match the other filter match conditions. In this lab, you will create a generic RaiseFault policy that rewrites the error for all other filter match conditions.

Create a RaiseFault policy for all other filters

  1. To create the generic RaiseFault policy, on the Develop tab, click Policies > Add Policy.

  2. For Select Policy, to filter the policies, type Raise Fault.

  3. Select Mediation > Raise Fault.

  4. In the Details section, for Name, type:

    RF-OtherError-Detected
  5. For Display name, type the same value, RF-OtherError-Detected.

    If present, remove the duplicate RF- prefix in the policy name and display name.
  6. Click Create.

  7. In the RF-OtherError-Detected.xml file, replace the entire <RaiseFault> element with:

    <RaiseFault continueOnError="false" enabled="true" name="RF-OtherError-Detected"> <DisplayName>RF-OtherError-Detected</DisplayName> <Properties/> <FaultResponse> <Set> <Payload contentType="application/json">{ "candidates": [ { "content": { "role": "model", "parts": [ { "text": "Your prompt has abusive content or contains sensitive information. Please review and try again." } ] }, "finishReason": "STOP" } ], "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}" } </Payload> <StatusCode>200</StatusCode> <ReasonPhrase>OK</ReasonPhrase> </Set> </FaultResponse> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> </RaiseFault> Note: This policy is identical to the RF-MaliciousURL-Detected policy with the exception of the policy name, display name, and the value in the text field in the xml.

    In the next subtask, you'll add these policies to the proxy and use specific conditions to trigger them.

Add RaiseFault policies to the API proxy endpoint

  1. In the Apigee UI, on the Develop tab, select Proxy endpoints > default > PreFlow.

  2. In the PreFlow, click Add Policy Step.

  3. For Select existing policy, select Mediation > RF-MaliciousURL-Detected.

  4. For Condition, type:

    SanitizeUserPrompt.SUP-Sanitize-User-Prompt.maliciousUriFilterResult.matchState = "MATCH_FOUND"
  5. Click Add.

  6. Repeat the steps above to add an additional step for the RF-OtherError-Detected RaiseFault policy with this condition:

    SanitizeUserPrompt.SUP-Sanitize-User-Prompt.filterMatchState = "MATCH_FOUND"

    After these policies are added, the ProxyEndpoint > PreFlow > Request xml should look like:

    <PreFlow name="PreFlow"> <Request> <Step> <Name>SUP-Sanitize-User-Prompt</Name> </Step> <Step> <Condition>SanitizeUserPrompt.SUP-Sanitize-User-Prompt.maliciousUriFilterResult.matchState = "MATCH_FOUND"</Condition> <Name>RF-MaliciousURL-Detected</Name> </Step> <Step> <Condition>SanitizeUserPrompt.SUP-Sanitize-User-Prompt.filterMatchState = "MATCH_FOUND"</Condition> <Name>RF-OtherError-Detected</Name> </Step> </Request> <Response/> </PreFlow>

    The RaiseFault policy RF-MaliciousURL-Detected is executed after the SanitizeUserPrompt policy SUP-Sanitize-User-Prompt if the specified condition evaluates to true. The SanitizeUserPrompt policy sets this flow variable for the malicious URL filter match state to MATCH_FOUND or NO_MATCH_FOUND depending on the content in the prompt.

    The RaiseFault policy RF-OtherError-Detected will execute when any of the other filter conditions match.

    To view the list of flow variables set by the SanitizeUserPrompt policy, read the policy documentation.

Update the SanitizeUserPrompt policy

To allow the proxy execution flow to reach the RaiseFault policies when the SanitizeUserPrompt policy returns an error, set the continueOnError attribute of this policy to true.

  1. To do this, click Policies > Sanitize User Prompt.

  2. In the SUP-Sanitize-User-Prompt.xml file, on line 2, set the value of the continueOnError attribute to true.

  3. To save the changes to the proxy, click Save. If prompted to save the proxy as a new revision, click Save as new revision.

Click Check my progress to verify the objective. Update the API proxy error response for user prompts

Task 7. Test the updated error responses from the proxy endpoint

Deploy the new proxy revision

  1. To deploy the new proxy revision, click Deploy.

  2. For Environment, select eval.

  3. For Service Account, specify the service account's email address:

    apigee-gc-service-access@{{{ project_0.project_id | "PROJECT_ID" }}}.iam.gserviceaccount.com
  4. Click Deploy.

  5. In the confirmation dialog, click Confirm.

  6. Click the Overview tab, and wait until the eval deployment status indicates that the proxy is deployed.

Test the API

  1. In Cloud Shell, open an SSH connection to your test VM:

    TEST_VM_ZONE=$(gcloud compute instances list --filter="name=('apigeex-test-vm')" --format "value(zone)") gcloud compute ssh apigeex-test-vm --zone=${TEST_VM_ZONE} --force-key-file-overwrite

    If asked Do you want to continue (Y/n)?, type Y.

  2. For each question asked in Cloud Shell, press ENTER to specify the default input.

    Your logged in identity is the owner of the project, so SSH to this machine is allowed.

    Your Cloud Shell session is now running inside the VM.

  3. Call the deployed promptllm-v1 API proxy in the eval environment:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/promptllm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Can you describe this link? https://testsafebrowsing.appspot.com/s/malware.html"}]}],"generationConfig":{"candidateCount":1}}'

    The response from the API should now resemble:

    { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "Your prompt has a malicious URL in it. Please review and try again." } ] }, "finishReason": "STOP" } ], "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}" }
  4. Repeat the call with a prompt that contains sensitive information:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/promptllm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"My social security number is 123-45-6789"}]}],"generationConfig":{"candidateCount":1}}'

    The request content matches the sensitive data protection filter, which triggers the generic RaiseFault policy RF-OtherError-Detected in the API proxy that returns the error response:

    { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "Your prompt has abusive content or contains sensitive information. Please review and try again." } ] }, "finishReason": "STOP" } ], "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}" }

Click Check my progress to verify the objective. Test the updated error responses from the proxy endpoint

Task 8. Update the API proxy error response for model responses (optional)

In this optional task, you create another RaiseFault policy in the API proxy to return error responses when harmful content is detected in the model response. The error response format is made consistent with the response returned from the model in the success scenario when the model response does not contain harmful content.

Create a RaiseFault policy for the sensitive data protection filter

To complete this subtask, follow option 1 or option 2.

Option 1: Create a RaiseFault policy named RF-SDP-Detected.

Option 2: Full solution (expand to see the steps)

  • After the policy is created using either option 1 or 2, replace the entire <RaiseFault> XML element in the RF-SDP-Detected.xml file:

    <RaiseFault continueOnError="false" enabled="true" name="RF-SDP-Detected"> <DisplayName>RF-SDP-Detected</DisplayName> <Properties/> <FaultResponse> <Set> <Payload contentType="application/json">{ "candidates": [ { "content": { "role": "model", "parts": [ { "text": "The model response contains sensitive information which should not be returned to the user." } ] }, "finishReason": "STOP" } ], "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}" } </Payload> <StatusCode>200</StatusCode> <ReasonPhrase>OK</ReasonPhrase> </Set> </FaultResponse> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> </RaiseFault>

Add RaiseFault policies to the API target endpoint

To complete this subtask, follow option 1 or option 2.

Option 1: Add the RaiseFault policy RF-SDP-Detected to the API target endpoint.

Option 2: Full solution (expand to see the steps)

  • Repeat the steps above to add an additional policy step for the RF-OtherError-Detected RaiseFault policy with this condition:

    SanitizeModelResponse.SMR-Sanitize-Model-Response.filterMatchState = "MATCH_FOUND"

    These RaiseFault policies are executed after the SanitizeModelResponse policy SMR-Sanitize-Model-Response if the specified condition evaluates to true.

    To view the list of flow variables set by the SanitizeModelResponse policy, read the policy documentation.

Update the SanitizeModelResponse policy

  1. To allow the proxy execution flow to reach the RaiseFault policies when the SanitizeModelResponse policy returns an error, set the continueOnError attribute of this policy to true.

    To do this, click Policies > Sanitize Model Response.

  2. In the SMR-Sanitize-Model-Response.xml file, on line 2, set the value of the continueOnError attribute to true.

  3. To save the changes to the proxy, click Save.

Task 9. Test the updated error responses from the target endpoint (optional)

Note: Only perform this task if you chose to perform the previous task.

To test the updated error responses from the target endpoint, you must override the successful model response to inject a bad message in the response payload. This is because in order for the execution flow to reach the target endpoint, the API request must reach the model successfully with a valid user prompt that generates a valid response from the model.

Add an AssignMessage policy

  1. In the Apigee UI, for the promptllm-v1 API proxy, click the Develop tab.

  2. In the Apigee navigation UI, click Target endpoints > default > PreFlow.

  3. In the PreFlow, click Add Policy Step.

  4. Select Create new policy, and click Mediation > Assign Message.

  5. For the policy name, type AM-InjectBadResponse. Provide the same value for Display name.

  6. Because this policy should only be executed for testing purposes, add a condition that checks for the presence of a header in the API request.

    To implement this step, follow option 1 or option 2:

    Option 1: Review the documentation.

    Option 2: Specify the condition.

    Later, when you test the proxy, you pass in this header in the request using curl. Apigee creates a flow variable with the name of the header as specified above with the value passed in the request.

  7. Click Add.

  8. In the Policies section, click the AM-InjectBadResponse policy, and replace the entire <AssignMessage> element in the AM-InjectBadResponse.xml file with this code:

    <AssignMessage continueOnError="false" enabled="true" name="AM-InjectBadResponse"> <DisplayName>AM-InjectBadResponse</DisplayName> <Properties/> <Set> <Payload contentType="application/json">{ "candidates": [ { "content": { "role": "model", "parts": [ { "text": "The person's social security number is 123-45-6789." } ] }, "finishReason": "STOP" } ], "modelVersion": "{{{project_0.startup_script.llm|'MODEL'}}}" } </Payload> <StatusCode>200</StatusCode> <ReasonPhrase>OK</ReasonPhrase> </Set> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> <AssignTo createNew="false" transport="http" type="response"/> </AssignMessage>
  9. In the Target Endpoint: default graphical UI pane, in PreFlow, select the AM-InjectBadResponse policy and drag it up so that it is the first policy to execute in the flow.

    The <TargetEndpoint>/<PreFlow> xml element should look like:

    <TargetEndpoint name="default"> <Description/> <FaultRules/> <PreFlow name="PreFlow"> <Request/> <Response> <Step> <Condition>request.header.injectbadresponse = "true"</Condition> <Name>AM-InjectBadResponse</Name> </Step> <Step> <Name>SMR-Sanitize-Model-Response</Name> </Step> <Step> <Condition>SanitizeModelResponse.SMR-Sanitize-Model-Response.sdpFilterResult.inspectResult.matchState = "MATCH_FOUND"</Condition> <Name>RF-SDP-Detected</Name> </Step> <Step> <Condition>SanitizeModelResponse.SMR-Sanitize-Model-Response.filterMatchState = "MATCH_FOUND"</Condition> <Name>RF-OtherError-Detected</Name> </Step> </Response> </PreFlow> ... </TargetEndpoint>
  10. To save the changes to the proxy, click Save. If prompted to save the proxy as a new revision, click Save as new revision.

Deploy the proxy revision

  1. To deploy the new proxy revision, click Deploy.

  2. For Environment, select eval.

  3. For Service Account, specify the service account's email address:

    apigee-gc-service-access@{{{ project_0.project_id | "PROJECT_ID" }}}.iam.gserviceaccount.com
  4. Click Deploy.

  5. In the confirmation dialog, click Confirm.

  6. Click the Overview tab, and wait until the eval deployment status indicates that the proxy is deployed.

Test the API

  1. In Cloud Shell, open an SSH connection to your test VM:

    TEST_VM_ZONE=$(gcloud compute instances list --filter="name=('apigeex-test-vm')" --format "value(zone)") gcloud compute ssh apigeex-test-vm --zone=${TEST_VM_ZONE} --force-key-file-overwrite

    If asked Do you want to continue (Y/n)?, type Y.

  2. For each question asked in Cloud Shell, press ENTER to specify the default input.

    Your logged in identity is the owner of the project, so SSH to this machine is allowed.

    Your Cloud Shell session is now running inside the VM.

  3. Call the deployed promptllm-v1 API proxy in the eval environment (without the test request header):

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/promptllm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Who is Santa Claus?"}]}],"generationConfig":{"candidateCount":1}}'

    The response from the API contains a successful response from the model.

  4. Call the API proxy again, this time supplying the test header in the request:

    curl -i -k -X POST -H "Content-Type: application/json" -H "injectbadresponse: true" 'https://eval.example.com/promptllm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Who is Santa Claus?"}]}],"generationConfig":{"candidateCount":1}}'

    The response from the API contains the error response from the RF-SDP-Detected RaiseFault policy which was triggered because of the sensitive data protection filter that matched the content in the response.

Congratulations!

In this lab, you:

  • Created a service account with the correct roles to integrate with Gemini Enterprise Agent Platform and Model Armor.
  • Created a Model Armor template with filters to detect harmful content in model prompts.
  • Used Apigee policies in an API proxy to sanitize user prompts and model responses.
  • Modified default error messages from the Apigee policies to return consistent API responses.

Next steps / learn more

Manual Last Updated on November 6, 2026

Manual last tested on September 16, 2026

Copyright 2026 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

Use private browsing

  1. Copy the provided Username and Password for the lab
  2. Click Open console in private mode

Sign in to the Console

  1. Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
  2. Accept the terms, and skip the recovery resource page
  3. Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project

This content is not currently available

We can notify you via email when it becomes available

Great!

We can contact you via email if it becomes available

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Using an Incognito or private browser window is the best way to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.