Atualizar a expiração do cache de contexto

Estender a data de validade de um cache de contexto para que ele possa continuar sendo usado.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C#

Antes de testar esse exemplo, siga as instruções de configuração para C# no Guia de início rápido da Vertex AI sobre como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vertex AI para C#.

Para autenticar na Vertex AI, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


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;
    }
}

Go

Antes de testar esse exemplo, siga as instruções de configuração para Go no Guia de início rápido da Vertex AI sobre como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vertex AI para Go.

Para autenticar na Vertex AI, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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
}

Python

Antes de testar esse exemplo, siga as instruções de configuração para Python no Guia de início rápido da Vertex AI sobre como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Vertex AI para Python.

Para autenticar na Vertex AI, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

A seguir

Para pesquisar e filtrar exemplos de código de outros Google Cloud produtos, consulte a pesquisa de exemplos de código doGoogle Cloud .