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 contenido multimedia:

Especificas el contenido que se almacenará en caché con un blob, texto o una ruta de acceso a un archivo que se almacena 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 deseas un tiempo de vencimiento diferente, puedes especificarlo con la propiedad ttl o expire_time cuando creas una caché de contexto. También puedes actualizar la fecha de vencimiento de una caché de contexto sin vencer. Para obtener información sobre cómo especificar ttl y expire_time, consulta Actualiza el tiempo de vencimiento.

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

Límites de la caché de contexto

El contenido que almacenes en caché debe cumplir con los siguientes límites:

Límites de almacenamiento en caché de contexto

Tamaño mínimo de una caché

32,769 tokens

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

10 MB

Es el tiempo mínimo antes de que venza una caché después de su creación.

1 minuto

Es el 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é.

Ejemplo de creación de caché de contexto

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

Gen AI SDK for Python

Obtén información para instalar o actualizar Gen AI SDK for Python.

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

Establece variables de entorno para usar el SDK de 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 Content, CreateCachedContentConfig, HttpOptions, Part

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

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-1.5-pro-002",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        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)

SDK de Vertex AI para Python

Si deseas obtener información para instalar o actualizar el SDK de Vertex AI para Python, consulta Instala el SDK de Vertex AI para Python. Si deseas obtener más información, consulta la documentación del SDK de Vertex AI de referencia de la API de Vertex para Python.

import vertexai
import datetime

from vertexai.generative_models import Part
from vertexai.preview import caching

# TODO(developer): Update and un-comment below line
# PROJECT_ID = "your-project-id"

vertexai.init(project=PROJECT_ID, location="us-central1")

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 = [
    Part.from_uri(
        "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
        mime_type="application/pdf",
    ),
    Part.from_uri(
        "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
        mime_type="application/pdf",
    ),
]

cached_content = caching.CachedContent.create(
    model_name="gemini-1.5-pro-002",
    system_instruction=system_instruction,
    contents=contents,
    ttl=datetime.timedelta(minutes=60),
    display_name="example-cache",
)

print(cached_content.name)
# Example response:
# 1234567890

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración para Go incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Go.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"
	"time"

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

// createContextCache shows how to create a cached content, and returns its name.
func createContextCache(w io.Writer, projectID, location, modelName string) (string, error) {
	// location := "us-central1"
	// modelName := "gemini-1.5-pro-001"
	ctx := context.Background()

	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.
    `

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return "", fmt.Errorf("unable to create client: %w", err)
	}
	defer client.Close()

	// These PDF are viewable at
	//   https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf
	//   https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf

	part1 := genai.FileData{
		MIMEType: "application/pdf",
		FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
	}

	part2 := genai.FileData{
		MIMEType: "application/pdf",
		FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
	}

	content := &genai.CachedContent{
		Model: modelName,
		SystemInstruction: &genai.Content{
			Parts: []genai.Part{genai.Text(systemInstruction)},
		},
		Expiration: genai.ExpireTimeOrTTL{TTL: 60 * time.Minute},
		Contents: []*genai.Content{
			{
				Role:  "user",
				Parts: []genai.Part{part1, part2},
			},
		},
	}

	result, err := client.CreateCachedContent(ctx, content)
	if err != nil {
		return "", fmt.Errorf("CreateCachedContent: %w", err)
	}
	fmt.Fprint(w, result.Name)
	return result.Name, nil
}

C#

Antes de probar este ejemplo, sigue las instrucciones de configuración para C# incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI C#.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


using Google.Cloud.AIPlatform.V1Beta1;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Threading.Tasks;

public class CreateContextCache
{
    public async Task<CachedContentName> Create(string projectId)
    {
        var client = await new GenAiCacheServiceClientBuilder
        {
            Endpoint = "us-central1-aiplatform.googleapis.com"
        }.BuildAsync();

        var request = new CreateCachedContentRequest
        {
            Parent = $"projects/{projectId}/locations/us-central1",
            CachedContent = new CachedContent
            {
                Model = $"projects/{projectId}/locations/us-central1/publishers/google/models/gemini-1.5-pro-001",
                SystemInstruction = new Content
                {
                    Parts =
                    {
                        new Part { Text = "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 =
                {
                    new Content
                    {
                        Role = "USER",
                        Parts =
                        {
                            new Part { FileData = new() { MimeType = "application/pdf", FileUri = "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf" } },
                            new Part { FileData = new() { MimeType = "application/pdf", FileUri = "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf" } }
                        }
                    }
                },
                Ttl = Duration.FromTimeSpan(TimeSpan.FromMinutes(60))
            }
        };

        var cachedContent = await client.CreateCachedContentAsync(request);
        Console.WriteLine($"Created cache: {cachedContent.CachedContentName}");
        return cachedContent.CachedContentName;
    }
}

REST

Puedes usar REST para crear una caché de contexto mediante 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 para procesar 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 que describe y te ayuda 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é.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-1.5-pro-002",
  "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/v1beta1/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/v1beta1/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-1.5-pro-002"
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/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}/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}"
          }
        }
      ]
    }
  ]
}'

¿Qué sigue?