Before you begin
- Labs create a Google Cloud project and resources for a fixed time
- Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
- On the top left of your screen, click Start lab to begin
Create an API proxy to manage LLM token quota
/ 20
Create an API product
/ 20
Create a developer and application
/ 20
Test token quota management
/ 20
Test token rate limit
/ 20
Create an API proxy to manage LLM token quota
/ 20
Create an API product
/ 20
Create a developer and application
/ 20
Test token quota management
/ 20
Test token rate limit
/ 20
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
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.
In this lab, you learn how to perform the following tasks:
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:
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:
Note that the lab timer is located near the top of the page, showing the remaining time.
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.
If necessary, copy the Username below and paste it into the Sign in dialog.
You can also find the Username in the Lab setup and access panel.
Click Next.
Copy the Password below and paste it into the Welcome dialog.
You can also find the Password in the Lab setup and access panel.
Click Next.
Click through the subsequent pages:
After a few moments, the Google Cloud console opens in this tab.
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.
Click Activate Cloud Shell at the top of the Google Cloud console.
Click through the following windows:
When you are connected, you are already authenticated, and the project is set to your Project_ID,
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
Output:
Output:
gcloud, in Google Cloud, refer to the gcloud CLI overview guide.
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.
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.In Cloud Shell, set environment variables:
Run the following command to verify that the service account is created:
Run the following command to verify that the service account has the Agent Platform User (roles/aiplatform.user) role:
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:
In this task, you create an Apigee API proxy with the relevant Apigee policies to manage the consumption of LLM tokens.
To open the Apigee console:
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.
In the navigation menu, select Proxy development > API proxies.
To create a new proxy using the proxy wizard, click Create.
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.
For Proxy details, specify the following:
| Property | Value |
|---|---|
| Proxy name | llmtokens-v1 |
| Base path | /llmtokens/v1 |
| Target (Existing API) |
/llmtokens/v1 for the base path, not /llmtokens-v1.Leave the remaining settings as their defaults, and click Next.
Leave the remaining settings as their defaults, and click Create.
The Apigee API proxy is created.
Click the Develop tab.
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.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.
To review and update the default policy, click the Develop tab in the Proxy Editor.
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.
In the Apigee UI navigation menu under Policies, click LLM Token Quota Enforce.
In the LLM-Token-Quota-Enforce.xml file in the UI, replace the entire <LLMTokenQuota> element with:
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.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.
Ensure that you are in the Develop tab in the Proxy Editor.
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.
In the Apigee UI navigation menu, under Policies, click LLM Token Quota Count.
In the LLM-Token-Quota-Count.xml file, replace the entire <LLMTokenQuota> element with:
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.
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.
In the Apigee UI navigation menu, select Proxy endpoints > default > PreFlow.
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.
In the Add policy step pane, select Create new policy, and then select Security > Verify API Key.
Specify the following values:
| Property | Value |
|---|---|
| Name | VA-VerifyAPIKey |
| Display name | VA-VerifyAPIKey |
stepName attribute of the UseQuotaConfigInAPIProduct element that was configured in the LLMTokenQuota policy earlier.Click Add.
Click Policies > VA-VerifyAPIKey, and review the APIKey element.
The configuration currently expects the API key in a query parameter named apikey.
Change the policy configuration so it expects the API key in a header named apikey. Replace:
with:
In the Apigee UI, click Proxy endpoints > default > PreFlow.
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.
To save your changes, click Save.
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.
Click the Develop tab in the Proxy Editor.
In the Navigator menu for the proxy, in the Target endpoints section, click default > PreFlow.
In the default.xml file, find the following code (your URL will be slightly different):
<HTTPTargetConnection> section, confirm that you clicked PreFlow in the Target endpoints section, and not in the Proxy endpoints section.Above the <URL> element, add this <Authentication> element:
Your TargetEndpoint code should now look similar to this:
Click Save.
Click Check my progress to verify the objective.
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.
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:
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.
If you are waiting for the org to be ready, you can explore the documentation on these topics:
In the Apigee UI, in the navigation menu, select Distribution > API products.
To create a new API product, click +Create.
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.
Select Set LLM token quota limit.
For LLM token quota limit, type 100.
For Time interval, type 2.
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.
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.
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.
To save the operation, click Save.
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.
To save the API product, click Save at the top.
Click Check my progress to verify the objective.
In this task, you create an app developer, which will allow you to create and register an app.
On the left navigation menu, click Distribution > Developers.
To create a new app developer, click +Create.
Specify the following:
| Property | Value |
|---|---|
| First Name | Joe |
| Last Name | Developer |
| joe@example.com | |
| Username | joe |
To create the app developer, click Add.
Create an app and register it to the app developer.
On the left navigation menu, click Distribution > Apps.
To create a new app, click +Create.
In the App Details pane, specify the following:
| Property | Value |
|---|---|
| App Name | llm-app |
| Display Name | Joe's LLM app |
| Developer | Select Joe Developer |
In the Credentials section, click +Add Credential.
In the Credential pane, click Add Products.
In the Select products drop-down list, select Gemini (full access), and then click OK.
Click Add.
Select the llm-access checkbox, and then click Approve.
To create the app, click Create.
The Key and Secret are now configured for the app.
For the Key, click the not shown icon ().
The API key for Joe's LLM app is displayed.
Click Check my progress to verify the objective.
Return to the llmtokens-v1 API proxy in the Apigee UI, and click the Develop tab.
Click Deploy.
For Environment, select eval.
For Service Account, specify the service account's email address:
Click Deploy.
In the confirmation dialog, click Confirm.
Click the Overview tab, and wait until the eval deployment status indicates that the proxy is deployed.
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.
In Cloud Shell, open an SSH connection to your test VM:
If asked Do you want to continue (Y/n)?, type Y.
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.
In the Apigee UI Distribution > Apps > App Details page for the llm-app, in the Credential section, for the Key, click Copy to clipboard ().
In the Cloud Shell SSH session on the test VM, run the following command:
Replace {key} with the API key for Joe's app. The command should look similar to this:
Call the deployed llmtokens-v1 API proxy in the eval environment:
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:
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.
Send the same request to the API:
The model response should resemble this:
This is the default error message from the LLMTokenQuota policy when the token quota limit is exceeded.
Wait two minutes, and then send the request again. This time, the request should succeed because the quota time interval is reset.
Type exit and press ENTER to leave the SSH session and return to Cloud Shell.
Click Check my progress to verify the objective.
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.
In this task, you add the PromptTokenLimit policy to the llmtokens-v1 API proxy that you developed earlier in the lab.
In the Apigee UI, on the left navigation menu, select Proxy development > API proxies.
Select the llmtokens-v1 proxy.
Click the Develop tab.
In the Navigator menu, click Proxy endpoints > default > PreFlow.
On the Request PreFlow flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select AI > Prompt Token Limit.
Specify the following values:
| Property | Value |
|---|---|
| Name | PTL-PromptTokenLimit |
| Display name | PTL-PromptTokenLimit |
Click Add.
Click Policies > PTL-PromptTokenLimit.
Replace the entire <PromptTokenLimit> element with:
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.
Click Proxy endpoints > default > PreFlow.
Drag the PTL-PromptTokenLimit policy to be first in the PreFlow.
Click Save, and then click Save as New Revision.
To deploy the new proxy revision, click Deploy.
For Environment, select eval.
For Service Account, specify the service account's email address:
Click Deploy.
In the confirmation dialog, click Confirm.
Click the Overview tab, and wait until the eval deployment status indicates that the proxy is deployed.
In Cloud Shell, open an SSH connection to your test VM:
If asked Do you want to continue (Y/n)?, type Y.
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.
In the Apigee UI Distribution > Apps, select llm-app, and copy the key from the Credential section using the clipboard icon ().
In the Cloud Shell SSH session on the test VM, run the following command:
Replace {key} with the API key for Joe's app. The command should look similar to this:
Call the deployed llmtokens-v1 API proxy in the eval environment:
Note the value of the usageMetadata.promptTokenCount field in the JSON response. The value is less than your configured rate.
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:
Wait one minute, and then send the request again. This time, the request should succeed because the rate time interval is reset.
Type exit and press ENTER to leave the SSH session and return to Cloud Shell.
Click Check my progress to verify the objective.
In this lab, you:
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.
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