Update context cache expiration

Extend the expiration date of a context cache so that the cache can continue to be used.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

Before trying this sample, follow the C# setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI C# API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

Before trying this sample, follow the Go setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Go API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

Before trying this sample, follow the Python setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Python API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.