Caching

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

Метод: cachedContents.create

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

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

опубликовать https: / /generativelanguage.googleapis.com /v1beta /cachedContents

Тело запроса

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

Поля
объект contents[] object ( Content )

Необязательный. Только ввод. Неизменяемый. Содержимое для кэширования.

объект tools[] object ( Tool )

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

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

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

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

строка ttl string ( Duration format)

Только ввод. Новый срок жизни для этого ресурса, только входные данные.

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

string displayName

Необязательный. Неизменяемый. Созданное пользователем значимое отображаемое имя кэшированного содержимого. Максимум 128 символов Юникода.

model string

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

object ( Content ) systemInstruction (Содержимое)

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

объект toolConfig object ( ToolConfig )

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

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

from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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'"
    }'
from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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)
from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-1.5-flash-001"
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)
// 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-1.5-flash-001";
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-1.5-flash-001"
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, "user"),
}, 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, "user"),
})
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

Перечисляет кэшированное содержимое.

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

получить https: / /generativelanguage.googleapis.com /v1beta /cachedContents

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

pageSize integer

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

string pageToken

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

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

Тело запроса

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

Тело ответа

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

В случае успеха тело ответа содержит данные следующей структуры:

Поля
объект cachedContents[] object ( CachedContent )

Список кэшированного содержимого.

nextPageToken string PageToken

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

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

Метод: кэшедКонтентс.get

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

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

получить https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

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

string name

Необходимый. Имя ресурса, относящееся к записи кэша контента. Формат: cachedContents/{id} Он принимает форму cachedContents/{cachedcontent} .

Тело запроса

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

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

from google import genai

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

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))
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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 (обновляется только срок действия).

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

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

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

string cachedContent.name

Только вывод. Идентификатор. Имя ресурса, относящееся к кэшированному содержимому. Формат: cachedContents/{id} Он принимает форму cachedContents/{cachedcontent} .

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

string ( FieldMask format) updateMask (формат FieldMask)

Список полей для обновления.

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

Тело запроса

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

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

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

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

строка ttl string ( Duration format)

Только ввод. Новый срок жизни для этого ресурса, только входные данные.

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

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

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-1.5-flash-001"

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),
)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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.

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

удалить https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

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

string name

Необходимый. Имя ресурса, относящееся к записи кэша контента. Формат: cachedContents/{id} Он принимает форму cachedContents/{cachedcontent} .

Тело запроса

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

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

from google import genai

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

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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: кэшированный контент

Ресурс: CachedContent

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

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

Поля
объект contents[] object ( Content )

Необязательный. Только ввод. Неизменяемый. Содержимое для кэширования.

объект tools[] object ( Tool )

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

строка createTime string ( Timestamp format)

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

Использует RFC 3339, где генерируемые выходные данные всегда будут Z-нормализованы и используют 0, 3, 6 или 9 дробных цифр. Также принимаются смещения, отличные от «Z». Примеры: "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 дробных цифр. Также принимаются смещения, отличные от «Z». Примеры: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30" .

объект usageMetadata object ( UsageMetadata )

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

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

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

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

строка ttl string ( Duration format)

Только ввод. Новый срок жизни для этого ресурса, только входные данные.

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

string name

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

string displayName

Необязательный. Неизменяемый. Созданное пользователем значимое отображаемое имя кэшированного содержимого. Максимум 128 символов Юникода.

model string

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

object ( Content ) systemInstruction (Содержимое)

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

объект 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)
  }
}

Содержание

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

Content включает в себя поле role , обозначающее производителя Content , и поле parts , содержащее данные, состоящие из нескольких частей, которые содержат содержимое очереди сообщения.

Поля
object ( Part ) parts[] ( Часть )

Заказанные Parts , составляющие одно сообщение. Части могут иметь разные типы MIME.

role string

Необязательный. Производитель контента. Должно быть либо «пользователь», либо «модель».

Полезно для многоходовых разговоров, в противном случае его можно оставить пустым или не установить.

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

Часть

Тип данных, содержащий медиафайлы, которые являются частью сообщения Content состоящего из нескольких частей.

Part состоит из данных, имеющих связанный тип данных. Part может содержать только один из типов, принятых в Part.data .

Part должна иметь фиксированный тип IANA MIME, определяющий тип и подтип носителя, если поле inlineData заполнено необработанными байтами.

Поля
thought boolean

Необязательный. Указывает, задумана ли деталь на основе модели.

Union type data
data могут быть только одним из следующих:
text string

Встроенный текст.

объект inlineData object ( Blob )

Встроенные медиабайты.

object ( FunctionCall ) functionCall ( FunctionCall )

Прогнозируемый вызов FunctionCall возвращенный из модели, содержит строку, представляющую FunctionDeclaration.name с аргументами и их значениями.

объект functionResponse object ( FunctionResponse )

Результат вызова FunctionCall , содержащий строку, представляющую FunctionDeclaration.name , и структурированный объект JSON, содержащий любые выходные данные функции, используется в качестве контекста для модели.

объект fileData object ( FileData )

Данные на основе URI.

object ( ExecutableCode ) executableCode (ExexetableCode)

Код, сгенерированный моделью, предназначенный для выполнения.

object ( CodeExecutionResult ) codeExecutionResult ( CodeExecutionResult )

Результат выполнения ExecutableCode .

JSON-представление
{
  "thought": boolean,

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  }
  // Union type
}

Блоб

Необработанные медиабайты.

Текст не следует отправлять в виде необработанных байтов, используйте поле «текст».

Поля
string mimeType

Стандартный MIME-тип IANA исходных данных. Примеры: - image/png - image/jpeg Если указан неподдерживаемый тип MIME, будет возвращена ошибка. Полный список поддерживаемых типов см. в разделе Поддерживаемые форматы файлов .

string ( bytes format) data (формат байтов)

Необработанные байты для медиаформатов.

Строка в кодировке Base64.

JSON-представление
{
  "mimeType": string,
  "data": string
}

Вызов функции

Прогнозируемый вызов FunctionCall возвращенный из модели, содержит строку, представляющую FunctionDeclaration.name с аргументами и их значениями.

Поля
string id

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

string name

Необходимый. Имя функции, которую нужно вызвать. Должен быть az, AZ, 0–9 или содержать символы подчеркивания и тире, максимальная длина — 63.

объект args object ( Struct format)

Необязательный. Параметры и значения функции в формате объекта JSON.

JSON-представление
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

ФункцияОтвет

Выходные данные FunctionCall , содержащие строку, представляющую FunctionDeclaration.name , и структурированный объект JSON, содержащий любые выходные данные функции, используются в качестве контекста для модели. Он должен содержать результат вызова FunctionCall , созданного на основе предсказания модели.

Поля
string id

Необязательный. Идентификатор вызова функции, для которого предназначен этот ответ. Заполняется клиентом в соответствии с id вызова соответствующей функции.

string name

Необходимый. Имя функции, которую нужно вызвать. Должен быть az, AZ, 0–9 или содержать символы подчеркивания и тире, максимальная длина — 63.

объект response object ( Struct format)

Необходимый. Ответ функции в формате объекта JSON.

JSON-представление
{
  "id": string,
  "name": string,
  "response": {
    object
  }
}

ФайлДанные

Данные на основе URI.

Поля
string mimeType

Необязательный. Стандартный MIME-тип IANA исходных данных.

string fileUri

Необходимый. УРИ.

JSON-представление
{
  "mimeType": string,
  "fileUri": string
}

Исполняемыйкод

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

Генерируется только при использовании инструмента CodeExecution , в котором код будет автоматически выполнен, а также будет сгенерирован соответствующий CodeExecutionResult .

Поля
language enum ( Language )

Необходимый. Язык программирования code .

code string

Необходимый. Код, который будет выполнен.

JSON-представление
{
  "language": enum (Language),
  "code": string
}

Язык

Поддерживаемые языки программирования для сгенерированного кода.

Перечисления
LANGUAGE_UNSPECIFIED Неуказанный язык. Это значение не следует использовать.
PYTHON Python >= 3.10, доступны numpy и simpy.

КодExecutionResult

Результат выполнения ExecutableCode .

Генерируется только при использовании CodeExecution и всегда следует за part содержащей ExecutableCode .

Поля
перечисление outcome enum ( Outcome )

Необходимый. Результат выполнения кода.

output string

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

JSON-представление
{
  "outcome": enum (Outcome),
  "output": string
}

Исход

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

Перечисления
OUTCOME_UNSPECIFIED Неопределенный статус. Это значение не следует использовать.
OUTCOME_OK Выполнение кода завершено успешно.
OUTCOME_FAILED Выполнение кода завершилось, но с ошибкой. stderr должен содержать причину.
OUTCOME_DEADLINE_EXCEEDED Выполнение кода продолжалось слишком долго и было отменено. Частичный вывод может присутствовать или отсутствовать.

Инструмент

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

Tool — это часть кода, которая позволяет системе взаимодействовать с внешними системами для выполнения действия или набора действий за пределами знаний и области действия модели.

Поля
объект functionDeclarations[] object ( FunctionDeclaration )

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

Модель или система не выполняет функцию. Вместо этого определенная функция может быть возвращена как FunctionCall с аргументами на стороне клиента для выполнения. Модель может решить вызвать подмножество этих функций, заполнив FunctionCall в ответе. Следующий ход диалога может содержать FunctionResponse с контекстом генерации «функции» Content.role для следующего хода модели.

object ( GoogleSearchRetrieval ) googleSearchRetrieval ( GoogleSearchRetrival )

Необязательный. Инструмент поиска, работающий на основе поиска Google.

object ( CodeExecution ) codeExecution ( CodeExecution )

Необязательный. Позволяет модели выполнять код в рамках генерации.

JSON-представление
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  }
}

Объявление функции

Структурированное представление объявления функции, определенное спецификацией OpenAPI 3.03 . В это объявление включены имя функции и параметры. Это объявление функции является представлением блока кода, который может использоваться моделью в качестве Tool и выполняться клиентом.

Поля
string name

Необходимый. Имя функции. Должен быть az, AZ, 0–9 или содержать символы подчеркивания и тире, максимальная длина — 63.

string description

Необходимый. Краткое описание функции.

объект parameters object ( Schema )

Необязательный. Описывает параметры этой функции. Отражает строку объекта параметра Open API 3.03. Ключ: имя параметра. Имена параметров чувствительны к регистру. Значение схемы: схема, определяющая тип, используемый для параметра.

объект response object ( Schema )

Необязательный. Описывает выходные данные этой функции в формате JSON Schema. Отражает объект ответа Open API 3.03. Схема определяет тип, используемый для значения ответа функции.

JSON-представление
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  },
  "response": {
    object (Schema)
  }
}

Схема

Объект Schema позволяет определять типы входных и выходных данных. Эти типы могут быть объектами, а также примитивами и массивами. Представляет выбранное подмножество объекта схемы OpenAPI 3.0 .

Поля
type enum ( Type )

Необходимый. Тип данных.

string format

Необязательный. Формат данных. Это используется только для примитивных типов данных. Поддерживаемые форматы: для типа NUMBER: float, double для типа INTEGER: int32, int64 для типа STRING: enum, date-time.

string title

Необязательный. Название схемы.

string description

Необязательный. Краткое описание параметра. Это может содержать примеры использования. Описание параметра может быть отформатировано как Markdown.

boolean nullable

Необязательный. Указывает, может ли значение быть нулевым.

string enum[]

Необязательный. Возможные значения элемента Type.STRING в формате перечисления. Например, мы можем определить направление перечисления как: {type:STRING, format:enum, enum:["ВОСТОК", СЕВЕР", "ЮГ", "ЗАПАД"]}

string ( int64 format) maxItems (формат int64)

Необязательный. Максимальное количество элементов для Type.ARRAY.

string ( int64 format) minItems (формат int64)

Необязательный. Минимальное количество элементов для Type.ARRAY.

карта properties map (key: string, value: object ( Schema ))

Необязательный. Свойства Type.OBJECT.

Объект, содержащий список пар "key": value . Пример: { "name": "wrench", "mass": "1.3kg", "count": "3" } .

required[] string

Необязательный. Обязательные свойства Type.OBJECT.

string ( int64 format) minProperties (формат int64)

Необязательный. Минимальное количество свойств для Type.OBJECT.

string ( int64 format) maxProperties (формат int64)

Необязательный. Максимальное количество свойств для Type.OBJECT.

string ( int64 format) minLength (формат int64)

Необязательный. ПОЛЯ СХЕМЫ ДЛЯ TYPE STRING Минимальная длина Type.STRING

string ( int64 format) maxLength (формат int64)

Необязательный. Максимальная длина Type.STRING

string pattern

Необязательный. Шаблон Type.STRING для ограничения строки регулярным выражением.

example value ( Value format)

Необязательный. Пример объекта. Будет заполняться только тогда, когда объект является корневым.

объект anyOf[] object ( Schema )

Необязательный. Значение должно быть проверено на соответствие любой (одной или нескольким) подсхемам в списке.

propertyOrdering[] string

Необязательный. Порядок свойств. Не стандартное поле в спецификации открытого API. Используется для определения порядка свойств в ответе.

значение default value ( Value format)

Необязательный. Значение поля по умолчанию. Согласно схеме JSON это поле предназначено для генераторов документации и не влияет на проверку. Таким образом, оно включено сюда и игнорируется, чтобы разработчики, отправляющие схемы с полем default не получали ошибки неизвестного поля.

объект items object ( Schema )

Необязательный. Схема элементов Type.ARRAY.

minimum number

Необязательный. ПОЛЯ СХЕМЫ ДЛЯ ТИПА INTEGER и NUMBER Минимальное значение Type.INTEGER и Type.NUMBER

maximum number

Необязательный. Максимальное значение Type.INTEGER и Type.NUMBER.

JSON-представление
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

Тип

Тип содержит список типов данных OpenAPI, как определено https://spec.openapis.org/oas/v3.0.3#data-types .

Перечисления
TYPE_UNSPECIFIED Не указано, не следует использовать.
STRING Тип строки.
NUMBER Тип номера.
INTEGER Целочисленный тип.
BOOLEAN Булев тип.
ARRAY Тип массива.
OBJECT Тип объекта.
NULL Нулевой тип.

Поиск GoogleПоиск

Инструмент для получения общедоступных веб-данных для заземления, разработанный Google.

Поля
object ( DynamicRetrievalConfig ) dynamicRetrievalConfig ( DynamicRetrivalConfig )

Указывает конфигурацию динамического получения для данного источника.

JSON-представление
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

Динамическая ретривалконфиг

Описывает параметры настройки динамического извлечения.

Поля
перечисление mode enum ( Mode )

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

number dynamicThreshold

Порог, который будет использоваться при динамическом извлечении. Если не установлено, используется системное значение по умолчанию.

JSON-представление
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

Режим

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

Перечисления
MODE_UNSPECIFIED Всегда запускайте извлечение.
MODE_DYNAMIC Запускайте извлечение только тогда, когда система сочтет это необходимым.

Выполнение кода

Этот тип не имеет полей.

Инструмент, который выполняет код, сгенерированный моделью, и автоматически возвращает результат в модель.

См. также ExecutableCode и CodeExecutionResult , которые генерируются только при использовании этого инструмента.

GoogleПоиск

Этот тип не имеет полей.

Тип инструмента GoogleSearch. Инструмент для поддержки поиска Google в модели. При поддержке Google.

ИнструментКонфигурация

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

Поля
объект functionCallingConfig object ( FunctionCallingConfig )

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

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

ФункцияCallingConfig

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

Поля
перечисление mode enum ( Mode )

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

allowedFunctionNames[] string

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

Это значение следует устанавливать только в том случае, если выбран режим ЛЮБОЙ. Имена функций должны соответствовать [FunctionDeclaration.name]. Если для режима установлено значение ЛЮБОЙ, модель будет прогнозировать вызов функции на основе предоставленного набора имен функций.

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

Режим

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

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

Использованиеметаданные

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

Поля
totalTokenCount integer

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

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

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

Метод: cachedContents.create

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

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

опубликовать https: / /generativelanguage.googleapis.com /v1beta /cachedContents

Тело запроса

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

Поля
объект contents[] object ( Content )

Необязательный. Только ввод. Неизменяемый. Содержимое для кэширования.

объект tools[] object ( Tool )

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

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

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

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

строка ttl string ( Duration format)

Только ввод. Новый срок жизни для этого ресурса, только входные данные.

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

string displayName

Необязательный. Неизменяемый. Созданное пользователем значимое отображаемое имя кэшированного содержимого. Максимум 128 символов Юникода.

model string

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

object ( Content ) systemInstruction (Содержимое)

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

объект toolConfig object ( ToolConfig )

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

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

from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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'"
    }'
from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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)
from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-1.5-flash-001"
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)
// 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-1.5-flash-001";
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-1.5-flash-001"
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, "user"),
}, 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, "user"),
})
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

Перечисляет кэшированное содержимое.

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

получить https: / /generativelanguage.googleapis.com /v1beta /cachedContents

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

pageSize integer

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

string pageToken

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

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

Тело запроса

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

Тело ответа

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

В случае успеха тело ответа содержит данные следующей структуры:

Поля
объект cachedContents[] object ( CachedContent )

Список кэшированного содержимого.

nextPageToken string PageToken

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

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

Метод: кэшедКонтентс.get

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

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

получить https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

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

string name

Необходимый. Имя ресурса, относящееся к записи кэша контента. Формат: cachedContents/{id} Он принимает форму cachedContents/{cachedcontent} .

Тело запроса

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

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

from google import genai

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

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))
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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 (обновляется только срок действия).

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

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

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

string cachedContent.name

Только вывод. Идентификатор. Имя ресурса, относящееся к кэшированному содержимому. Формат: cachedContents/{id} Он принимает форму cachedContents/{cachedcontent} .

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

string ( FieldMask format) updateMask (формат FieldMask)

Список полей для обновления.

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

Тело запроса

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

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

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

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

строка ttl string ( Duration format)

Только ввод. Новый срок жизни для этого ресурса, только входные данные.

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

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

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-1.5-flash-001"

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),
)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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.

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

удалить https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

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

string name

Необходимый. Имя ресурса, относящееся к записи кэша контента. Формат: cachedContents/{id} Он принимает форму cachedContents/{cachedcontent} .

Тело запроса

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

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

from google import genai

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

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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: кэшированный контент

Ресурс: CachedContent

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

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

Поля
объект contents[] object ( Content )

Необязательный. Только ввод. Неизменяемый. Содержимое для кэширования.

объект tools[] object ( Tool )

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

строка createTime string ( Timestamp format)

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

Использует RFC 3339, где генерируемые выходные данные всегда будут нормализованы по Z и используют 0, 3, 6 или 9 дробных цифр. Также принимаются смещения, отличные от «Z». Примеры: "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 дробных цифр. Также принимаются смещения, отличные от «Z». Примеры: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30" .

объект usageMetadata object ( UsageMetadata )

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

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

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

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

строка ttl string ( Duration format)

Только ввод. Новый срок жизни для этого ресурса, только входные данные.

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

string name

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

string displayName

Необязательный. Неизменяемый. Созданное пользователем значимое отображаемое имя кэшированного содержимого. Максимум 128 символов Юникода.

model string

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

object ( Content ) systemInstruction (Содержимое)

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

объект 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)
  }
}

Содержание

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

Content включает в себя поле role , обозначающее производителя Content , и поле parts , содержащее данные, состоящие из нескольких частей, которые содержат содержимое очереди сообщения.

Поля
object ( Part ) parts[] ( Часть )

Заказанные Parts , составляющие одно сообщение. Части могут иметь разные типы MIME.

role string

Необязательный. Производитель контента. Должно быть либо «пользователь», либо «модель».

Полезно для многоходовых разговоров, в противном случае его можно оставить пустым или не установить.

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

Часть

Тип данных, содержащий медиафайлы, которые являются частью сообщения Content состоящего из нескольких частей.

Part состоит из данных, имеющих связанный тип данных. Part может содержать только один из типов, принятых в Part.data .

Part должна иметь фиксированный тип IANA MIME, определяющий тип и подтип носителя, если поле inlineData заполнено необработанными байтами.

Поля
thought boolean

Необязательный. Указывает, задумана ли деталь на основе модели.

Union type data
data могут быть только одним из следующих:
text string

Встроенный текст.

объект inlineData object ( Blob )

Встроенные медиабайты.

object ( FunctionCall ) functionCall ( FunctionCall )

Прогнозируемый вызов FunctionCall возвращенный из модели, содержит строку, представляющую FunctionDeclaration.name с аргументами и их значениями.

объект functionResponse object ( FunctionResponse )

Результат вывода FunctionCall , которая содержит строку, представляющую FunctionDeclaration.name , и структурированный объект json, содержащий любой выход из функции, используется в качестве контекста для модели.

Объект fileData object ( FileData )

Данные на основе URI.

executableCode object ( ExecutableCode )

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

codeExecutionResult object ( CodeExecutionResult )

Результат выполнения ExecutableCode .

Представление JSON
{
  "thought": boolean,

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  }
  // Union type
}

Капля

Необработанные носители.

Текст не должен быть отправлен в качестве необработанных байтов, используйте поле «Текст».

Поля
mimeType string

Стандартный тип исходных данных IANA. Примеры: - Image/PNG - Image/JPEG Если предоставлен непреодолимый тип MIME, будет возвращена ошибка. Полный список поддерживаемых типов см. Вспомогаемые форматы файлов .

string ( bytes format) data (формат байтов)

Сырые байты для форматов медиа.

Base64-кодированная строка.

Представление JSON
{
  "mimeType": string,
  "data": string
}

FunctionCall

Прогнозируемая FunctionCall возвращенная из модели, которая содержит строку, представляющую FunctionDeclaration.name с аргументами и их значениями.

Поля
id string

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

name string

Необходимый. Имя функции для вызова. Должен быть AZ, AZ, 0-9 или содержать подчеркивание и тире, с максимальной длиной 63.

Объект args object ( Struct format)

Необязательный. Параметры и значения функции в формате объекта JSON.

Представление JSON
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

Функциональный ответ

Результат вывода от FunctionCall , которая содержит строку, представляющую FunctionDeclaration.name , и структурированный объект JSON, содержащий любой выход из функции, используется в качестве контекста для модели. Это должно содержать результат FunctionCall выполненной на основе прогнозирования модели.

Поля
id string

Необязательный. Идентификатор функции вызывает этот ответ для. Заполнено клиентом, чтобы соответствовать соответствующему id вызова функции.

name string

Необходимый. Имя функции для вызова. Должен быть AZ, AZ, 0-9 или содержать подчеркивание и тире, с максимальной длиной 63.

объект response object ( Struct format)

Необходимый. Ответ функции в формате объекта JSON.

Представление JSON
{
  "id": string,
  "name": string,
  "response": {
    object
  }
}

Filedata

Данные на основе URI.

Поля
mimeType string

Необязательный. Стандартный тип исходных данных IANA.

fileUri string

Необходимый. Ури.

Представление JSON
{
  "mimeType": string,
  "fileUri": string
}

ExecutableCode

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

Сгенерировано только при использовании инструмента CodeExecution , в котором код будет автоматически выполнен, и также будет сгенерирован соответствующий CodeExecutionResult .

Поля
language enum ( Language )

Необходимый. Язык программирования code .

code string

Необходимый. Код будет выполнен.

Представление JSON
{
  "language": enum (Language),
  "code": string
}

Язык

Поддерживаемые языки программирования для сгенерированного кода.

Перечисление
LANGUAGE_UNSPECIFIED Неуказанный язык. Это значение не должно использоваться.
PYTHON Python> = 3.10, с Numpy и Simpy.

CodeExecutionResult

Результат выполнения ExecutableCode .

Сгенерированный только при использовании CodeExecution , и всегда следует за part содержащей ExecutableCode .

Поля
outcome enum ( Outcome )

Необходимый. Результат выполнения кода.

output string

Необязательный. Содержит Stdout, когда выполнение кода успешно, STDERR или другое описание в противном случае.

Представление JSON
{
  "outcome": enum (Outcome),
  "output": string
}

Исход

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

Перечисление
OUTCOME_UNSPECIFIED Неуказанный статус. Это значение не должно использоваться.
OUTCOME_OK Выполнение кода завершено успешно.
OUTCOME_FAILED Выполнение кода завершено, но с неудачей. stderr должен содержать причину.
OUTCOME_DEADLINE_EXCEEDED Выполнение кода работало слишком долго и было отменено. Там может или не может быть частичный выход.

Инструмент

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

Tool - это кусок кода, который позволяет системе взаимодействовать с внешними системами для выполнения действия или набора действий вне знаний и объема модели.

Поля
functionDeclarations[] object ( FunctionDeclaration )

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

Модель или система не выполняют функцию. Вместо этого определенная функция может быть возвращена как FunctionCall с аргументами на стороне клиента для выполнения. Модель может принять решение вызвать подмножество этих функций путем заполнения FunctionCall в ответе. Следующий поворот разговора может содержать FunctionResponse с контекстом генерации функции Content.role «Функция» для следующего поворота модели.

googleSearchRetrieval object ( GoogleSearchRetrieval )

Необязательный. Инструмент поиска, который питается Google Search.

object ( CodeExecution ) codeExecution (CodeExecution)

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

Представление JSON
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  }
}

Функциональная декларация

Структурированное представление функции объявления, как определено спецификацией OpenAPI 3.03 . В это объявление включены имя функции и параметры. Эта функциональная декларация является представлением блока кода, который можно использовать в качестве Tool моделью и выполняемый клиентом.

Поля
name string

Необходимый. Имя функции. Должен быть AZ, AZ, 0-9 или содержать подчеркивание и тире, с максимальной длиной 63.

description string

Необходимый. Краткое описание функции.

parameters object ( Schema )

Необязательный. Описывает параметры этой функции. Отражает клавишу open api 3.03 Parameter String string: имя параметра. Названия параметров чувствительны к случаю. Значение схемы: схема, определяющая тип, используемый для параметра.

объект response object ( Schema )

Необязательный. Описывает выход из этой функции в формате схемы JSON. Отражает Open API 3.03 объект ответа. Схема определяет тип, используемый для значения ответа функции.

Представление JSON
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  },
  "response": {
    object (Schema)
  }
}

Схема

Объект Schema позволяет определять входные и выходные типы данных. Эти типы могут быть объектами, но также примитивами и массивами. Представляет собой выбранную подмножество объекта схемы OpenAPI 3.0 .

Поля
type enum ( Type )

Необходимый. Тип данных.

string format

Необязательный. Формат данных. Это используется только для примитивных данных данных. Поддерживаемые форматы: для типа номера: float, двойной для целочисленного типа: int32, int64 для типа строки: enum, дата времени

title string

Необязательный. Название схемы.

description string

Необязательный. Краткое описание параметра. Это может содержать примеры использования. Описание параметра может быть отформатировано как отметка.

nullable boolean

Необязательный. Указывает, может ли значение быть нулевым.

enum[] string

Необязательный. Возможные значения элемента типа. Стрига с форматом enum. Например, мы можем определить направление перечисления как: {type: string, format: enum, enum: [«Восток», Север »,« Юг »,« Запад »]}

maxItems string ( int64 format)

Необязательный. Максимальное количество элементов для типа. Аррейт.

Строка minItems string ( int64 format)

Необязательный. Минимальное количество элементов для типа. Аррейт.

Карта properties map (key: string, value: object ( Schema ))

Необязательный. Свойства типа.object.

Объект, содержащий список "key": value . Пример: { "name": "wrench", "mass": "1.3kg", "count": "3" } .

required[] string

Необязательный. Требуемые свойства типа. Объект.

string ( int64 format) minProperties (формат int64)

Необязательный. Минимальное количество свойств для типа.object.

maxProperties string ( int64 format)

Необязательный. Максимальное количество свойств для type.object.

строка minLength string ( int64 format)

Необязательный. Поля схемы для типа строки минимальная длина типа.

String maxLength string ( int64 format)

Необязательный. Максимальная длина типа.

pattern string

Необязательный. Шаблон типа. Стрига, чтобы ограничить строку регулярным выражением.

example value ( Value format)

Необязательный. Пример объекта. Будет заполняться только тогда, когда объект является корнем.

anyOf[] object ( Schema )

Необязательный. Значение должно быть подтверждено против любого (одного или нескольких) подмножествах в списке.

propertyOrdering[] string

Необязательный. Порядок свойств. Не стандартное поле в Open API Spec. Используется для определения порядка свойств в ответе.

Значение default value ( Value format)

Необязательный. Значение по умолчанию поля. В соответствии с схемой JSON это поле предназначено для генераторов документов и не влияет на проверку. Таким образом, он включен здесь и игнорируется так, что разработчики, которые отправляют схемы с полем default не получают ошибок в неизвестном поле.

items object ( Schema )

Необязательный. Схема элементов типа. Аррейт.

minimum number

Необязательный. Поля схемы для типа целочисленного и числа

maximum number

Необязательный. Максимальное значение типа. INTEGER и TYPE.Number

Представление JSON
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

Тип

Тип содержит список типов данных OpenAPI, как определено https://spec.openapis.org/oas/v3.0.3#data-types

Перечисление
TYPE_UNSPECIFIED Не указано, не должно использоваться.
STRING Тип строки.
NUMBER Тип числа.
INTEGER Целочисленный тип.
BOOLEAN Логический тип.
ARRAY Тип массива.
OBJECT Тип объекта.
NULL Нулевой тип.

GoogleSearchRetrieval

Инструмент для получения общедоступных веб -данных для заземления, питания Google.

Поля
dynamicRetrievalConfig object ( DynamicRetrievalConfig )

Определяет динамическую конфигурацию поиска для данного источника.

Представление JSON
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

DynamicretrievalConfig

Описывает параметры для настройки динамического поиска.

Поля
mode enum ( Mode )

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

dynamicThreshold number

Порог, который будет использоваться в динамическом поиске. Если не установлено, используется системное значение по умолчанию.

Представление JSON
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

Режим

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

Перечисление
MODE_UNSPECIFIED Всегда запускает поиск.
MODE_DYNAMIC Запустите поиск только тогда, когда система решает, что это необходимо.

Codeexecution

Этот тип не имеет полей.

Инструмент, который выполняет код, сгенерированный моделью, и автоматически возвращает результат в модель.

См. Также ExecutableCode и CodeExecutionResult , которые генерируются только при использовании этого инструмента.

Googlesearch

Этот тип не имеет полей.

Тип инструмента GoogleSearch. Инструмент для поддержки Google Search в модели. Питается Google.

ToolConfig

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

Поля
functionCallingConfig object ( FunctionCallingConfig )

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

Представление JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

FunctionCallingConfig

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

Поля
mode enum ( Mode )

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

allowedFunctionNames[] string

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

Это должно быть установлено только тогда, когда режим есть. Имена функций должны соответствовать [functionDeclaration.name]. С помощью режима, установленного в любом, модель будет предсказать вызов функции из набора представленных имен функций.

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

Режим

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

Перечисление
MODE_UNSPECIFIED Неуказанный режим вызова функции. Это значение не должно использоваться.
AUTO Поведение модели по умолчанию, модель решает предсказать либо функциональный вызов, либо реакцию естественного языка.
ANY Модель ограничена, чтобы всегда прогнозировать только функциональный вызов. Если установлены «разрешенные функции» имени, прогнозируемый вызов функции будет ограничен любым из «разрешенных функций», иначе, предсказанным вызовом функции будет любым из предоставленных «функциональных деклараций».
NONE Модель не будет предсказывать какой -либо вызов функции. Поведение модели такое же, как при прохождении каких -либо объявлений функции.
VALIDATED Модель решает предсказать либо функциональный вызов, либо ответ естественного языка, но будет проверять функции вызовов с ограниченным декодированием.

USAGEMETADATA

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

Поля
totalTokenCount integer

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

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

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

Метод: CachedContents.create

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

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

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

Запросить тело

Организация запроса содержит экземпляр CachedContent .

Поля
contents[] object ( Content )

Необязательный. Только вход. Неизменен. Контент в кеш.

tools[] object ( Tool )

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

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

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

Использует RFC 3339, где сгенерированный выход всегда будет нормализован Z и использует 0, 3, 6 или 9 дробных цифр. Смещения, кроме «z», также принимаются. Примеры: "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" .

string displayName

Необязательный. Неизменен. Пользовательское значимое отображаемое имя кэшированного контента. Максимум 128 символов Unicode.

string model

Необходимый. Неизменен. Имя Model для использования для кэшированного формата контента: models/{model}

object ( Content ) systemInstruction (Content)

Необязательный. Только вход. Неизменен. Разработчик устанавливает системную инструкцию. В настоящее время только текст.

объект toolConfig object ( ToolConfig )

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

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

from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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'"
    }'
from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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)
from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-1.5-flash-001"
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)
// 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-1.5-flash-001";
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-1.5-flash-001"
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, "user"),
}, 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, "user"),
})
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

Списки кэш -контейнеры.

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

Получить https: / /generativelanguage.googleapis.com /v1beta /cachedContents

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

pageSize integer

Необязательный. Максимальное количество кэшированного содержимого для возврата. Служба может вернуть меньше этого значения. В случае неопределенности, некоторое количество дефолта (по максимум) будет возвращено количество элементов. Максимальное значение составляет 1000; Значения выше 1000 будут принуждены к 1000.

pageToken string

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

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

Запросить тело

Организация запроса должно быть пустым.

Тело ответа

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

В случае успеха тело ответа содержит данные со следующей структурой:

Поля
cachedContents[] object ( CachedContent )

Список кэшированного содержимого.

nextPageToken string

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

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

Метод: CachedContents.get

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

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

Получить https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

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

name string

Необходимый. Имя ресурса, относящееся к записи кэша содержимого. Формат: cachedContents/{id} Это принимает форму cachedContents/{cachedcontent} .

Запросить тело

Организация запроса должно быть пустым.

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

from google import genai

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

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))
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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 Resource (только истечение срока действия обновляется).

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

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
Указывает, когда истечет этот ресурс. expiration может быть только одним из следующих:
Строка expireTime string ( Timestamp format)

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

Использует RFC 3339, где сгенерированный выход всегда будет нормализован Z и использует 0, 3, 6 или 9 дробных цифр. Смещения, кроме «z», также принимаются. Примеры: "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" .

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

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-1.5-flash-001"

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),
)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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} .

Запросить тело

Организация запроса должно быть пустым.

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

from google import genai

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

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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

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

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

Поля
contents[] object ( Content )

Необязательный. Только вход. Неизменен. Контент в кеш.

tools[] object ( Tool )

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

createTime string ( Timestamp format)

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

Использует RFC 3339, где сгенерированный выход всегда будет нормализован Z и использует 0, 3, 6 или 9 дробных цифр. Смещения, кроме «z», также принимаются. Примеры: "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 дробных цифр. Смещения, кроме «z», также принимаются. Примеры: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" или "2014-10-02T15:01:23+05:30" .

object ( UsageMetadata ) usageMetadata (USAGEMETADATA)

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

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

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

Использует RFC 3339, где сгенерированный выход всегда будет нормализован Z и использует 0, 3, 6 или 9 дробных цифр. Смещения, кроме «z», также принимаются. Примеры: "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}

string displayName

Необязательный. Неизменен. Пользовательское значимое отображаемое имя кэшированного контента. Максимум 128 символов Unicode.

string model

Необходимый. Неизменен. Имя Model для использования для кэшированного формата контента: models/{model}

object ( Content ) systemInstruction (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)
  }
}

Содержание

Базовый структурированный данных, содержащий многочасовую контент сообщения.

Content включает в себя поле role , обозначающее производителя Content , и поле parts , содержащее многочасовые данные, которые содержат содержание поворота сообщения.

Поля
parts[] object ( Part )

Заказаны Parts , которые составляют единое сообщение. Части могут иметь разные типы MIME.

role string

Необязательный. Производитель контента. Должен быть либо «пользователь», либо «модель».

Полезно для установки для разговоров с несколькими разворотами, в противном случае можно оставить пустым или неразделенным.

Представление JSON
{
  "parts": [
    {
      object (Part)
    }
  ],
  "role": string
}

Часть

Датат, содержащий носитель, который является частью многопартийного сообщества Content .

Part состоит из данных, которые имеют связанный дата данных. Part может содержать только один из принятых типов в части. Part.data .

В Part должна быть фиксированный тип Iana MIME, определяющий тип и подтип носителя, если поле inlineData заполнено сырыми байтами.

Поля
thought boolean

Необязательный. Указывает, если часть мыслите из модели.

Union type data
data могут быть только одним из следующих:
text string

Встроенный текст.

объект inlineData object ( Blob )

Встроенные медиа -байты.

functionCall object ( FunctionCall )

Прогнозируемая FunctionCall возвращенная из модели, которая содержит строку, представляющую FunctionDeclaration.name с аргументами и их значениями.

functionResponse object ( FunctionResponse )

Результат вывода FunctionCall , которая содержит строку, представляющую FunctionDeclaration.name , и структурированный объект json, содержащий любой выход из функции, используется в качестве контекста для модели.

Объект fileData object ( FileData )

Данные на основе URI.

executableCode object ( ExecutableCode )

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

codeExecutionResult object ( CodeExecutionResult )

Результат выполнения ExecutableCode .

Представление JSON
{
  "thought": boolean,

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  }
  // Union type
}

Капля

Необработанные носители.

Текст не должен быть отправлен в качестве необработанных байтов, используйте поле «Текст».

Поля
mimeType string

Стандартный тип исходных данных IANA. Примеры: - Image/PNG - Image/JPEG Если предоставлен непреодолимый тип MIME, будет возвращена ошибка. Полный список поддерживаемых типов см. Вспомогаемые форматы файлов .

string ( bytes format) data (формат байтов)

Сырые байты для форматов медиа.

Base64-кодированная строка.

Представление JSON
{
  "mimeType": string,
  "data": string
}

FunctionCall

Прогнозируемая FunctionCall возвращенная из модели, которая содержит строку, представляющую FunctionDeclaration.name с аргументами и их значениями.

Поля
id string

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

name string

Необходимый. Имя функции для вызова. Должен быть AZ, AZ, 0-9 или содержать подчеркивание и тире, с максимальной длиной 63.

Объект args object ( Struct format)

Необязательный. Параметры и значения функции в формате объекта JSON.

Представление JSON
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

Функциональный ответ

Результат вывода от FunctionCall , которая содержит строку, представляющую FunctionDeclaration.name , и структурированный объект JSON, содержащий любой выход из функции, используется в качестве контекста для модели. Это должно содержать результат FunctionCall выполненной на основе прогнозирования модели.

Поля
id string

Необязательный. Идентификатор функции вызывает этот ответ для. Заполнено клиентом, чтобы соответствовать соответствующему id вызова функции.

name string

Необходимый. Имя функции для вызова. Должен быть AZ, AZ, 0-9 или содержать подчеркивание и тире, с максимальной длиной 63.

объект response object ( Struct format)

Необходимый. Ответ функции в формате объекта JSON.

Представление JSON
{
  "id": string,
  "name": string,
  "response": {
    object
  }
}

Filedata

Данные на основе URI.

Поля
mimeType string

Необязательный. Стандартный тип исходных данных IANA.

fileUri string

Необходимый. Ури.

Представление JSON
{
  "mimeType": string,
  "fileUri": string
}

ExecutableCode

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

Сгенерировано только при использовании инструмента CodeExecution , в котором код будет автоматически выполнен, и также будет сгенерирован соответствующий CodeExecutionResult .

Поля
language enum ( Language )

Необходимый. Язык программирования code .

code string

Необходимый. Код будет выполнен.

Представление JSON
{
  "language": enum (Language),
  "code": string
}

Язык

Поддерживаемые языки программирования для сгенерированного кода.

Перечисление
LANGUAGE_UNSPECIFIED Неуказанный язык. Это значение не должно использоваться.
PYTHON Python> = 3.10, с Numpy и Simpy.

CodeExecutionResult

Результат выполнения ExecutableCode .

Сгенерированный только при использовании CodeExecution , и всегда следует за part содержащей ExecutableCode .

Поля
outcome enum ( Outcome )

Необходимый. Результат выполнения кода.

output string

Необязательный. Содержит Stdout, когда выполнение кода успешно, STDERR или другое описание в противном случае.

Представление JSON
{
  "outcome": enum (Outcome),
  "output": string
}

Исход

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

Перечисление
OUTCOME_UNSPECIFIED Неуказанный статус. Это значение не должно использоваться.
OUTCOME_OK Выполнение кода завершено успешно.
OUTCOME_FAILED Выполнение кода завершено, но с неудачей. stderr должен содержать причину.
OUTCOME_DEADLINE_EXCEEDED Выполнение кода работало слишком долго и было отменено. Там может или не может быть частичный выход.

Инструмент

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

Tool - это кусок кода, который позволяет системе взаимодействовать с внешними системами для выполнения действия или набора действий вне знаний и объема модели.

Поля
functionDeclarations[] object ( FunctionDeclaration )

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

Модель или система не выполняют функцию. Вместо этого определенная функция может быть возвращена как FunctionCall с аргументами на стороне клиента для выполнения. Модель может принять решение вызвать подмножество этих функций путем заполнения FunctionCall в ответе. Следующий поворот разговора может содержать FunctionResponse с контекстом генерации функции Content.role «Функция» для следующего поворота модели.

googleSearchRetrieval object ( GoogleSearchRetrieval )

Необязательный. Инструмент поиска, который питается Google Search.

object ( CodeExecution ) codeExecution (CodeExecution)

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

Представление JSON
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  }
}

Функциональная декларация

Структурированное представление функции объявления, как определено спецификацией OpenAPI 3.03 . В это объявление включены имя функции и параметры. Эта функциональная декларация является представлением блока кода, который можно использовать в качестве Tool моделью и выполняемый клиентом.

Поля
name string

Необходимый. Имя функции. Должен быть AZ, AZ, 0-9 или содержать подчеркивание и тире, с максимальной длиной 63.

description string

Необходимый. Краткое описание функции.

parameters object ( Schema )

Необязательный. Описывает параметры этой функции. Отражает клавишу open api 3.03 Parameter String string: имя параметра. Названия параметров чувствительны к случаю. Значение схемы: схема, определяющая тип, используемый для параметра.

объект response object ( Schema )

Необязательный. Описывает выход из этой функции в формате схемы JSON. Отражает Open API 3.03 объект ответа. Схема определяет тип, используемый для значения ответа функции.

Представление JSON
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  },
  "response": {
    object (Schema)
  }
}

Схема

Объект Schema позволяет определять входные и выходные типы данных. Эти типы могут быть объектами, но также примитивами и массивами. Представляет собой выбранную подмножество объекта схемы OpenAPI 3.0 .

Поля
type enum ( Type )

Необходимый. Тип данных.

string format

Необязательный. Формат данных. Это используется только для примитивных данных данных. Поддерживаемые форматы: для типа номера: float, двойной для целочисленного типа: int32, int64 для типа строки: enum, дата времени

title string

Необязательный. Название схемы.

description string

Необязательный. Краткое описание параметра. Это может содержать примеры использования. Описание параметра может быть отформатировано как отметка.

nullable boolean

Необязательный. Указывает, может ли значение быть нулевым.

enum[] string

Необязательный. Возможные значения элемента типа. Стрига с форматом enum. Например, мы можем определить направление перечисления как: {type: string, format: enum, enum: [«Восток», Север »,« Юг »,« Запад »]}

maxItems string ( int64 format)

Необязательный. Максимальное количество элементов для типа. Аррейт.

Строка minItems string ( int64 format)

Необязательный. Минимальное количество элементов для типа. Аррейт.

Карта properties map (key: string, value: object ( Schema ))

Необязательный. Свойства типа.object.

Объект, содержащий список "key": value . Пример: { "name": "wrench", "mass": "1.3kg", "count": "3" } .

required[] string

Необязательный. Требуемые свойства типа. Объект.

string ( int64 format) minProperties (формат int64)

Необязательный. Минимальное количество свойств для типа.object.

maxProperties string ( int64 format)

Необязательный. Максимальное количество свойств для type.object.

строка minLength string ( int64 format)

Необязательный. Поля схемы для типа строки минимальная длина типа.

String maxLength string ( int64 format)

Необязательный. Максимальная длина типа.

pattern string

Необязательный. Шаблон типа. Стрига, чтобы ограничить строку регулярным выражением.

example value ( Value format)

Необязательный. Пример объекта. Будет заполняться только тогда, когда объект является корнем.

anyOf[] object ( Schema )

Необязательный. Значение должно быть подтверждено против любого (одного или нескольких) подмножествах в списке.

propertyOrdering[] string

Необязательный. Порядок свойств. Не стандартное поле в Open API Spec. Используется для определения порядка свойств в ответе.

Значение default value ( Value format)

Необязательный. Значение по умолчанию поля. В соответствии с схемой JSON это поле предназначено для генераторов документов и не влияет на проверку. Таким образом, он включен здесь и игнорируется так, что разработчики, которые отправляют схемы с полем default не получают ошибок в неизвестном поле.

items object ( Schema )

Необязательный. Схема элементов типа. Аррейт.

minimum number

Необязательный. Поля схемы для типа целочисленного и числа

maximum number

Необязательный. Максимальное значение типа. INTEGER и TYPE.Number

Представление JSON
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

Тип

Тип содержит список типов данных OpenAPI, как определено https://spec.openapis.org/oas/v3.0.3#data-types

Перечисление
TYPE_UNSPECIFIED Не указано, не должно использоваться.
STRING Тип строки.
NUMBER Тип числа.
INTEGER Целочисленный тип.
BOOLEAN Логический тип.
ARRAY Тип массива.
OBJECT Тип объекта.
NULL Нулевой тип.

GoogleSearchRetrieval

Инструмент для получения общедоступных веб -данных для заземления, питания Google.

Поля
dynamicRetrievalConfig object ( DynamicRetrievalConfig )

Определяет динамическую конфигурацию поиска для данного источника.

Представление JSON
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

DynamicretrievalConfig

Описывает параметры для настройки динамического поиска.

Поля
mode enum ( Mode )

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

dynamicThreshold number

Порог, который будет использоваться в динамическом поиске. Если не установлено, используется системное значение по умолчанию.

Представление JSON
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

Режим

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

Перечисление
MODE_UNSPECIFIED Всегда запускает поиск.
MODE_DYNAMIC Запустите поиск только тогда, когда система решает, что это необходимо.

Codeexecution

Этот тип не имеет полей.

Инструмент, который выполняет код, сгенерированный моделью, и автоматически возвращает результат в модель.

См. Также ExecutableCode и CodeExecutionResult , которые генерируются только при использовании этого инструмента.

Googlesearch

Этот тип не имеет полей.

Тип инструмента GoogleSearch. Инструмент для поддержки Google Search в модели. Питается Google.

ToolConfig

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

Поля
functionCallingConfig object ( FunctionCallingConfig )

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

Представление JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

FunctionCallingConfig

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

Поля
mode enum ( Mode )

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

allowedFunctionNames[] string

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

Это должно быть установлено только тогда, когда режим есть. Имена функций должны соответствовать [functionDeclaration.name]. С помощью режима, установленного в любом, модель будет предсказать вызов функции из набора представленных имен функций.

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

Режим

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

Перечисление
MODE_UNSPECIFIED Неуказанный режим вызова функции. Это значение не должно использоваться.
AUTO Default model behavior, model decides to predict either a function call or a natural language response.
ANY Model is constrained to always predicting a function call only. If "allowedFunctionNames" are set, the predicted function call will be limited to any one of "allowedFunctionNames", else the predicted function call will be any one of the provided "functionDeclarations".
NONE Model will not predict any function call. Model behavior is same as when not passing any function declarations.
VALIDATED Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding.

UsageMetadata

Metadata on the usage of the cached content.

Поля
totalTokenCount integer

Total number of tokens that the cached content consumes.

JSON representation
{
  "totalTokenCount": integer
}
,

Context caching allows you to save and reuse precomputed input tokens that you wish to use repeatedly, for example when asking different questions about the same media file. This can lead to cost and speed savings, depending on the usage. For a detailed introduction, see the Context caching guide.

Method: cachedContents.create

Creates CachedContent resource.

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

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

Request body

The request body contains an instance of CachedContent .

Поля
contents[] object ( Content )

Необязательный. Input only. Immutable. The content to cache.

tools[] object ( Tool )

Необязательный. Input only. Immutable. A list of Tools the model may use to generate the next response

expiration Union type
Specifies when this resource will expire. expiration can be only one of the following:
expireTime string ( Timestamp format)

Timestamp in UTC of when this resource is considered expired. This is always provided on output, regardless of what was sent on input.

Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

ttl string ( Duration format)

Input only. New TTL for this resource, input only.

A duration in seconds with up to nine fractional digits, ending with ' s '. Example: "3.5s" .

displayName string

Необязательный. Immutable. The user-generated meaningful display name of the cached content. Maximum 128 Unicode characters.

model string

Необходимый. Immutable. The name of the Model to use for cached content Format: models/{model}

systemInstruction object ( Content )

Необязательный. Input only. Immutable. Developer set system instruction. Currently text only.

toolConfig object ( ToolConfig )

Необязательный. Input only. Immutable. Tool config. This config is shared for all tools.

Example request

from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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'"
    }'
from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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)
from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-1.5-flash-001"
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)
// 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-1.5-flash-001";
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-1.5-flash-001"
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, "user"),
}, 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, "user"),
})
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())

Response body

If successful, the response body contains a newly created instance of CachedContent .

Method: cachedContents.list

Lists CachedContents.

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

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

Query parameters

pageSize integer

Необязательный. The maximum number of cached contents to return. The service may return fewer than this value. If unspecified, some default (under maximum) number of items will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000.

pageToken string

Необязательный. A page token, received from a previous cachedContents.list call. Provide this to retrieve the subsequent page.

When paginating, all other parameters provided to cachedContents.list must match the call that provided the page token.

Request body

The request body must be empty.

Response body

Response with CachedContents list.

If successful, the response body contains data with the following structure:

Поля
cachedContents[] object ( CachedContent )

List of cached contents.

nextPageToken string

A token, which can be sent as pageToken to retrieve the next page. If this field is omitted, there are no subsequent pages.

JSON representation
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Method: cachedContents.get

Reads CachedContent resource.

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

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

Path parameters

name string

Необходимый. The resource name referring to the content cache entry. Format: cachedContents/{id} It takes the form cachedContents/{cachedcontent} .

Request body

The request body must be empty.

Example request

from google import genai

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

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))
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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"

Response body

If successful, the response body contains an instance of CachedContent .

Method: cachedContents.patch

Updates CachedContent resource (only expiration is updatable).

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

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

Path parameters

cachedContent.name string

Output only. Идентификатор. The resource name referring to the cached content. Format: cachedContents/{id} It takes the form cachedContents/{cachedcontent} .

Query parameters

updateMask string ( FieldMask format)

The list of fields to update.

This is a comma-separated list of fully qualified names of fields. Example: "user.displayName,photo" .

Request body

The request body contains an instance of CachedContent .

Поля
expiration Union type
Specifies when this resource will expire. expiration can be only one of the following:
expireTime string ( Timestamp format)

Timestamp in UTC of when this resource is considered expired. This is always provided on output, regardless of what was sent on input.

Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

ttl string ( Duration format)

Input only. New TTL for this resource, input only.

A duration in seconds with up to nine fractional digits, ending with ' s '. Example: "3.5s" .

Example request

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-1.5-flash-001"

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),
)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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"}'

Response body

If successful, the response body contains an instance of CachedContent .

Method: cachedContents.delete

Deletes CachedContent resource.

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

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

Path parameters

name string

Необходимый. The resource name referring to the content cache entry Format: cachedContents/{id} It takes the form cachedContents/{cachedcontent} .

Request body

The request body must be empty.

Example request

from google import genai

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

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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"

Response body

If successful, the response body is an empty JSON object.

REST Resource: cachedContents

Resource: CachedContent

Content that has been preprocessed and can be used in subsequent request to GenerativeService.

Cached content can be only used with model it was created for.

Поля
contents[] object ( Content )

Необязательный. Input only. Immutable. The content to cache.

tools[] object ( Tool )

Необязательный. Input only. Immutable. A list of Tools the model may use to generate the next response

createTime string ( Timestamp format)

Output only. Creation time of the cache entry.

Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

updateTime string ( Timestamp format)

Output only. When the cache entry was last updated in UTC time.

Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

usageMetadata object ( UsageMetadata )

Output only. Metadata on the usage of the cached content.

expiration Union type
Specifies when this resource will expire. expiration can be only one of the following:
expireTime string ( Timestamp format)

Timestamp in UTC of when this resource is considered expired. This is always provided on output, regardless of what was sent on input.

Uses RFC 3339, where generated output will always be Z-normalized and uses 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

ttl string ( Duration format)

Input only. New TTL for this resource, input only.

A duration in seconds with up to nine fractional digits, ending with ' s '. Example: "3.5s" .

name string

Output only. Идентификатор. The resource name referring to the cached content. Format: cachedContents/{id}

displayName string

Необязательный. Immutable. The user-generated meaningful display name of the cached content. Maximum 128 Unicode characters.

model string

Необходимый. Immutable. The name of the Model to use for cached content Format: models/{model}

systemInstruction object ( Content )

Необязательный. Input only. Immutable. Developer set system instruction. Currently text only.

toolConfig object ( ToolConfig )

Необязательный. Input only. Immutable. Tool config. This config is shared for all tools.

JSON representation
{
  "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)
  }
}

Содержание

The base structured datatype containing multi-part content of a message.

A Content includes a role field designating the producer of the Content and a parts field containing multi-part data that contains the content of the message turn.

Поля
parts[] object ( Part )

Ordered Parts that constitute a single message. Parts may have different MIME types.

role string

Необязательный. The producer of the content. Must be either 'user' or 'model'.

Useful to set for multi-turn conversations, otherwise can be left blank or unset.

JSON representation
{
  "parts": [
    {
      object (Part)
    }
  ],
  "role": string
}

Часть

A datatype containing media that is part of a multi-part Content message.

A Part consists of data which has an associated datatype. A Part can only contain one of the accepted types in Part.data .

A Part must have a fixed IANA MIME type identifying the type and subtype of the media if the inlineData field is filled with raw bytes.

Поля
thought boolean

Необязательный. Indicates if the part is thought from the model.

data Union type
data can be only one of the following:
text string

Inline text.

inlineData object ( Blob )

Inline media bytes.

functionCall object ( FunctionCall )

A predicted FunctionCall returned from the model that contains a string representing the FunctionDeclaration.name with the arguments and their values.

functionResponse object ( FunctionResponse )

The result output of a FunctionCall that contains a string representing the FunctionDeclaration.name and a structured JSON object containing any output from the function is used as context to the model.

fileData object ( FileData )

URI based data.

executableCode object ( ExecutableCode )

Code generated by the model that is meant to be executed.

codeExecutionResult object ( CodeExecutionResult )

Result of executing the ExecutableCode .

JSON representation
{
  "thought": boolean,

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  }
  // Union type
}

Blob

Raw media bytes.

Text should not be sent as raw bytes, use the 'text' field.

Поля
mimeType string

The IANA standard MIME type of the source data. Examples: - image/png - image/jpeg If an unsupported MIME type is provided, an error will be returned. For a complete list of supported types, see Supported file formats .

data string ( bytes format)

Raw bytes for media formats.

A base64-encoded string.

JSON representation
{
  "mimeType": string,
  "data": string
}

FunctionCall

A predicted FunctionCall returned from the model that contains a string representing the FunctionDeclaration.name with the arguments and their values.

Поля
id string

Необязательный. The unique id of the function call. If populated, the client to execute the functionCall and return the response with the matching id .

name string

Необходимый. The name of the function to call. Must be az, AZ, 0-9, or contain underscores and dashes, with a maximum length of 63.

args object ( Struct format)

Необязательный. The function parameters and values in JSON object format.

JSON representation
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

FunctionResponse

The result output from a FunctionCall that contains a string representing the FunctionDeclaration.name and a structured JSON object containing any output from the function is used as context to the model. This should contain the result of a FunctionCall made based on model prediction.

Поля
id string

Необязательный. The id of the function call this response is for. Populated by the client to match the corresponding function call id .

name string

Необходимый. The name of the function to call. Must be az, AZ, 0-9, or contain underscores and dashes, with a maximum length of 63.

response object ( Struct format)

Необходимый. The function response in JSON object format.

JSON representation
{
  "id": string,
  "name": string,
  "response": {
    object
  }
}

FileData

URI based data.

Поля
mimeType string

Необязательный. The IANA standard MIME type of the source data.

fileUri string

Необходимый. URI.

JSON representation
{
  "mimeType": string,
  "fileUri": string
}

ExecutableCode

Code generated by the model that is meant to be executed, and the result returned to the model.

Only generated when using the CodeExecution tool, in which the code will be automatically executed, and a corresponding CodeExecutionResult will also be generated.

Поля
language enum ( Language )

Необходимый. Programming language of the code .

code string

Необходимый. The code to be executed.

JSON representation
{
  "language": enum (Language),
  "code": string
}

Язык

Supported programming languages for the generated code.

Enums
LANGUAGE_UNSPECIFIED Unspecified language. This value should not be used.
PYTHON Python >= 3.10, with numpy and simpy available.

CodeExecutionResult

Result of executing the ExecutableCode .

Only generated when using the CodeExecution , and always follows a part containing the ExecutableCode .

Поля
outcome enum ( Outcome )

Необходимый. Outcome of the code execution.

output string

Необязательный. Contains stdout when code execution is successful, stderr or other description otherwise.

JSON representation
{
  "outcome": enum (Outcome),
  "output": string
}

Исход

Enumeration of possible outcomes of the code execution.

Enums
OUTCOME_UNSPECIFIED Unspecified status. This value should not be used.
OUTCOME_OK Code execution completed successfully.
OUTCOME_FAILED Code execution finished but with a failure. stderr should contain the reason.
OUTCOME_DEADLINE_EXCEEDED Code execution ran for too long, and was cancelled. There may or may not be a partial output present.

Инструмент

Tool details that the model may use to generate response.

A Tool is a piece of code that enables the system to interact with external systems to perform an action, or set of actions, outside of knowledge and scope of the model.

Поля
functionDeclarations[] object ( FunctionDeclaration )

Необязательный. A list of FunctionDeclarations available to the model that can be used for function calling.

The model or system does not execute the function. Instead the defined function may be returned as a FunctionCall with arguments to the client side for execution. The model may decide to call a subset of these functions by populating FunctionCall in the response. The next conversation turn may contain a FunctionResponse with the Content.role "function" generation context for the next model turn.

googleSearchRetrieval object ( GoogleSearchRetrieval )

Необязательный. Retrieval tool that is powered by Google search.

codeExecution object ( CodeExecution )

Необязательный. Enables the model to execute code as part of generation.

JSON representation
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  }
}

FunctionDeclaration

Structured representation of a function declaration as defined by the OpenAPI 3.03 specification . Included in this declaration are the function name and parameters. This FunctionDeclaration is a representation of a block of code that can be used as a Tool by the model and executed by the client.

Поля
name string

Необходимый. The name of the function. Must be az, AZ, 0-9, or contain underscores and dashes, with a maximum length of 63.

description string

Необходимый. A brief description of the function.

parameters object ( Schema )

Необязательный. Describes the parameters to this function. Reflects the Open API 3.03 Parameter Object string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter.

response object ( Schema )

Необязательный. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function.

JSON representation
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  },
  "response": {
    object (Schema)
  }
}

Схема

The Schema object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an OpenAPI 3.0 schema object .

Поля
type enum ( Type )

Необходимый. Data type.

string format

Необязательный. The format of the data. This is used only for primitive datatypes. Supported formats: for NUMBER type: float, double for INTEGER type: int32, int64 for STRING type: enum, date-time

title string

Необязательный. The title of the schema.

description string

Необязательный. A brief description of the parameter. This could contain examples of use. Parameter description may be formatted as Markdown.

nullable boolean

Необязательный. Indicates if the value may be null.

enum[] string

Необязательный. Possible values of the element of Type.STRING with enum format. For example we can define an Enum Direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}

maxItems string ( int64 format)

Необязательный. Maximum number of the elements for Type.ARRAY.

minItems string ( int64 format)

Необязательный. Minimum number of the elements for Type.ARRAY.

properties map (key: string, value: object ( Schema ))

Необязательный. Properties of Type.OBJECT.

An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" } .

required[] string

Необязательный. Required properties of Type.OBJECT.

minProperties string ( int64 format)

Необязательный. Minimum number of the properties for Type.OBJECT.

maxProperties string ( int64 format)

Необязательный. Maximum number of the properties for Type.OBJECT.

minLength string ( int64 format)

Необязательный. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING

maxLength string ( int64 format)

Необязательный. Maximum length of the Type.STRING

pattern string

Необязательный. Pattern of the Type.STRING to restrict a string to a regular expression.

example value ( Value format)

Необязательный. Example of the object. Will only populated when the object is the root.

anyOf[] object ( Schema )

Необязательный. The value should be validated against any (one or more) of the subschemas in the list.

propertyOrdering[] string

Необязательный. The order of the properties. Not a standard field in open api spec. Used to determine the order of the properties in the response.

default value ( Value format)

Необязательный. Default value of the field. Per JSON Schema, this field is intended for documentation generators and doesn't affect validation. Thus it's included here and ignored so that developers who send schemas with a default field don't get unknown-field errors.

items object ( Schema )

Необязательный. Schema of the elements of Type.ARRAY.

minimum number

Необязательный. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER

maximum number

Необязательный. Maximum value of the Type.INTEGER and Type.NUMBER

JSON representation
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

Тип

Type contains the list of OpenAPI data types as defined by https://spec.openapis.org/oas/v3.0.3#data-types

Enums
TYPE_UNSPECIFIED Not specified, should not be used.
STRING String type.
NUMBER Number type.
INTEGER Integer type.
BOOLEAN Boolean type.
ARRAY Array type.
OBJECT Object type.
NULL Null type.

GoogleSearchRetrieval

Tool to retrieve public web data for grounding, powered by Google.

Поля
dynamicRetrievalConfig object ( DynamicRetrievalConfig )

Specifies the dynamic retrieval configuration for the given source.

JSON representation
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

DynamicRetrievalConfig

Describes the options to customize dynamic retrieval.

Поля
mode enum ( Mode )

The mode of the predictor to be used in dynamic retrieval.

dynamicThreshold number

The threshold to be used in dynamic retrieval. If not set, a system default value is used.

JSON representation
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

Режим

The mode of the predictor to be used in dynamic retrieval.

Enums
MODE_UNSPECIFIED Always trigger retrieval.
MODE_DYNAMIC Run retrieval only when system decides it is necessary.

CodeExecution

This type has no fields.

Tool that executes code generated by the model, and automatically returns the result to the model.

See also ExecutableCode and CodeExecutionResult which are only generated when using this tool.

GoogleSearch

This type has no fields.

GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google.

ToolConfig

The Tool configuration containing parameters for specifying Tool use in the request.

Поля
functionCallingConfig object ( FunctionCallingConfig )

Необязательный. Function calling config.

JSON representation
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

FunctionCallingConfig

Configuration for specifying function calling behavior.

Поля
mode enum ( Mode )

Необязательный. Specifies the mode in which function calling should execute. If unspecified, the default value will be set to AUTO.

allowedFunctionNames[] string

Необязательный. A set of function names that, when provided, limits the functions the model will call.

This should only be set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided.

JSON representation
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Режим

Defines the execution behavior for function calling by defining the execution mode.

Enums
MODE_UNSPECIFIED Unspecified function calling mode. This value should not be used.
AUTO Default model behavior, model decides to predict either a function call or a natural language response.
ANY Model is constrained to always predicting a function call only. If "allowedFunctionNames" are set, the predicted function call will be limited to any one of "allowedFunctionNames", else the predicted function call will be any one of the provided "functionDeclarations".
NONE Model will not predict any function call. Model behavior is same as when not passing any function declarations.
VALIDATED Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding.

UsageMetadata

Metadata on the usage of the cached content.

Поля
totalTokenCount integer

Total number of tokens that the cached content consumes.

JSON representation
{
  "totalTokenCount": integer
}