Usar una caché de contexto

Puedes usar las APIs REST o el SDK de Python para hacer referencia al contenido almacenado en una caché de contexto en una aplicación de IA generativa. Antes de poder usarlo, debes crear la caché de contexto.

El objeto de caché de contexto que usas en tu código incluye las siguientes propiedades:

  • name: nombre del recurso de la caché de contexto. Su formato es projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID. Cuando creas una caché de contexto, puedes encontrar su nombre de recurso en la respuesta. El número de proyecto es un identificador único de tu proyecto. El ID de caché es el ID de tu caché. Cuando especifiques una caché de contexto en tu código, debes usar el nombre completo del recurso de caché de contexto. A continuación, se muestra un ejemplo de cómo especificar el nombre de un recurso de contenido almacenado en caché en el cuerpo de una solicitud:

    "cached_content": "projects/123456789012/locations/us-central1/123456789012345678"
    
  • model: nombre del recurso del modelo usado para crear la caché. Su formato es projects/PROJECT_NUMBER/locations/LOCATION/publishers/PUBLISHER_NAME/models/MODEL_ID.

  • createTime: un Timestamp que especifica la hora de creación de la caché de contexto.

  • updateTime: un Timestamp que especifica la hora de la actualización más reciente de una caché de contexto. Después de crear una caché de contexto y antes de actualizarla, sus valores de createTime y updateTime son los mismos.

  • expireTime: un Timestamp que especifica cuándo caduca una caché de contexto. El valor predeterminado expireTime es de 60 minutos después de la createTime. Puedes actualizar la caché con un nuevo tiempo de vencimiento. Para obtener más información, consulta Actualizar la caché de contexto. Cuando caduca una caché, se marca para su eliminación y no debes dar por hecho que se puede usar o actualizar. Si necesitas usar una caché de contexto que ha caducado, debes volver a crearla con un tiempo de caducidad adecuado.

Restricciones de uso de la caché de contexto

Puedes especificar las siguientes funciones al crear una caché de contexto. No debes volver a especificarlos en tu solicitud:

  • La propiedad GenerativeModel.system_instructions. Esta propiedad se usa para especificar instrucciones al modelo antes de que este reciba instrucciones de un usuario. Para obtener más información, consulta las instrucciones del sistema.

  • La propiedad GenerativeModel.tool_config. La propiedad tool_config se usa para especificar las herramientas que utiliza el modelo de Gemini, como una herramienta que usa la función llamadas a funciones.

  • La propiedad GenerativeModel.tools. La propiedad GenerativeModel.tools se usa para especificar funciones con las que crear una aplicación de llamadas a funciones. Para obtener más información, consulta Llamadas a funciones.

Usar una muestra de caché de contexto

A continuación, se muestra cómo usar una caché de contexto. Cuando usas una caché de contexto, no puedes especificar las siguientes propiedades:

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

Python

Instalar

pip install --upgrade google-genai

Para obtener más información, consulta la documentación de referencia del SDK.

Define variables de entorno para usar el SDK de IA generativa 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 GenerateContentConfig, HttpOptions

client = genai.Client(http_options=HttpOptions(api_version="v1"))
# Use content cache to generate text response
# E.g cache_name = 'projects/111111111111/locations/us-central1/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

Consulta cómo instalar o actualizar Go.

Para obtener más información, consulta la documentación de referencia del SDK.

Define variables de entorno para usar el SDK de IA generativa 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"

	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

Consulta cómo instalar o actualizar Java.

Para obtener más información, consulta la documentación de referencia del SDK.

Define variables de entorno para usar el SDK de IA generativa 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.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();
    }
  }
}

REST

Puedes usar REST para usar una caché de contexto con una petición enviando una solicitud POST al endpoint del modelo de editor mediante la API de Vertex AI.

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "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"
      }
  ],
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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

Deberías recibir una respuesta JSON similar a la siguiente.

Comando curl de ejemplo

LOCATION="us-central1"
MODEL_ID="gemini-2.0-flash-001"
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"
    }
  ],
}'