Receber informações sobre um cache de contexto

É possível saber mais sobre a hora em que um cache de contexto foi criado, o horário em que foi atualizados recentemente e o tempo de expiração. Para receber informações sobre cada cache de contexto associado a um Google Cloud projeto, incluindo os IDs de cache, use o comando para listar caches de contexto. Se você souber o ID do cache de um contexto é possível conseguir informações apenas sobre esse cache de contexto.

Acessar uma lista de caches de contexto

Para conferir uma lista dos caches de contexto associados a um Google Cloud projeto, você vai precisar a região onde você criou e o ID do seu Google Cloud projeto. Os seguintes mostra como receber uma lista de caches de contexto para um Google Cloud projeto.

Python

Instalar

pip install --upgrade google-genai

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA Generativa do Google com a 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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import HttpOptions

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

content_cache_list = client.caches.list()

# Access individual properties of a ContentCache object(s)
for content_cache in content_cache_list:
    print(f"Cache `{content_cache.name}` for model `{content_cache.model}`")
    print(f"Last updated at: {content_cache.update_time}")
    print(f"Expires at: {content_cache.expire_time}")

# Example response:
# * Cache `projects/111111111111/locations/.../cachedContents/1111111111111111111` for
#       model `projects/111111111111/locations/.../publishers/google/models/gemini-XXX-pro-XXX`
# * Last updated at: 2025-02-13 14:46:42.620490+00:00
# * CachedContentUsageMetadata(audio_duration_seconds=None, image_count=167, text_count=153, total_token_count=43130, video_duration_seconds=None)
# ...

Go

Saiba como instalar ou atualizar o Go.

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA Generativa do Google com a 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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"time"

	"google.golang.org/genai"
)

// listContentCache shows how to retrieve details about cached content.
func listContentCache(w io.Writer) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	// Retrieve cached content metadata
	cache, err := client.Caches.List(ctx, &genai.ListCachedContentsConfig{
		HTTPOptions: &genai.HTTPOptions{
			Headers:    http.Header{"X-Custom-Header": []string{"example"}},
			APIVersion: "v1",
		},
	})
	if err != nil {
		return fmt.Errorf("failed to get content cache: %w", err)
	}

	// Print basic info about the cached content
	fmt.Fprintf(w, "Cache name: %s\n", cache.Name)
	fmt.Fprintf(w, "Display name: %s\n", cache.Items[0].DisplayName)
	fmt.Fprintf(w, "Model: %s\n", cache.Items[0].Model)
	fmt.Fprintf(w, "Create time: %s\n", cache.Items[0].CreateTime.Format(time.RFC3339))
	fmt.Fprintf(w, "Update time: %s\n", cache.Items[0].UpdateTime.Format(time.RFC3339))
	fmt.Fprintf(w, "Expire time: %s (in %s)\n", cache.Items[0].ExpireTime.Format(time.RFC3339), time.Until(cache.Items[0].ExpireTime).Round(time.Second))

	if cache.Items[0].UsageMetadata != nil {
		fmt.Fprintf(w, "Usage metadata: %+v\n", cache.Items[0].UsageMetadata)
	}

	// Example response:
	// Cache name: projects/111111111111/locations/us-central1/cachedContents/1234567890123456789
	// Display name: product_recommendations_prompt
	// Model: models/gemini-2.5-flash
	// Create time: 2025-04-08T02:15:23Z
	// Update time: 2025-04-08T03:05:11Z
	// Expire time: 2025-04-20T03:05:11Z (in 167h59m59s)
	// Usage metadata: &{AudioDurationSeconds:0 ImageCount:167 TextCount:153 TotalTokenCount:43124 VideoDurationSeconds:0}

	return nil
}

Java

Saiba como instalar ou atualizar o Java.

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA Generativa do Google com a 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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.CachedContent;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.ListCachedContentsConfig;

public class ContentCacheList {

  public static void main(String[] args) {
    contentCacheList();
  }

  // Lists all cached contents
  public static void contentCacheList() {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      for (CachedContent content : client.caches.list(ListCachedContentsConfig.builder().build())) {
        content.name().ifPresent(name -> System.out.println("Name: " + name));
        content.model().ifPresent(model -> System.out.println("Model: " + model));
        content.updateTime().ifPresent(time -> System.out.println("Last updated at: " + time));
        content.expireTime().ifPresent(time -> System.out.println("Expires at: " + time));
      }
      // Example response:
      // Name: projects/111111111111/locations/global/cachedContents/1111111111111111111
      // Model:
      // projects/111111111111/locations/global/publishers/google/models/gemini-2.5-flash
      // Last updated at: 2025-07-28T21:54:19.125825Z
      // Expires at: 2025-08-04T21:54:18.328233500Z
      // ...
    }
  }
}

Node.js

Instalar

npm install @google/genai

Para saber mais, consulte a documentação de referência do SDK.

Defina variáveis de ambiente para usar o SDK de IA Generativa do Google com a 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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
async function listContentCaches(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
    httpOptions: {
      apiVersion: 'v1',
    },
  });

  const contentCacheList = await client.caches.list();

  // Access individual properties of a ContentCache object(s)
  const contentCacheNames = [];
  for (const contentCache of contentCacheList.pageInternal) {
    console.log(
      `Cache \`${contentCache.name}\` for model \`${contentCache.model}\``
    );
    console.log(`Last updated at: ${contentCache.updateTime}`);
    console.log(`Expires at: ${contentCache.expireTime}`);
    contentCacheNames.push(contentCache.name);
  }
  console.log(contentCacheNames);

  // Example response:
  //  * Cache `projects/111111111111/locations/us-central1/cachedContents/1111111111111111111` for
  //  model `projects/111111111111/locations/us-central1/publishers/google/models/gemini-XXX-pro-XXX`
  //  * Last updated at: 2025-02-13 14:46:42.620490+00:00
  //  * CachedContentUsageMetadata(audio_duration_seconds=None, image_count=167, text_count=153, total_token_count=43130, video_duration_seconds=None)
  // ...

  return contentCacheNames;
}

REST

A seguir, mostramos como usar o REST para listar os caches de contexto associados a um Google Cloud projeto enviando uma solicitação GET ao endpoint do modelo do publisher.

Antes de usar os dados da solicitação abaixo, faça estas substituições:

Método HTTP e URL:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents

Para enviar a solicitação, escolha uma destas opções:

curl

Execute o seguinte comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents"

PowerShell

Execute o seguinte comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents" | Select-Object -Expand Content

Você receberá uma resposta JSON semelhante a esta:

Exemplo de comando curl

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

curl \
-X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents

Receber informações sobre um cache de contexto

Para conseguir informações sobre um cache de contexto, você precisa do ID do cache, o Google Cloud ID do projeto ao qual o cache de contexto está associado e a região em que a solicitação para criar o cache de contexto foi processado. O ID de um cache de contexto é retornado quando você cria o cache de contexto. Também é possível conseguir o ID de cada cache de contexto associado a um projeto usando o comando de lista de cache de contexto.

Veja a seguir como receber informações sobre um cache de contexto.

Go

Antes de testar esta amostra, siga as instruções de configuração para Go no Guia de início rápido da Agent Platform usando bibliotecas de cliente.

Para autenticar no Agent Platform, configure o Application Default Credentials. Se quiser mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"time"

	"google.golang.org/genai"
)

// getContentCache shows how to retrieve the metadata of a cached content
// contentName is the ID of the cached content to retrieve
func getContentCache(w io.Writer, contentName string) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	cachedContent, err := client.Caches.Get(ctx, contentName, &genai.GetCachedContentConfig{
		HTTPOptions: &genai.HTTPOptions{
			Headers:    http.Header{"X-Custom-Header": []string{"example"}},
			APIVersion: "v1",
		},
	})
	if err != nil {
		return fmt.Errorf("GetCachedContent: %w", err)
	}

	// Print basic info about the cached content
	fmt.Fprintf(w, "Cache name: %s\n", cachedContent.Name)
	fmt.Fprintf(w, "Display name: %s\n", cachedContent.DisplayName)
	fmt.Fprintf(w, "Model: %s\n", cachedContent.Model)
	fmt.Fprintf(w, "Create time: %s\n", cachedContent.CreateTime.Format(time.RFC3339))
	fmt.Fprintf(w, "Update time: %s\n", cachedContent.UpdateTime.Format(time.RFC3339))
	fmt.Fprintf(w, "Expire time: %s (in %s)\n", cachedContent.ExpireTime.Format(time.RFC3339), time.Until(cachedContent.ExpireTime).Round(time.Second))

	if cachedContent.UsageMetadata != nil {
		fmt.Fprintf(w, "Usage metadata: %+v\n", cachedContent.UsageMetadata)
	}

	// Example response:
	// Cache name: projects/111111111111/locations/us-central1/cachedContents/1234567890123456789
	// Display name: product_recommendations_prompt
	// Model: models/gemini-2.5-flash
	// Create time: 2025-04-08T02:15:23Z
	// Update time: 2025-04-08T03:05:11Z
	// Expire time: 2025-04-20T03:05:11Z (in 167h59m59s)
	// Usage metadata: &{AudioDurationSeconds:0 ImageCount:167 TextCount:153 TotalTokenCount:43124 VideoDurationSeconds:0}
	return nil
}

REST

A seguir, mostramos como usar o REST para listar os caches de contexto associados a um Google Cloud projeto enviando uma solicitação GET ao endpoint do modelo do publisher.

Antes de usar os dados da solicitação abaixo, faça estas substituições:

  • PROJECT_ID: .
  • LOCATION: a região onde a solicitação para criar o cache de contexto foi processado.
  • CACHE_ID: o ID do cache de contexto. O ID do cache de contexto é retornado quando você o cria. Você também pode encontrar IDs de cache de contexto listando os caches de contexto de um Google Cloud projeto usando. Para mais informações, consulte criar um cache de contexto e listar caches de contexto.

Método HTTP e URL:

GET https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID

Para enviar a solicitação, escolha uma destas opções:

curl

Execute o seguinte comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID"

PowerShell

Execute o seguinte comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID" | Select-Object -Expand Content

Você receberá uma resposta JSON semelhante a esta:

Exemplo de comando curl

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

curl \
-X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/${CACHE_ID}

A seguir