Ottenere informazioni su una cache di contesto

Puoi scoprire l'ora in cui è stata creata una cache del contesto, l'ora in cui è stata aggiornata più di recente e l'ora in cui scade. Per ottenere informazioni su ogni cache contestuale associata a un progetto Google Cloud , inclusi gli ID cache, utilizza il comando per elencare le cache contestuali. Se conosci l'ID cache di una cache di contesto, puoi ottenere informazioni solo su quella cache di contesto.

Ottenere un elenco di cache contestuali

Per ottenere un elenco delle cache contestuali associate a un progetto Google Cloud , devi disporre della regione in cui hai creato il progetto Google Cloud e del relativo ID. Di seguito viene illustrato come ottenere un elenco di cache contestuali per un progetto Google Cloud .

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con 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=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=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/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)
# ...

Go

Scopri come installare o aggiornare Go.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con 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=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=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

Scopri come installare o aggiornare Java.

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con 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=us-central1
export GOOGLE_GENAI_USE_VERTEXAI=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
      // ...
    }
  }
}

REST

Di seguito viene mostrato come utilizzare REST per elencare le cache contestuali associate a un progetto Google Cloud inviando una richiesta GET all'endpoint del modello del publisher.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

Metodo HTTP e URL:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Esegui questo 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

Esegui questo 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

Dovresti ricevere una risposta JSON simile alla seguente:

Comando curl di esempio

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

Ottenere informazioni su una cache del contesto

Per ottenere informazioni su una cache di contesto, devi disporre del relativo ID cache, dell'ID progettoGoogle Cloud a cui è associata la cache di contesto e della regione in cui è stata elaborata la richiesta di creazione della cache di contesto. L'ID cache di una cache di contesto viene restituito quando crei la cache di contesto. Puoi anche ottenere l'ID cache di ogni cache di contesto associata a un progetto utilizzando il comando di elenco della cache di contesto.

Di seguito viene illustrato come ottenere informazioni su una cache del contesto.

Go

Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vertex AI. Per ulteriori informazioni, consulta la documentazione di riferimento dell'SDK Vertex AI Go per Gemini.

Per eseguire l'autenticazione in Vertex AI, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, vedi Configurare ADC per un ambiente di sviluppo locale.

Risposte in streaming e non in streaming

Puoi scegliere se il modello genera risposte in streaming o non in streaming. Per le risposte dinamiche, ricevi ogni risposta non appena viene generato il token di output. Per le risposte non dinamiche, ricevi tutte le risposte dopo la generazione di tutti i token di output.

Per una risposta dinamica, utilizza il metodo GenerateContentStream.

  iter := model.GenerateContentStream(ctx, genai.Text("Tell me a story about a lumberjack and his giant ox. Keep it very short."))
  

Per una risposta non in streaming, utilizza il metodo GenerateContent.

  resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
  

Codice di esempio

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// getContextCache shows how to retrieve the metadata of a cached content
// contentName is the ID of the cached content to retrieve
func getContextCache(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)
	}
	fmt.Fprintf(w, "Retrieved cached content %q", cachedContent.Name)
	return nil
}

REST

Di seguito viene mostrato come utilizzare REST per elencare le cache contestuali associate a un progetto Google Cloud inviando una richiesta GET all'endpoint del modello del publisher.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

Metodo HTTP e URL:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Esegui questo 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

Esegui questo 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

Dovresti ricevere una risposta JSON simile alla seguente:

Comando curl di esempio

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}