Memperbarui cache konteks

Anda dapat memperbarui saat cache konteks berakhir masa berlakunya. Waktu habis masa berlaku default cache konteks adalah 60 menit setelah waktu pembuatannya. Cache konteks yang sudah tidak berlaku akan dihapus selama proses pembersihan sampah memori dan tidak dapat digunakan atau diperbarui. Untuk memperbarui waktu habis masa berlaku cache konteks yang belum habis masa berlakunya, perbarui salah satu propertinya berikut:

  • ttl - Jumlah detik dan nanodetik yang digunakan cache setelah dibuat atau setelah ttl diperbarui sebelum masa berlakunya berakhir. Saat Anda menetapkan ttl, expireTime cache akan diperbarui.

  • expire_time - Timestamp yang menentukan tanggal dan waktu absolut saat cache konteks berakhir masa berlakunya.

Memperbarui cache konteks menggunakan parameter ttl-nya

Berikut adalah contoh perintah curl yang memperbarui waktu habis masa berlakunya selama 3.600 detik.

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 datetime import datetime as dt
from datetime import timezone as tz
from datetime import timedelta

from google import genai
from google.genai.types import HttpOptions, UpdateCachedContentConfig

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

# Get content cache by name
# cache_name = "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111"
content_cache = client.caches.get(name=cache_name)
print("Expire time", content_cache.expire_time)
# Example response
#   Expire time 2025-02-20 15:50:18.434482+00:00

# Update expire time using TTL
content_cache = client.caches.update(
    name=cache_name, config=UpdateCachedContentConfig(ttl="36000s")
)
time_diff = content_cache.expire_time - dt.now(tz.utc)
print("Expire time(after update):", content_cache.expire_time)
print("Expire time(in seconds):", time_diff.seconds)
# Example response
#   Expire time(after update): 2025-02-14 01:51:42.571696+00:00
#   Expire time(in seconds): 35999

# Update expire time using specific time stamp
next_week_utc = dt.now(tz.utc) + timedelta(days=7)
content_cache = client.caches.update(
    name=cache_name, config=UpdateCachedContentConfig(expireTime=next_week_utc)
)
print("Expire time(after update):", content_cache.expire_time)
# Example response
#   Expire time(after update): 2025-02-20 15:51:42.614968+00:00

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
from datetime import datetime as dt
from datetime import timezone as tz
from datetime import timedelta

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)

# Option1: Update the context cache using TTL (Time to live)
cached_content.update(ttl=timedelta(hours=3))
cached_content.refresh()

# Option2: Update the context cache using specific time
next_week_utc = dt.now(tz.utc) + timedelta(days=7)
cached_content.update(expire_time=next_week_utc)
cached_content.refresh()

print(cached_content.expire_time)
# Example response:
# 2024-09-11 17:16:45.864520+00:00

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

// updateContextCache shows how to update the expiration time of a cached content, by specifying
// a new TTL (time-to-live duration)
// contentName is the ID of the cached content to update
func updateContextCache(w io.Writer, contentName string, projectID, location string) error {
	// location := "us-central1"
	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()

	cachedContent, err := client.GetCachedContent(ctx, contentName)
	if err != nil {
		return fmt.Errorf("GetCachedContent: %w", err)
	}

	update := &genai.CachedContentToUpdate{
		Expiration: &genai.ExpireTimeOrTTL{TTL: 2 * time.Hour},
	}

	_, err = client.UpdateCachedContent(ctx, cachedContent, update)
	fmt.Fprintf(w, "Updated cached content %q", contentName)
	return err
}

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 UpdateContextCache
{
    public async Task<Timestamp> UpdateExpireTime(CachedContentName name)
    {
        var client = await new GenAiCacheServiceClientBuilder
        {
            Endpoint = "us-central1-aiplatform.googleapis.com"
        }.BuildAsync();

        var cachedContent = await client.GetCachedContentAsync(new GetCachedContentRequest
        {
            CachedContentName = name
        });
        Console.WriteLine($"Original expire time: {cachedContent.ExpireTime}");

        // Update the expiration time by 2 hours
        cachedContent.Ttl = Duration.FromTimeSpan(TimeSpan.FromHours(2));

        var updatedCachedContent = await client.UpdateCachedContentAsync(new UpdateCachedContentRequest
        {
            CachedContent = cachedContent
        });

        Console.WriteLine($"Updated expire time: {updatedCachedContent.ExpireTime}");

        return updatedCachedContent.ExpireTime;
    }
}

REST

Anda dapat menggunakan REST untuk membuat pembaruan cache konteks menggunakan Vertex AI API untuk mengirim permintaan PATCH ke endpoint model penayang. Contoh berikut menunjukkan cara memperbarui tanggal habis masa berlaku menggunakan parameter ttl.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region tempat permintaan untuk membuat cache konteks diproses.
  • CACHE_ID: ID cache konteks. ID cache konteks ditampilkan saat Anda membuat cache konteks. Anda juga dapat menemukan ID cache konteks dengan mencantumkan cache konteks untuk project Google Cloud menggunakan. Untuk informasi selengkapnya, lihat membuat cache konteks dan mencantumkan cache konteks.
  • SECONDS: float yang menentukan komponen detik dari durasi sebelum cache berakhir masa berlakunya.
  • NANOSECONDS: float yang menentukan komponen durasi dalam nanodetik sebelum cache berakhir masa berlakunya.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
  "seconds":"SECONDS",
  "nanos":"NANOSECONDS"
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

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

curl -X PATCH \
-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/CACHE_ID"

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 PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID" | Select-Object -Expand Content

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

Contoh perintah curl

PROJECT_ID="PROJECT_ID"
LOCATION="us-central1"
CACHE_ID="CACHE_ID"

curl \
-X PATCH \
-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/${CACHE_ID}" -d \
'{
   "ttl": {"seconds":"3600","nanos":"0"}
}'

Memperbarui cache konteks menggunakan parameter expire_time-nya

Berikut adalah contoh perintah curl yang menggunakan parameter expire_time untuk memperbarui waktu habis masa berlakunya menjadi pukul 09.00 pada 30 Juni 2024.

REST

Anda dapat menggunakan REST untuk membuat pembaruan cache konteks menggunakan Vertex AI API untuk mengirim permintaan PATCH ke endpoint model penayang. Contoh berikut menunjukkan cara memperbarui tanggal habis masa berlaku menggunakan parameter expire_time.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region tempat permintaan untuk membuat cache konteks diproses.
  • CACHE_ID: ID cache konteks. Anda dapat menemukan ID dalam respons saat membuat cache konteks.
  • EXPIRE_TIME: Timestamp yang menentukan waktu berakhirnya masa berlaku cache konteks.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
   "expire_time":"EXPIRE_TIME"
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

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

curl -X PATCH \
-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/CACHE_ID"

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 PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID" | Select-Object -Expand Content

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

Contoh perintah curl

PROJECT_ID="PROJECT_ID"
LOCATION="us-central1"
CACHE_ID="CACHE_ID"

curl \
-X PATCH \
-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/${CACHE_ID}" -d \
'{
   "expire_time":"2024-06-30T09:00:00.000000Z"
}'

Langkah berikutnya