列出缓存的内容项

此代码示例演示了如何列出给定项目和位置的所有缓存内容项。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Go

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Go 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Go API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
	"google.golang.org/api/iterator"
)

// listContextCaches retrieves all context caches associated with the specified
// Google Cloud project and region
func listContextCaches(w io.Writer, 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()

	cacheList := client.ListCachedContents(ctx)
	// `cacheList` is a standard Google API iterator.
	// See https://pkg.go.dev/google.golang.org/api/iterator#example-package for more details
	for {
		item, err := cacheList.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("listContextCaches failed: %w", err)
		}

		fmt.Fprintf(w, "Cache %q will expire at %v\n", item.Name, item.Expiration.ExpireTime.String())
		// Example response:
		// Cache "projects/.../locations/.../cachedContents/12345678900000000" will expire at 2024-10-25 09:13:58.67004 +0000 UTC
	}

	return nil
}

Python

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Python API 参考文档

如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import vertexai

from vertexai.preview import caching

# TODO(developer): Update & uncomment line below
# PROJECT_ID = "your-project-id"
vertexai.init(project=PROJECT_ID, location="us-central1")

cache_list = caching.CachedContent.list()
# Access individual properties of a CachedContent object
for cached_content in cache_list:
    print(f"Cache '{cached_content.name}' for model '{cached_content.model_name}'")
    print(f"Last updated at: {cached_content.update_time}")
    print(f"Expires at: {cached_content.expire_time}")
    # Example response:
    # Cached content 'example-cache' for model '.../gemini-1.5-pro-001'
    # Last updated at: 2024-09-16T12:41:09.998635Z
    # Expires at: 2024-09-16T13:41:09.989729Z

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器