在典型的 AI 工作流程中,您可能會重複將相同的輸入權杖傳遞至模型。Gemini API 提供兩種不同的快取機制:
- 隱式快取 (Gemini 2.5 模型會自動啟用,不保證能節省費用)
- 明確快取 (大多數模型可手動啟用,保證節省費用)
如果您想確保節省費用,但願意增加開發人員工作量,則可使用明確快取。
隱含快取
所有 Gemini 2.5 模型都會預設啟用隱式快取功能。如果要求命中快取,系統會自動將節省的費用轉移給您。你不需要採取任何行動,這項異動將於 2025 年 5 月 8 日生效。如要使用內容快取,2.5 Flash 的輸入權杖數下限為 1,024,2.5 Pro 則為 4,096。
如要提高隱含快取命中的機率,請採取下列做法:
- 嘗試在提示開頭放入大型和常見內容
- 嘗試在短時間內傳送具有類似前置字串的要求
您可以在回應物件的 usage_metadata
欄位中,查看快取命中次數。
明確快取
使用 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
中的快取權杖數量。