Crea una caché de contexto

Debes crear una caché de contexto antes de poder usarla. La caché de contexto que creas contiene una gran cantidad de datos que puedes usar en varias solicitudes a un modelo de Gemini. El contenido almacenado en caché se almacena en la región en la que realizas la solicitud para crear la caché.

El contenido almacenado en caché puede ser cualquiera de los tipos de MIME compatibles con los modelos multimodales de Gemini. Por ejemplo, puedes almacenar en caché una gran cantidad de texto, audio o video. Puedes especificar más de un archivo para almacenar en caché. Para obtener más información, consulta los siguientes requisitos de medios:

Especificas el contenido que se almacenará en caché con un BLOB, texto o una ruta de acceso a un archivo almacenado en un bucket de Cloud Storage. Si el tamaño del contenido que almacenas en caché es superior a 10 MB, debes especificarlo con el URI de un archivo almacenado en un bucket de Cloud Storage.

El contenido almacenado en caché tiene una vida útil finita. El tiempo de vencimiento predeterminado de una caché de contexto es de 60 minutos después de su creación. Si quieres un tiempo de vencimiento diferente, puedes especificarlo con la propiedad ttl o expire_time cuando crees una caché de contexto. También puedes actualizar la fecha de vencimiento de una caché de contexto que no haya vencido. Para obtener información sobre cómo especificar ttl y expire_time, consulta Actualiza la hora de vencimiento.

Después de que vence una caché de contexto, ya no está disponible. Si quieres hacer referencia al contenido de una caché de contexto vencida en futuras solicitudes de instrucciones, debes volver a crear la caché de contexto.

Límites

El contenido que almacenes en caché debe cumplir con los límites que se muestran en la siguiente tabla:

Límites del almacenamiento de contexto en caché

Cantidad mínima de tokens de caché

  • 2,048 (Gemini 2.5 Pro)
  • 1,024 (Gemini 2.5 Flash)
  • 1,024 (Gemini 2.0 Flash)
  • 1,024 (Gemini 2.0 Flash-Lite)

Tamaño máximo del contenido que puedes almacenar en caché con un BLOB o texto

10 MB

Tiempo mínimo antes de que venza una caché después de su creación

1 minuto

Tiempo máximo antes de que venza una caché después de su creación

No hay una duración máxima de la caché.

Compatibilidad con la ubicación

El almacenamiento en caché del contexto no es compatible con la región de Sídney, Australia (australia-southeast1).

Compatibilidad con claves de encriptación

El almacenamiento en caché de contexto admite las claves de encriptación administradas por el cliente (CMEK), lo que te permite controlar la encriptación de tus datos almacenados en caché y proteger tu información sensible con claves de encriptación que tú administras y posees. Esto proporciona una capa adicional de seguridad y cumplimiento.

Consulta el ejemplo para obtener más detalles.

Compatibilidad con la Transparencia de acceso

La caché de contexto admite la Transparencia de acceso.

Ejemplo de creación de caché de contexto

En los siguientes ejemplos, se muestra cómo crear una caché de contexto.

Python

Instalar

pip install --upgrade google-genai

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

Establece 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 Content, CreateCachedContentConfig, HttpOptions, Part

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

system_instruction = """
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
Now look at these research papers, and answer the following questions.
"""

contents = [
    Content(
        role="user",
        parts=[
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
                mime_type="application/pdf",
            ),
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
                mime_type="application/pdf",
            ),
        ],
    )
]

content_cache = client.caches.create(
    model="gemini-2.5-flash",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        # (Optional) For enhanced security, the content cache can be encrypted using a Cloud KMS key
        # kms_key_name = "projects/.../locations/us-central1/keyRings/.../cryptoKeys/..."
        display_name="example-cache",
        ttl="86400s",
    ),
)

print(content_cache.name)
print(content_cache.usage_metadata)
# Example response:
#   projects/111111111111/locations/us-central1/cachedContents/1111111111111111111
#   CachedContentUsageMetadata(audio_duration_seconds=None, image_count=167,
#       text_count=153, total_token_count=43130, video_duration_seconds=None)

Go

Obtén información para instalar o actualizar Go.

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

Establece 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"
	"encoding/json"
	"fmt"
	"io"
	"time"

	genai "google.golang.org/genai"
)

// createContentCache shows how to create a content cache with an expiration parameter.
func createContentCache(w io.Writer) (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)
	}

	modelName := "gemini-2.0-flash-001"

	systemInstruction := "You are an expert researcher. You always stick to the facts " +
		"in the sources provided, and never make up new facts. " +
		"Now look at these research papers, and answer the following questions."

	cacheContents := []*genai.Content{
		{
			Parts: []*genai.Part{
				{FileData: &genai.FileData{
					FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
					MIMEType: "application/pdf",
				}},
				{FileData: &genai.FileData{
					FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
					MIMEType: "application/pdf",
				}},
			},
			Role: "user",
		},
	}
	config := &genai.CreateCachedContentConfig{
		Contents: cacheContents,
		SystemInstruction: &genai.Content{
			Parts: []*genai.Part{
				{Text: systemInstruction},
			},
		},
		DisplayName: "example-cache",
		TTL:         time.Duration(time.Duration.Seconds(86400)),
	}

	res, err := client.Caches.Create(ctx, modelName, config)
	if err != nil {
		return "", fmt.Errorf("failed to create content cache: %w", err)
	}

	cachedContent, err := json.MarshalIndent(res, "", "  ")
	if err != nil {
		return "", fmt.Errorf("failed to marshal cache info: %w", err)
	}

	// See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
	fmt.Fprintln(w, string(cachedContent))

	// Example response:
	// {
	//   "name": "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111",
	//   "displayName": "example-cache",
	//   "model": "projects/111111111111/locations/us-central1/publishers/google/models/gemini-2.0-flash-001",
	//   "createTime": "2025-02-18T15:05:08.29468Z",
	//   "updateTime": "2025-02-18T15:05:08.29468Z",
	//   "expireTime": "2025-02-19T15:05:08.280828Z",
	//   "usageMetadata": {
	//     "imageCount": 167,
	//     "textCount": 153,
	//     "totalTokenCount": 43125
	//   }
	// }

	return res.Name, nil
}

REST

Puedes usar REST para crear una caché de contexto con la API de Vertex AI para enviar una solicitud POST al extremo del modelo del publicador. En el siguiente ejemplo, se muestra cómo crear una caché de contexto con un archivo almacenado en un bucket de Cloud Storage.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: El ID del proyecto.
  • LOCATION: Es la región en la que se procesa la solicitud y en la que se almacena el contenido almacenado en caché. Para obtener una lista de las regiones compatibles, consulta Regiones disponibles.
  • CACHE_DISPLAY_NAME: Es un nombre visible significativo para describir y ayudarte a identificar cada caché de contexto.
  • MIME_TYPE: Es el tipo de MIME del contenido que se almacenará en caché.
  • CONTENT_TO_CACHE_URI: Es el URI de Cloud Storage del contenido que se almacenará en caché.
  • MODEL_ID: Es el modelo que se usará para el almacenamiento en caché.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID",
  "displayName": "CACHE_DISPLAY_NAME",
  "contents": [{
    "role": "user",
      "parts": [{
        "fileData": {
          "mimeType": "MIME_TYPE",
          "fileUri": "CONTENT_TO_CACHE_URI"
        }
      }]
  },
  {
    "role": "model",
      "parts": [{
        "text": "This is sample text to demonstrate explicit caching."
      }]
  }]
}

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/cachedContents"

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/cachedContents" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

Ejemplo del comando curl

LOCATION="us-central1"
MODEL_ID="gemini-2.0-flash-001"
PROJECT_ID="test-project"
MIME_TYPE="video/mp4"
CACHED_CONTENT_URI="gs://path-to-bucket/video-file-name.mp4"

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}/cachedContents -d \
'{
  "model":"projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}",
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "mimeType": "${MIME_TYPE}",
            "fileUri": "${CACHED_CONTENT_URI}"
          }
        }
      ]
    }
  ]
}'

Crea una caché de contexto con CMEK

Para implementar el almacenamiento en caché del contexto con CMEK, crea una CMEK siguiendo las instrucciones y asegúrate de que la cuenta de servicio (P4SA) de Vertex AI por producto y por proyecto tenga los permisos necesarios de encriptador/desencriptador de CryptoKey de Cloud KMS en la clave. Esto te permite crear y administrar contenido almacenado en caché de forma segura, así como realizar otras llamadas, como {List, Update, Delete, Get} CachedContent(s), sin especificar repetidamente una clave de KMS.

REST

Puedes usar REST para crear una caché de contexto con la API de Vertex AI para enviar una solicitud POST al extremo del modelo del publicador. En el siguiente ejemplo, se muestra cómo crear una caché de contexto con un archivo almacenado en un bucket de Cloud Storage.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: El ID del proyecto.
  • LOCATION: Es la región en la que se procesa la solicitud y en la que se almacena el contenido almacenado en caché. Para obtener una lista de las regiones compatibles, consulta Regiones disponibles.
  • MODEL_ID: gemini-2.0-flash-001.
  • CACHE_DISPLAY_NAME: Es un nombre visible significativo para describir y ayudarte a identificar cada caché de contexto.
  • MIME_TYPE: Es el tipo de MIME del contenido que se almacenará en caché.
  • CACHED_CONTENT_URI: Es el URI de Cloud Storage del contenido que se almacenará en caché.
  • KMS_KEY_NAME: Es el nombre de la clave de Cloud KMS.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-2.0-flash-001",
  "displayName": "CACHE_DISPLAY_NAME",
  "contents": [{
    "role": "user",
      "parts": [{
        "fileData": {
          "mimeType": "MIME_TYPE",
          "fileUri": "CONTENT_TO_CACHE_URI"
        }
      }]}],
    "encryptionSpec": {
      "kmsKeyName": "KMS_KEY_NAME"
    }
}

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/cachedContents"

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/cachedContents" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

Ejemplo del comando curl

LOCATION="us-central1"
MODEL_ID="gemini-2.0-flash-001"
PROJECT_ID="test-project"
MIME_TYPE="video/mp4"
CACHED_CONTENT_URI="gs://path-to-bucket/video-file-name.mp4"
KMS_KEY_NAME="projects/${PROJECT_ID}/locations/{LOCATION}/keyRings/your-key-ring/cryptoKeys/your-key"

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}/cachedContents -d \
'{

"model": "projects/{PROJECT_ID}}/locations/{LOCATION}/publishers/google/models/{MODEL_ID}",
  "contents" : [
    {
      "role": "user",
      "parts": [
        {
          "file_data": {
            "mime_type":"{MIME_TYPE}",
            "file_uri":"{CACHED_CONTENT_URI}"
          }
        }
      ]
    }
  ],
  "encryption_spec" :
  {
    "kms_key_name":"{KMS_KEY_NAME}"
  }
}'

SDK de IA generativa para Python

Instalar

pip install --upgrade google-genai

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

Establece 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 os
from google import genai
from google.genai.types import Content, CreateCachedContentConfig, HttpOptions, Part

os.environ['GOOGLE_CLOUD_PROJECT'] = 'vertexsdk'
os.environ['GOOGLE_CLOUD_LOCATION'] = 'us-central1'
os.environ['GOOGLE_GENAI_USE_VERTEXAI'] = 'True'
  
client = genai.Client(http_options=HttpOptions(api_version="v1"))

system_instruction = """
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
Now look at these research papers, and answer the following questions.
"""

contents = [
    Content(
        role="user",
        parts=[
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
                mime_type="application/pdf",
            ),
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
                mime_type="application/pdf",
            ),
        ],
    )
]

content_cache = client.caches.create(
    model="gemini-2.0-flash-001",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        display_name="example-cache",
        kms_key_name="projects/vertexsdk/locations/us-central1/keyRings/your-project/cryptoKeys/your-key",
        ttl="86400s",
    ),
)

print(content_cache.name)
print(content_cache.usage_metadata)

SDK de IA generativa para Go

Aprende a instalar o actualizar el SDK de IA generativa para Go.

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

Establece variables de entorno para usar el SDK de IA generativa con Vertex AI:


import (
    "context"
    "encoding/json"
    "fmt"
    "io"

    genai "google.golang.org/genai"
)

// createContentCache shows how to create a content cache with an expiration parameter.
func createContentCache(w io.Writer) (string, error) {
    ctx := context.Background()

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

    modelName := "gemini-2.0-flash-001"

    systemInstruction := "You are an expert researcher. You always stick to the facts " +
        "in the sources provided, and never make up new facts. " +
        "Now look at these research papers, and answer the following questions."

    cacheContents := []*genai.Content{
        {
            Parts: []*genai.Part{
                {FileData: &genai.FileData{
                    FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
                    MIMEType: "application/pdf",
                }},
                {FileData: &genai.FileData{
                    FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
                    MIMEType: "application/pdf",
                }},
            },
            Role: "user",
        },
    }
    config := &genai.CreateCachedContentConfig{
        Contents: cacheContents,
        SystemInstruction: &genai.Content{
            Parts: []*genai.Part{
                {Text: systemInstruction},
            },
        },
        DisplayName: "example-cache",
        KmsKeyName:  "projects/vertexsdk/locations/us-central1/keyRings/your-project/cryptoKeys/your-key",
        TTL:         "86400s",
    }

    res, err := client.Caches.Create(ctx, modelName, config)
    if err != nil {
        return "", fmt.Errorf("failed to create content cache: %w", err)
    }

    cachedContent, err := json.MarshalIndent(res, "", "  ")
    if err != nil {
        return "", fmt.Errorf("failed to marshal cache info: %w", err)
    }

    // See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
    fmt.Fprintln(w, string(cachedContent))

    return res.Name, nil
}

¿Qué sigue?