Membuat cache konteks

Anda harus membuat cache konteks sebelum dapat menggunakannya. Cache konteks yang Anda buat berisi data dalam jumlah besar 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 dalam cache dapat berupa jenis MIME apa pun yang didukung oleh model multimodal Gemini. Misalnya, Anda dapat menyimpan teks, audio, atau video dalam jumlah besar ke dalam cache. Anda dapat menentukan lebih dari satu file untuk di-cache. Untuk 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 simpan dalam cache lebih dari 10 MB, Anda harus menentukannya menggunakan URI file yang disimpan di bucket Cloud Storage.

Konten dalam cache memiliki masa aktif terbatas. Waktu habis masa berlaku default cache konteks adalah 60 menit setelah dibuat. Jika 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 cache konteks yang belum habis masa berlakunya. Untuk informasi tentang cara menentukan ttl dan expire_time, lihat Memperbarui waktu habis masa berlaku.

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

Batas cache konteks

Konten yang Anda simpan dalam cache harus mematuhi batas berikut:

Batas penyimpanan dalam cache konteks

Ukuran minimum cache

32.769 token

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

10 MB

Waktu minimum sebelum cache berakhir masa berlakunya setelah dibuat

1 menit

Waktu maksimum sebelum cache berakhir masa berlakunya setelah dibuat

Tidak ada durasi cache maksimum

Membuat contoh cache konteks

Contoh berikut menunjukkan cara membuat cache konteks.

Gen AI SDK for Python

Pelajari cara menginstal atau mengupdate Gen AI SDK for Python.

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="v1beta1"))

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-1.5-pro-002",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        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)

Vertex AI SDK untuk Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Vertex AI SDK untuk Python.

import vertexai
import datetime

from vertexai.generative_models import Part
from vertexai.preview import caching

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"

vertexai.init(project=PROJECT_ID, location="us-central1")

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 = [
    Part.from_uri(
        "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
        mime_type="application/pdf",
    ),
    Part.from_uri(
        "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
        mime_type="application/pdf",
    ),
]

cached_content = caching.CachedContent.create(
    model_name="gemini-1.5-pro-002",
    system_instruction=system_instruction,
    contents=contents,
    ttl=datetime.timedelta(minutes=60),
    display_name="example-cache",
)

print(cached_content.name)
# Example response:
# 1234567890

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Go Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/vertexai/genai"
)

// createContextCache shows how to create a cached content, and returns its name.
func createContextCache(w io.Writer, projectID, location, modelName string) (string, error) {
	// location := "us-central1"
	// modelName := "gemini-1.5-pro-001"
	ctx := context.Background()

	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.
    `

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return "", fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	// These PDF are viewable at
	//   https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf
	//   https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf

	part1 := genai.FileData{
		MIMEType: "application/pdf",
		FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
	}

	part2 := genai.FileData{
		MIMEType: "application/pdf",
		FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
	}

	content := &genai.CachedContent{
		Model: modelName,
		SystemInstruction: &genai.Content{
			Parts: []genai.Part{genai.Text(systemInstruction)},
		},
		Expiration: genai.ExpireTimeOrTTL{TTL: 60 * time.Minute},
		Contents: []*genai.Content{
			{
				Role:  "user",
				Parts: []genai.Part{part1, part2},
			},
		},
	}

	result, err := client.CreateCachedContent(ctx, content)
	if err != nil {
		return "", fmt.Errorf("CreateCachedContent: %w", err)
	}
	fmt.Fprint(w, result.Name)
	return result.Name, nil
}

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API C# Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


using Google.Cloud.AIPlatform.V1Beta1;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Threading.Tasks;

public class CreateContextCache
{
    public async Task<CachedContentName> Create(string projectId)
    {
        var client = await new GenAiCacheServiceClientBuilder
        {
            Endpoint = "us-central1-aiplatform.googleapis.com"
        }.BuildAsync();

        var request = new CreateCachedContentRequest
        {
            Parent = $"projects/{projectId}/locations/us-central1",
            CachedContent = new CachedContent
            {
                Model = $"projects/{projectId}/locations/us-central1/publishers/google/models/gemini-1.5-pro-001",
                SystemInstruction = new Content
                {
                    Parts =
                    {
                        new Part { Text = "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 =
                {
                    new Content
                    {
                        Role = "USER",
                        Parts =
                        {
                            new Part { FileData = new() { MimeType = "application/pdf", FileUri = "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf" } },
                            new Part { FileData = new() { MimeType = "application/pdf", FileUri = "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf" } }
                        }
                    }
                },
                Ttl = Duration.FromTimeSpan(TimeSpan.FromMinutes(60))
            }
        };

        var cachedContent = await client.CreateCachedContentAsync(request);
        Console.WriteLine($"Created cache: {cachedContent.CachedContentName}");
        return cachedContent.CachedContentName;
    }
}

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.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-1.5-pro-002",
  "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/v1beta1/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/v1beta1/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-1.5-pro-002"
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/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}/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}"
          }
        }
      ]
    }
  ]
}'

Langkah berikutnya