# 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:

- Try putting large and common content at the beginning of your prompt.
- Try to send requests with a similar prefix in a short amount of time.

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:**

- [Create and then use an explicit cache](/content/docs/ai-logic/context-caching#create-and-use-explicit-cache/index.html)
- Manage explicit caches, including:
  - [List all caches](/content/docs/ai-logic/context-caching#list-caches/index.html)
  - [Get metadata about a cache](/content/docs/ai-logic/context-caching#get-metadata-about-cache/index.html)
  - [Update the TTL or expiration time of a cache](/content/docs/ai-logic/context-caching#update-ttl-expiration-time-of-cache/index.html)
  - [Delete a cache](/content/docs/ai-logic/context-caching#delete-cache/index.html)

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](https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/zero-data-retention#enabling-disabling-caching).

### Create and use an explicit cache  
Creating and using an explicit content cache requires the following:

1. [Create an explicit cache.](/content/docs/ai-logic/context-caching#create-cache/index.html)
2. [Reference the cache in a server prompt template.](/content/docs/ai-logic/context-caching#reference-cache-in-template/index.html)
3. [Reference the server prompt template in a prompt request from your app.](/content/docs/ai-logic/context-caching#reference-template-in-request/index.html)

#### 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:

- The cache is specific to a Gemini API provider.
Your app's prompt request must use the same provider.

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 cache is specific to a Gemini model.
Your app's prompt request must use the same model.

- The cache is specific to a location when using the Agent Platform Gemini API (formerly Vertex AI).

The location for the explicit cache must match the [location of the server prompt template](/content/docs/ai-logic/server-prompt-templates/advanced-workflows?api=vertex#specify-location-for-template/index.html) and the [location where you access the model](/content/docs/ai-logic/locations?api=vertex/index.html) in your app's prompt request.

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

- Once an explicit cache is created, you can't change anything about the cache except the TTL or expiration time.
- You can cache any [supported input file MIME type](/content/docs/ai-logic/input-file-requirements?api=vertex/index.html) or even just text provided within the cache creation request.
- If you want to include a file in the cache, you must provide the file as a Cloud Storage URI. It can't be a browser URL or YouTube URL.

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.
- If you want to use system instructions or tools (like code execution, URL context, Grounding with Google Search, or Grounding with Google Maps), then the cache itself must contain their configurations. They _cannot_ be configured in the server prompt template or in your app's prompt request. Note that server prompt templates do _not yet_ support function calling (or chat). For details about how to configure system instructions and tools in your cache, see the [REST API of the Agent Platform Gemini API (formerly Vertex AI)](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.cachedContents).

#### **Step 1**: Create the cache

Create the cache by directly using the [REST API of the Agent Platform Gemini API (formerly Vertex AI)](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.cachedContents).

**Example request:**

```bash
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.

```json
{
  "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](/content/docs/ai-logic/server-prompt-templates/get-started?api=vertex/index.html).

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

- Use the fully-qualified resource `name` from the response when you created the cache. This is _**not**_ the optional display name that you specified in the request.
- The [location for the server prompt template](/content/docs/ai-logic/server-prompt-templates/advanced-workflows?api=vertex#specify-location-for-template/index.html) must match the location of the cache.
- To use system instructions or tools, they must be configured as [part of the cache](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.cachedContents#CachedContent) and _not_ as part of the 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](/content/docs/ai-logic/server-prompt-templates/syntax-and-examples?api=vertex#gemini-input-variables/index.html). 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

- Use the Agent Platform Gemini API (formerly Vertex AI) since the cache was created with that Gemini API provider.
- The [location where you access the model](/content/docs/ai-logic/locations?api=vertex/index.html) in your app's prompt request must match the location of the server prompt template and the cache.

### Manage explicit caches  
This section describes managing explicit content caches, including how to [list all caches](/content/docs/ai-logic/context-caching#list-caches/index.html), [get metadata about a cache](/content/docs/ai-logic/context-caching#get-metadata-about-cache/index.html), [update the TTL or expiration time of a cache](/content/docs/ai-logic/context-caching#update-ttl-expiration-time-of-cache/index.html), and [delete a cache](/content/docs/ai-logic/context-caching#delete-cache/index.html).

You manage explicit caches using the [REST API of the Agent Platform Gemini API (formerly Vertex AI)](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/projects.locations.cachedContents).

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.

```bash
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.

```bash
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`.

- `ttl`: The TTL (time-to-live) for the cache, specifically the number of seconds and nanoseconds that the cache lives after it's created or after the `ttl` is updated before it expires. When you set the `ttl`, the `expireTime` of the cache is automatically updated.

- `expire_time`: A `Timestamp` (like `2024-06-30T09:00:00.000000Z`) that specifies the _absolute_ date and time when the cache expires.

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`**

```bash
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`**

```bash
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.

```bash
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:

- **Input tokens for cache creation**: For both implicit and explicit caching, you're billed for the input tokens used to create the cache at the standard input token price.
- **Storage of cache**: For explicit caching, there are also storage costs based on how long caches are stored. There are no storage costs for implicit caching. For more information, see the [pricing for the Agent Platform Gemini API (formerly Vertex AI)](https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing#context-caching).
- **Usage of cached content**: Explicit caching ensures a discount when explicit caches are referenced, meaning you get a discount on the input tokens when they reference an existing cache. For Gemini 2.5 and later models, this discount is 90%.

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