Membuat cache konteks

Anda harus membuat context cache sebelum dapat menggunakannya. Cache konteks yang Anda buat berisi sejumlah besar data yang dapat Anda gunakan dalam beberapa permintaan ke model Gemini. Konten yang di-cache disimpan di region tempat Anda membuat permintaan untuk membuat cache.

Konten yang di-cache dapat berupa jenis MIME apa pun yang didukung oleh model multimodal Gemini. Misalnya, Anda dapat menyimpan dalam cache sejumlah besar teks, audio, atau video. Anda dapat menentukan lebih dari satu file untuk di-cache. Untuk mengetahui informasi selengkapnya, lihat persyaratan media berikut:

Anda menentukan konten yang akan di-cache menggunakan blob, teks, atau jalur ke file yang disimpan di bucket Cloud Storage. Jika ukuran konten yang Anda-cache lebih besar dari 10 MB, Anda harus menentukannya menggunakan URI file yang disimpan di bucket Cloud Storage.

Masa berlaku konten yang di-cache terbatas. Waktu habis masa berlaku default cache konteks adalah 60 menit setelah dibuat. Jika Anda menginginkan waktu habis masa berlaku yang berbeda, Anda dapat menentukan waktu habis masa berlaku yang berbeda menggunakan properti ttl atau expire_time saat membuat cache konteks. Anda juga dapat memperbarui waktu habis masa berlaku untuk context cache yang belum habis masa berlakunya. Untuk mengetahui informasi tentang cara menentukan ttl dan expire_time, lihat Memperbarui waktu habis masa berlaku.

Setelah cache konteks berakhir, cache tersebut tidak lagi tersedia. Jika Anda ingin merujuk konten dalam context cache yang sudah habis masa berlakunya dalam permintaan perintah mendatang, Anda harus membuat ulang context cache.

Batas

Konten yang Anda simpan dalam cache harus mematuhi batas yang ditampilkan dalam tabel berikut:

Batas context caching

Jumlah token cache minimum

  • 2,048 (Gemini 2.5 Pro)
  • 1,024 (Gemini 2.5 Flash)
  • 1,024 (Gemini 2.0 Flash)
  • 1,024 (Gemini 2.0 Flash-Lite)

Ukuran maksimum konten yang dapat Anda simpan dalam cache menggunakan blob atau teks

10 MB

Waktu minimum sebelum cache berakhir setelah dibuat

1 menit

Waktu maksimum sebelum cache berakhir setelah dibuat

Tidak ada durasi cache maksimum

Dukungan lokasi

Caching konteks tidak didukung di wilayah Sydney, Australia (australia-southeast1).

Dukungan kunci enkripsi

Caching konteks mendukung Kunci Enkripsi yang Dikelola Pelanggan (CMEK), sehingga Anda dapat mengontrol enkripsi data yang di-cache dan melindungi informasi sensitif Anda dengan kunci enkripsi yang Anda kelola dan miliki. Hal ini memberikan lapisan keamanan dan kepatuhan tambahan.

Lihat contoh untuk mengetahui detail selengkapnya.

Dukungan Transparansi Akses

Penyimpanan dalam cache konteks mendukung Transparansi Akses.

Contoh pembuatan context cache

Contoh berikut menunjukkan cara membuat cache konteks.

Gen AI SDK for Python

Instal

pip install --upgrade google-genai

Untuk mempelajari lebih lanjut, lihat dokumentasi referensi SDK.

Tetapkan variabel lingkungan untuk menggunakan Gen AI SDK dengan Vertex AI:

# 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

from google import genai
from google.genai.types import Content, CreateCachedContentConfig, HttpOptions, Part

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.5-flash",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        # (Optional) For enhanced security, the content cache can be encrypted using a Cloud KMS key
        # kms_key_name = "projects/.../locations/us-central1/keyRings/.../cryptoKeys/..."
        display_name="example-cache",
        ttl="86400s",
    ),
)

print(content_cache.name)
print(content_cache.usage_metadata)
# Example response:
#   projects/111111111111/locations/us-central1/cachedContents/1111111111111111111
#   CachedContentUsageMetadata(audio_duration_seconds=None, image_count=167,
#       text_count=153, total_token_count=43130, video_duration_seconds=None)

Gen AI SDK for Go

Pelajari cara menginstal atau mengupdate Gen AI SDK for Go.

Untuk mempelajari lebih lanjut, lihat dokumentasi referensi SDK.

Tetapkan variabel lingkungan untuk menggunakan Gen AI SDK dengan Vertex AI:

# 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 (
	"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: "v1"},
	})
	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",
		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))

	// Example response:
	// {
	//   "name": "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111",
	//   "displayName": "example-cache",
	//   "model": "projects/111111111111/locations/us-central1/publishers/google/models/gemini-2.0-flash-001",
	//   "createTime": "2025-02-18T15:05:08.29468Z",
	//   "updateTime": "2025-02-18T15:05:08.29468Z",
	//   "expireTime": "2025-02-19T15:05:08.280828Z",
	//   "usageMetadata": {
	//     "imageCount": 167,
	//     "textCount": 153,
	//     "totalTokenCount": 43125
	//   }
	// }

	return res.Name, nil
}

REST

Anda dapat menggunakan REST untuk membuat cache konteks menggunakan Vertex AI API guna mengirim permintaan POST ke endpoint model penayang. Contoh berikut menunjukkan cara membuat cache konteks menggunakan file yang disimpan di bucket Cloud Storage.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan dan tempat konten yang di-cache disimpan. Untuk mengetahui daftar region yang didukung, lihat Region yang tersedia.
  • CACHE_DISPLAY_NAME: Nama tampilan yang bermakna untuk mendeskripsikan dan membantu Anda mengidentifikasi setiap cache konteks.
  • MIME_TYPE: Jenis MIME konten yang akan di-cache.
  • CONTENT_TO_CACHE_URI: URI Cloud Storage konten yang akan di-cache.
  • MODEL_ID: Model yang akan digunakan untuk meng-cache.

Metode HTTP dan URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents

Isi JSON permintaan:

{
  "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."
      }]
  }]
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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

Anda akan menerima respons JSON yang mirip dengan yang berikut ini:

Contoh perintah 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}"
          }
        }
      ]
    }
  ]
}'

Membuat context cache dengan CMEK

Untuk menerapkan caching konteks dengan CMEK, buat CMEK dengan mengikuti petunjuknya dan pastikan akun layanan per-produk, per-project Vertex AI (P4SA) memiliki izin Encrypter/Decrypter CryptoKey Cloud KMS yang diperlukan pada kunci tersebut. Hal ini memungkinkan Anda membuat dan mengelola konten yang di-cache secara aman, serta melakukan panggilan lain seperti {List, Update, Delete, Get} CachedContent(s) tanpa berulang kali menentukan kunci KMS.

REST

Anda dapat menggunakan REST untuk membuat cache konteks menggunakan Vertex AI API guna mengirim permintaan POST ke endpoint model penayang. Contoh berikut menunjukkan cara membuat cache konteks menggunakan file yang disimpan di bucket Cloud Storage.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan dan tempat konten yang di-cache disimpan. Untuk mengetahui daftar region yang didukung, lihat Region yang tersedia.
  • MODEL_ID: gemini-2.0-flash-001.
  • CACHE_DISPLAY_NAME: Nama tampilan yang bermakna untuk mendeskripsikan dan membantu Anda mengidentifikasi setiap cache konteks.
  • MIME_TYPE: Jenis MIME konten yang akan di-cache.
  • CACHED_CONTENT_URI: URI Cloud Storage konten yang akan di-cache.
  • KMS_KEY_NAME: Nama kunci Cloud KMS.

Metode HTTP dan URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents

Isi JSON permintaan:

{
  "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"
    }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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

Anda akan menerima respons JSON yang mirip dengan yang berikut ini:

Contoh perintah 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}"
  }
}'

GenAI SDK for Python

Instal

pip install --upgrade google-genai

Untuk mempelajari lebih lanjut, lihat dokumentasi referensi SDK.

Tetapkan variabel lingkungan untuk menggunakan Gen AI SDK dengan Vertex AI:

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

GenAI SDK untuk Go

Pelajari cara menginstal atau mengupdate Gen AI SDK for Go.

Untuk mempelajari lebih lanjut, lihat dokumentasi referensi SDK.

Tetapkan variabel lingkungan untuk menggunakan Gen AI SDK dengan Vertex AI:


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
}

Langkah berikutnya