Create an API proxy to manage LLM token quota

Check my progress

/ 20

Create an API product

Check my progress

/ 20

Create a developer and application

Check my progress

/ 20

Test token quota management

Check my progress

/ 20

Test token rate limit

Check my progress

/ 20

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.

GSP1376

Google Cloud self-paced labs

Overview

Large language models (LLMs) break text into tokens (words, characters, punctuation) to process and convert them into numerical IDs. This helps LLMs understand relationships and context. Tokens also act as the currency for API usage. Their costs are usually tied to the count of input and output tokens and vary by model. Models also have a token limit per request known as the context window. It includes the prompt, conversation history, and retrieved data. For example, the model features a 1 million context window.

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

In this lab, you develop an Apigee API proxy to rate limit input tokens in model prompts and manage token quotas when using an LLM.

Objectives

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

  • Verify the service account used by an API proxy to integrate with Gemini platform.
  • Develop an API proxy with the relevant Apigee policies to manage LLM token quotas and implement token rate limiting for model prompts.
  • Test the API proxy by calling a Gemini model and verifying the policy operation.

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 service account

In this task, you verify the pre-provisioned service account that will be used by the Apigee API proxy, and grant the required role to the Apigee Service Agent.

Note: To maintain least-privilege security, the apigee-gc-service-access service account and its project-level Agent Platform User role (roles/aiplatform.user) have been pre-provisioned for you during lab startup.
  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. Run the following command to verify that the service account is created:

    gcloud iam service-accounts describe apigee-gc-service-access@${PROJECT_ID}.iam.gserviceaccount.com
  3. Run the following command to 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"

Task 2. Create an API proxy to manage LLM token quota

In this task, you create an Apigee API proxy with the relevant Apigee policies to manage the consumption of LLM tokens.

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 LLM Token Quota.

    The proxy will be created with the relevant policy to manage LLM token consumption.

  4. For Proxy details, specify the following:

    Property Value
    Proxy name llmtokens-v1
    Base path /llmtokens/v1
    Target (Existing API)
    Note: Confirm that you are using /llmtokens/v1 for the base path, not /llmtokens-v1.
  5. Leave the remaining settings as their defaults, and click Next.

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

    The Apigee API proxy is created.

  7. Click the Develop tab.

    Note: The LLMTokenQuota policy is automatically added to the default proxy endpoint request preflow with the EnforceOnly element set to true. The policy is also automatically added to the default target endpoint response preflow in the API proxy with the CountOnly element set to true.

Review and update the LLMTokenQuota policy to enforce token quota

The LLMTokenQuota policy uses quotas to control token consumption for LLM workloads. This enables you to control costs, optimize performance, and maintain platform stability when using AI models.

A quota is an allotment of LLM tokens (input or output) that an API proxy is allowed to consume over a time period, such as minute, hour, day, week, or month. The LLMTokenQuota policy maintains counters that tally the number of tokens consumed by the API proxy. This capability enables API providers to enforce limits on token consumption by apps over an interval of time.

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

  2. In the Apigee UI navigation menu, select Proxy endpoints > default > PreFlow.

    The LLM Token Quota Enforce policy of type LLMTokenQuota is automatically added to the default proxy endpoint preflow request.

  3. In the Apigee UI navigation menu under Policies, click LLM Token Quota Enforce.

  4. In the LLM-Token-Quota-Enforce.xml file in the UI, replace the entire <LLMTokenQuota> element with:

    <LLMTokenQuota continueOnError="false" enabled="true" name="LLM-Token-Quota-Enforce" type="calendar"> <DisplayName>LLM Token Quota Enforce</DisplayName> <Properties/> <EnforceOnly>true</EnforceOnly> <SharedName>common-counter</SharedName> <Identifier ref="client_id"/> <UseQuotaConfigInAPIProduct stepName="VA-VerifyAPIKey"> <DefaultConfig> <Allow>100</Allow> <Interval>2</Interval> <TimeUnit>minute</TimeUnit> </DefaultConfig> </UseQuotaConfigInAPIProduct> <Distributed>true</Distributed> <Synchronous>true</Synchronous> <StartTime>2026-01-01 00:00:00</StartTime> <LLMModelSource>{jsonPath('$.model',request.content,true)}</LLMModelSource> </LLMTokenQuota>

    The updated policy uses an API product to specify the allowed quota configuration. You will create the API product later in the lab. The stepName attribute of the UseQuotaConfigInAPIProduct element specifies which step will determine the API product to use. When an API key or OAuth token is validated, it can be associated with an app that is associated with an API product. Using these policy settings, the VerifyAPIKey step called VA-VerifyAPIKey determines the API product. The VerifyAPIKey policy must run before the LLM-Token-Quota-Enforce policy.

    The default configuration values specified in the LLMTokenQuota policy specify a maximum of 100 (Allow) tokens consumed per 2 (Interval) minutes (TimeUnit). The default values will only be used if the values are not available, which should only happen if the quota settings are not set for the API product associated with the API key.

    EnforceOnly is set to true to enforce the token limit without incrementing the quota counter.

    The SharedName element sets the name of the quota counter that is shared with the LLMTokenQuota policy used in the API proxy's response flow. This allows you to customize the LLMTokenQuota policy to enforce the quota on incoming requests, but only increment the counter in the response flow.

    The Identifier element configures the policy to create a unique counter based on a flow variable. In this case, the client_id variable is used, which is set by the VerifyAPIKey policy that identifies the application that sends the request to the API. You will add this policy to the API proxy later in the lab. This enables you to count and enforce tokens separately for each application.

    The Distributed element is set to true, so the LLMTokenQuota counter will be shared by all message processors. The Synchronous element is set to true, so the distributed LLMTokenQuota counter is updated at the same time the quota is checked on a request to the API.

    StartTime specifies the date and time when the quota counter begins counting, regardless of whether any requests have been received from any apps.

    The LLMModelSource element provides the source of the model name in the request.

    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 usageMetadata.candidatesTokenCount and model fields in the response from the LLM.

Update the LLMTokenQuota policy to count tokens

In the previous subtask, you updated the LLM Token Quota Enforce policy in the default proxy endpoint preflow request to enforce the token quota limit when a request is made to the API proxy.

In this subtask, you update the LLM Token Quota Count policy in the default target endpoint preflow response to update the token quota count using the value returned in the response from the model.

For more details on how these policies are used to count and enforce tokens, view the documentation on using shared quota counters.

  1. Ensure that you are in the Develop tab in the Proxy Editor.

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

    The LLM Token Quota Count policy of type LLMTokenQuota was automatically added to the default target endpoint preflow response.

  3. In the Apigee UI navigation menu, under Policies, click LLM Token Quota Count.

  4. In the LLM-Token-Quota-Count.xml file, replace the entire <LLMTokenQuota> element with:

    <LLMTokenQuota continueOnError="false" enabled="true" name="LLM-Token-Quota-Count" type="calendar"> <DisplayName>LLM Token Quota Count</DisplayName> <Properties/> <CountOnly>true</CountOnly> <SharedName>common-counter</SharedName> <Identifier ref="client_id"/> <UseQuotaConfigInAPIProduct stepName="VA-VerifyAPIKey"> <DefaultConfig> <Allow>100</Allow> <Interval>2</Interval> <TimeUnit>minute</TimeUnit> </DefaultConfig> </UseQuotaConfigInAPIProduct> <Distributed>true</Distributed> <Synchronous>true</Synchronous> <StartTime>2026-01-01 00:00:00</StartTime> <LLMTokenUsageSource>{jsonPath('$.usageMetadata.candidatesTokenCount',response.content,true)}</LLMTokenUsageSource> <LLMModelSource>{jsonPath('$.modelVersion',response.content,true)}</LLMModelSource> </LLMTokenQuota>

    In the updated policy, CountOnly is set to true to count and track the number of tokens without sending an error back to the client when the token quota limit is exceeded.

    The LLMTokenUsageSource element provides the source of the token usage or count from the LLM response.

    The LLMTokenQuota policy is structurally similar to the Quota policy, but the LLMTokenQuota policy tracks the number of input and output tokens to and from LLMs instead of the number of API requests. One significant difference in functionality is that the LLMTokenQuota policy must be attached in two places (both before and after the call to the LLM), instead of a single location for the Quota policy. The LLMTokenQuota policy does not know how many tokens will be used for the current request until it receives the response from the LLM. Therefore, quota enforcement occurs before the LLM call, and quota counting occurs after the LLM response is received.

Modify the proxy endpoint to perform API key verification

API key verification ensures that only apps with valid, unrevoked keys and associated with the correct API product can access your APIs. You can achieve this by adding the VerifyAPIKey policy to your API proxy.

  1. In the Apigee UI navigation menu, select Proxy endpoints > default > PreFlow.

  2. On the Request PreFlow, click Add Policy Step (+).

    The policy should be added as early as possible so that requests with invalid keys can be rejected without incurring additional processing of further policies in the proxy.

  3. In the Add policy step pane, select Create new policy, and then select Security > Verify API Key.

  4. Specify the following values:

    Property Value
    Name VA-VerifyAPIKey
    Display name VA-VerifyAPIKey
    Note: The policy step name must match the stepName attribute of the UseQuotaConfigInAPIProduct element that was configured in the LLMTokenQuota policy earlier.
  5. Click Add.

  6. Click Policies > VA-VerifyAPIKey, and review the APIKey element.

    The configuration currently expects the API key in a query parameter named apikey.

  7. Change the policy configuration so it expects the API key in a header named apikey. Replace:

    <APIKey ref="request.queryparam.apikey"/>

    with:

    <APIKey ref="request.header.apikey"/> Note: In real-world proxy development, any API key specified in a query parameter will probably appear in access logs, because the entire URL is generally logged. This can result in API keys being compromised. It is a better practice to specify the API key in a field that is less likely to be logged, such as a header.
  8. In the Apigee UI, click Proxy endpoints > default > PreFlow.

  9. In the PreFlow graphical pane, select the VA-VerifyAPIKey policy and drag it so it is the first policy to be executed in the flow.

    Verify API Key policy

  10. To save your changes, 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>LLM-Token-Quota-Count</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 3. Create an API product

As mentioned earlier, apps that present API keys when invoking an API proxy must be associated with an API product in Apigee. In this task, you create and configure an API product and associate it with an API proxy. You then create an application and associate it with the API product.

Confirm that the runtime instance is available

Certain assets, including API products, developers, developer apps, and KVMs, cannot be saved until the runtime is available.

For example, when navigating to the API products page, you might see an error message that reads "Products were not loaded successfully."

This is an error you should see when you are waiting for the runtime instance to be available. After the runtime is available, refreshing the page removes the error.

If you get this type of error, you can check the status of provisioning.

  • 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) might have been created before you started the lab, so you might not have to wait for the instance to be created.

Explore documentation while waiting

If you are waiting for the org to be ready, you can explore the documentation on these topics:

Create the API product

  1. In the Apigee UI, in the navigation menu, select Distribution > API products.

  2. To create a new API product, click +Create.

  3. In the Product details section, specify the following:

    Property Value
    Name llm-access
    Display Name Gemini (full access)
    Description full access to Gemini API
    Environment Select eval, and then click OK
    Access Select Public

    Leave Automatically approve access requests selected.

  4. Select Set LLM token quota limit.

  5. For LLM token quota limit, type 100.

  6. For Time interval, type 2.

  7. For Unit, select minute.

    This sets the LLM token quota limit to 100 tokens every two minutes. The quota is set artificially low for lab testing purposes.

    Note: Ensure that you leave the API quota limit values empty. They are used to manage quotas for API requests, which is not the goal of this lab.
  8. In the LLM Operations section, click +Add an Operation.

    Operations are used to specify the requests in API proxies that are allowed for an application associated with the API product. Configuring an LLM operation in an API product allows you to manage model access and enforce token-based quotas for AI services.

    Note: Confirm that the button is in the LLM Operations section.
  9. In the Operation pane, specify the following values:

    Property Value
    API Proxy Select the llmtokens-v1 API proxy
    Path /**
    Model
    Methods Select POST, and then click OK

    The path expression "/**" indicates that any path suffix of any depth is a match for the operation.

    In a production environment, you might choose to add each operation that is allowed separately rather than use this wildcard path expression.

  10. To save the operation, click Save.

  11. Repeat the three previous steps to add another LLM Operation using / for the Path. Use the same values as those used for the other properties of the previous operation. This allows API calls using only the proxy base path.

  12. To save the API product, click Save at the top.

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

Task 4. Create a developer and an application

In this task, you create an app developer, which will allow you to create and register an app.

Note: App developers and apps are typically created using a developer portal. For now, use the Apigee console to create the developer and app.

Create an app developer

  1. On the left navigation menu, click Distribution > Developers.

  2. To create a new app developer, click +Create.

  3. Specify the following:

    Property Value
    First Name Joe
    Last Name Developer
    Email joe@example.com
    Username joe
  4. To create the app developer, click Add.

Create and register an app

Create an app and register it to the app developer.

  1. On the left navigation menu, click Distribution > Apps.

  2. To create a new app, click +Create.

  3. In the App Details pane, specify the following:

    Property Value
    App Name llm-app
    Display Name Joe's LLM app
    Developer Select Joe Developer
  4. In the Credentials section, click +Add Credential.

  5. In the Credential pane, click Add Products.

  6. In the Select products drop-down list, select Gemini (full access), and then click OK.

  7. Click Add.

  8. Select the llm-access checkbox, and then click Approve.

  9. To create the app, click Create.

    The Key and Secret are now configured for the app.

  10. For the Key, click the not shown icon (key not shown icon).

    The API key for Joe's LLM app is displayed.

Click Check my progress to verify the objective. Create a developer and an app

Task 5. Test the API proxy

Deploy the API

  1. Return to the llmtokens-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.

  1. 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.

  2. In the Apigee UI Distribution > Apps > App Details page for the llm-app, in the Credential section, for the Key, click Copy to clipboard (key copy button).

  3. In the Cloud Shell SSH session on the test VM, run the following command:

    export API_KEY={key}

    Replace {key} with the API key for Joe's app. The command should look similar to this:

    export API_KEY=ZyncwYSmswgJVKNCw204dmjPp0XnGihgu5NoWXHXHpUpSd1jL
  4. Call the deployed llmtokens-v1 API proxy in the eval environment:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/llmtokens/v1' -H "apikey: ${API_KEY}" -d '{"model":"{{{project_0.startup_script.llm|model_id|disablehighlight}}}", "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 successful response from the API looks like this:

    { "candidates": [ { "content": { "role": "model", "parts": [ { "text": "The sky is blue because of a phenomenon called **Rayleigh Scattering**. Here's a breakdown of how it works:\n\n1. **Sunlight is White Light:** The light from the sun appears white to us, but it's actually made up of all the colors of the rainbow (ROYGBIV - Red, Orange, Yellow, Green, Blue, Indigo, Violet). Each of these colors has a different **wavelength**; red light has the longest wavelength, and violet/blue light has the shortest.\n\n2. **The Earth's Atmosphere:** Our atmosphere is composed of tiny gas molecules (mostly nitrogen and oxygen) and small particles. These particles are much smaller than the wavelengths of visible light.\n\n3. **Rayleigh Scattering:** When sunlight enters the Earth's atmosphere, it hits these tiny gas molecules and particles. This causes the light to be \"scattered,\" meaning it's absorbed and re-emitted in different directions.\n * **The key:** Rayleigh scattering states that shorter wavelengths of light (like blue and violet) are scattered *much more efficiently* than longer wavelengths (like red and yellow). In fact, blue light is scattered about 10 times more than red light!\n\n4. **Why Blue (and not Violet)?**\n * **Violet is scattered even more than blue,** but there are two main reasons why we see blue:\n 1. **Our eyes are more sensitive to blue light** than to violet light.\n 2. **The sun's spectrum emits slightly less violet light** than blue light to begin with.\n * So, while violet is scattered, the combination of our eye's sensitivity and the amount of blue light present makes blue the dominant color we perceive.\n\n5. **What Happens to Other Colors?**\n * The longer wavelengths (red, orange, yellow) are scattered much less. They tend to travel in a straighter line from the sun to our eyes.\n\n**In summary:**\n\nWhen you look up at the sky, you're seeing the blue light that has been scattered in all directions by the tiny molecules in our atmosphere. This scattered blue light reaches your eyes from every part of the sky, making it appear blue.\n\n**What about Sunrises and Sunsets?**\n\nAt sunrise and sunset, the sunlight has to travel through *much more* of the atmosphere to reach our eyes. By the time it gets to us, most of the blue and violet light has been scattered away, leaving primarily the longer wavelengths (red, orange, and yellow) to pass directly through, which is why we see those beautiful warm colors." } ] }, "finishReason": "STOP", "avgLogprobs": -0.72083819558043771 } ], "usageMetadata": { "promptTokenCount": 6, "candidatesTokenCount": 554, "totalTokenCount": 1644, "trafficType": "ON_DEMAND", "promptTokensDetails": [ { "modality": "TEXT", "tokenCount": 6 } ], "candidatesTokensDetails": [ { "modality": "TEXT", "tokenCount": 554 } ], "thoughtsTokenCount": 1084 }, "modelVersion": "{{{project_0.startup_script.llm | "model_id"}}}", "createTime": "2026-01-27T04:15:20.174047Z", "responseId": "2Dt4ad_PCtSyt_gP2antyAw" }

    Note the value of the usageMetadata.candidatesTokenCount field in the JSON response. The value already exceeded your token quota configuration of 100 tokens every two minutes that was specified in the API product.

  5. Send the same request to the API:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/llmtokens/v1' -H "apikey: ${API_KEY}" -d '{"model":"{{{project_0.startup_script.llm|model_id|disablehighlight}}}", "contents":[{"role":"user","parts":[{"text":"Why is the sky blue?"}]}],"generationConfig":{"candidateCount":1}}'

    The model response should resemble this:

    {"fault":{"faultstring":"Rate limit LLM Token quota violation. Quota limit exceeded. Identifier : knyJGvLJn37yM5KoSKdAyDjPnLpkC45stUwz1lN8024kGJaV","detail":{"errorcode":"policies.llmtokenquota.LLMTokenQuotaViolation"}}}

    This is the default error message from the LLMTokenQuota policy when the token quota limit is exceeded.

    Note: If you receive a successful response from the API proxy, the quota was probably reset after the original two-minute time interval had elapsed. If you send the request again, the token violation error message should be returned.
  6. Wait two minutes, and then send the request again. This time, the request should succeed because the quota time interval is reset.

  7. Type exit and press ENTER to leave the SSH session and return to Cloud Shell.

Click Check my progress to verify the objective. Test token quota management

Task 6. Implement token rate limiting in user prompts

The LLMTokenQuota policy that you used in the previous tasks enforced token consumption limits on client apps. To manage costs and enforce business agreements, this policy is used to manage token consumption over longer periods (such as hours, days, or months). To protect LLM backends from spikes in token usage, you use the PromptTokenLimit policy to throttle the number of tokens in user prompts.

The PromptTokenLimit policy limits the number of tokens in prompts within API requests. This policy is specifically tailored for LLM applications where the cost and performance are directly related to the number of tokens processed.

The PromptTokenLimit policy uses a standard library to count LLM tokens for an input prompt, which might differ from the token count used by the specific LLM that would be called. To successfully protect the API proxy against a spike in token usage, the PromptTokenLimit policy cannot call the LLM to determine the token count for the prompt.

In this task, you add the PromptTokenLimit policy to the llmtokens-v1 API proxy that you developed earlier in the lab.

Create the policy

  1. In the Apigee UI, on the left navigation menu, select Proxy development > API proxies.

  2. Select the llmtokens-v1 proxy.

  3. Click the Develop tab.

  4. In the Navigator menu, click Proxy endpoints > default > PreFlow.

  5. On the Request PreFlow flow, click Add Policy Step (+).

  6. In the Add policy step pane, select Create new policy, and then select AI > Prompt Token Limit.

  7. Specify the following values:

    Property Value
    Name PTL-PromptTokenLimit
    Display name PTL-PromptTokenLimit
  8. Click Add.

  9. Click Policies > PTL-PromptTokenLimit.

  10. Replace the entire <PromptTokenLimit> element with:

    <PromptTokenLimit continueOnError="false" enabled="true" name="PTL-PromptTokenLimit"> <DisplayName>PTL-PromptTokenLimit</DisplayName> <Properties/> <UserPromptSource>{jsonPath('$.contents[-1].parts[-1].text',request.content,true)}</UserPromptSource> <Rate ref="">10pm</Rate> <UseEffectiveCount>true</UseEffectiveCount> </PromptTokenLimit>

    The UserPromptSource element provides the source of the user prompt text in the payload sent to the API proxy.

    The Rate element specifies the rate at which to limit token spikes (or bursts) by setting the number of tokens that are allowed in per minute or per second intervals. A rate of "10pm" indicates that requests with user prompts will be allowed to contain tokens at a rate of only ten tokens per minute. The PromptTokenLimit rate is a sustained rate, and you might be able to make several requests in a row without being blocked.

    The UseEffectiveCount element with a value of true synchronizes the prompt token counts across message processors in a region. There might be multiple message processors running your proxy. This algorithm provides consistent rate limit behavior across the message processors.

    Note: Ten tokens per minute is a very low rate. This rate has been chosen only for ease of testing in the lab.

    The PromptTokenLimit policy is structurally similar to the SpikeArrest policy, but the PromptTokenLimit policy limits the rate of LLM token consumption instead of API requests.
  11. Click Proxy endpoints > default > PreFlow.

  12. Drag the PTL-PromptTokenLimit policy to be first in the PreFlow.

    PreFlow pane showing PTL-PromptTokenLimit placed first in the Request PreFlow

  13. Click Save, and then click Save as New Revision.

Deploy the API 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.

  1. 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.

  2. In the Apigee UI Distribution > Apps, select llm-app, and copy the key from the Credential section using the clipboard icon (key copy button).

  3. In the Cloud Shell SSH session on the test VM, run the following command:

    export API_KEY={key}

    Replace {key} with the API key for Joe's app. The command should look similar to this:

    export API_KEY=ZyncwYSmswgJVKNCw204dmjPp0XnGihgu5NoWXHXHpUpSd1jL
  4. Call the deployed llmtokens-v1 API proxy in the eval environment:

    curl -i -k -X POST -H "Content-Type: application/json" 'https://eval.example.com/llmtokens/v1' -H "apikey: ${API_KEY}" -d '{"model":"{{{project_0.startup_script.llm|model_id|disablehighlight}}}", "contents":[{"role":"user","parts":[{"text":"Why is the sky blue?"}]}],"generationConfig":{"candidateCount":1}}'

    Note the value of the usageMetadata.promptTokenCount field in the JSON response. The value is less than your configured rate.

  5. Send the same request to the API, and you should see an error response from the API proxy.

    The total count of the user prompt tokens from both requests exceeds the rate configured in the PromptTokenLimit policy of ten tokens per minute.

    The error response from the PromptTokenLimit policy when the token rate limit is exceeded should resemble:

    {"fault":{"faultstring":"Prompt Token Limit Violation. Allowed rate : MessageRate{capacity=10, period=Minutes}","detail":{"errorcode":"policies.prompttokenlimit.PromptTokenLimitViolation"}}}
  6. Wait one minute, and then send the request again. This time, the request should succeed because the rate time interval is reset.

  7. Type exit and press ENTER to leave the SSH session and return to Cloud Shell.

Click Check my progress to verify the objective. Test token rate limit

Congratulations!

In this lab, you:

  • Created a service account for use by an API proxy to integrate with Gemini platform.
  • Developed an API proxy with the relevant Apigee policies to manage LLM token quotas and implement token rate limiting for model prompts.
  • Tested the API proxy by calling a Gemini model and verifying the policy operation.

Next steps / learn more

Manual Last Updated on November 25, 2026

Manual last tested on November 26, 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.