Caching

การแคชบริบทช่วยให้คุณบันทึกและนำโทเค็นอินพุตที่คำนวณไว้ล่วงหน้าซึ่งคุณต้องการใช้ซ้ำมาใช้ได้ เช่น เมื่อถามคำถามต่างๆ เกี่ยวกับไฟล์สื่อเดียวกัน ซึ่งอาจช่วยประหยัดค่าใช้จ่ายและเพิ่มความเร็วได้ ทั้งนี้ขึ้นอยู่กับการใช้งาน ดูคำแนะนำโดยละเอียดได้ที่หัวข้อการแคชบริบท

เมธอด: cachedContents.create

สร้างทรัพยากร CachedContent

ปลายทาง

โพสต์ https://generativelanguage.googleapis.com/v1beta/cachedContents

เนื้อความของคำขอ

เนื้อความของคำขอมีอินสแตนซ์ของ CachedContent

ฟิลด์
contents[] object (Content)

ไม่บังคับ อินพุตเท่านั้น เปลี่ยนแปลงไม่ได้ เนื้อหาที่จะแคช

tools[] object (Tool)

ไม่บังคับ อินพุตเท่านั้น เปลี่ยนแปลงไม่ได้ รายการToolsที่โมเดลอาจใช้เพื่อสร้างคำตอบถัดไป

expiration Union type
ระบุว่าทรัพยากรนี้จะหมดอายุเมื่อใด expiration ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
expireTime string (Timestamp format)

การประทับเวลาใน UTC ของเวลาที่ถือว่าทรัพยากรนี้หมดอายุ ระบบจะระบุข้อมูลนี้ในเอาต์พุตเสมอ ไม่ว่าอินพุตจะเป็นอะไรก็ตาม

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย เช่น "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

ttl string (Duration format)

อินพุตเท่านั้น TTL ใหม่สำหรับทรัพยากรนี้ ซึ่งเป็นอินพุตเท่านั้น

ระยะเวลาเป็นวินาทีที่มีเศษทศนิยมได้สูงสุด 9 หลัก โดยลงท้ายด้วย "s" เช่น "3.5s"

displayName string

ไม่บังคับ เปลี่ยนแปลงไม่ได้ ชื่อที่แสดงที่มีความหมายซึ่งผู้ใช้สร้างขึ้นของเนื้อหาที่แคชไว้ มีอักขระ Unicode ได้สูงสุด 128 ตัว

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)

เปลือกหอย

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

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

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

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

ชื่อผู้ส่ง

Python

from google import genai
from google.genai import types

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

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

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

Node.js

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

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

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

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

Go

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

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

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

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

จากแชท

Python

from google import genai
from google.genai import types

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

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

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

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

Node.js

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

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

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

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

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

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

Go

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

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

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

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

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

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

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

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

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

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

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีอินสแตนซ์ CachedContent ที่สร้างขึ้นใหม่

เมธอด: cachedContents.list

แสดงรายการ CachedContents

ปลายทาง

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

พารามิเตอร์การค้นหา

pageSize integer

ไม่บังคับ จำนวนเนื้อหาที่แคชไว้สูงสุดที่จะแสดง บริการอาจแสดงผลน้อยกว่าค่านี้ หากไม่ได้ระบุ ระบบจะแสดงผลรายการตามจำนวนเริ่มต้น (ต่ำกว่าจำนวนสูงสุด) ค่าสูงสุดคือ 1,000 และค่าที่สูงกว่า 1,000 จะถูกบังคับให้เป็น 1,000

pageToken string

ไม่บังคับ โทเค็นหน้าเว็บที่ได้รับจากการเรียกใช้ cachedContents.list ก่อนหน้า ระบุค่านี้เพื่อดึงข้อมูลหน้าถัดไป

เมื่อแบ่งหน้า พารามิเตอร์อื่นๆ ทั้งหมดที่ระบุให้กับ cachedContents.list ต้องตรงกับการเรียกที่ให้โทเค็นหน้าเว็บ

เนื้อความของคำขอ

เนื้อหาของคำขอต้องว่างเปล่า

เนื้อหาการตอบกลับ

การตอบกลับพร้อมรายการ CachedContents

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีข้อมูลซึ่งมีโครงสร้างดังต่อไปนี้

ฟิลด์
cachedContents[] object (CachedContent)

รายการเนื้อหาที่แคชไว้

nextPageToken string

โทเค็นที่ส่งเป็น pageToken เพื่อดึงข้อมูลหน้าถัดไปได้ หากละเว้นฟิลด์นี้ จะไม่มีหน้าถัดไป

การแสดง JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

เมธอด: cachedContents.get

อ่านทรัพยากร CachedContent

ปลายทาง

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

พารามิเตอร์เส้นทาง

name string

ต้องระบุ ชื่อทรัพยากรที่อ้างอิงถึงรายการแคชเนื้อหา รูปแบบ: cachedContents/{id} ซึ่งจะอยู่ในรูปแบบ cachedContents/{cachedcontent}

เนื้อความของคำขอ

เนื้อหาของคำขอต้องว่างเปล่า

ตัวอย่างคำขอ

Python

from google import genai

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

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

Node.js

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

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

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

Go

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

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

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

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

เปลือกหอย

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

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาการตอบกลับจะมีอินสแตนซ์ CachedContent

เมธอด: cachedContents.patch

อัปเดตทรัพยากร CachedContent (อัปเดตได้เฉพาะการหมดอายุ)

ปลายทาง

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

การประทับเวลาใน UTC ของเวลาที่ถือว่าทรัพยากรนี้หมดอายุ ระบบจะระบุข้อมูลนี้ในเอาต์พุตเสมอ ไม่ว่าอินพุตจะเป็นอะไรก็ตาม

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย เช่น "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

ttl string (Duration format)

อินพุตเท่านั้น TTL ใหม่สำหรับทรัพยากรนี้ ซึ่งเป็นอินพุตเท่านั้น

ระยะเวลาเป็นวินาทีที่มีเศษทศนิยมได้สูงสุด 9 หลัก โดยลงท้ายด้วย "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)

เปลือกหอย

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)

เปลือกหอย

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

เนื้อหาการตอบกลับ

หากทำสำเร็จ เนื้อหาคำตอบจะเป็นออบเจ็กต์ JSON ว่าง

ทรัพยากร REST: cachedContents

ทรัพยากร: CachedContent

เนื้อหาที่ประมวลผลล่วงหน้าแล้วและใช้ในคำขอที่ตามมาไปยัง GenerativeService ได้

เนื้อหาที่แคชไว้จะใช้ได้กับโมเดลที่สร้างขึ้นเท่านั้น

ฟิลด์
contents[] object (Content)

ไม่บังคับ อินพุตเท่านั้น เปลี่ยนแปลงไม่ได้ เนื้อหาที่จะแคช

tools[] object (Tool)

ไม่บังคับ อินพุตเท่านั้น เปลี่ยนแปลงไม่ได้ รายการToolsที่โมเดลอาจใช้เพื่อสร้างคำตอบถัดไป

createTime string (Timestamp format)

เอาต์พุตเท่านั้น เวลาที่สร้างรายการแคช

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย เช่น "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

updateTime string (Timestamp format)

เอาต์พุตเท่านั้น เวลา UTC ที่อัปเดตรายการแคชครั้งล่าสุด

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย เช่น "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

usageMetadata object (UsageMetadata)

เอาต์พุตเท่านั้น ข้อมูลเมตาเกี่ยวกับการใช้งานเนื้อหาที่แคชไว้

expiration Union type
ระบุว่าทรัพยากรนี้จะหมดอายุเมื่อใด expiration ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้เท่านั้น
expireTime string (Timestamp format)

การประทับเวลาใน UTC ของเวลาที่ถือว่าทรัพยากรนี้หมดอายุ ระบบจะระบุข้อมูลนี้ในเอาต์พุตเสมอ ไม่ว่าอินพุตจะเป็นอะไรก็ตาม

ใช้ RFC 3339 โดยเอาต์พุตที่สร้างขึ้นจะได้รับการแปลงเป็นรูปแบบ Z เสมอ และใช้ตัวเลขเศษส่วน 0, 3, 6 หรือ 9 หลัก นอกจากนี้ ระบบยังยอมรับออฟเซ็ตอื่นๆ นอกเหนือจาก "Z" ด้วย เช่น "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" หรือ "2014-10-02T15:01:23+05:30"

ttl string (Duration format)

อินพุตเท่านั้น TTL ใหม่สำหรับทรัพยากรนี้ ซึ่งเป็นอินพุตเท่านั้น

ระยะเวลาเป็นวินาทีที่มีเศษทศนิยมได้สูงสุด 9 หลัก โดยลงท้ายด้วย "s" เช่น "3.5s"

name string

เอาต์พุตเท่านั้น ตัวระบุ ชื่อทรัพยากรที่อ้างอิงถึงเนื้อหาที่แคชไว้ รูปแบบ: cachedContents/{id}

displayName string

ไม่บังคับ เปลี่ยนแปลงไม่ได้ ชื่อที่แสดงที่มีความหมายซึ่งผู้ใช้สร้างขึ้นของเนื้อหาที่แคชไว้ มีอักขระ Unicode ได้สูงสุด 128 ตัว

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

ไม่บังคับ หากเป็นจริง การตอบกลับของ 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
  ]
}

โหมด

กำหนดลักษณะการทำงานของการเรียกใช้ฟังก์ชันโดยการกำหนดโหมดการดำเนินการ

Enum
MODE_UNSPECIFIED โหมดการเรียกใช้ฟังก์ชันที่ไม่ได้ระบุ ไม่ควรใช้ค่านี้
AUTO ลักษณะการทำงานของโมเดลเริ่มต้น โมเดลจะตัดสินใจคาดการณ์การเรียกใช้ฟังก์ชันหรือคำตอบที่เป็นภาษาธรรมชาติ
ANY โมเดลถูกจำกัดให้คาดการณ์การเรียกใช้ฟังก์ชันเท่านั้นเสมอ หากตั้งค่า "allowedFunctionNames" ไว้ การเรียกใช้ฟังก์ชันที่คาดการณ์ไว้จะจำกัดอยู่เพียง "allowedFunctionNames" รายการใดรายการหนึ่ง ไม่เช่นนั้น การเรียกใช้ฟังก์ชันที่คาดการณ์ไว้จะเป็น "functionDeclarations" รายการใดรายการหนึ่งที่ระบุไว้
NONE โมเดลจะไม่คาดการณ์การเรียกใช้ฟังก์ชันใดๆ ลักษณะการทำงานของโมเดลจะเหมือนกับเมื่อไม่ได้ส่งการประกาศฟังก์ชันใดๆ
VALIDATED โมเดลจะตัดสินใจว่าจะคาดการณ์การเรียกใช้ฟังก์ชันหรือคำตอบที่เป็นภาษาธรรมชาติ แต่จะตรวจสอบการเรียกใช้ฟังก์ชันด้วยการถอดรหัสแบบจำกัด หากตั้งค่า "allowedFunctionNames" ไว้ การเรียกใช้ฟังก์ชันที่คาดการณ์ไว้จะจำกัดอยู่เพียงหนึ่งใน "allowedFunctionNames" แต่หากไม่ได้ตั้งค่าไว้ การเรียกใช้ฟังก์ชันที่คาดการณ์ไว้จะเป็นหนึ่งใน "functionDeclarations" ที่ระบุ

RetrievalConfig

การกำหนดค่าการดึงข้อมูล

ฟิลด์
latLng object (LatLng)

ไม่บังคับ ตำแหน่งของผู้ใช้

languageCode string

ไม่บังคับ รหัสภาษาของผู้ใช้ รหัสภาษาของเนื้อหา ใช้แท็กภาษาที่กำหนดโดย BCP47

การแสดง JSON
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

ออบเจ็กต์ที่แสดงคู่ละติจูด/ลองจิจูด โดยจะแสดงเป็นคู่ของจำนวนจริงเพื่อแสดงองศาละติจูดและองศาลองจิจูด ออบเจ็กต์นี้ต้องเป็นไปตาม มาตรฐาน WGS84 เว้นแต่จะระบุไว้เป็นอย่างอื่น ค่าต้องอยู่ในช่วงที่ทำให้เป็นปกติ

ฟิลด์
latitude number

ละติจูดเป็นองศา ต้องอยู่ในช่วง [-90.0, +90.0]

longitude number

ลองจิจูดเป็นองศา ต้องอยู่ในช่วง [-180.0, +180.0]

การแสดง JSON
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

ข้อมูลเมตาเกี่ยวกับการใช้งานเนื้อหาที่แคชไว้

ฟิลด์
totalTokenCount integer

จำนวนโทเค็นทั้งหมดที่เนื้อหาที่แคชใช้

การแสดง JSON
{
  "totalTokenCount": integer
}