Utilizzare una cache di contesto

Puoi utilizzare le API REST o l'SDK Python per fare riferimento ai contenuti archiviati in una cache di contesto in un'applicazione di AI generativa. Prima di poterla utilizzare, devi prima creare la cache di contesto.

L'oggetto cache di contesto che utilizzi nel codice include le seguenti proprietà:

  • name : il nome della risorsa della cache di contesto. Il formato è projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID. Quando crei una cache di contesto, il nome della risorsa viene restituito nella risposta. Il numero del progetto è un identificatore univoco del progetto. L'ID cache è un ID per la cache. Quando specifichi una cache di contesto nel codice, devi utilizzare il nome completo della risorsa della cache di contesto. Di seguito è riportato un esempio che mostra come specificare il nome di una risorsa di contenuti memorizzati nella cache nel corpo di una richiesta:

    "cached_content": "projects/123456789012/locations/us-central1/123456789012345678"
    
  • model : il nome della risorsa del modello utilizzato per creare la cache. Il formato è projects/PROJECT_NUMBER/locations/LOCATION/publishers/PUBLISHER_NAME/models/MODEL_ID.

  • createTime : un Timestamp che specifica l'ora di creazione della cache di contesto.

  • updateTime : un Timestamp che specifica l'ora dell'ultimo aggiornamento di una cache di contesto. Dopo la creazione di una cache di contesto e prima dell'aggiornamento, createTime e updateTime sono uguali.

  • expireTime : un Timestamp che specifica la scadenza di una cache di contesto. Il valore predefinito di expireTime è 60 minuti dopo createTime. Puoi aggiornare la cache con una nuova data di scadenza. Per ulteriori informazioni, vedi Aggiornare la cache di contesto. Una volta scaduta, la cache viene contrassegnata per l'eliminazione e non devi presupporre che possa essere utilizzata o aggiornata. Se devi utilizzare una cache di contesto scaduta, devi ricrearla con una data di scadenza appropriata.

Limitazioni d'uso della cache di contesto

Se le seguenti funzionalità sono specificate quando crei una cache di contesto, non devi specificarle di nuovo nella richiesta:

  • La proprietà GenerativeModel.system_instructions. Questa proprietà viene utilizzata per specificare le istruzioni al modello prima che riceva le istruzioni da un utente. Per ulteriori informazioni, vedi Istruzioni di sistema.

  • La proprietà GenerativeModel.tool_config. La proprietà tool_config viene utilizzata per specificare gli strumenti utilizzati dal modello Gemini, ad esempio uno strumento utilizzato dalla funzionalità di chiamata di funzione.

  • La proprietà GenerativeModel.tools. La proprietà GenerativeModel.tools viene utilizzata per specificare le funzioni per creare un'applicazione di chiamata di funzione. Per ulteriori informazioni, vedi Chiamata di funzione.

Utilizzare un esempio di cache di contesto

Di seguito viene mostrato come utilizzare una cache di contesto. Quando utilizzi una cache di contesto, non puoi specificare le seguenti proprietà:

  • GenerativeModel.system_instructions
  • GenerativeModel.tool_config
  • GenerativeModel.tools

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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
# Use content cache to generate text response
# E.g cache_name = 'projects/.../locations/.../cachedContents/1111111111111111111'
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Summarize the pdfs",
    config=GenerateContentConfig(
        cached_content=cache_name,
    ),
)
print(response.text)
# Example response
#   The Gemini family of multimodal models from Google DeepMind demonstrates remarkable capabilities across various
#   modalities, including image, audio, video, and text....

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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"

	genai "google.golang.org/genai"
)

// useContentCacheWithTxt shows how to use content cache to generate text content.
func useContentCacheWithTxt(w io.Writer, cacheName 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)
	}

	resp, err := client.Models.GenerateContent(ctx,
		"gemini-2.5-flash",
		genai.Text("Summarize the pdfs"),
		&genai.GenerateContentConfig{
			CachedContent: cacheName,
		},
	)
	if err != nil {
		return fmt.Errorf("failed to use content cache to generate content: %w", err)
	}

	respText := resp.Text()

	fmt.Fprintln(w, respText)

	// Example response:
	// The provided research paper introduces Gemini 1.5 Pro, a multimodal model capable of recalling
	// and reasoning over information from very long contexts (up to 10 million tokens).  Key findings include:
	//
	// * **Long Context Performance:**
	// ...

	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=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.HttpOptions;

public class ContentCacheUseWithText {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    // E.g cacheName = "projects/111111111111/locations/global/cachedContents/1111111111111111111"
    String cacheName = "your-cache-name";
    contentCacheUseWithText(modelId, cacheName);
  }

  // Shows how to generate text using cached content
  public static String contentCacheUseWithText(String modelId, String cacheName) {
    // 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()) {

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Summarize the pdfs",
              GenerateContentConfig.builder().cachedContent(cacheName).build());

      System.out.println(response.text());
      // Example response
      // The Gemini family of multimodal models from Google DeepMind demonstrates remarkable
      // capabilities across various
      // modalities, including image, audio, video, and text....
      return response.text();
    }
  }
}

Node.js

Installa

npm install @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=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 useContentCache(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION,
  cacheName = 'example-cache'
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
    httpOptions: {
      apiVersion: 'v1',
    },
  });

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: 'Summarize the pdfs',
    config: {
      cachedContent: cacheName,
    },
  });

  console.log(response.text);

  return response.text;
}
// Example response
//    The Gemini family of multimodal models from Google DeepMind demonstrates remarkable capabilities across various
//    modalities, including image, audio, video, and text....

REST

Puoi utilizzare REST per utilizzare una cache di contesto con un prompt utilizzando l' API Agent Platform per inviare una richiesta POST all'endpoint del modello del publisher.

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

  • PROJECT_ID: il tuo [ID progetto](/resource-manager/docs/creating-managing-projects#identifiers). .
  • LOCATION: la regione in cui è stata elaborata la richiesta di creazione della cache di contesto.
  • PROMPT_TEXT: il prompt di testo da inviare al modello.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-2.0-flash-001:generateContent

Corpo JSON della richiesta:

{
  "cachedContent": "projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
  "contents": [
      {"role":"user","parts":[{"text":"PROMPT_TEXT"}]}
  ],
  "generationConfig": {
      "maxOutputTokens": 8192,
      "temperature": 1,
      "topP": 0.95,
  },
  "safetySettings": [
      {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      },
      {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      },
      {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      },
      {
          "category": "HARM_CATEGORY_HARASSMENT",
          "threshold": "BLOCK_MEDIUM_AND_ABOVE"
      }
  ],
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-2.0-flash-001:generateContent"

PowerShell

Salva il corpo della richiesta in un file denominato request.json, e quindi esegui il comando seguente:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-2.0-flash-001:generateContent" | Select-Object -Expand Content

Dovresti ricevere una risposta JSON simile alla seguente.

Comando curl di esempio

LOCATION="us-central1"
MODEL_ID="gemini-2.5-flash"
PROJECT_ID="test-project"

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent" -d \
'{
  "cachedContent": "projects/${PROJECT_NUMBER}/locations/${LOCATION}/cachedContents/${CACHE_ID}",
  "contents": [
      {"role":"user","parts":[{"text":"What are the benefits of exercise?"}]}
  ],
  "generationConfig": {
      "maxOutputTokens": 8192,
      "temperature": 1,
      "topP": 0.95,
  },
  "safetySettings": [
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    }
  ],
}'

Passaggi successivi