內容快取

在典型的 AI 工作流程中,您可能會一再將相同的輸入符記傳遞至模型。使用 Gemini API 情境快取功能,您可以將部分內容傳遞至模型一次,快取輸入符記,然後在後續要求中參照快取的符記。在某些情況下,使用快取符記比重複傳遞相同的符記集合更省錢。

快取一組符記時,您可以選擇快取要保留多久,再自動刪除符記。這個快取時間長度稱為存留時間 (TTL)。如果未設定,TTL 預設為 1 小時。快取的成本取決於輸入符記的大小,以及您希望符記保留多久。

脈絡快取功能支援 Gemini 1.5 Pro 和 Gemini 1.5 Flash。

使用內容快取的時機

在較短要求中重複參照大量初始情境的情況下,情境快取功能特別適合。請考慮在下列用途中使用情境快取:

  • 包含大量系統指示的聊天機器人
  • 重複分析長篇影片檔案
  • 針對大量文件集執行週期性查詢
  • 經常分析或修正程式碼存放區

快取功能如何降低成本

情境快取是一項付費功能,旨在降低整體營運成本。費用則按照下列因素計算:

  1. 快取符號數量:快取的輸入符號數量,如果納入後續提示,則以較低的費率計費。
  2. 儲存時間:快取權杖的儲存時間 (TTL),根據快取權杖數量的 TTL 時間計費。存留時間沒有最低或最高限制。
  3. 其他因素:其他費用也會產生,例如未快取的輸入符記和輸出符記。

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

如何使用脈絡快取

本節假設您已安裝 Gemini SDK (或已安裝 curl),且已設定 API 金鑰,如快速入門所示。

使用快取產生內容

以下範例說明如何使用快取的系統指令和影片檔案產生內容。

import os
import pathlib
import requests
import time

from google import genai
from google.genai import types

# Get your API key from https://aistudio.google.com/app/apikey
# Put it in a "GOOGLE_API_KEY" environment variable.
# For more details, see
# https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb
client = genai.Client()

# Download video file
url = 'https://storage.googleapis.com/generativeai-downloads/data/Sherlock_Jr_FullMovie.mp4'
path_to_video_file = pathlib.Path('Sherlock_Jr_FullMovie.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(path=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-1.5-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)

列出快取

您無法擷取或查看快取內容,但可以擷取快取中繼資料 (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)

其他注意事項

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

  • 快取內容參照的最小輸入符記數量為 32,768,上限則與指定模型的上限相同。(如要進一步瞭解如何計算符記,請參閱「符記指南」)。
  • 模型不會區分快取符記和一般輸入符記。快取內容只是提示的字首。
  • 快取內容沒有特別的頻率或用量限制;系統會套用 GenerateContent 的標準頻率限制,符記限制則包括快取的符記。
  • 快取憑證的數量會在快取服務的建立、取得和清單作業的 usage_metadata 中傳回,也會在使用快取時的 GenerateContent 中傳回。