Gemini 中文指南
获取 API 密钥 ↗

上下文缓存

↓ 下载 Markdown

在典型的 AI 工作流程中,您可能会将相同的输入 token 一遍又一遍地传递给模型。 Gemini API 提供两种不同的缓存机制:

  • 隐式缓存(在 Gemini 2.5 及更新型号上自动启用,无成本节省保证)
  • 显式缓存(可在Gemini 3和2.5型号上手动启用,节省成本保证;Gemini 4型号不支持)

当您想要保证节省成本但需要增加一些开发人员工作时,显式缓存非常有用。

隐式缓存 #

默认情况下,所有 Gemini、2.5 及更新型号均启用隐式缓存。如果您的请求命中缓存,我们会自动节省成本。您无需配置任何内容即可将其打开。下表列出了每个型号的最小输入 token 数量:

模型最小 token 限制
Gemini 4 Carbon4,096
Gemini 4 Argon4,096
Gemini 4 Hydrogen4,096
Gemini 3.8 Flash4,096
Gemini 3.6 Flash4,096
Gemini 3.1 Pro Preview4,096
Gemini 2.5 Flash2,048
Gemini 2.5 Pro2,048

要增加隐式缓存命中的机会:

  • 尝试将大而常见的内容放在提示的开头
  • 尝试在短时间内发送具有相似前缀的请求

您可以在响应对象的缓存命中中看到 token 的数量 usage_metadata 场。

显式缓存 #

使用Gemini API显式缓存功能,您可以将一些内容传递给模型一次,缓存输入token,然后在后续请求时引用缓存的token。在某些数量上,使用缓存的 token 比重复传递 token 的同一语料库的成本更低。

当您缓存一组 token 时,您可以选择在 token 被自动删除之前希望缓存存在多长时间。该缓存持续时间称为 生存时间 (TTL)。如果未设置,TTL 默认为 1 小时。缓存的成本取决于输入 token 的大小以及您希望 token 保留的时间。

本节假设您已经安装了 Gemini SDK(或安装了curl)并且您已经配置了 API 密钥,如 入门指南.

使用缓存生成内容 #

以下示例演示如何使用缓存的系统指令和视频文件生成内容。

python
import os
import pathlib
import requests
import time

from google import genai
from google.genai import types

client = genai.Client(http_options={"api_version": "v1beta"})

# Download a test video file and save it locally
url = 'https://storage.googleapis.com/generativeai-downloads/data/SherlockJr._10min.mp4'
path_to_video_file = pathlib.Path('SherlockJr._10min.mp4')
if not path_to_video_file.exists():
    path_to_video_file.write_bytes(requests.get(url).content)

# Upload the video using the Files API
video_file = client.files.upload(file=path_to_video_file)

# Wait for the file to finish processing
while video_file.state.name == 'PROCESSING':
    time.sleep(2.5)
    video_file = client.files.get(name=video_file.name)

print(f'Video processing complete: {video_file.uri}')

model='models/gemini-3.8-flash'

# Create a cache with a 5 minute TTL (300 seconds)
cache = client.caches.create(
    model=model,
    config=types.CreateCachedContentConfig(
        display_name='sherlock jr movie', # used to identify the cache
        system_instruction=(
            'You are an expert video analyzer, and your job is to answer '
            'the user\'s query based on the video file you have access to.'
        ),
        contents=[video_file],
        ttl="300s",
    )
)

response = client.models.generate_content(
    model = model,
    contents= (
    'Introduce different characters in the movie by describing '
    'their personality, looks, and names. Also list the timestamps '
    'they were introduced for the first time.'),
    config=types.GenerateContentConfig(cached_content=cache.name)
)

print(response.usage_metadata)

print(response.text)

列出缓存 #

无法检索或查看缓存内容,但您可以检索缓存元数据 (name, model, display_name, usage_metadata, create_time, update_time, 和 expire_time).

要列出所有上传缓存的元数据,请使用 CachedContent.list():

Python
for cache in client.caches.list():
  print(cache)

要获取一个缓存对象的元数据,如果您知道其名称,请使用 get:

Python
client.caches.get(name=name)

更新缓存 #

您可以设置一个新的 ttl 或 expire_time 用于缓存。不支持更改有关缓存的任何其他内容。

以下示例展示了如何更新 ttl 缓存使用 client.caches.update().

python
from google import genai
from google.genai import types

client.caches.update(
  name = cache.name,
  config  = types.UpdateCachedContentConfig(
      ttl='300s'
  )
)

要设置到期时间,它将接受 datetime 对象或 ISO 格式的日期时间字符串 (dt.isoformat(),像 2025-01-27T16:02:36.473528+00:00)。您的时间必须包含时区(datetime.utcnow() 不附加时区, datetime.now(datetime.timezone.utc) 确实附加了时区)。

Python
from google import genai
from google.genai import types
import datetime

# You must use a time zone-aware time.
in10min = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=10)

client.caches.update(
  name = cache.name,
  config  = types.UpdateCachedContentConfig(
      expire_time=in10min
  )
)

删除缓存 #

缓存服务提供删除操作,用于手动从缓存中删除内容。以下示例展示了如何删除缓存:

python
client.caches.delete(cache.name)

使用 OpenAI 库的显式缓存 #

如果您使用的是 OpenAI 库,您可以使用以下命令启用显式缓存 cached_content 属性于 extra_body.

何时使用显式缓存 #

上下文缓存特别适合较短的请求重复引用大量初始上下文的场景。考虑将上下文缓存用于以下用例:

  • 具有广泛功能的聊天机器人 系统指令
  • 冗长视频文件的重复分析
  • 针对大型文档集的重复查询
  • 频繁的代码存储库分析或错误修复

显式缓存如何降低成本 #

上下文缓存是一项付费功能,旨在降低成本。计费基于以下因素:

  1. 缓存 token 计数: 缓存的输入 token 数量,包含在后续提示中时按降低的费率计费。

  2. 储存期限: 缓存 token 的存储时间量 (TTL),根据缓存 token 计数的 TTL 持续时间计费。 TTL 没有最小或最大界限。

  3. 其他因素: 其他费用适用,例如非缓存输入 token 和输出 token。

有关最新定价详细信息,请参阅 Gemini API 定价页面。要了解如何计算 token,请参阅 代币指南.

其他注意事项 #

使用上下文缓存时请记住以下注意事项:

  • 该 最小值 上下文缓存的输入 token 计数因型号而异。的 最大 与给定模型的最大值相同。 (有关计算 token 的更多信息,请参阅 代币指南).

  • 该模型不会对缓存的 token 和常规输入 token 进行任何区分。缓存内容是提示的前缀。

  • 上下文缓存没有特殊的费率或使用限制;标准速率限制 GenerateContent 应用,并且 token 限制包括缓存的 token。

  • 返回缓存的token的数量 usage_metadata 来自缓存服务的创建、获取和列表操作,以及 GenerateContent 使用缓存时。

  • 当请求使用显式缓存时,隐式缓存不适用。与显式缓存一起发送的任何附加输入 token 均按标准输入费率计费。

搜索标题、API 名称或正文内容