Caching

借助上下文缓存,您可以保存并重复使用预计算的输入 token,例如在针对同一媒体文件提出不同问题时。这有助于节省费用和时间,具体取决于使用情况。如需详细了解,请参阅上下文缓存指南。

方法: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)

资源被视为过期时的时间戳(世界协调时间)。无论输入中发送的是什么内容,输出中始终都会提供此时间戳

采用 RFC 3339 标准,生成的输出将始终进行 Z 规范化(即转换为 UTC 零时区格式并在末尾附加 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"

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

From 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

列出 CachedContent。

端点

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

仅限输出。标识符。引用缓存内容的资源名称。格式:cachedContents/{id}。其格式为 cachedContents/{cachedcontent}

查询参数

updateMask string (FieldMask format)

要更新的字段列表。

这是完全限定字段名称的逗号分隔列表。示例:"user.displayName,photo"

请求正文

请求正文包含一个 CachedContent 实例。

字段
expiration Union type
指定相应资源何时过期。expiration 只能是下列其中一项:
expireTime string (Timestamp format)

资源被视为过期时的时间戳(世界协调时间)。无论输入中发送的是什么内容,输出中始终都会提供此时间戳

采用 RFC 3339 标准,生成的输出将始终进行 Z 规范化(即转换为 UTC 零时区格式并在末尾附加 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"

示例请求

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 规范化(即转换为 UTC 零时区格式并在末尾附加 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)

仅限输出。缓存条目的上次更新时间(世界协调时间)。

采用 RFC 3339 标准,生成的输出将始终进行 Z 规范化(即转换为 UTC 零时区格式并在末尾附加 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)

资源被视为过期时的时间戳(世界协调时间)。无论输入中发送的是什么内容,输出中始终都会提供此时间戳

采用 RFC 3339 标准,生成的输出将始终进行 Z 规范化(即转换为 UTC 零时区格式并在末尾附加 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}

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

可选。一组函数名称,提供后可限制模型将调用的函数。

仅当模式为“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

缓存内容消耗的 token 总数。

JSON 表示法
{
  "totalTokenCount": integer
}