Actualiza el vencimiento de la caché de contexto

Extiende la fecha de vencimiento de una caché de contexto para que se pueda seguir usando.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C#

Antes de probar este ejemplo, sigue las instrucciones de configuración para C# incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI C#.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar este ejemplo, sigue las instrucciones de configuración para Go incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Go.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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 probar este ejemplo, sigue las instrucciones de configuración para Python incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Python.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .