在典型的 AI 工作流程中,您可能會一再將相同的輸入符記傳遞至模型。Gemini API 提供兩種不同的快取機制:
- 隱含快取 (自動執行,無法保證可節省成本)
- 明確快取 (手動,保證節省成本)
根據預設,Gemini 2.5 模型會啟用隱式快取功能。如果要求包含快取命中的內容,我們會自動將節省的費用轉回給您。
如果您想確保節省成本,但需要額外進行開發人員作業,則可使用明確快取。
Gemini 中有兩個快取層:
- 預先填入快取:為準備產生第一個符記的模型快取。無法在不同模型之間共用。
- 預先處理快取:快取格式化和標記多模態輸入內容,例如影片和 PDF。可供不同模型重複使用
隱含快取
所有 Gemini 2.5 模型都會預設啟用隱式快取功能。如果您的要求命中快取,我們會自動將節省的費用轉嫁給您。您不必採取任何行動即可啟用這項功能。這項政策已於 2025 年 5 月 8 日生效。2.5 Flash 的內容快取最小輸入符記數為 1,024,2.5 Pro 則為 2,048。
如要提高隱含快取命中的機率,請採取以下做法:
- 請嘗試在提示的開頭放入大量常見內容
- 在短時間內嘗試傳送含有類似前置字串的要求
您可以查看回應物件 usage_metadata
欄位中命中快取的符記數量。
節省的費用是以預先填入的快取命中次數來評估。只有預先填入的快取和 YouTube 影片預先處理快取可啟用隱含快取。如要降低其他多模態輸入的 Gemini 呼叫延遲時間,請考慮使用明確快取。
明確快取
您可以使用 Gemini API 明確快取功能,將部分內容傳送至模型一次,快取輸入符記,然後在後續要求中參照快取的符記。在某些情況下,使用快取符記比重複傳遞相同的符記集合更省錢。
快取一組符記時,您可以選擇快取要存在多久,然後符記才會自動刪除。這個快取時間長度稱為存留時間 (TTL)。如果未設定,TTL 預設為 1 小時。快取的成本取決於輸入符記的大小,以及您希望符記保留多久。
本節假設您已安裝 Gemini SDK (或已安裝 curl),且已設定 API 金鑰,如快速入門所示。
使用快取產生內容
以下範例說明如何使用快取的系統指令和影片檔案產生內容。
影片
import os
import pathlib
import requests
import time
from google import genai
from google.genai import types
client = genai.Client()
# Download video file
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():
with path_to_video_file.open('wb') as wf:
response = requests.get(url, stream=True)
for chunk in response.iter_content(chunk_size=32768):
wf.write(chunk)
# 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':
print('Waiting for video to be processed.')
time.sleep(2)
video_file = client.files.get(name=video_file.name)
print(f'Video processing complete: {video_file.uri}')
# You must use an explicit version suffix: "-flash-001", not just "-flash".
model='models/gemini-2.0-flash-001'
# Create a cache with a 5 minute TTL
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",
)
)
# Construct a GenerativeModel which uses the created cache.
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)
# The output should look something like this:
#
# prompt_token_count: 696219
# cached_content_token_count: 696190
# candidates_token_count: 214
# total_token_count: 696433
print(response.text)
from google import genai
from google.genai import types
import io
import httpx
client = genai.Client()
long_context_pdf_path = "https://www.nasa.gov/wp-content/uploads/static/history/alsj/a17/A17_FlightPlan.pdf"
# Retrieve and upload the PDF using the File API
doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content)
document = client.files.upload(
file=doc_io,
config=dict(mime_type='application/pdf')
)
model_name = "gemini-2.0-flash-001"
system_instruction = "You are an expert analyzing transcripts."
# Create a cached content object
cache = client.caches.create(
model=model_name,
config=types.CreateCachedContentConfig(
system_instruction=system_instruction,
contents=[document],
)
)
# Display the cache details
print(f'{cache=}')
# Generate content using the cached prompt and document
response = client.models.generate_content(
model=model_name,
contents="Please summarize this transcript",
config=types.GenerateContentConfig(
cached_content=cache.name
))
# (Optional) Print usage metadata for insights into the API call
print(f'{response.usage_metadata=}')
# Print the generated text
print('\n\n', response.text)
列出快取
您無法擷取或查看快取內容,但可以擷取快取中繼資料 (name
、model
、display_name
、usage_metadata
、create_time
、update_time
和 expire_time
)。
如要列出所有已上傳快取項目的中繼資料,請使用 CachedContent.list()
:
for cache in client.caches.list():
print(cache)
如要擷取快取物件的中繼資料,如果您知道其名稱,請使用 get
:
client.caches.get(name=name)
更新快取
您可以為快取設定新的 ttl
或 expire_time
。系統不支援變更快取的其他內容。
以下範例說明如何使用 client.caches.update()
更新快取的 ttl
。
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)
會附加時區)。
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
)
)
刪除快取
快取服務提供刪除作業,可用於手動從快取中移除內容。以下範例說明如何刪除快取:
client.caches.delete(cache.name)
使用 OpenAI 程式庫進行明確快取
如果您使用的是 OpenAI 程式庫,可以使用 extra_body
上的 cached_content
屬性啟用明確快取。
使用明確快取的時機
脈絡快取功能特別適合用於以下情況:較短的請求會重複參照大量初始脈絡。請考慮在下列用途中使用情境快取:
- 含大量系統指示的聊天機器人
- 重複分析長篇影片檔案
- 針對大量文件集執行週期性查詢
- 經常分析或修正程式碼存放區
明確快取功能如何降低成本
情境快取是一項付費功能,旨在降低整體營運成本。費用則按照下列因素計算:
- 快取符號數量:快取的輸入符號數量,如果納入後續提示,則以較低的費率計費。
- 儲存時間:快取權杖的儲存時間 (TTL),根據快取權杖數量的 TTL 時間收費。存留時間沒有最低或最高限制。
- 其他因素:其他費用也會產生,例如未快取的輸入符記和輸出符記。
如需最新的定價詳細資料,請參閱 Gemini API 定價頁面。如要瞭解如何計算符記,請參閱符記指南。
其他注意事項
使用內容快取時,請注意下列事項:
- 在 2.5 Flash 中,背景資訊快取的最小輸入符記數量為 1,024,在 2.5 Pro 中則為 2,048。最大值與指定模型的最大值相同。(如要進一步瞭解如何計算符記,請參閱「符記指南」)。
- 模型不會區分快取符記和一般輸入符記。快取內容是提示的字首。
- 快取內容沒有特別的頻率或用量限制,而是採用
GenerateContent
的標準頻率限制,符記限制則包含快取的符記。 - 快取憑證的數量會在快取服務的建立、取得和清單作業的
usage_metadata
中傳回,也會在使用快取時的GenerateContent
中傳回。