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)

資源到期時間的時間戳記 (世界標準時間)。不論輸入什麼內容,這項資訊「一律」會顯示在輸出內容中。

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

僅限輸入。這個資源的新存留時間,僅供輸入。

以秒為單位的時間長度,最多可有 9 個小數位數,結尾為「s」,例如:"3.5s"

name string

(非必要) ID。參照快取內容的資源名稱。格式:cachedContents/{id}

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

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

貝殼

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

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

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

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

寄件者名稱

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

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

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

透過即時通訊

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, "user"),
}, nil)
if err != nil {
	log.Fatal(err)
}

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

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

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

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

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

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

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

回應主體

如果成功,回應主體會包含新建立的 CachedContent 例項。

方法:cachedContents.list

列出 CachedContents。

端點

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

查詢參數

pageSize integer

(非必要) 要傳回的快取內容數量上限。服務傳回的產品數量可能會少於這個值。如未指定,系統會傳回一些預設 (低於上限) 的項目數量。許可的最大值為 1000;超出的數值將一律指定為 1000。

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

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

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

貝殼

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

回應主體

如果成功,回應主體會包含 CachedContent 的執行例項。

方法:cachedContents.patch

更新 CachedContent 資源 (僅可更新到期時間)。

端點

修補 https://generativelanguage.googleapis.com/v1beta/{cachedContent.name=cachedContents/*}

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

路徑參數

cachedContent.name string

(非必要) ID。參照快取內容的資源名稱。格式: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)

僅限輸入。這個資源的新存留時間,僅供輸入。

以秒為單位的時間長度,最多可有 9 個小數位數,結尾為「s」,例如:"3.5s"

name string

(非必要) ID。參照快取內容的資源名稱。格式:cachedContents/{id}

要求範例

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

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

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

貝殼

curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d '{"ttl": "600s"}'

回應主體

如果成功,回應主體會包含 CachedContent 的執行例項。

方法:cachedContents.delete

刪除 CachedContent 資源。

端點

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

路徑參數

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

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

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

貝殼

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

回應主體

如果成功,回應主體會是空的 JSON 物件。

REST 資源:cachedContents

資源:CachedContent

已預先處理的內容,可用於向 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)

僅限輸入。這個資源的新存留時間,僅供輸入。

以秒為單位的時間長度,最多可有 9 個小數位數,結尾為「s」,例如:"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 包含 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

(非必要) 指出該零件是否來自模型。

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 的結果。

JSON 表示法
{
  "thought": boolean,

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

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 物件格式傳回的函式回應。

JSON 表示法
{
  "id": string,
  "name": string,
  "response": {
    object
  }
}

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 程式碼執行時間過長,已取消執行作業。部分輸出內容可能會出現。

工具

模型可能會用來產生回覆的工具詳細資料。

Tool 是一段程式碼,可讓系統與外部系統互動,執行模型知識和範圍以外的動作或一組動作。

欄位
functionDeclarations[] object (FunctionDeclaration)

(非必要) 可供模型使用的 FunctionDeclarations 清單,可用於函式呼叫。

模型或系統未執行函式。相反地,定義的函式可能會以 FunctionCall 的形式傳回,並將引數傳送至用戶端執行。模型可能會決定在回應中填入 FunctionCall,藉此呼叫部分函式。下一個對話回合可能會包含 FunctionResponse,其中包含 Content.role「函式」產生下一個模型回合的背景資訊。

googleSearchRetrieval object (GoogleSearchRetrieval)

(非必要) 由 Google 搜尋提供的擷取工具。

codeExecution object (CodeExecution)

(非必要) 讓模型在生成過程中執行程式碼。

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

FunctionDeclaration

根據 OpenAPI 3.03 規範定義的函式宣告結構化表示法。此宣告包含函式名稱和參數。這個 FunctionDeclaration 是程式碼區塊的表示法,可由模型用作 Tool,並由用戶端執行。

欄位
name string

必要欄位。函式的名稱。必須是 a-z、A-Z、0-9,或包含底線和破折號,長度上限為 63 個半形字元。

description string

必要欄位。簡短說明功能。

parameters object (Schema)

(非必要) 說明此函式的參數。反映 Open API 3.03 參數物件字串索引鍵:參數名稱。參數名稱區分大小寫。結構定義值:定義參數所用型別的結構定義。

response object (Schema)

(非必要) 以 JSON 結構定義格式說明此函式的輸出內容。反映 Open API 3.03 回應物件。定義用於函式回應值的類型。

JSON 表示法
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  },
  "response": {
    object (Schema)
  }
}

結構定義

Schema 物件可定義輸入和輸出資料類型。這些類型可以是物件,也可以是基本類型和陣列。代表 OpenAPI 3.0 架構物件的選取子集。

欄位
type enum (Type)

必要欄位。資料類型。

format string

(非必要) 資料格式。這只適用於基本資料類型。支援的格式:NUMBER 類型:float、double;INTEGER 類型:int32、int64;STRING 類型:enum、日期時間

title string

(非必要) 結構定義的標題。

description string

(非必要) 簡短說明參數。這可能包含使用範例。參數說明可採用 Markdown 格式。

nullable boolean

(非必要) 指出值是否可能為空值。

enum[] string

(非必要) 使用列舉格式的 Type.STRING 元素可能的值。舉例來說,我們可以將列舉方向定義為:{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)

(非必要) 類型字串的結構定義欄位 最短的 Type.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

(非必要) SCHEMA 欄位 (類型 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 空值類型。

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 搜尋的工具。體現 Google 的技術結晶

ToolConfig

工具設定,其中包含用於指定要求中 Tool 用法的參數。

欄位
functionCallingConfig object (FunctionCallingConfig)

(非必要) 函式呼叫設定。

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

FunctionCallingConfig

用於指定函式呼叫行為的設定。

欄位
mode enum (Mode)

(非必要) 指定函式呼叫應執行的模式。如未指定,則預設值會設為 AUTO。

allowedFunctionNames[] string

(非必要) 一組函式名稱,提供後可限制模型要呼叫的函式。

只有在模式為 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
}