Caching

Кеширование контекста позволяет сохранять и повторно использовать предварительно вычисленные входные токены, например когда вы задаете разные вопросы об одном и том же медиафайле. Это может привести к экономии средств и повышению скорости в зависимости от использования. Подробную информацию вы найдете в руководстве по кешированию контекста.

Метод: cachedContents.create

Создает ресурс CachedContent.

Конечная точка

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

Тело запроса

Тело запроса содержит экземпляр CachedContent.

Поля
contents[] object (Content)

Необязательное поле. Только для ввода. Не меняется. Контент, который нужно кешировать.

tools[] object (Tool)

Необязательное поле. Только для ввода. Не меняется. Список Tools, которые модель может использовать для генерации следующего ответа.

expiration Union type
Указывает, когда истечет срок действия этого ресурса. Ниже приведен список взаимоисключающих полей. В ответе будет задано не более одного из следующих полей:
expireTime string (Timestamp format)

Временная метка по UTC, указывающая, когда ресурс считается устаревшим. Это значение всегда указывается в выходных данных, независимо от того, что было отправлено во входных.

Используется формат RFC 3339. Результат всегда будет Z-нормализованным, и в нем будут использоваться цифры дробных частей 0, 3, 6 или 9. Допустимы и другие типы нормализации. Примеры: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Только для ввода. Новое значение TTL для этого ресурса (только для ввода).

Продолжительность в секундах, может содержать до девяти дробных цифр и заканчиваться на букву s. Пример: "3.5s".

Конец взаимоисключающих полей.
displayName string

Необязательное поле. Не меняется. Понятное отображаемое название кешированного контента, созданное пользователем. Максимум 128 символов Unicode.

model string

Обязательно. Не меняется. Название Model, которое будет использоваться для кешированного контента. Формат: models/{model}.

systemInstruction object (Content)

Необязательное поле. Только для ввода. Не меняется. Системные инструкции, заданные разработчиком. Пока только текст.

toolConfig object (ToolConfig)

Необязательное поле. Только для ввода. Не меняется. Конфигурация инструмента. Эта конфигурация используется для всех инструментов.

Пример запроса

Основные

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.8-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.8-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);

Проложить маршрут

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.8-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)

Ракушка

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'"
    }'

Имя отправителя

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.8-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.8-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);

Проложить маршрут

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.8-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)

Из чата

Python

from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-3.8-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.8-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);

Проложить маршрут

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.8-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())

Тело ответа

Тело ответа, полученного на запрос, содержит новый экземпляр CachedContent.

Метод: cachedContents.list

Возвращает список CachedContents.

Конечная точка

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

Параметры запроса

pageSize integer

Необязательное поле. Максимальное количество кешированных объектов, которые нужно вернуть. Сервис может вернуть меньше результатов, чем указано в этом значении. Если значение не указано, будет возвращено количество объектов по умолчанию (меньше максимального). Максимальное значение – 1000. Если указать большее значение, оно будет автоматически уменьшено до 1000.

pageToken string

Необязательное поле. Токен страницы, полученный из предыдущего вызова cachedContents.list. Укажите его, чтобы получить следующую страницу.

При разбиении на страницы все остальные параметры, передаваемые в cachedContents.list, должны соответствовать вызову, который предоставил токен страницы.

Тело запроса

Тело запроса должно быть пустым.

Тело ответа

Ответ со списком CachedContents.

Ниже приведена структура данных в ответе, полученном на запрос.

Поля
cachedContents[] object (CachedContent)

Список кешированного контента.

nextPageToken string

Токен, который можно отправить как pageToken, чтобы получить следующую страницу. Если это поле отсутствует, значит последующих страниц нет.

JSON-представление
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Метод cachedContents.get

Читает ресурс CachedContent.

Конечная точка

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

Параметры пути

name string

Обязательно. Название ресурса, ссылающегося на запись кеша контента. Формат: cachedContents/{id}. Форма: cachedContents/{cachedcontent}.

Тело запроса

Тело запроса должно быть пустым.

Пример запроса

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.8-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.8-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);

Проложить маршрут

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.8-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)

Ракушка

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

Тело ответа

Если ответ получен успешно, его тело содержит экземпляр CachedContent.

Метод: cachedContents.patch

Обновляет ресурс CachedContent (обновлять можно только срок действия).

Конечная точка

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

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

Параметры пути

cachedContent.name string

Только для вывода. Идентификатор. Название ресурса, ссылающегося на кешированный контент. Формат: cachedContents/{id}. Форма: cachedContents/{cachedcontent}.

Параметры запроса

updateMask string (FieldMask format)

Список полей, которые нужно обновить.

Это список полных названий полей, разделенных запятыми. Пример: "user.displayName,photo".

Тело запроса

Тело запроса содержит экземпляр CachedContent.

Поля
expiration Union type
Указывает, когда истечет срок действия этого ресурса. Ниже приведен список взаимоисключающих полей. В ответе будет задано не более одного из следующих полей:
expireTime string (Timestamp format)

Временная метка по UTC, указывающая, когда ресурс считается устаревшим. Это значение всегда указывается в выходных данных, независимо от того, что было отправлено во входных.

Используется формат RFC 3339. Результат всегда будет Z-нормализованным, и в нем будут использоваться цифры дробных частей 0, 3, 6 или 9. Допустимы и другие типы нормализации. Примеры: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Только для ввода. Новое значение TTL для этого ресурса (только для ввода).

Продолжительность в секундах, может содержать до девяти дробных цифр и заканчиваться на букву s. Пример: "3.5s".

Конец взаимоисключающих полей.

Пример запроса

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.8-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.8-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);

Проложить маршрут

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.8-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)

Ракушка

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

Тело ответа

Если ответ получен успешно, его тело содержит экземпляр CachedContent.

Метод cachedContents.delete

Удаляет ресурс CachedContent.

Конечная точка

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

Параметры пути

name string

Обязательно. Название ресурса, относящееся к записи кеша контента. Формат: cachedContents/{id}. Форма: cachedContents/{cachedcontent}.

Тело запроса

Тело запроса должно быть пустым.

Пример запроса

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.8-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.8-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);

Проложить маршрут

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.8-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)

Ракушка

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

Тело ответа

Если запрос выполнен успешно, тело ответа представляет собой пустой объект JSON.

Ресурс REST: cachedContents

Ресурс: CachedContent

Контент, который был предварительно обработан и может использоваться в последующем запросе к GenerativeService.

Кешированный контент можно использовать только с моделью, для которой он был создан.

Поля
contents[] object (Content)

Необязательное поле. Только для ввода. Не меняется. Контент, который нужно кешировать.

tools[] object (Tool)

Необязательное поле. Только для ввода. Не меняется. Список Tools, которые модель может использовать для генерации следующего ответа.

createTime string (Timestamp format)

Только для вывода. Время создания записи кеша.

Используется формат RFC 3339. Результат всегда будет Z-нормализованным, и в нем будут использоваться цифры дробных частей 0, 3, 6 или 9. Допустимы и другие типы нормализации. Примеры: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Только для вывода. Время последнего обновления записи кеша по UTC.

Используется формат RFC 3339. Результат всегда будет Z-нормализованным, и в нем будут использоваться цифры дробных частей 0, 3, 6 или 9. Допустимы и другие типы нормализации. Примеры: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

Только для вывода. Метаданные об использовании кешированного контента.

expiration Union type
Указывает, когда истечет срок действия этого ресурса. Ниже приведен список взаимоисключающих полей. В ответе будет задано не более одного из следующих полей:
expireTime string (Timestamp format)

Временная метка по UTC, указывающая, когда ресурс считается устаревшим. Это значение всегда указывается в выходных данных, независимо от того, что было отправлено во входных.

Используется формат RFC 3339. Результат всегда будет Z-нормализованным, и в нем будут использоваться цифры дробных частей 0, 3, 6 или 9. Допустимы и другие типы нормализации. Примеры: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Только для ввода. Новое значение TTL для этого ресурса (только для ввода).

Продолжительность в секундах, может содержать до девяти дробных цифр и заканчиваться на букву s. Пример: "3.5s".

Конец взаимоисключающих полей.
name string

Только для вывода. Идентификатор. Название ресурса, ссылающегося на кешированный контент. Формат: cachedContents/{id}

displayName string

Необязательное поле. Не меняется. Понятное отображаемое название кешированного контента, созданное пользователем. Максимум 128 символов Unicode.

model string

Обязательно. Не меняется. Название Model, которое будет использоваться для кешированного контента. Формат: models/{model}.

systemInstruction object (Content)

Необязательное поле. Только для ввода. Не меняется. Системные инструкции, заданные разработчиком. Пока только текст.

toolConfig object (ToolConfig)

Необязательное поле. Только для ввода. Не меняется. Конфигурация инструмента. Эта конфигурация используется для всех инструментов.

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

Конфигурация инструмента, содержащая параметры для указания использования Tool в запросе.

Поля
functionCallingConfig object (FunctionCallingConfig)

Необязательное поле. Конфигурация вызова функций.

retrievalConfig object (RetrievalConfig)

Необязательное поле. Конфигурация извлечения.

includeServerSideToolInvocations boolean

Необязательное поле. Если задано значение true, ответ API будет включать вызовы инструментов на стороне сервера и ответы в сообщении Content. Это позволяет клиентам наблюдать за взаимодействием сервера с инструментами.

JSON-представление
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

Конфигурация для указания поведения вызова функций.

Поля
mode enum (Mode)

Необязательное поле. Указывает режим, в котором должен выполняться вызов функции. Если значение не указано, по умолчанию будет задано AUTO.

allowedFunctionNames[] string

Необязательное поле. Набор названий функций, которые модель может вызывать.

Это значение следует задавать, только если для параметра Mode установлено значение ANY или VALIDATED. Названия функций должны соответствовать [FunctionDeclaration.name]. Если задано, модель будет прогнозировать вызов функции только из разрешенных названий функций.

JSON-представление
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Режим

Определяет поведение при вызове функции, задавая режим выполнения.

Перечисления
MODE_UNSPECIFIED Режим вызова функций не указан. Это значение не должно использоваться.
AUTO Поведение модели по умолчанию. Модель решает, что предсказать: вызов функции или ответ на естественном языке.
ANY Модель всегда прогнозирует только вызов функции. Если задано свойство allowedFunctionNames, то вызов функции будет ограничен одним из значений allowedFunctionNames. В противном случае вызов функции будет ограничен одним из значений functionDeclarations.
NONE Модель не будет прогнозировать вызовы функций. Поведение модели такое же, как если бы не передавались никакие объявления функций.
VALIDATED Модель решает, что предсказать: вызов функции или ответ на естественном языке. При этом вызовы функций будут проверяться с помощью ограниченного декодирования. Если задано свойство allowedFunctionNames, то вызов функции будет ограничен одним из значений allowedFunctionNames. В противном случае вызов функции будет ограничен одним из значений functionDeclarations.

RetrievalConfig

Конфигурация извлечения.

Поля
latLng object (LatLng)

Необязательное поле. Местоположение пользователя.

languageCode string

Необязательное поле. Код языка пользователя. Код языка контента. Используйте языковые теги, определенные в BCP47.

JSON-представление
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

Объект, содержащий географические координаты в виде значений широты и долготы. Это выражается в виде пары значений с плавающей запятой (double), представляющих градусы широты и градусы долготы. Если не указано иное, координаты задаются в системе WGS84. Также они должны попадать в нормализованные диапазоны значений.

Поля
latitude number

Градусная мера широты. Должна попадать в диапазон [-90,0, +90,0].

longitude number

Градусная мера долготы. Должна попадать в диапазон [-180,0, +180,0].

JSON-представление
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Метаданные об использовании кешированного контента.

Поля
totalTokenCount integer

Общее количество токенов, которые занимает кешированный контент.

JSON-представление
{
  "totalTokenCount": integer
}