Caching

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

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

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

采用 RFC 3339 标准,生成的输出将始终在末尾带 Z,并使用 0、3、6 或 9 个小数位。不带“Z”的偏差时间也是可以接受的。示例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z""2014-10-02T15:01:23+05:30"

ttl string (Duration format)

仅限输入。相应资源的新 TTL,仅限输入。

该时长以秒为单位,最多包含九个小数位,以“s”结尾。示例:"3.5s"

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

列出 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-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

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

查询参数

updateMask string (FieldMask format)

要更新的字段的列表。

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

请求正文

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

字段
expiration Union type
指定相应资源何时过期。expiration 只能是下列其中一项:
expireTime 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"

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-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 资源。

端点

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

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

采用 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)

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

采用 RFC 3339 标准,生成的输出将始终在末尾带 Z,并使用 0、3、6 或 9 个小数位。不带“Z”的偏差时间也是可以接受的。示例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z""2014-10-02T15:01:23+05:30"

ttl string (Duration format)

仅限输入。相应资源的新 TTL,仅限输入。

该时长以秒为单位,最多包含九个小数位,以“s”结尾。示例:"3.5s"

name string

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

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 包含一个 role 字段(用于指定 Content 的提供方)和一个 parts 字段(包含多部分数据,其中包含消息轮次的内容)。

字段
parts[] object (Part)

构成单条消息的有序 Parts。部分可能具有不同的 MIME 类型。

role string

可选。内容的制作方。必须是“user”或“model”。

对于多轮对话,此字段很有用;否则,可以留空或不设置。

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

部分

一种数据类型,包含属于多部分 Content 消息一部分的媒体。

Part 由具有关联数据类型的数据组成。Part 只能包含 Part.data 中接受的类型之一。

如果 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,以表明函数调用已完成。这可能仍会触发模型生成。为避免触发生成并完成函数调用,请额外将 scheduling 设置为 SILENT

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 Python >= 3.10,且提供 numpy 和 simpy。

CodeExecutionResult

执行 ExecutableCode 的结果。

仅在使用 CodeExecution 时生成,并且始终跟在包含 ExecutableCodepart 之后。

字段
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”结尾。示例:"3.5s"

endOffset string (Duration format)

可选。视频的结束偏移量。

该时长以秒为单位,最多包含九个小数位,以“s”结尾。示例:"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 来决定调用这些函数中的一部分。下一个对话轮次可能包含一个 FunctionResponse,其中包含 Content.role“函数”生成上下文,用于下一个模型轮次。

googleSearchRetrieval object (GoogleSearchRetrieval)

可选。由 Google 搜索提供支持的检索工具。

codeExecution object (CodeExecution)

可选。使模型能够在生成过程中执行代码。

urlContext object (UrlContext)

可选。用于支持网址上下文检索的工具。

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

可选。数据的格式。允许使用任何值,但大多数值不会触发任何特殊功能。

title string

可选。架构的标题。

description string

可选。参数的简要说明。这可能包含使用示例。参数说明可以采用 Markdown 格式。

nullable boolean

可选。指示值是否为 null。

enum[] string

可选。Type.STRING 类型的元素可能的具有枚举格式的值。例如,我们可以将 Enum 方向定义为:{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)

可选。类型为 STRING 的架构字段的最小长度。STRING

maxLength string (int64 format)

可选。Type.STRING 的最大长度

pattern string

可选。Type.STRING 的模式,用于将字符串限制为正则表达式。

example value (Value format)

可选。对象的示例。仅当对象为根对象时才会填充。

anyOf[] object (Schema)

可选。该值应根据列表中的任何(一个或多个)子架构进行验证。

propertyOrdering[] string

可选。属性的顺序。不是 OpenAPI 规范中的标准字段。用于确定响应中属性的顺序。

default value (Value format)

可选。字段的默认值。根据 JSON 架构,此字段适用于文档生成器,不会影响验证。因此,此处包含该字段并将其忽略,以便发送包含 default 字段的架构的开发者不会收到未知字段错误。

items object (Schema)

可选。Type.ARRAY 的元素的架构。

minimum number

可选。类型为 INTEGER 和 NUMBER 的架构字段的最小值。

maximum number

可选。Type.INTEGER 和 Type.NUMBER 的最大值

JSON 表示法
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

类型

类型包含 OpenAPI 数据类型列表,如 https://spec.openapis.org/oas/v3.0.3#data-types 中所定义

枚举
TYPE_UNSPECIFIED 未指定,不应使用。
STRING 字符串类型。
NUMBER 号码类型。
INTEGER 整数类型。
BOOLEAN 布尔值类型。
ARRAY 数组类型。
OBJECT 对象类型。
NULL Null 类型。

行为

定义函数行为。默认为 BLOCKING

枚举
UNSPECIFIED 此值未使用。
BLOCKING 如果设置,系统将等待接收函数响应,然后再继续对话。
NON_BLOCKING 如果设置,系统将不会等待接收函数响应。相反,它会尝试在函数响应可用时处理这些响应,同时保持用户与模型之间的对话。

GoogleSearchRetrieval

由 Google 提供支持的工具,用于检索公开 Web 数据以建立回答依据。

字段
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 搜索的工具。由 Google 提供支持。

字段
timeRangeFilter object (Interval)

可选。将搜索结果过滤为特定时间范围。如果客户设置了开始时间,则必须设置结束时间(反之亦然)。

JSON 表示法
{
  "timeRangeFilter": {
    object (Interval)
  }
}

间隔

表示时间间隔,编码为开始时间戳(含)和结束时间戳(不含)。

开始时间必须早于或等于结束时间。如果开始时间与结束时间相同,则时间间隔为空(不匹配任何时间)。如果未指定开始时间和结束时间,则该时间段会匹配任何时间。

字段
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

此类型没有字段。

用于支持网址上下文检索的工具。

ToolConfig

包含用于指定请求中 Tool 用法的参数的工具配置。

字段
functionCallingConfig object (FunctionCallingConfig)

可选。函数调用配置。

JSON 表示法
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

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”中的任何一个。

UsageMetadata

有关缓存内容使用情况的元数据。

字段
totalTokenCount integer

缓存内容消耗的令牌总数。

JSON 表示法
{
  "totalTokenCount": integer
}