Menggunakan cache konteks

Anda dapat menggunakan REST API atau Python SDK untuk mereferensikan konten yang disimpan dalam cache konteks dalam aplikasi AI generatif. Sebelum dapat digunakan, Anda harus membuat cache konteks terlebih dahulu.

Objek cache konteks yang Anda gunakan dalam kode menyertakan properti berikut:

  • name - Nama resource cache konteks. Formatnya adalah projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID. Saat membuat cache konteks, Anda dapat menemukan nama resource-nya dalam respons. Nomor project adalah ID unik untuk project Anda. ID cache adalah ID untuk cache Anda. Saat menentukan cache konteks dalam kode, Anda harus menggunakan nama resource cache konteks lengkap. Berikut adalah contoh yang menunjukkan cara menentukan nama resource konten yang di-cache dalam isi permintaan:

    "cached_content": "projects/123456789012/locations/us-central1/123456789012345678"
    
  • model - Nama resource untuk model yang digunakan untuk membuat cache. Formatnya adalah projects/PROJECT_NUMBER/locations/LOCATION/publishers/PUBLISHER_NAME/models/MODEL_ID.

  • createTime - Timestamp yang menentukan waktu pembuatan cache konteks.

  • updateTime - Timestamp yang menentukan waktu pembaruan terbaru cache konteks. Setelah cache konteks dibuat, dan sebelum diupdate, createTime dan updateTime-nya sama.

  • expireTime - Timestamp yang menentukan kapan cache konteks berakhir masa berlakunya. expireTime default adalah 60 menit setelah createTime. Anda dapat memperbarui cache dengan waktu habis masa berlaku baru. Untuk informasi selengkapnya, lihat Memperbarui cache konteks. Setelah masa berlakunya berakhir, cache akan ditandai untuk dihapus dan Anda tidak boleh berasumsi bahwa cache tersebut dapat digunakan atau diperbarui. Jika perlu menggunakan cache konteks yang telah habis masa berlakunya, Anda harus membuatnya ulang dengan waktu habis masa berlaku yang sesuai.

Batasan penggunaan cache konteks

Fitur berikut dapat ditentukan saat Anda membuat cache konteks. Anda tidak boleh menentukannya lagi dalam permintaan:

  • Properti GenerativeModel.system_instructions. Properti ini digunakan untuk menentukan petunjuk ke model sebelum model menerima petunjuk dari pengguna. Untuk mengetahui informasi selengkapnya, lihat Petunjuk sistem.

  • Properti GenerativeModel.tool_config. Properti tool_config digunakan untuk menentukan alat yang digunakan oleh model Gemini, seperti alat yang digunakan oleh fitur panggilan fungsi.

  • Properti GenerativeModel.tools. Properti GenerativeModel.tools digunakan untuk menentukan fungsi guna membuat aplikasi panggilan fungsi. Untuk mengetahui informasi selengkapnya, lihat Panggilan fungsi.

Menggunakan contoh cache konteks

Berikut ini cara menggunakan cache konteks. Saat menggunakan cache konteks, Anda tidak dapat menentukan properti berikut:

  • GenerativeModel.system_instructions
  • GenerativeModel.tool_config
  • GenerativeModel.tools

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 GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1beta1"))

# Use content cache to generate text response
# E.g cache_name = 'projects/111111111111/locations/us-central1/cachedContents/1111111111111111111'
response = client.models.generate_content(
    model="gemini-1.5-pro-002",
    contents="Summarize the pdfs",
    config=GenerateContentConfig(
        cached_content=cache_name,
    ),
)
print(response.text)
# Example response
#   The Gemini family of multimodal models from Google DeepMind demonstrates remarkable capabilities across various
#   modalities, including image, audio, video, and text....

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

from vertexai.preview.generative_models import GenerativeModel
from vertexai.preview import caching

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

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

cached_content = caching.CachedContent(cached_content_name=cache_id)

model = GenerativeModel.from_cached_content(cached_content=cached_content)

response = model.generate_content("What are the papers about?")

print(response.text)
# Example response:
# The provided text is about a new family of multimodal models called Gemini, developed by Google.
# ...

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"
	"errors"
	"fmt"
	"io"

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

// useContextCache shows how to use an existing cached content, when prompting the model
// contentName is the ID of the cached content
func useContextCache(w io.Writer, contentName string, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.5-pro-001"
	ctx := context.Background()

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

	model := client.GenerativeModel(modelName)
	model.CachedContentName = contentName
	prompt := genai.Text("What are the papers about?")

	res, err := model.GenerateContent(ctx, prompt)
	if err != nil {
		return fmt.Errorf("error generating content: %w", err)
	}

	if len(res.Candidates) == 0 ||
		len(res.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	fmt.Fprintf(w, "generated response: %s\n", res.Candidates[0].Content.Parts[0])
	return nil
}

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 System;
using System.Threading.Tasks;

public class UseContextCache
{
    public async Task<string> Use(string projectId, CachedContentName name)
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"us-central1-aiplatform.googleapis.com"
        }.Build();

        var generateContentRequest = new GenerateContentRequest
        {
            CachedContentAsCachedContentName = name,
            Model = $"projects/{projectId}/locations/us-central1/publishers/google/models/gemini-1.5-pro-001",
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { Text = "What are the papers about?" },
                    }
                }
            }
        };

        GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine($"Response: {responseText}");

        return responseText;
    }
}

Anda dapat menggunakan REST untuk menggunakan cache konteks dengan perintah menggunakan Vertex AI API untuk mengirim permintaan POST ke endpoint model penayang.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region tempat permintaan untuk membuat cache konteks diproses.
  • MIME_TYPE: Perintah teks yang akan dikirim ke model.

Metode HTTP dan URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-1.5-pro-002:generateContent

Isi JSON permintaan:

{
  "cachedContent": "projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
  "contents": [
      {"role":"user","parts":[{"text":"PROMPT_TEXT"}]}
  ],
  "generationConfig": {
      "maxOutputTokens": 8192,
      "temperature": 1,
      "topP": 0.95,
  },
  "safetySettings": [
      {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      },
      {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      },
      {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      },
      {
          "category": "HARM_CATEGORY_HARASSMENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      }
  ],
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

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/publishers/google/models/gemini-1.5-pro-002:generateContent"

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/publishers/google/models/gemini-1.5-pro-002:generateContent" | Select-Object -Expand Content

Anda akan melihat respons JSON yang mirip seperti berikut:

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "MODEL_RESPONSE"
          }
        ]
      },
      "finishReason": "STOP",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.21866937,
          "severity": "HARM_SEVERITY_NEGLIGIBLE",
          "severityScore": 0.19946389
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "MEDIUM",
          "probabilityScore": 0.6880493,
          "severity": "HARM_SEVERITY_MEDIUM",
          "severityScore": 0.43374163
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.4442634,
          "severity": "HARM_SEVERITY_LOW",
          "severityScore": 0.37903354
        },
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE",
          "probabilityScore": 0.10502681,
          "severity": "HARM_SEVERITY_LOW",
          "severityScore": 0.28170192
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 55927,
    "candidatesTokenCount": 105,
    "totalTokenCount": 56032
  }
}

Contoh perintah curl

LOCATION="us-central1"
MODEL_ID="gemini-1.5-pro-002"
PROJECT_ID="test-project"

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}:generateContent" -d \
'{
  "cachedContent": "projects/${PROJECT_NUMBER}/locations/${LOCATION}/cachedContents/${CACHE_ID}",
  "contents": [
      {"role":"user","parts":[{"text":"What are the benefits of exercise?"}]}
  ],
  "generationConfig": {
      "maxOutputTokens": 8192,
      "temperature": 1,
      "topP": 0.95,
  },
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    }
  ],
}'