快取內容可以是 Gemini 多模態模型支援的任何 MIME 類型。舉例來說,您可以快取大量文字、音訊或影片。您可以指定多個要快取的檔案。詳情請參閱下列媒體規定:
您可以使用 Blob、文字或儲存在 Cloud Storage 值區中的檔案路徑,指定要快取的內容。如果快取內容的大小超過 10 MB,則必須使用儲存在 Cloud Storage 值區中的檔案 URI 指定。
快取內容有使用期限,根據預設,背景資訊快取會在建立後 60 分鐘失效。如要設定不同的到期時間,可以在建立內容快取時,使用 ttl
或 expire_time
屬性指定其他到期時間。您也可以更新未過期脈絡快取的到期時間。如要瞭解如何指定 ttl
和 expire_time
,請參閱「更新到期時間」。
內容快取過期後,就無法再使用。如要在日後的提示要求中參照過期的脈絡快取內容,請重新建立脈絡快取。
限制
快取內容必須遵守下表所示的限制:
脈絡快取限制 | |
---|---|
快取權杖數下限 |
|
使用 Blob 或文字可快取的內容大小上限 |
10 MB |
快取建立後失效前的最短時間 |
1 分鐘 |
快取建立後失效前的時間上限 |
快取時間沒有上限 |
支援的地區
澳洲雪梨 (australia-southeast1
) 地區不支援內容快取。
加密金鑰支援
內容快取支援客戶自行管理的加密金鑰 (CMEK),讓您控管快取資料的加密作業,並使用您管理及擁有的加密金鑰保護機密資訊。這項功能可提供額外的安全防護和法規遵循保障。
詳情請參閱範例。
支援資料存取透明化控管機制
情境快取支援資料存取透明化控管機制。
建立脈絡快取範例
下列範例說明如何建立內容快取。
Python
安裝
pip install --upgrade google-genai
詳情請參閱 SDK 參考說明文件。
設定環境變數,透過 Vertex AI 使用 Gen AI SDK:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=us-central1 export GOOGLE_GENAI_USE_VERTEXAI=True
Go
瞭解如何安裝或更新 Go。
詳情請參閱 SDK 參考說明文件。
設定環境變數,透過 Vertex AI 使用 Gen AI SDK:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=us-central1 export GOOGLE_GENAI_USE_VERTEXAI=True
REST
您可以使用 REST,透過 Vertex AI API 向發布者模型端點傳送 POST 要求,藉此建立內容快取。下列範例說明如何使用儲存在 Cloud Storage 值區中的檔案建立內容快取。
使用任何要求資料之前,請先替換以下項目:
- PROJECT_ID:您的專案 ID。
- LOCATION:處理要求的區域,也是儲存快取內容的區域。 如需支援的地區清單,請參閱「可用地區」。
- CACHE_DISPLAY_NAME:有意義的顯示名稱,用於說明及識別每個內容快取。
- MIME_TYPE:要快取的內容 MIME 類型。
- CONTENT_TO_CACHE_URI:要快取內容的 Cloud Storage URI。
- MODEL_ID:用於快取的模型。
HTTP 方法和網址:
POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents
JSON 要求主體:
{ "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID", "displayName": "CACHE_DISPLAY_NAME", "contents": [{ "role": "user", "parts": [{ "fileData": { "mimeType": "MIME_TYPE", "fileUri": "CONTENT_TO_CACHE_URI" } }] }, { "role": "model", "parts": [{ "text": "This is sample text to demonstrate explicit caching." }] }] }
如要傳送要求,請選擇以下其中一個選項:
curl
將要求主體儲存在名為 request.json
的檔案中,然後執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents"
PowerShell
將要求主體儲存在名為 request.json
的檔案中,然後執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents" | Select-Object -Expand Content
您應該會收到類似以下的 JSON 回應:
cURL 指令範例
LOCATION="us-central1"
MODEL_ID="gemini-2.0-flash-001"
PROJECT_ID="test-project"
MIME_TYPE="video/mp4"
CACHED_CONTENT_URI="gs://path-to-bucket/video-file-name.mp4"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents -d \
'{
"model":"projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}",
"contents": [
{
"role": "user",
"parts": [
{
"fileData": {
"mimeType": "${MIME_TYPE}",
"fileUri": "${CACHED_CONTENT_URI}"
}
}
]
}
]
}'
使用 CMEK 建立脈絡快取
如要使用 CMEK 實作內容快取,請按照操作說明建立 CMEK,並確保 Vertex AI 每個產品/專案的服務帳戶 (P4SA) 具備金鑰的必要 Cloud KMS CryptoKey 加密者/解密者權限。這樣一來,您就能安全地建立及管理快取內容,並進行其他呼叫 (例如 {List
、Update
、Delete
、Get
} CachedContent
(s)),不必重複指定 KMS 金鑰。
REST
您可以使用 REST,透過 Vertex AI API 向發布者模型端點傳送 POST 要求,藉此建立內容快取。下列範例說明如何使用儲存在 Cloud Storage 值區中的檔案建立內容快取。
使用任何要求資料之前,請先替換以下項目:
- PROJECT_ID:。
- LOCATION:處理要求的區域,也是儲存快取內容的區域。 如需支援的地區清單,請參閱「可用地區」。
- MODEL_ID:gemini-2.0-flash-001。
- CACHE_DISPLAY_NAME:有意義的顯示名稱,用於說明及識別每個內容快取。
- MIME_TYPE:要快取的內容 MIME 類型。
- CACHED_CONTENT_URI:要快取內容的 Cloud Storage URI。
- KMS_KEY_NAME:Cloud KMS 金鑰名稱。
HTTP 方法和網址:
POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents
JSON 要求主體:
{ "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-2.0-flash-001", "displayName": "CACHE_DISPLAY_NAME", "contents": [{ "role": "user", "parts": [{ "fileData": { "mimeType": "MIME_TYPE", "fileUri": "CONTENT_TO_CACHE_URI" } }]}], "encryptionSpec": { "kmsKeyName": "KMS_KEY_NAME" } }
如要傳送要求,請選擇以下其中一個選項:
curl
將要求主體儲存在名為 request.json
的檔案中,然後執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents"
PowerShell
將要求主體儲存在名為 request.json
的檔案中,然後執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents" | Select-Object -Expand Content
您應該會收到類似以下的 JSON 回應:
cURL 指令範例
LOCATION="us-central1"
MODEL_ID="gemini-2.0-flash-001"
PROJECT_ID="test-project"
MIME_TYPE="video/mp4"
CACHED_CONTENT_URI="gs://path-to-bucket/video-file-name.mp4"
KMS_KEY_NAME="projects/${PROJECT_ID}/locations/{LOCATION}/keyRings/your-key-ring/cryptoKeys/your-key"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents -d \
'{
"model": "projects/{PROJECT_ID}}/locations/{LOCATION}/publishers/google/models/{MODEL_ID}",
"contents" : [
{
"role": "user",
"parts": [
{
"file_data": {
"mime_type":"{MIME_TYPE}",
"file_uri":"{CACHED_CONTENT_URI}"
}
}
]
}
],
"encryption_spec" :
{
"kms_key_name":"{KMS_KEY_NAME}"
}
}'
Python 適用的 GenAI SDK
安裝
pip install --upgrade google-genai
詳情請參閱 SDK 參考說明文件。
設定環境變數,以便搭配 Vertex AI 使用 Gen AI SDK:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=True
import os
from google import genai
from google.genai.types import Content, CreateCachedContentConfig, HttpOptions, Part
os.environ['GOOGLE_CLOUD_PROJECT'] = 'vertexsdk'
os.environ['GOOGLE_CLOUD_LOCATION'] = 'us-central1'
os.environ['GOOGLE_GENAI_USE_VERTEXAI'] = 'True'
client = genai.Client(http_options=HttpOptions(api_version="v1"))
system_instruction = """
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
Now look at these research papers, and answer the following questions.
"""
contents = [
Content(
role="user",
parts=[
Part.from_uri(
file_uri="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
mime_type="application/pdf",
),
Part.from_uri(
file_uri="gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
mime_type="application/pdf",
),
],
)
]
content_cache = client.caches.create(
model="gemini-2.0-flash-001",
config=CreateCachedContentConfig(
contents=contents,
system_instruction=system_instruction,
display_name="example-cache",
kms_key_name="projects/vertexsdk/locations/us-central1/keyRings/your-project/cryptoKeys/your-key",
ttl="86400s",
),
)
print(content_cache.name)
print(content_cache.usage_metadata)
Go 適用的 GenAI SDK
瞭解如何安裝或更新 Go 專用的 Gen AI SDK。
詳情請參閱 SDK 參考說明文件。
設定環境變數,以便搭配 Vertex AI 使用 Gen AI SDK:
import (
"context"
"encoding/json"
"fmt"
"io"
genai "google.golang.org/genai"
)
// createContentCache shows how to create a content cache with an expiration parameter.
func createContentCache(w io.Writer) (string, error) {
ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1beta1"},
})
if err != nil {
return "", fmt.Errorf("failed to create genai client: %w", err)
}
modelName := "gemini-2.0-flash-001"
systemInstruction := "You are an expert researcher. You always stick to the facts " +
"in the sources provided, and never make up new facts. " +
"Now look at these research papers, and answer the following questions."
cacheContents := []*genai.Content{
{
Parts: []*genai.Part{
{FileData: &genai.FileData{
FileURI: "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
MIMEType: "application/pdf",
}},
{FileData: &genai.FileData{
FileURI: "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
MIMEType: "application/pdf",
}},
},
Role: "user",
},
}
config := &genai.CreateCachedContentConfig{
Contents: cacheContents,
SystemInstruction: &genai.Content{
Parts: []*genai.Part{
{Text: systemInstruction},
},
},
DisplayName: "example-cache",
KmsKeyName: "projects/vertexsdk/locations/us-central1/keyRings/your-project/cryptoKeys/your-key",
TTL: "86400s",
}
res, err := client.Caches.Create(ctx, modelName, config)
if err != nil {
return "", fmt.Errorf("failed to create content cache: %w", err)
}
cachedContent, err := json.MarshalIndent(res, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal cache info: %w", err)
}
// See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
fmt.Fprintln(w, string(cachedContent))
return res.Name, nil
}
後續步驟
- 瞭解如何使用脈絡快取。
- 瞭解如何更新脈絡快取的到期時間。