Caching

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

メソッド: cachedContents.create

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

エンドポイント

post 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-3.7-flash"

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

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

Node.js

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

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

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

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

Go

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

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

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

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-3.7-flash"

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

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

Node.js

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

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

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

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

Go

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

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

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

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

チャットから

Python

from google import genai
from google.genai import types

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

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

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

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

Node.js

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

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

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

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

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

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

Go

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

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

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

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

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

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

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

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

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

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

レスポンスの本文

成功した場合、レスポンスの本文には、新しく作成された 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-3.7-flash"

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

Node.js

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

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

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

Go

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

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

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

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

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-3.7-flash"

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

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

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

Node.js

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

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

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

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

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

Go

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

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

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

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

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 リソースを削除します。

エンドポイント

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

パスパラメータ

name string

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

リクエストの本文

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

リクエスト例

Python

from google import genai

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

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

Node.js

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

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

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

Go

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

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

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

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

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)
  }
}

ToolConfig

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

フィールド
functionCallingConfig object (FunctionCallingConfig)

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

retrievalConfig object (RetrievalConfig)

省略可。取得構成。

includeServerSideToolInvocations boolean

省略可。true の場合、API レスポンスには、サーバーサイドのツール呼び出しとレスポンスが Content メッセージ内に含まれます。これにより、クライアントはサーバーのツール操作を監視できます。

JSON 表現
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

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

フィールド
mode enum (Mode)

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

allowedFunctionNames[] string

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

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

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

モード

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

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

RetrievalConfig

取得構成。

フィールド
latLng object (LatLng)

省略可。ユーザーの所在地。

languageCode string

省略可。ユーザーの言語コード。コンテンツの言語コード。BCP47 で定義されている言語タグを使用します。

JSON 表現
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

緯度と経度のペアを表すオブジェクト。これは緯度を表す倍精度値と経度を表す倍精度値のペアで表現されます。特に明記されていない場合、このオブジェクトは WGS84 規格に準拠する必要があります。値は正規化範囲内で指定する必要があります。

フィールド
latitude number

緯度(度単位)。範囲 [-90.0, +90.0] 内になければなりません。

longitude number

経度(度単位)。範囲 [-180.0, +180.0] 内になければなりません。

JSON 表現
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

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

フィールド
totalTokenCount integer

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

JSON 表現
{
  "totalTokenCount": integer
}