Context caching in Firebase AI Logic  |  Firebase AI Logic

Context caching in Firebase AI Logic

Stay organized with collections
Save and categorize content based on your preferences.

Implicit caching

Implicit caching is enabled by default and available for most Gemini models.

Google automatically passes on cost savings if your request hits the cached content. Here are some ways to increase the chance that your request uses implicit caching:

The number of tokens in the cached part of your input is provided in the cachedContentTokenCount field in the metadata of a response.

Explicit caching

Explicit caching is not enabled by default, and it's an optional capability of the Gemini models.

Here's how you can set up and work with explicit content caches:

Note that explicit content caches interact with implicit caching, potentially leading to additional caching beyond the explicit cached content. You can prevent cache data retention by disabling implicit caching and not creating explicit caches. For more information, see Enable and disable caching.

Create and use an explicit cache

Creating and using an explicit content cache requires the following:

  1. Create an explicit cache.
  2. Reference the cache in a server prompt template.
  3. Reference the server prompt template in a prompt request from your app.

Important information about creating and using an explicit cache

Your cache must be aligned with your app's prompt requests and your server prompt template:

For Firebase AI Logic, we strongly recommend using explicit content caches only with the Agent Platform Gemini API (formerly Vertex AI). All the information and examples on this page are specific to that Gemini API provider.

The location for the explicit cache must match the location of the server prompt template and the location where you access the model in your app's prompt request.

Also, be aware of the following limitations and requirements for explicit caching:

Additionally, access restrictions to the file are checked at cache-creation-time, and access restrictions are not checked again at user-request-time. For this reason, make sure that any data included in the explicit cache is suitable for any user making a request that includes that cache.

Step 1: Create the cache

Create the cache by directly using the REST API of the Agent Platform Gemini API (formerly Vertex AI).

Example request:

PROJECT_ID="my-amazing-app"
MODEL_ID="gemini-3.8-flash"
LOCATION="global"
MIME_TYPE="application/pdf"
CACHED_CONTENT_URI="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf"
CACHE_DISPLAY_NAME="Gemini - A Family of Highly Capable Multimodal Model (PDF)"
TTL="7200s"

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents \
-d @- <<EOF
{
  "model":"projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}",
  "contents": [\
    {\\
      "role": "user",\
      "parts": [\
        {\
          "fileData": {\
            "mimeType": "${MIME_TYPE}",\
            "fileUri": "${CACHED_CONTENT_URI}"
          }\
        }\
      ]\
    }\
  ],
  "displayName": "${CACHE_DISPLAY_NAME}",
  "ttl": "${TTL}"
}
EOF

Example Response:

The response includes a fully-qualified resource name which is globally unique to the cache (note that the last segment is the cache ID). You'll use this entire name value in the next step of the workflow.

{
  "name": "projects/861083271981/locations/global/cachedContents/4545031458888089601",
  "model": "projects/my-amazing-app/locations/global/publishers/google/models/gemini-3.8-flash",
  "createTime": "2024-06-04T01:11:50.808236Z",
  "updateTime": "2024-06-04T01:11:50.808236Z",
  "expireTime": "2024-06-04T02:11:50.794542Z"
}

Step 2: Reference the cache in a server prompt template

After creating the cache, reference it by name within the cachedContent property of a server prompt template.

Make sure you follow these requirements when creating your server prompt template:

Example:

{{cachedContent name="projects/861083271981/locations/global/cachedContents/4545031458888089601"}}

{{role "user"}}
{{userPrompt}}

Alternatively, the value of the name parameter in the server prompt template can be a dynamic input variable. For example, {{cachedContent name=someVariable}} lets you to include the name of the cache as an input for the request from your app.

Step 3: Reference the server prompt template in the request from your app

Manage explicit caches

This section describes managing explicit content caches, including how to list all caches, get metadata about a cache, update the TTL or expiration time of a cache, and delete a cache.

You manage explicit caches using the REST API of the Agent Platform Gemini API (formerly Vertex AI).

Once an explicit content cache is created, you can't change anything about the cache except the TTL or expiration time.

List all caches

You can list all the explicit caches available for your project. This command will only return the caches in the specified location.

PROJECT_ID="PROJECT_ID"
LOCATION="LOCATION"

curl \
-X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents

Get metadata about a cache

It's not possible to retrieve or view the actual cached content. However, you can retrieve metadata about an explicit cache, including name, model, display_name, usage_metadata, create_time, update_time, and expire_time.

You need to provide the CACHE_ID, which is the final segment in the fully-qualified resource name of the cache.

PROJECT_ID="PROJECT_ID"
LOCATION="LOCATION"
CACHE_ID="CACHE_ID"  # the final segment in the `name` of the cache

curl \
-X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents/${CACHE_ID}

Update the TTL or expiration time for a cache

When you create an explicit cache, you can optionally set the ttl or the expire_time.

If you don't set either of these values, the default TTL is 1 hour. There are no minimum or maximum bounds on the TTL.

For existing explicit caches, you can add or update the ttl or expire_time. You need to provide the CACHE_ID, which is the final segment in the fully-qualified resource name of the cache.

Update ttl

PROJECT_ID="PROJECT_ID"
LOCATION="LOCATION"
CACHE_ID="CACHE_ID"  # the final segment in the `name` of the cache
TTL="CACHE_TIME_TO_LIVE"

curl \
-X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents/${CACHE_ID} -d \
'{
  "ttl": "'$TTL'"
}'

Update expire_time

PROJECT_ID="PROJECT_ID"
LOCATION="LOCATION"
CACHE_ID="CACHE_ID"  # the final segment in the `name` of the cache
EXPIRE_TIME="ABSOLUTE_TIME_CACHE_EXPIRES"

curl \
-X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents/${CACHE_ID} -d \
'{
  "expire_time": "'$EXPIRE_TIME'"
}'

Delete a cache

When an explicit cache is no longer needed, you can delete it.

You need to provide the CACHE_ID, which is the final segment in the fully-qualified resource name of the cache.

PROJECT_ID="PROJECT_ID"
LOCATION="LOCATION"
CACHE_ID="CACHE_ID"  # the final segment in the `name` of the cache

curl \
-X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents/${CACHE_ID}

Pricing for explicit caching

Explicit caching is a paid feature designed to reduce cost. Pricing is based on the following factors:

The number of tokens in the cached part of your input is provided in the cachedContentTokenCount field in the metadata of a response.