Caching

コンテキスト キャッシュ保存を使用すると、同じメディア ファイルについて異なる質問をする場合など、繰り返し使用する事前計算された入力トークンを保存して再利用できます。これにより、使用状況に応じてコストと速度を節約できます。詳細な概要については、コンテキスト キャッシュ保存ガイドをご覧ください。

メソッド: cachedContents.create

CachedContent リソースを作成します。

エンドポイント

投稿 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 で終わる小数点以下 9 桁までの秒単位の期間。例: "3.5s"

displayName string

省略可。変更不可。キャッシュに保存されたコンテンツのユーザー作成のわかりやすい表示名。最大 128 Unicode 文字。

model string

必須。変更不可。キャッシュに保存されたコンテンツに使用する Model の名前。形式: models/{model}

systemInstruction object (Content)

省略可。入力のみの変更不可。デベロッパーがシステム指示を設定します。現在はテキストのみです。

toolConfig object (ToolConfig)

省略可。入力のみの変更不可。ツール構成。この構成はすべてのツールで共有されます。

リクエスト例

基本

Python

from google import genai
from google.genai import types

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

Node.js

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

Go

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

modelName := "gemini-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, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache created:")
fmt.Println(cache)

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

Shell

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

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

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

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

送信者名

Python

from google import genai
from google.genai import types

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

Node.js

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

Go

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

modelName := "gemini-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, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
cacheName := cache.Name

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

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

チャットから作成されたタスク

Python

from google import genai
from google.genai import types

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

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const modelName = "gemini-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);

Go

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

modelName := "gemini-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, genai.RoleUser),
}, nil)
if err != nil {
	log.Fatal(err)
}

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

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

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

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

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

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

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

レスポンスの本文

成功した場合、レスポンスの本文には、新しく作成された CachedContent のインスタンスが含まれます。

メソッド: cachedContents.list

CachedContents を一覧表示します。

エンドポイント

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

クエリ パラメータ

pageSize integer

省略可。返すキャッシュ コンテンツの最大数。サービスが返す値はこれよりも少ないことがあります。指定されていない場合は、デフォルトの(最大数以下の)アイテム数が返されます。最大値は 1,000 です。1,000 を超える値は 1,000 に強制変換されます。

pageToken string

省略可。前回の cachedContents.list 呼び出しから受け取ったページトークン。後続のページを取得するにはこれを指定します。

ページ分割を行う場合、cachedContents.list に指定する他のすべてのパラメータは、ページトークンを提供した呼び出しと一致する必要があります。

リクエストの本文

リクエストの本文は空にする必要があります。

レスポンスの本文

CachedContents リストを含むレスポンス。

成功した場合、レスポンスの本文には次の構造のデータが含まれます。

フィールド
cachedContents[] object (CachedContent)

キャッシュに保存されたコンテンツのリスト。

nextPageToken string

次のページを取得するために pageToken として送信できるトークン。このフィールドを省略すると、後続のページはなくなります。

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

メソッド: cachedContents.get

CachedContent リソースを読み取ります。

エンドポイント

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

パスパラメータ

name string

必須。コンテンツ キャッシュ エントリを参照するリソース名。形式: cachedContents/{id} 形式は cachedContents/{cachedcontent} です。

リクエストの本文

リクエストの本文は空にする必要があります。

リクエスト例

Python

from google import genai

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

Node.js

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

Go

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

modelName := "gemini-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, genai.RoleUser),
}

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

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

Shell

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/*}

パスパラメータ

cachedContent.name string

出力専用。ID。キャッシュに保存されたコンテンツを参照するリソース名。形式: 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 で終わる小数点以下 9 桁までの秒単位の期間。例: "3.5s"

リクエスト例

Python

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

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

Node.js

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

Go

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

modelName := "gemini-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, genai.RoleUser),
}

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

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

Shell

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/*}

パスパラメータ

name string

必須。コンテンツ キャッシュ エントリを参照するリソース名。形式: cachedContents/{id}cachedContents/{cachedcontent} の形式になります。

リクエストの本文

リクエストの本文は空にする必要があります。

リクエスト例

Python

from google import genai

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

Node.js

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

Go

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

modelName := "gemini-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, genai.RoleUser),
}

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

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

Shell

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

レスポンスの本文

成功した場合、レスポンスの本文は空の JSON オブジェクトになります。

REST リソース: cachedContents

リソース: CachedContent

前処理され、GenerativeService への後続のリクエストで使用できるコンテンツ。

キャッシュに保存されたコンテンツは、作成されたモデルでのみ使用できます。

フィールド
contents[] object (Content)

省略可。入力のみの変更不可。キャッシュに保存するコンテンツ。

tools[] object (Tool)

省略可。入力のみの変更不可。モデルが次のレスポンスの生成に使用できる Tools のリスト

createTime string (Timestamp format)

出力専用。キャッシュ エントリの作成日時。

RFC 3339 を使用します。生成された出力は常に Z 正規化され、小数点以下は 0、3、6、または 9 桁になります。「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)

出力専用。キャッシュに保存されたコンテンツの使用に関するメタデータ。

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 で終わる小数点以下 9 桁までの秒単位の期間。例: "3.5s"

name string

出力専用。ID。キャッシュに保存されたコンテンツを参照するリソース名。形式: cachedContents/{id}

displayName string

省略可。変更不可。キャッシュに保存されたコンテンツのユーザー作成のわかりやすい表示名。最大 128 Unicode 文字。

model string

必須。変更不可。キャッシュに保存されたコンテンツに使用する Model の名前。形式: models/{model}

systemInstruction object (Content)

省略可。入力のみの変更不可。デベロッパーがシステム指示を設定します。現在はテキストのみです。

toolConfig object (ToolConfig)

省略可。入力のみの変更不可。ツール構成。この構成はすべてのツールで共有されます。

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

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

コンテンツ

メッセージのマルチパート コンテンツを含む基本的な構造化データ型。

Content には、Content のプロデューサーを指定する role フィールドと、メッセージ ターンのコンテンツを含むマルチパート データを含む parts フィールドが含まれます。

フィールド
parts[] object (Part)

1 つのメッセージを構成する順序付きの Parts。パーツによって MIME タイプが異なる場合があります。

role string

省略可。コンテンツの作成者。「user」または「model」のいずれかである必要があります。

マルチターンの会話を設定する場合に便利です。それ以外の場合は、空白のままにするか、未設定のままにできます。

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

Part

マルチパート Content メッセージの一部であるメディアを含むデータ型。

Part は、関連付けられたデータ型を持つデータで構成されます。Part には、Part.data で受け入れられるタイプのいずれか 1 つのみを含めることができます。

inlineData フィールドに未加工のバイトが入力されている場合、Part にはメディアのタイプとサブタイプを識別する固定の IANA MIME タイプが必要です。

フィールド
thought boolean

省略可。モデルによって考えられた部分かどうかを示します。

thoughtSignature string (bytes format)

省略可。後続のリクエストで再利用できるように、思考の不透明な署名。

Base64 でエンコードされた文字列。

data Union type
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 の実行結果。

metadata Union type
データの前処理の追加を制御します。metadata は次のいずれかになります。
videoMetadata object (VideoMetadata)

省略可。動画のメタデータ。メタデータは、動画データが inlineData または fileData で表されている場合にのみ指定する必要があります。

JSON 表現
{
  "thought": boolean,
  "thoughtSignature": string,

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

  // metadata
  "videoMetadata": {
    object (VideoMetadata)
  }
  // Union type
}

Blob

未加工のメディア バイト。

テキストは未加工のバイトとして送信しないでください。'text' フィールドを使用してください。

フィールド
mimeType string

ソースデータの IANA 標準 MIME タイプ。例: - image/png - image/jpeg サポートされていない MIME タイプが指定された場合は、エラーが返されます。サポートされているタイプの一覧については、サポートされているファイル形式をご覧ください。

data string (bytes format)

メディア フォーマットの未加工のバイト。

Base64 でエンコードされた文字列。

JSON 表現
{
  "mimeType": string,
  "data": string
}

FunctionCall

モデルから返される、予測された FunctionCall。引数とその値を含む FunctionDeclaration.name を表す文字列が含まれます。

フィールド
id string

省略可。関数呼び出しの一意の ID。入力されている場合、functionCall を実行して、一致する id を含むレスポンスを返すクライアント。

name string

必須。呼び出す関数の名前。a ~ z、A ~ Z、0 ~ 9 にする必要があり、アンダースコアとダッシュを含めることができます。最大長は 63 文字です。

args object (Struct format)

省略可。JSON オブジェクト形式の関数パラメータと値。

JSON 表現
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

FunctionResponse

FunctionCall からの結果の出力。FunctionDeclaration.name を表す文字列と、関数からの出力を含む構造化 JSON オブジェクトが含まれます。これはモデルのコンテキストとして使用されます。これには、モデル予測に基づいて作成された FunctionCall の結果が含まれている必要があります。

フィールド
id string

省略可。このレスポンスが対象とする関数呼び出しの ID。対応する関数呼び出し id と一致するようにクライアントによって入力されます。

name string

必須。呼び出す関数の名前。a ~ z、A ~ Z、0 ~ 9 にする必要があり、アンダースコアとダッシュを含めることができます。最大長は 63 文字です。

response object (Struct format)

必須。JSON オブジェクト形式の関数のレスポンス。

willContinue boolean

省略可。関数呼び出しが継続され、さらにレスポンスが返されることを示し、関数呼び出しをジェネレータに変換します。NON_BLOCKING 関数呼び出しにのみ適用され、それ以外の場合は無視されます。false に設定すると、今後の回答は考慮されません。関数呼び出しが完了したことを示すために、willContinue=False を含む空の response を返すことが許可されています。この場合でも、モデルの生成がトリガーされる可能性があります。生成をトリガーして関数呼び出しを終了しないようにするには、schedulingSILENT に設定します。

scheduling enum (Scheduling)

省略可。会話でレスポンスをスケジュールする方法を指定します。NON_BLOCKING 関数呼び出しにのみ適用され、それ以外の場合は無視されます。デフォルトは WHEN_IDLE です。

JSON 表現
{
  "id": string,
  "name": string,
  "response": {
    object
  },
  "willContinue": boolean,
  "scheduling": enum (Scheduling)
}

スケジュール

会話でレスポンスをスケジュールする方法を指定します。

列挙型
SCHEDULING_UNSPECIFIED この値は使用されません。
SILENT 結果を会話コンテキストに追加するだけで、生成を中断したりトリガーしたりしないでください。
WHEN_IDLE 結果を会話コンテキストに追加し、進行中の生成を中断することなく出力を生成するようにプロンプトします。
INTERRUPT 結果を会話コンテキストに追加し、進行中の生成を中断して、出力を生成するようプロンプトします。

FileData

URI ベースのデータ。

フィールド
mimeType string

省略可。ソースデータの IANA 標準 MIME タイプ。

fileUri string

必須。URI。

JSON 表現
{
  "mimeType": string,
  "fileUri": string
}

ExecutableCode

実行されることを想定してモデルによって生成されたコードと、モデルに返される結果。

CodeExecution ツールを使用した場合にのみ生成されます。この場合、コードが自動的に実行され、対応する CodeExecutionResult も生成されます。

フィールド
language enum (Language)

必須。code のプログラミング言語。

code string

必須。実行されるコード。

JSON 表現
{
  "language": enum (Language),
  "code": string
}

言語

生成されたコードでサポートされているプログラミング言語。

列挙型
LANGUAGE_UNSPECIFIED 言語が指定されていません。この値は使用しないでください。
PYTHON numpy と simpy が利用可能な Python >= 3.10。

CodeExecutionResult

ExecutableCode の実行結果。

CodeExecution を使用する場合にのみ生成され、常に ExecutableCode を含む part が続きます。

フィールド
outcome enum (Outcome)

必須。コード実行の結果。

output string

省略可。コードの実行が成功した場合は stdout、それ以外の場合は stderr またはその他の説明が含まれます。

JSON 表現
{
  "outcome": enum (Outcome),
  "output": string
}

結果

コード実行の結果の列挙。

列挙型
OUTCOME_UNSPECIFIED ステータスが指定されていません。この値は使用しないでください。
OUTCOME_OK コードの実行が正常に完了しました。
OUTCOME_FAILED コードの実行は完了しましたが、失敗しました。stderr に理由を含める必要があります。
OUTCOME_DEADLINE_EXCEEDED コードの実行に時間がかかり過ぎたため、キャンセルされました。部分的な出力が存在する場合と存在しない場合があります。

VideoMetadata

メタデータは、入力動画コンテンツを記述します。

フィールド
startOffset string (Duration format)

省略可。動画の開始オフセット

s で終わる小数点以下 9 桁までの秒単位の期間。例: "3.5s"

endOffset string (Duration format)

省略可。動画の終了オフセット。

s で終わる小数点以下 9 桁までの秒単位の期間。例: "3.5s"

fps number

省略可。モデルに送信された動画のフレームレート。指定しない場合、デフォルト値は 1.0 になります。fps の範囲は (0.0, 24.0] です。

JSON 表現
{
  "startOffset": string,
  "endOffset": string,
  "fps": number
}

ツール

モデルがレスポンスの生成に使用する可能性のあるツールの詳細。

Tool は、システムが外部システムと対話して、モデルの知識や範囲外のアクションまたは一連のアクションを実行できるようにするコードです。

フィールド
functionDeclarations[] object (FunctionDeclaration)

省略可。関数呼び出しに使用できるモデルで使用可能な FunctionDeclarations のリスト。

モデルまたはシステムが関数を実行しません。代わりに、定義された関数が実行のために引数とともに FunctionCall としてクライアント側に返されることがあります。モデルは、レスポンスで FunctionCall を入力して、これらの関数のサブセットを呼び出すことを決定する場合があります。次の会話ターンには、次のモデルターンの Content.role「関数」生成コンテキストを含む FunctionResponse が含まれる場合があります。

googleSearchRetrieval object (GoogleSearchRetrieval)

省略可。Google 検索を利用した取得ツール。

codeExecution object (CodeExecution)

省略可。モデルが生成の一部としてコードを実行できるようにします。

urlContext object (UrlContext)

省略可。URL コンテキストの取得をサポートするツール。

JSON 表現
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  },
  "urlContext": {
    object (UrlContext)
  }
}

FunctionDeclaration

OpenAPI 3.03 仕様で定義されている関数宣言の構造化表現。この宣言には、関数名とパラメータが含まれます。この FunctionDeclaration は、モデルによって Tool として使用され、クライアントによって実行されるコードブロックの表現です。

フィールド
name string

必須。関数の名前。a ~ z、A ~ Z、0 ~ 9 にする必要があり、アンダースコアとダッシュを含めることができます。最大長は 63 文字です。

description string

必須。関数の簡単な説明。

behavior enum (Behavior)

省略可。関数の動作を指定します。現在、BidiGenerateContent メソッドでのみサポートされています。

parameters object (Schema)

省略可。この関数のパラメータについて説明します。Open API 3.03 パラメータ オブジェクトの文字列キー(パラメータの名前)を反映します。パラメータ名では大文字と小文字が区別されます。スキーマ値: パラメータに使用される型を定義するスキーマ。

parametersJsonSchema value (Value format)

省略可。関数のパラメータを JSON スキーマ形式で記述します。スキーマは、プロパティが関数のパラメータであるオブジェクトを記述する必要があります。次に例を示します。

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "additionalProperties": false,
  "required": ["name", "age"],
  "propertyOrdering": ["name", "age"]
}

このフィールドは parameters と相互に排他的です。

response object (Schema)

省略可。この関数からの出力を JSON スキーマ形式で記述します。Open API 3.03 レスポンス オブジェクトを反映します。スキーマは、関数のレスポンス値に使用される型を定義します。

responseJsonSchema value (Value format)

省略可。この関数からの出力を JSON スキーマ形式で記述します。スキーマで指定された値は、関数のレスポンス値です。

このフィールドは response と相互に排他的です。

JSON 表現
{
  "name": string,
  "description": string,
  "behavior": enum (Behavior),
  "parameters": {
    object (Schema)
  },
  "parametersJsonSchema": value,
  "response": {
    object (Schema)
  },
  "responseJsonSchema": value
}

スキーマ

Schema オブジェクトを使用すると、入力データ型と出力データ型を定義できます。これらの型はオブジェクトにできますが、プリミティブや配列にもできます。OpenAPI 3.0 スキーマ オブジェクトの選択されたサブセットを表します。

フィールド
type enum (Type)

必須。データ型。

format string

省略可。データの形式。これはプリミティブ データ型でのみ使用されます。サポートされている形式: NUMBER 型の場合: float、double INTEGER 型の場合: int32、int64 STRING 型の場合: enum、date-time

title string

省略可。スキーマのタイトル。

description string

省略可。パラメータの簡単な説明。これには使用例が含まれることがあります。パラメータの説明は Markdown 形式で記述できます。

nullable boolean

省略可。値が null の可能性があるかどうかを示します。

enum[] string

省略可。Type.STRING の要素の可能な値(列挙型形式)。たとえば、列挙型 Direction を {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} として定義できます。

maxItems string (int64 format)

省略可。Type.ARRAY の要素の最大数。

minItems string (int64 format)

省略可。Type.ARRAY の要素の最小数。

properties map (key: string, value: object (Schema))

省略可。Type.OBJECT のプロパティ。

"key": value ペアのリストを含むオブジェクト。例: { "name": "wrench", "mass": "1.3kg", "count": "3" }

required[] string

省略可。Type.OBJECT の必須プロパティ。

minProperties string (int64 format)

省略可。Type.OBJECT のプロパティの最小数。

maxProperties string (int64 format)

省略可。Type.OBJECT のプロパティの最大数。

minLength string (int64 format)

省略可。SCHEMA FIELDS FOR TYPE STRING 型の最小長

maxLength string (int64 format)

省略可。Type.STRING の最大長

pattern string

省略可。文字列を正規表現に制限する Type.STRING のパターン。

example value (Value format)

省略可。オブジェクトの例。オブジェクトがルートの場合にのみ入力されます。

anyOf[] object (Schema)

省略可。値は、リスト内のサブスキーマのいずれか(1 つ以上)に対して検証される必要があります。

propertyOrdering[] string

省略可。プロパティの順序。OpenAPI 仕様の標準フィールドではありません。レスポンス内のプロパティの順序を決定するために使用されます。

default value (Value format)

省略可。フィールドのデフォルト値。JSON スキーマでは、このフィールドはドキュメント ジェネレータを対象としており、検証には影響しません。そのため、default フィールドを含むスキーマを送信するデベロッパーが不明なフィールド エラーを受け取らないように、ここで無視されます。

items object (Schema)

省略可。Type.ARRAY の要素のスキーマ。

minimum number

省略可。SCHEMA FIELDS FOR TYPE INTEGER and 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
}

タイプ

Type には、https://spec.openapis.org/oas/v3.0.3#data-types で定義されている OpenAPI データ型のリストが含まれます。

列挙型
TYPE_UNSPECIFIED 指定されていません。使用しないでください。
STRING 文字列型。
NUMBER 数値型。
INTEGER 整数型。
BOOLEAN ブール型。
ARRAY 配列型。
OBJECT オブジェクトのタイプ。
NULL Null 型。

動作

関数の動作を定義します。デフォルトは BLOCKING です。

列挙型
UNSPECIFIED この値は使用されません。
BLOCKING 設定されている場合、システムは関数レスポンスを受け取るまで待機してから、会話を続行します。
NON_BLOCKING 設定されている場合、システムは関数レスポンスの受信を待機しません。代わりに、ユーザーとモデル間の会話を維持しながら、関数レスポンスが利用可能になった時点で処理を試みます。

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

この型にはフィールドがありません。

モデルによって生成されたコードを実行し、結果をモデルに自動的に返すツール。

このツールを使用した場合にのみ生成される ExecutableCodeCodeExecutionResult もご覧ください。

GoogleSearch

GoogleSearch ツールタイプ。モデルで Google 検索をサポートするツール。Powered by Google。

フィールド
timeRangeFilter object (Interval)

省略可。検索結果を特定の期間に絞り込みます。開始時刻を設定した場合は、終了時刻も設定する必要があります(逆も同様です)。

JSON 表現
{
  "timeRangeFilter": {
    object (Interval)
  }
}

間隔

時間間隔を表します。Timestamp の開始(この時間を含む)と Timestamp の終了(この時間を除く)としてエンコードされます。

開始は終了以下にする必要があります。開始時刻と終了時刻が同じ場合、間隔は空になります(時刻と一致しません)。開始と終了の両方が指定されていない場合、間隔は任意の時刻と一致します。

フィールド
startTime 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"

endTime 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"

JSON 表現
{
  "startTime": string,
  "endTime": string
}

UrlContext

この型にはフィールドがありません。

URL コンテキストの取得をサポートするツール。

ToolConfig

リクエストで Tool の使用を指定するためのパラメータを含むツール構成。

フィールド
functionCallingConfig object (FunctionCallingConfig)

省略可。関数呼び出しの構成。

JSON 表現
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

FunctionCallingConfig

関数呼び出しの動作を指定するための構成。

フィールド
mode enum (Mode)

省略可。関数呼び出しを実行するモードを指定します。指定しない場合、デフォルト値は AUTO に設定されます。

allowedFunctionNames[] string

省略可。指定すると、モデルが呼び出す関数を制限する関数名のセット。

Mode が ANY の場合にのみ設定する必要があります。関数名は [FunctionDeclaration.name] と一致する必要があります。モードを ANY に設定すると、モデルは指定された関数名のセットから関数呼び出しを予測します。

JSON 表現
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

モード

実行モードを定義して、関数呼び出しの実行動作を定義します。

列挙型
MODE_UNSPECIFIED 関数呼び出しモードが指定されていません。この値は使用しないでください。
AUTO デフォルトのモデルの動作。モデルは、関数呼び出しまたは自然言語によるレスポンスのどちらを予測するかを決定します。
ANY モデルは、常に関数呼び出しのみを予測するように制約されています。「allowedFunctionNames」が設定されている場合、予測された関数呼び出しは「allowedFunctionNames」のいずれかに限定されます。それ以外の場合、予測された関数呼び出しは、指定された「functionDeclarations」のいずれかになります。
NONE モデルは関数呼び出しを予測しません。モデルの動作は、関数宣言を渡さない場合と同じです。
VALIDATED モデルは、関数呼び出しと自然言語によるレスポンスのどちらを予測するかを決定しますが、制約付きデコードを使用して関数呼び出しを検証します。

UsageMetadata

キャッシュに保存されたコンテンツの使用に関するメタデータ。

フィールド
totalTokenCount integer

キャッシュに保存されたコンテンツが消費するトークンの合計数。

JSON 表現
{
  "totalTokenCount": integer
}