內容快取

在典型的 AI 工作流程中,您可能會反覆將相同的輸入權杖傳遞至模型。Gemini API 提供兩種不同的快取機制:

  • 隱式快取 (大多數 Gemini 模型會自動啟用,但無法保證節省費用)
  • 明確快取 (大多數模型可手動啟用,保證節省費用)

如果您想確保節省費用,但願意增加開發人員工作量,則可使用明確快取。

隱含快取

隱式快取功能預設為啟用,適用於大多數 Gemini 模型。如果要求命中快取,系統會自動將節省的費用退還給您。這項功能會自動啟用,你無需採取任何行動。這項異動將於 2025 年 5 月 8 日生效。下表列出各模型進行內容快取時的最低輸入權杖數:

型號 最低權杖限制
Gemini 3 Flash 預先發布版 1024
Gemini 3 Pro 預先發布版 4096
Gemini 2.5 Flash 1024
Gemini 2.5 Pro 4096

如要提高隱含快取命中的機率,請採取下列行動:

  • 請嘗試在提示開頭放入大型和常見內容
  • 嘗試在短時間內傳送具有類似前置字串的要求

您可以在回應物件的 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 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-flash-preview'

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

PDF

from google import genai
from google.genai import types
import io
import httpx

client = genai.Client()

long_context_pdf_path = "https://sma.nasa.gov/SignificantIncidents/assets/a11_missionreport.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-3-flash-preview"
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],
    )
)

print(f'{cache=}')

response = client.models.generate_content(
  model=model_name,
  contents="Please summarize this transcript",
  config=types.GenerateContentConfig(
    cached_content=cache.name
  ))

print(f'{response.usage_metadata=}')

print('\n\n', response.text)

列出快取

您無法擷取或查看快取內容,但可以擷取快取中繼資料 (namemodeldisplay_nameusage_metadatacreate_timeupdate_timeexpire_time)。

如要列出所有上傳快取的中繼資料,請使用 CachedContent.list()

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

如要擷取一個快取物件的中繼資料 (如果知道物件名稱),請使用 get

client.caches.get(name=name)

更新快取

您可以為快取設定新的 ttlexpire_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_bodycached_content 屬性啟用明確快取。

使用明確快取的時機

如果較短的要求會重複參照大量初始脈絡,就特別適合使用脈絡快取。請考慮在下列用途使用內容快取:

  • 具有大量系統指令的聊天機器人
  • 重複分析冗長的影片檔案
  • 針對大量文件集重複查詢
  • 經常分析程式碼存放區或修正錯誤

明確快取如何降低成本

情境快取是付費功能,可降低成本。計費依據下列因素:

  1. 快取權杖數:快取的輸入權杖數,如果後續提示包含這些權杖,費用會以較低的費率計算。
  2. 儲存時間:快取權杖的儲存時間 (TTL),費用會根據快取權杖數量的 TTL 時間長度計費。存留時間沒有上下限。
  3. 其他因素:系統會收取其他費用,例如非快取輸入權杖和輸出權杖的費用。

如需最新定價詳細資料,請參閱 Gemini API 定價頁面。如要瞭解如何計算權杖,請參閱權杖指南

其他注意事項

使用內容快取時,請注意下列事項:

  • 不同模型有不同的內容快取最低輸入權杖數。最大值與指定模型的最大值相同。(如要進一步瞭解如何計算權杖,請參閱權杖指南)。
  • 模型不會區分快取權杖和一般輸入權杖。快取內容是提示的前置字元。
  • 內容快取沒有特殊費率或用量限制,適用 GenerateContent 的標準費率限制,且權杖限制包含快取的權杖。
  • 快取服務的建立、取得和列出作業會傳回 usage_metadata 中的快取權杖數量,使用快取時也會傳回 GenerateContent 中的快取權杖數量。