Caching

El almacenamiento de contexto en caché te permite guardar y reutilizar tokens de entrada precalculados que deseas usar repetidamente, por ejemplo, cuando haces diferentes preguntas sobre el mismo archivo multimedia. Esto puede generar ahorros de costos y tiempo, según el uso. Para obtener una introducción detallada, consulta la guía Almacenamiento en caché del contexto.

Método: cachedContents.create

Crea un recurso CachedContent.

Extremo

post https://generativelanguage.googleapis.com/v1beta/cachedContents

Cuerpo de la solicitud

El cuerpo de la solicitud contiene una instancia de CachedContent.

Campos
contents[] object (Content)

Opcional. Solo entrada. Inmutable. Es el contenido que se almacenará en caché.

tools[] object (Tool)

Opcional. Solo entrada. Inmutable. Es una lista de Tools que el modelo puede usar para generar la siguiente respuesta.

expiration Union type
Especifica cuándo vencerá este recurso. expiration puede ser una de las siguientes opciones:
expireTime string (Timestamp format)

Marca de tiempo en UTC del momento en que este recurso se consideró vencido. Esto siempre se proporciona en la salida, sin importar si se envió en la entrada.

Usa el formato RFC 3339, en el que el resultado generado siempre usará la normalización Z y los dígitos fraccionarios 0, 3, 6 o 9. También se aceptan otras compensaciones que no sean “Z”. Ejemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" o "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Solo entrada. Es el nuevo TTL para este recurso (solo entrada).

Una duración en segundos con hasta nueve dígitos decimales, que terminan en “s”. Ejemplo: "3.5s".

displayName string

Opcional. Inmutable. Es el nombre visible significativo del contenido almacenado en caché que generó el usuario. Se pueden utilizar 128 caracteres Unicode como máximo.

model string

Obligatorio. Inmutable. Nombre del Model que se usará para el contenido almacenado en caché. Formato: models/{model}

systemInstruction object (Content)

Opcional. Solo entrada. Inmutable. Es la instrucción del sistema establecida por el desarrollador. Por el momento, solo se admite texto.

toolConfig object (ToolConfig)

Opcional. Solo entrada. Inmutable. Configuración de la herramienta Esta configuración se comparte para todas las herramientas.

Ejemplo de solicitud

Básico

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
print(cache)

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
console.log("Cache created:", cache);

const response = await ai.models.generateContent({
  model: modelName,
  contents: "Please summarize this transcript",
  config: { cachedContent: cache.name },
});
console.log("Response text:", response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"), 
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache created:")
fmt.Println(cache)

// Use the cache for generating content.
response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Please summarize this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

Almeja

wget https://storage.googleapis.com/generativeai-downloads/data/a11.txt
echo '{
  "model": "models/gemini-1.5-flash-001",
  "contents":[
    {
      "parts":[
        {
          "inline_data": {
            "mime_type":"text/plain",
            "data": "'$(base64 $B64FLAGS a11.txt)'"
          }
        }
      ],
    "role": "user"
    }
  ],
  "systemInstruction": {
    "parts": [
      {
        "text": "You are an expert at analyzing transcripts."
      }
    ]
  },
  "ttl": "300s"
}' > request.json

curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d @request.json \
 > cache.json

CACHE_NAME=$(cat cache.json | grep '"name":' | cut -d '"' -f 4 | head -n 1)

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-001:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
      "contents": [
        {
          "parts":[{
            "text": "Please summarize this transcript"
          }],
          "role": "user"
        },
      ],
      "cachedContent": "'$CACHE_NAME'"
    }'

Nombre del remitente

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
cache_name = cache.name  # Save the name for later

# Later retrieve the cache
cache = client.caches.get(name=cache_name)
response = client.models.generate_content(
    model=model_name,
    contents="Find a lighthearted moment from this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
const cacheName = cache.name; // Save the name for later

// Later retrieve the cache
const retrievedCache = await ai.caches.get({ name: cacheName });
const response = await ai.models.generateContent({
  model: modelName,
  contents: "Find a lighthearted moment from this transcript",
  config: { cachedContent: retrievedCache.name },
});
console.log("Response text:", response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
cacheName := cache.Name

// Later retrieve the cache.
cache, err = client.Caches.Get(ctx, cacheName, &genai.GetCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}

response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Find a lighthearted moment from this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Response from cache (create from name):")
printResponse(response)

Desde el chat

Python

from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-3.7-flash"
system_instruction = "You are an expert analyzing transcripts."

# Create a chat session with the given system instruction.
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(system_instruction=system_instruction),
)
document = client.files.upload(file=media / "a11.txt")

response = chat.send_message(
    message=["Hi, could you summarize this transcript?", document]
)
print("\n\nmodel:  ", response.text)
response = chat.send_message(
    message=["Okay, could you tell me more about the trans-lunar injection"]
)
print("\n\nmodel:  ", response.text)

# To cache the conversation so far, pass the chat history as the list of contents.
cache = client.caches.create(
    model=model_name,
    config={
        "contents": chat.get_history(),
        "system_instruction": system_instruction,
    },
)
# Continue the conversation using the cached content.
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(cached_content=cache.name),
)
response = chat.send_message(
    message="I didn't understand that last part, could you explain it in simpler language?"
)
print("\n\nmodel:  ", response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const modelName = "gemini-3.7-flash";
const systemInstruction = "You are an expert analyzing transcripts.";

// Create a chat session with the system instruction.
const chat = ai.chats.create({
  model: modelName,
  config: { systemInstruction: systemInstruction },
});
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);

let response = await chat.sendMessage({
  message: createUserContent([
    "Hi, could you summarize this transcript?",
    createPartFromUri(document.uri, document.mimeType),
  ]),
});
console.log("\n\nmodel:", response.text);

response = await chat.sendMessage({
  message: "Okay, could you tell me more about the trans-lunar injection",
});
console.log("\n\nmodel:", response.text);

// To cache the conversation so far, pass the chat history as the list of contents.
const chatHistory = chat.getHistory();
const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: chatHistory,
    systemInstruction: systemInstruction,
  },
});

// Continue the conversation using the cached content.
const chatWithCache = ai.chats.create({
  model: modelName,
  config: { cachedContent: cache.name },
});
response = await chatWithCache.sendMessage({
  message:
    "I didn't understand that last part, could you explain it in simpler language?",
});
console.log("\n\nmodel:", response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
systemInstruction := "You are an expert analyzing transcripts."

// Create initial chat with a system instruction.
chat, err := client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
	SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
}, nil)
if err != nil {
	log.Fatal(err)
}

document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}

// Send first message with the transcript.
parts := make([]genai.Part, 2)
parts[0] = genai.Part{Text: "Hi, could you summarize this transcript?"}
parts[1] = genai.Part{
	FileData: &genai.FileData{
		FileURI :      document.URI,
		MIMEType: document.MIMEType,
	},
}

// Send chat message.
resp, err := chat.SendMessage(ctx, parts...)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

resp, err = chat.SendMessage(
	ctx, 
	genai.Part{
		Text: "Okay, could you tell me more about the trans-lunar injection",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

// To cache the conversation so far, pass the chat history as the list of contents.
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          chat.History(false),
	SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
})
if err != nil {
	log.Fatal(err)
}

// Continue the conversation using the cached history.
chat, err = client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
	CachedContent: cache.Name,
}, nil)
if err != nil {
	log.Fatal(err)
}

resp, err = chat.SendMessage(
	ctx, 
	genai.Part{
		Text: "I didn't understand that last part, could you explain it in simpler language?",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

Cuerpo de la respuesta

Si el proceso se realiza de forma correcta, el cuerpo de la respuesta contiene una instancia recién creada de CachedContent.

Método: cachedContents.list

Enumera los objetos CachedContent.

Extremo

get https://generativelanguage.googleapis.com/v1beta/cachedContents

Parámetros de consulta

pageSize integer

Opcional. Es la cantidad máxima de contenido almacenado en caché que se devolverá. El servicio puede mostrar menos que este valor. Si no se especifica, se devolverá una cantidad predeterminada de elementos (inferior al máximo). El valor máximo es 1,000; valores superiores a 1,000 se convertirán en 1,000.

pageToken string

Opcional. Un token de página, recibido desde una llamada cachedContents.list anterior. Proporciona esto para recuperar la página siguiente.

Cuando se pagina, todos los demás parámetros proporcionados a cachedContents.list deben coincidir con la llamada que proporcionó el token de la página.

Cuerpo de la solicitud

El cuerpo de la solicitud debe estar vacío.

Cuerpo de la respuesta

Es la respuesta con la lista de CachedContents.

Si se ejecuta correctamente, el cuerpo de la respuesta contendrá datos con la siguiente estructura:

Campos
cachedContents[] object (CachedContent)

Es una lista del contenido almacenado en caché.

nextPageToken string

Un token, que se puede enviar como pageToken para recuperar la página siguiente. Si se omite este campo, no habrá páginas siguientes.

Representación JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Método: cachedContents.get

Lee el recurso CachedContent.

Extremo

get https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

Parámetros de ruta

name string

Obligatorio. Es el nombre del recurso que hace referencia a la entrada de caché de contenido. Formato: cachedContents/{id} Toma la forma cachedContents/{cachedcontent}.

Cuerpo de la solicitud

El cuerpo de la solicitud debe estar vacío.

Ejemplo de solicitud

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
print(client.caches.get(name=cache.name))

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
const retrievedCache = await ai.caches.get({ name: cache.name });
console.log("Retrieved Cache:", retrievedCache);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

cache, err = client.Caches.Get(ctx, cache.Name, &genai.GetCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Retrieved cache:")
fmt.Println(cache)

Almeja

curl "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY"

Cuerpo de la respuesta

Si se ejecuta de forma correcta, el cuerpo de la respuesta contiene una instancia de CachedContent.

Método: cachedContents.patch

Actualiza el recurso CachedContent (solo se puede actualizar la fecha de vencimiento).

Extremo

patch https://generativelanguage.googleapis.com/v1beta/{cachedContent.name=cachedContents/*}

PATCH https://generativelanguage.googleapis.com/v1beta/{cachedContent.name=cachedContents/*}

Parámetros de ruta

cachedContent.name string

Solo salida. Es el identificador. Nombre del recurso que hace referencia al contenido almacenado en caché. Formato: cachedContents/{id} Toma la forma cachedContents/{cachedcontent}.

Parámetros de consulta

updateMask string (FieldMask format)

La lista de campos que se deben actualizar.

Esta es una lista separada por comas de los nombres de campos totalmente calificados. Ejemplo: "user.displayName,photo".

Cuerpo de la solicitud

El cuerpo de la solicitud contiene una instancia de CachedContent.

Campos
expiration Union type
Especifica cuándo vencerá este recurso. expiration puede ser una de las siguientes opciones:
expireTime string (Timestamp format)

Marca de tiempo en UTC del momento en que este recurso se consideró vencido. Esto siempre se proporciona en la salida, sin importar si se envió en la entrada.

Usa el formato RFC 3339, en el que el resultado generado siempre usará la normalización Z y los dígitos fraccionarios 0, 3, 6 o 9. También se aceptan otras compensaciones que no sean “Z”. Ejemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" o "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Solo entrada. Es el nuevo TTL para este recurso (solo entrada).

Una duración en segundos con hasta nueve dígitos decimales, que terminan en “s”. Ejemplo: "3.5s".

Ejemplo de solicitud

Python

from google import genai
from google.genai import types
import datetime

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)

# Update the cache's time-to-live (ttl)
ttl = f"{int(datetime.timedelta(hours=2).total_seconds())}s"
client.caches.update(
    name=cache.name, config=types.UpdateCachedContentConfig(ttl=ttl)
)
print(f"After update:\n {cache}")

# Alternatively, update the expire_time directly
# Update the expire_time directly in valid RFC 3339 format (UTC with a "Z" suffix)
expire_time = (
    (
        datetime.datetime.now(datetime.timezone.utc)
        + datetime.timedelta(minutes=15)
    )
    .isoformat()
    .replace("+00:00", "Z")
)
client.caches.update(
    name=cache.name,
    config=types.UpdateCachedContentConfig(expire_time=expire_time),
)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

let cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});

// Update the cache's time-to-live (ttl)
const ttl = `${2 * 3600}s`; // 2 hours in seconds
cache = await ai.caches.update({
  name: cache.name,
  config: { ttl },
});
console.log("After update (TTL):", cache);

// Alternatively, update the expire_time directly (in RFC 3339 format with a "Z" suffix)
const expireTime = new Date(Date.now() + 15 * 60000)
  .toISOString()
  .replace(/\.\d{3}Z$/, "Z");
cache = await ai.caches.update({
  name: cache.name,
  config: { expireTime: expireTime },
});
console.log("After update (expire_time):", cache);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache deleted:", cache.Name)

Almeja

curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d '{"ttl": "600s"}'

Cuerpo de la respuesta

Si se ejecuta de forma correcta, el cuerpo de la respuesta contiene una instancia de CachedContent.

Método: cachedContents.delete

Borra el recurso CachedContent.

Extremo

delete https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

Parámetros de ruta

name string

Obligatorio. Es el nombre del recurso que hace referencia a la entrada de la caché de contenido. Formato: cachedContents/{id}. Toma la forma cachedContents/{cachedcontent}.

Cuerpo de la solicitud

El cuerpo de la solicitud debe estar vacío.

Ejemplo de solicitud

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
await ai.caches.delete({ name: cache.name });
console.log("Cache deleted:", cache.name);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache deleted:", cache.Name)

Almeja

curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY"

Cuerpo de la respuesta

Si se ejecuta correctamente, el cuerpo de la respuesta es un objeto JSON vacío.

Recurso de REST: cachedContents

Recurso: CachedContent

Es el contenido que se procesó previamente y que se puede usar en solicitudes posteriores a GenerativeService.

El contenido almacenado en caché solo se puede usar con el modelo para el que se creó.

Campos
contents[] object (Content)

Opcional. Solo entrada. Inmutable. Es el contenido que se almacenará en caché.

tools[] object (Tool)

Opcional. Solo entrada. Inmutable. Es una lista de Tools que el modelo puede usar para generar la siguiente respuesta.

createTime string (Timestamp format)

Solo salida. Es la fecha y hora de creación de la entrada de caché.

Usa el formato RFC 3339, en el que el resultado generado siempre usará la normalización Z y los dígitos fraccionarios 0, 3, 6 o 9. También se aceptan otras compensaciones que no sean “Z”. Ejemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" o "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Solo salida. Fecha y hora en que se actualizó la entrada de caché por última vez en hora UTC.

Usa el formato RFC 3339, en el que el resultado generado siempre usará la normalización Z y los dígitos fraccionarios 0, 3, 6 o 9. También se aceptan otras compensaciones que no sean “Z”. Ejemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" o "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

Solo salida. Son metadatos sobre el uso del contenido almacenado en caché.

expiration Union type
Especifica cuándo vencerá este recurso. expiration puede ser una de las siguientes opciones:
expireTime string (Timestamp format)

Marca de tiempo en UTC del momento en que este recurso se consideró vencido. Esto siempre se proporciona en la salida, sin importar si se envió en la entrada.

Usa el formato RFC 3339, en el que el resultado generado siempre usará la normalización Z y los dígitos fraccionarios 0, 3, 6 o 9. También se aceptan otras compensaciones que no sean “Z”. Ejemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" o "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Solo entrada. Es el nuevo TTL para este recurso (solo entrada).

Una duración en segundos con hasta nueve dígitos decimales, que terminan en “s”. Ejemplo: "3.5s".

name string

Solo salida. Es el identificador. Nombre del recurso que hace referencia al contenido almacenado en caché. Formato: cachedContents/{id}

displayName string

Opcional. Inmutable. Es el nombre visible significativo del contenido almacenado en caché que generó el usuario. Se pueden utilizar 128 caracteres Unicode como máximo.

model string

Obligatorio. Inmutable. Nombre del Model que se usará para el contenido almacenado en caché. Formato: models/{model}

systemInstruction object (Content)

Opcional. Solo entrada. Inmutable. Es la instrucción del sistema establecida por el desarrollador. Por el momento, solo se admite texto.

toolConfig object (ToolConfig)

Opcional. Solo entrada. Inmutable. Configuración de la herramienta Esta configuración se comparte para todas las herramientas.

Representación JSON
{
  "contents": [
    {
      object (Content)
    }
  ],
  "tools": [
    {
      object (Tool)
    }
  ],
  "createTime": string,
  "updateTime": string,
  "usageMetadata": {
    object (UsageMetadata)
  },

  // expiration
  "expireTime": string,
  "ttl": string
  // Union type
  "name": string,
  "displayName": string,
  "model": string,
  "systemInstruction": {
    object (Content)
  },
  "toolConfig": {
    object (ToolConfig)
  }
}

ToolConfig

Es la configuración de la herramienta que contiene parámetros para especificar el uso de Tool en la solicitud.

Campos
functionCallingConfig object (FunctionCallingConfig)

Opcional. Es la configuración de la llamada a función.

retrievalConfig object (RetrievalConfig)

Opcional. Es la configuración de recuperación.

includeServerSideToolInvocations boolean

Opcional. Si es verdadero, la respuesta de la API incluirá las llamadas y respuestas de herramientas del servidor dentro del mensaje Content. Esto permite que los clientes observen las interacciones de la herramienta del servidor.

Representación JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

Es la configuración para especificar el comportamiento de las llamadas a funciones.

Campos
mode enum (Mode)

Opcional. Especifica el modo en el que se debe ejecutar la llamada a función. Si no se especifica, el valor predeterminado se establecerá en AUTO.

allowedFunctionNames[] string

Opcional. Es un conjunto de nombres de funciones que, cuando se proporcionan, limitan las funciones que llamará el modelo.

Este parámetro solo se debe establecer cuando el modo es ANY o VALIDATED. Los nombres de las funciones deben coincidir con [FunctionDeclaration.name]. Cuando se establece, el modelo predecirá una llamada a función solo a partir de los nombres de función permitidos.

Representación JSON
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Modo

Define el comportamiento de ejecución para la llamada a funciones definiendo el modo de ejecución.

Enums
MODE_UNSPECIFIED Modo de llamada a función sin especificar. No se debe usar este valor.
AUTO Comportamiento predeterminado del modelo: El modelo decide si predecir una llamada a función o una respuesta de lenguaje natural.
ANY El modelo está restringido para predecir siempre solo una llamada a función. Si se establece "allowedFunctionNames", la llamada a función predicha se limitará a cualquiera de los "allowedFunctionNames". De lo contrario, la llamada a función predicha será cualquiera de las "functionDeclarations" proporcionadas.
NONE El modelo no predecirá ninguna llamada a función. El comportamiento del modelo es el mismo que cuando no se pasan declaraciones de funciones.
VALIDATED El modelo decide si predecir una llamada a función o una respuesta de lenguaje natural, pero validará las llamadas a función con la decodificación restringida. Si se establece "allowedFunctionNames", la llamada a función predicha se limitará a cualquiera de los "allowedFunctionNames". De lo contrario, la llamada a función predicha será cualquiera de las "functionDeclarations" proporcionadas.

RetrievalConfig

Es la configuración de recuperación.

Campos
latLng object (LatLng)

Opcional. Ubicación del usuario.

languageCode string

Opcional. Es el código de idioma del usuario. Es el código de idioma del contenido. Usa las etiquetas de idioma definidas por BCP47.

Representación JSON
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

Es un objeto que representa un par de valores de latitud y longitud. Esto se expresa como un par de números de punto flotante de doble precisión que representan los grados de latitud y longitud. A menos que se especifique lo contrario, este objeto debe cumplir con el estándar WGS84. Los valores deben pertenecer a rangos normalizados.

Campos
latitude number

Es la latitud expresada en grados. Debe pertenecer al rango [-90.0, +90.0].

longitude number

La longitud expresada en grados. Debe pertenecer al rango [-180.0, +180.0].

Representación JSON
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Son metadatos sobre el uso del contenido almacenado en caché.

Campos
totalTokenCount integer

Es la cantidad total de tokens que consume el contenido almacenado en caché.

Representación JSON
{
  "totalTokenCount": integer
}