Create a service account

Check my progress

/ 25

Create an Apigee API proxy

Check my progress

/ 25

Test the API proxy

Check my progress

/ 50

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.

GSP1368

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.

When using LLMs, it is highly beneficial to intelligently and efficiently serve identical or semantically similar prompts by minimizing API calls to backend models and reducing resource consumption. Apigee provides semantic caching policies that enable intelligent response reuse based on semantic similarity. By using these policies in your Apigee API proxy, you can minimize redundant backend API calls, reduce latency, and lower operational costs of your API.

In this lab, you develop an Apigee API proxy to perform a semantic similarity search of similar request prompts using Vector Search on Gemini Enterprise Agent Platform as an embeddings database. A semantic similarity search compares the vector proximity of the prompt to prior requests and uses a configurable similarity score threshold. If a similar prompt data point is found, the cached response is returned to the client. If no similar previous prompt is found in Vector Search, the request is sent to the backend, where the LLM generates a response. Apigee caches the model response and returns it to the client. Then, it updates the Vector Search index for future API requests.

Objectives

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

  • Verify the Apigee service account.
  • View and deploy a Vector Search index.
  • Create an Apigee API proxy with semantic caching policies.
  • Test the API proxy and review cached response times.

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. Verify the Apigee service account

In this task, you verify 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 role (roles/aiplatform.user) have been pre-provisioned for you during lab startup. You can verify the service account in IAM & Admin > Service Accounts and click Check my progress.
  1. In Cloud Shell, set 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. Verify that the service account is created:

    gcloud iam service-accounts describe apigee-gc-service-access@${PROJECT_ID}.iam.gserviceaccount.com
  3. Verify that the service account has the Agent Platform User (roles/aiplatform.user) role:

    gcloud projects get-iam-policy $PROJECT_ID \ --filter="bindings.members:apigee-gc-service-access@${PROJECT_ID}.iam.gserviceaccount.com"
  4. 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_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 2. View and deploy a Vector Search index

The Apigee semantic caching policies use Vector Search to find similar prompts based on semantic similarity and update Vector Search with embeddings for new prompts.

Vector Search is a powerful vector search engine from Google that leverages the ScaNN (Scalable Nearest Neighbors) algorithm. It enables you to build next-generation search and recommendation systems and generative AI applications.

To use Vector Search, you create an index to quickly and efficiently find semantically related items. In this lab, you index text prompts submitted in requests to the Apigee API proxy.

View index configuration

An index consists of one or more files that contain embedding vectors. With Vector Search, you can create an index designed for batch updates or an index designed for streaming updates. In this subtask, you create an index for streaming updates. The API proxy will update the index when a submitted prompt is not found in the Vector Search database.

A batch index is used when you want to update your index in a batch with data that has been stored over a set amount of time. For example, in systems which are processed weekly or monthly. A streaming index is used when you want index data to be updated as new data is available or added to your data store.
  1. In the Google Cloud console, from the Navigation menu (Navigation menu icon), navigate to Agent Platform > Agents > Vector Search.

  2. An index has been pre-created for this lab. To list the indexes for your region, on the Indexes tab, from the Region drop-down list, select .

  3. To view the index configuration, click the index name apigee-semantic-cache-index.

    Some of the configuration properties are:

    Property Value
    Dimensions 768
    Approximate Neighbors Count 150
    Distance measure type Dot product distance
    Update method Stream
    • The number of dimensions matches the output dimensions of the text embeddings model that will be used to generate the vectors.
    • The Approximate Neighbors Count value specifies how many potential nearest neighbors the approximate search algorithm should find initially, before a more precise re-ranking step is performed.
    • The Distance measure type is the default setting for the distance measure that is used in the nearest neighbor search algorithm.
    • The Update method creates a streaming index as new prompt data is added by the Apigee API proxy as they are received in requests.

    For more information, read the documentation on index configuration parameters.

  4. Confirm that the Status indicates that the index is Ready. If not, wait until the index is Ready.

    You might need to refresh the browser page to view the latest status in the UI.

View the index endpoint

Before you can query the Vector Search index, you must first create an index endpoint and deploy the index to that endpoint.

An index endpoint is a dedicated network access point that hosts one or more deployed Vector Search indexes. It acts as the server instance that processes query requests against your indexes. An index endpoint has been pre-created for this lab.

  1. On the Vector Search page for the apigee-semantic-cache-index, click the Deployed indexes tab.

  2. To view the endpoint details, click the index endpoint name.

    • The Access type of Public enables the endpoint to be accessible over the internet with OAuth authentication. You can also create an index endpoint for private access using Private Service Connect or using VPC Network Peering.

    • The Public domain name is part of the unique URL used to send Vector Search queries to a deployed index.

  3. To navigate back to the list of index endpoints, click Index endpoint list.

  4. Confirm that the Status indicates the index endpoint is Ready. If not, wait until the endpoint is Ready.

    You might need to refresh the browser page to view the latest status in the UI.

Deploy the index to the endpoint

  • The lab initiates the index deployment automatically. Under Deployed indexes, check for the deployment status.

    The deployment might still be in progress. A green check mark is displayed when the deployment is complete.

    Note: Initial deployment of an index to an endpoint can take between 20 and 30 minutes to complete. You can continue to the next task to create the Apigee API proxy while the index deployment is in progress.

Task 3. Create an Apigee API proxy

In this task, you create the Apigee API proxy. The API proxy will use a specific proxy template that contains the semantic cache policies.

Set environment variables

Before developing the API proxy, set a few environment variables that will be used to configure the proxy.

  1. In Cloud Shell, retrieve and set the index ID environment variable:

    INDEX_ID=$(gcloud ai indexes list --project=$PROJECT_ID --region=$REGION --format=json | jq -c -r '.[] | select(.displayName=="apigee-semantic-cache-index") | .name | split("/") | .[5]'); echo "INDEX_ID=$INDEX_ID"
  2. Retrieve and set the index endpoint ID environment variable:

    INDEX_ENDPOINT_ID=$(gcloud ai index-endpoints list --project=$PROJECT_ID --region=$REGION --format=json | jq -c -r '.[] | select(.displayName=="apigee-semantic-cache-index-endpoint") | .name | split("/") | .[5]'); echo "INDEX_ENDPOINT_ID=$INDEX_ENDPOINT_ID"
  3. Retrieve and set the public endpoint domain name environment variable:

    PUBLIC_ENDPOINT_DOMAIN_NAME=$(gcloud ai index-endpoints describe $INDEX_ENDPOINT_ID --region=$REGION --project=$PROJECT_ID --format=json | jq -c -r '.publicEndpointDomainName'); echo "PUBLIC_ENDPOINT_DOMAIN_NAME=$PUBLIC_ENDPOINT_DOMAIN_NAME"

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 API proxy

  1. From the Apigee navigation menu, click 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 Semantic Cache.

  4. For Proxy details, specify the following:

    Property Value
    Proxy name cachellm-v1
    Base path /cachellm/v1
    Target (Existing API)
    Note: Confirm that you are using /cachellm/v1 for the base path, not /cachellm-v1.
  5. Under Semantic Cache URLs, for Generate Embeddings URL, append this value to the https:// prefix:

    ${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/{{{project_0.startup_script.embedding_model_id|"EMBEDDING_MODEL_ID"}}}:predict

    This URL points to the embeddings model that converts text input into numerical form for semantic analysis.

  6. For Query Nearest Neighbour URL, execute the command in Cloud Shell, and append the command output to the https:// prefix:

    echo "$PUBLIC_ENDPOINT_DOMAIN_NAME/v1/projects/$PROJECT_ID/locations/$REGION/indexEndpoints/$INDEX_ENDPOINT_ID:findNeighbors"

    This URL points to the Agent Platform service that uses the Vector Search index you created earlier to search for similar text prompts from previous requests to the API proxy.

  7. For Upsert index URL, execute the command in Cloud Shell, and append the command output to the https:// prefix:

    echo "$REGION-aiplatform.googleapis.com/v1/projects/$PROJECT_ID/locations/$REGION/indexes/${INDEX_ID}:upsertDatapoints"

    This URL points to the Agent Platform service that updates the Vector Search index with new or modified entries.

  8. Click Next.

  9. Leave the remaining settings as their defaults, and click Create.

    The Apigee API proxy is created with two AI policies automatically added to the proxy:

Update the SemanticCacheLookup policy

The SemanticCacheLookup policy uses the Text embeddings API to generate embeddings for text, and Vector Search to find similar prompts based on semantic similarity, rather than exact matches.

In this subtask, you make a few updates to the policy.

  1. First, set an environment variable for the deployed index ID:

    DEPLOYED_INDEX_ID=$(gcloud ai indexes list --project=$PROJECT_ID --region=$REGION --format=json | jq -c -r '.[] | select(.displayName=="apigee-semantic-cache-index") | .deployedIndexes[] | select(.displayName=="apigee_semantic_cache") | .deployedIndexId'); echo "DEPLOYED_INDEX_ID=$DEPLOYED_INDEX_ID" Note: If the DEPLOYED_INDEX_ID variable is empty, wait for the index to be deployed to the endpoint. You can verify this on the Agent Platform > Agents > Vector Search > Index Endpoints page in the console. After it is deployed, rerun the command to set the DEPLOYED_INDEX_ID environment variable.
  2. To update the policy, click the Develop tab in the Proxy Editor.

  3. In the navigation menu in the Apigee UI, select Policies > Semantic Cache Lookup.

  4. In the SCL-Semantic-Cache-Lookup.xml file, update the <DeployedIndexID> element with the value of the DEPLOYED_INDEX_ID variable from the earlier step.

    Leave the remaining elements as their defaults. The updated XML file should look similar to:

    <SemanticCacheLookup async="false" continueOnError="false" enabled="true" name="SCL-Semantic-Cache-Lookup"> <DisplayName>Semantic Cache Lookup</DisplayName> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <UserPromptSource>{jsonPath('$.contents[-1].parts[-1].text',request.content,true)}</UserPromptSource> <Embeddings> <VertexAI> <URL>https://{{{project_0.default_region|"REGION"}}}-aiplatform.googleapis.com/v1/projects/{{{project_0.project_id|"PROJECT_ID"}}}/locations/{{{project_0.default_region|"REGION"}}}/publishers/google/models/{{{project_0.startup_script.embedding_model_id|"EMBEDDING_MODEL_ID"}}}:predict</URL> </VertexAI> </Embeddings> <SimilaritySearch> <VertexAI> <URL>https://1361963375.{{{project_0.default_region|"REGION"}}}-715458342156.vdb.vertexai.goog/v1/projects/{{{project_0.project_id|"PROJECT_ID"}}}/locations/{{{project_0.default_region|"REGION"}}}/indexEndpoints/5909971756319244288:findNeighbors</URL> <DeployedIndexID>apigee_semantic_cache</DeployedIndexID> <Threshold>0.95</Threshold> </VertexAI> </SimilaritySearch> </SemanticCacheLookup>

    The policy includes:

    • The UserPromptSource element that provides the location of the content in the request prompt that will be evaluated.
    • The URL of the model endpoint that generates vector embeddings.
    • The URL of the index endpoint that performs similarity search using Vector Search.
    • The DeployedIndexID of the Vector Search index that you deployed to the endpoint.
    • The Threshold value between 0 and 1 for the similarity score that is used to determine if two prompts are considered a match.
    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 the last element of the parts[] array within the last element of the contents[] array from the request message sent to the API proxy. This JSON structure is required to extract the input prompt that is sent to the Gemini model.
  5. To save the changes to the policy, click Save.

Update the SemanticCachePopulate policy

The SemanticCachePopulate policy is used in conjunction with the SemanticCacheLookup policy.

The policy updates a Vector Search index and caches API responses based on semantic similarity of the text prompt in the input request.

Note that although the SemanticCacheLookup policy is added to the API proxy endpoint request, the SemanticCachePopulate policy is added to the API target endpoint response. To use the policy, you must provide the index ID of a Vector Search index.

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

  2. In the navigation menu in the Apigee UI, select Policies > Semantic Cache Populate.

  3. In the SCP-Semantic-Cache-Populate.xml file, update the time to live <TTLInSeconds> element to 600 seconds.

    The SCP-Semantic-Cache-Populate.xml file should look similar to:

    <SemanticCachePopulate async="false" continueOnError="false" enabled="true" name="SCP-Semantic-Cache-Populate"> <DisplayName>Semantic Cache Populate</DisplayName> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <SimilaritySearch> <VertexAI> <URL>https://europe-west4-aiplatform.googleapis.com/v1/projects/qwiklabs-gcp-01-e954ced037c4/locations/europe-west4/indexes/5383358463172673536:upsertDatapoints</URL> </VertexAI> </SimilaritySearch> <TTLInSeconds>600</TTLInSeconds> </SemanticCachePopulate>

    The policy includes:

    • The location of the Vector Search index that you created earlier and supplied when creating the API proxy. The upsertDatapoints operation inserts or updates the index with a vector embedding.
    • The time to live (TTL) for the cached responses in seconds.
  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>SCP-Semantic-Cache-Populate</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>

    The Authentication section specifies the authentication for the Google Cloud API. A Google OAuth access token is automatically added to the request to the target URL. The Scope specifies that the access token provides access to the model endpoint.

  5. To save changes to the API proxy, click Save.

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

Task 4. 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; if [ -z "${GOOGLE_CLOUD_PROJECT}" ]; then echo "Error: GOOGLE_CLOUD_PROJECT environment variable is not set. Please set it to your project ID."; else 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}\" or (.environment | endswith(\"/${ENV_NAME}\"))) | .environment" --raw-output); [[ -n "${ATTACHMENT_DONE}" ]] && break; echo -n "."; sleep 5; done; echo; echo "${ENV_NAME} environment attached"; echo "***ORG IS READY TO USE***"; fi

    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.

Check the deployment status of the Vector Search index

Before deploying and testing the Apigee API proxy, confirm that the Vector Search index has been deployed to the index endpoint.

  1. In the Google Cloud console, from the Navigation menu (Navigation menu icon), navigate to Agent Platform > Agents > Vector Search.

  2. Confirm that the index has been deployed. A green status check under Deployed indexes is visible indicating the index is deployed. If it is not yet visible, wait until the index is deployed.

    You might need to periodically refresh the browser page to view the latest status in the UI.
  3. After the index is deployed and the green check is displayed, expand the Deployed indexes list.

  4. To view the details of the deployed index, click its name.

Deploy the API proxy

  1. From the Navigation menu (Navigation menu icon), navigate to Apigee > API proxies.

  2. In the Apigee UI, select the cachellm-v1 API proxy, and click the Develop tab.

  3. Click Deploy.

  4. For Environment, select eval.

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

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

  7. In the confirmation dialog, click Confirm.

  8. 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. In the Apigee proxy UI, click the Debug tab.

  4. Click Start Debug Session.

  5. In the Start debug session pane, from the Environment drop-down list, select eval.

    The deployed revision number is also displayed in the drop-down list.

  6. Click Start.

  7. In the Cloud Shell SSH session on the test VM, call the deployed cachellm-v1 API proxy in the eval environment:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/cachellm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Why is the sky blue?"}]}],"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 includes the model response.

View transactions in the Debug tool

  1. In the Transactions pane on the left, select the transaction for the request to view the trace of the request and response through Apigee.

    You should see a 200 Status if your backend URL was correctly set and you correctly sent the curl command.

    The debug session transactions pane shows a list of transactions that have been received since the debug session was started.

    The debug transaction showing the request to the Apigee API proxy and the model response.

  2. In the main debug panel, hover over the policy and flow items to review their execution.

    In this transaction, the SemanticCacheLookup policy was executed in the proxy request flow, the target endpoint (model) was invoked, and the SemanticCachePopulate policy was executed in the target response flow to cache the response from the model. Also note the elapsed time of the request, which in this case was 13708 milliseconds.

  3. Send another similar prompt in the request to the API:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/cachellm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"What makes the sky blue?"}]}],"generationConfig":{"candidateCount":1}}'

    The debug transaction showing the request to the Apigee API proxy and the cached response.

  4. In the main debug panel, hover over the policy and flow items to review their execution.

    In this transaction, the request was not sent to the target (model) endpoint, because a semantically similar prompt was found in Vector Search. The entire target endpoint was skipped, and the SemanticCacheLookup policy was executed to fetch the cached model response. This response was cached by the SemanticCachePopulate policy that was executed in the previous transaction. Also note the elapsed time of this request, which in this case was only 207 milliseconds, which is considerably less than that of the previous transaction.

  5. Repeat the curl calls on the test VM with similar prompts:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/cachellm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Why is the sky blue colored?"}]}],"generationConfig":{"candidateCount":1}}' curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/cachellm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Can you explain why the sky is blue?"}]}],"generationConfig":{"candidateCount":1}}' curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/cachellm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"The sky is blue, why is that?"}]}],"generationConfig":{"candidateCount":1}}'

    All of these calls should result in the same cached model response from the API.

    Note: The TTL configuration in the SemanticCachePopulate policy is set at 600 seconds (10 minutes). If this time has already elapsed, some of these calls might result in the API proxy calling the target (model) endpoint and re-caching the model response.

  6. Finally, perform another test with a prompt that is close but different enough to confirm that the response is not served from the cache:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/cachellm/v1' -d '{"contents":[{"role":"user","parts":[{"text":"Why are clouds white in the blue sky?"}]}],"generationConfig":{"candidateCount":1}}'

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

Congratulations!

In this lab, you:

  • Created a service account with the correct roles to integrate with Agent Platform.
  • Set up and configured Vector Search in Agent Platform.
  • Developed an API proxy with the relevant Apigee semantic caching policies.
  • Used the proxy to call a Gemini model with a user prompt.
  • Reviewed the flow and response times of the API proxy when model responses are cached.

Next steps / learn more

Manual Last Updated on November 6, 2026

Manual last tested on October 30, 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.