Caching

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

เมธอด: cacheContents.create

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

ปลายทาง

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

เนื้อหาของคำขอ

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

ช่อง
contents[] object (Content)

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

tools[] object (Tool)

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

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

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

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

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)

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

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

พื้นฐาน

Python

document = genai.upload_file(path=media / "a11.txt")
model_name = "gemini-1.5-flash-001"
cache = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction="You are an expert analyzing transcripts.",
    contents=[document],
)
print(cache)

model = genai.GenerativeModel.from_cached_content(cache)
response = model.generate_content("Please summarize this transcript")
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});

console.log(cacheResult);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModelFromCachedContent(cacheResult);
const result = await model.generateContent(
  "Please summarize this transcript.",
);
console.log(result.response.text());

Go

file, err := client.UploadFileFromPath(ctx,
	filepath.Join(testDataDir, "a11.txt"),
	&genai.UploadFileOptions{MIMEType: "text/plain"})
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
fd := genai.FileData{URI: file.URI}

argcc := &genai.CachedContent{
	Model:             "gemini-1.5-flash-001",
	SystemInstruction: genai.NewUserContent(genai.Text("You are an expert analyzing transcripts.")),
	Contents:          []*genai.Content{genai.NewUserContent(fd)},
}
cc, err := client.CreateCachedContent(ctx, argcc)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteCachedContent(ctx, cc.Name)

modelWithCache := client.GenerativeModelFromCachedContent(cc)
prompt := "Please summarize this transcript"
resp, err := modelWithCache.GenerateContent(ctx, genai.Text(prompt))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

เปลือกหอย

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=$GOOGLE_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=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
      "contents": [
        {
          "parts":[{
            "text": "Please summarize this transcript"
          }],
          "role": "user"
        },
      ],
      "cachedContent": "'$CACHE_NAME'"
    }'

จากชื่อ

Python

document = genai.upload_file(path=media / "a11.txt")
model_name = "gemini-1.5-flash-001"
cache = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction="You are an expert analyzing transcripts.",
    contents=[document],
)
cache_name = cache.name  # Save the name for later

# Later
cache = genai.caching.CachedContent.get(cache_name)
apollo_model = genai.GenerativeModel.from_cached_content(cache)
response = apollo_model.generate_content("Find a lighthearted moment from this transcript")
print(response.text)

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});
const cacheName = cacheResult.name; // Save the name for later.

// Later
const getCacheResult = await cacheManager.get(cacheName);
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModelFromCachedContent(getCacheResult);
model.generateContent("Please summarize this transcript.");

Go

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "a11.txt"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
fd := genai.FileData{URI: file.URI}

argcc := &genai.CachedContent{
	Model:             "gemini-1.5-flash-001",
	SystemInstruction: genai.NewUserContent(genai.Text("You are an expert analyzing transcripts.")),
	Contents:          []*genai.Content{genai.NewUserContent(fd)},
}
cc, err := client.CreateCachedContent(ctx, argcc)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteCachedContent(ctx, cc.Name)

// Save the name for later
cacheName := cc.Name

// ... Later
cc2, err := client.GetCachedContent(ctx, cacheName)
if err != nil {
	log.Fatal(err)
}
modelWithCache := client.GenerativeModelFromCachedContent(cc2)
prompt := "Find a lighthearted moment from this transcript"
resp, err := modelWithCache.GenerateContent(ctx, genai.Text(prompt))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

จากแชท

Python

model_name = "gemini-1.5-flash-001"
system_instruction = "You are an expert analyzing transcripts."

model = genai.GenerativeModel(model_name=model_name, system_instruction=system_instruction)
chat = model.start_chat()
document = genai.upload_file(path=media / "a11.txt")
response = chat.send_message(["Hi, could you summarize this transcript?", document])
print("\n\nmodel:  ", response.text)
response = chat.send_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 = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction=system_instruction,
    contents=chat.history,
)
model = genai.GenerativeModel.from_cached_content(cached_content=cache)

# Continue the chat where you left off.
chat = model.start_chat()
response = chat.send_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 these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash-001" });
const chat = model.startChat();

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

let result = await chat.sendMessage([
  "Hi, could you summarize this transcript?",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(`\n\nmodel: ${result.response.text()}`);
result = await chat.sendMessage(
  "Okay, could you tell me more about the trans-lunar injection",
);
console.log(`\n\nmodel: ${result.response.text()}`);

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: await chat.getHistory(),
});

const newModel = genAI.getGenerativeModelFromCachedContent(cacheResult);

const newChat = newModel.startChat();
result = await newChat.sendMessage(
  "I didn't understand that last part, could you explain it in simpler language?",
);
console.log(`\n\nmodel: ${result.response.text()}`);

Go

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "a11.txt"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
fd := genai.FileData{URI: file.URI}

modelName := "gemini-1.5-flash-001"
model := client.GenerativeModel(modelName)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are an expert analyzing transcripts."))

cs := model.StartChat()
resp, err := cs.SendMessage(ctx, genai.Text("Hi, could you summarize this transcript?"), fd)
if err != nil {
	log.Fatal(err)
}

resp, err = cs.SendMessage(ctx, genai.Text("Okay, could you tell me more about the trans-lunar injection"))
if err != nil {
	log.Fatal(err)
}

// To cache the conversation so far, pass the chat history as the list of
// contents.

argcc := &genai.CachedContent{
	Model:             modelName,
	SystemInstruction: model.SystemInstruction,
	Contents:          cs.History,
}
cc, err := client.CreateCachedContent(ctx, argcc)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteCachedContent(ctx, cc.Name)

modelWithCache := client.GenerativeModelFromCachedContent(cc)
cs = modelWithCache.StartChat()
resp, err = cs.SendMessage(ctx, genai.Text("I didn't understand that last part, could you please explain it in simpler language?"))
if err != nil {
	log.Fatal(err)
}
printResponse(resp)

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

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

เมธอด: cacheContents.list

แสดงรายการเนื้อหาแคช

ปลายทาง

ซื้อ https://generativelanguage.googleapis.com/v1beta/cachedContents

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

pageSize integer

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

pageToken string

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

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

เนื้อหาของคำขอ

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

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

ตอบกลับด้วยรายการ CachedContents

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

ช่อง
cachedContents[] object (CachedContent)

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

nextPageToken string

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

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

เมธอด: cacheContents.get

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

ปลายทาง

ซื้อ https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

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

name string

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

เนื้อหาของคำขอ

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

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

Python

document = genai.upload_file(path=media / "a11.txt")
model_name = "gemini-1.5-flash-001"
cache = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction="You are an expert analyzing transcripts.",
    contents=[document],
)
print(genai.caching.CachedContent.get(name=cache.name))

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});
const cacheGetResult = await cacheManager.get(cacheResult.name);
console.log(cacheGetResult);

Go

file, err := client.UploadFileFromPath(ctx, filepath.Join(testDataDir, "a11.txt"), nil)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
fd := genai.FileData{URI: file.URI}

argcc := &genai.CachedContent{
	Model:             "gemini-1.5-flash-001",
	SystemInstruction: genai.NewUserContent(genai.Text("You are an expert analyzing transcripts.")),
	Contents:          []*genai.Content{genai.NewUserContent(fd)},
}
cc, err := client.CreateCachedContent(ctx, argcc)
if err != nil {
	log.Fatal(err)
}
defer client.DeleteCachedContent(ctx, cc.Name)

// Save the name for later
cacheName := cc.Name

// ... Later
cc2, err := client.GetCachedContent(ctx, cacheName)
if err != nil {
	log.Fatal(err)
}
modelWithCache := client.GenerativeModelFromCachedContent(cc2)
prompt := "Find a lighthearted moment from this transcript"
resp, err := modelWithCache.GenerateContent(ctx, genai.Text(prompt))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

เปลือกหอย

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

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

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

เมธอด: cacheContents.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 ระบุว่าทรัพยากรนี้จะหมดอายุเมื่อใด expiration ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
expireTime string (Timestamp format)

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

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

ttl string (Duration format)

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

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

name string

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

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

Python

import datetime

document = genai.upload_file(path=media / "a11.txt")
model_name = "gemini-1.5-flash-001"
cache = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction="You are an expert analyzing transcripts.",
    contents=[document],
)

# You can update the ttl
cache.update(ttl=datetime.timedelta(hours=2))
print(f"After update:\n {cache}")

# Or you can update the expire_time
cache.update(expire_time=datetime.datetime.now() + datetime.timedelta(minutes=15))

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});
console.log("initial cache data:", cacheResult);
const cacheUpdateResult = await cacheManager.update(cacheResult.name, {
  cachedContent: {
    // 2 hours
    ttlSeconds: 60 * 60 * 2,
  },
});
console.log("updated cache data:", cacheUpdateResult);

Go

file, err := client.UploadFileFromPath(ctx,
	filepath.Join(testDataDir, "a11.txt"),
	&genai.UploadFileOptions{MIMEType: "text/plain"})
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

เปลือกหอย

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

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

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

เมธอด: cacheContents.delete

ลบทรัพยากร CachedContent

ปลายทาง

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

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

name string

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

เนื้อหาของคำขอ

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

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

Python

document = genai.upload_file(path=media / "a11.txt")
model_name = "gemini-1.5-flash-001"
cache = genai.caching.CachedContent.create(
    model=model_name,
    system_instruction="You are an expert analyzing transcripts.",
    contents=[document],
)
cache.delete()

Node.js

// Make sure to include these imports:
// import { GoogleAICacheManager, GoogleAIFileManager } from "@google/generative-ai/server";
const cacheManager = new GoogleAICacheManager(process.env.API_KEY);
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
});

const cacheResult = await cacheManager.create({
  model: "models/gemini-1.5-flash-001",
  contents: [
    {
      role: "user",
      parts: [
        {
          fileData: {
            fileUri: uploadResult.file.uri,
            mimeType: uploadResult.file.mimeType,
          },
        },
      ],
    },
  ],
});
await cacheManager.delete(cacheResult.name);

Go

file, err := client.UploadFileFromPath(ctx,
	filepath.Join(testDataDir, "a11.txt"),
	&genai.UploadFileOptions{MIMEType: "text/plain"})
if err != nil {
	log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

เปลือกหอย

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

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

หากสำเร็จ เนื้อหาการตอบกลับจะว่างเปล่า

ทรัพยากร REST: cacheContents

ทรัพยากร: CachedContent

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

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

ช่อง
contents[] object (Content)

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

tools[] object (Tool)

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

createTime string (Timestamp format)

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

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

updateTime string (Timestamp format)

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

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

usageMetadata object (UsageMetadata)

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

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

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

การประทับเวลาเป็น RFC3339 UTC "Zulu" โดยมีความละเอียดระดับนาโนวินาทีและมีเลขเศษส่วนสูงสุด 9 หลัก ตัวอย่าง: "2014-10-02T15:01:23Z" และ "2014-10-02T15:01:23.045123456Z"

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

  // Union field expiration can be only one of the following:
  "expireTime": string,
  "ttl": string
  // End of list of possible types for union field expiration.
  "name": string,
  "displayName": string,
  "model": string,
  "systemInstruction": {
    object (Content)
  },
  "toolConfig": {
    object (ToolConfig)
  }
}

เนื้อหา

ประเภทข้อมูลที่มีโครงสร้างฐานซึ่งมีเนื้อหาของข้อความหลายส่วน

Content ประกอบด้วยช่อง role ที่ระบุผู้ผลิต Content และฟิลด์ parts ที่มีข้อมูลหลายส่วนซึ่งมีเนื้อหาของการเปลี่ยนข้อความ

ช่อง
parts[] object (Part)

สั่งซื้อ Parts ที่ประกอบขึ้นเป็นข้อความเดียว ส่วนต่างๆ อาจมีประเภท MIME ที่แตกต่างกัน

role string

ไม่บังคับ ผู้สร้างเนื้อหา ต้องเป็น "ผู้ใช้" อย่างใดอย่างหนึ่ง หรือ "model"

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

การแสดง JSON
{
  "parts": [
    {
      object (Part)
    }
  ],
  "role": string
}

ส่วน

ประเภทข้อมูลที่มีสื่อซึ่งเป็นส่วนหนึ่งของข้อความ Content ที่มีหลายส่วน

Part ประกอบด้วยข้อมูลซึ่งมีประเภทข้อมูลที่เชื่อมโยงกัน Part จะมีประเภทที่ยอมรับใน Part.data ได้เพียง 1 ประเภทเท่านั้น

Part ต้องมีประเภท MIME ของ IANA แบบคงที่ที่ระบุประเภทและประเภทย่อยของสื่อ หากช่อง inlineData มีไบต์ดิบ

ช่อง

ช่องการรวม data

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
{

  // Union field data can be only one of the following:
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  }
  // End of list of possible types for union field data.
}

Blob

ไบต์ของสื่อดิบ

ไม่ควรส่งข้อความเป็นไบต์ดิบ โปรดใช้ "ข้อความ" ด้วย

ช่อง
mimeType string

ประเภท MIME มาตรฐานของ IANA ของข้อมูลต้นทาง ตัวอย่าง: - image/png - image/jpeg หากระบุประเภท MIME ที่ไม่รองรับ ระบบจะแสดงข้อผิดพลาด โปรดดูรายการประเภทที่รองรับทั้งหมดที่หัวข้อรูปแบบไฟล์ที่รองรับ

data string (bytes format)

ไบต์ดิบสำหรับรูปแบบสื่อ

สตริงที่เข้ารหัสฐาน 64

การแสดง JSON
{
  "mimeType": string,
  "data": string
}

การเรียกใช้ฟังก์ชัน

FunctionCall ที่คาดการณ์ไว้ซึ่งแสดงผลจากโมเดลที่มีสตริงที่แสดงถึง FunctionDeclaration.name พร้อมอาร์กิวเมนต์และค่าของอาร์กิวเมนต์

ช่อง
name string

ต้องระบุ ชื่อของฟังก์ชันที่จะเรียก ต้องเป็น a-z, A-Z, 0-9 หรือมีขีดล่างและขีดกลางยาวไม่เกิน 63 อักขระ

args object (Struct format)

ไม่บังคับ พารามิเตอร์ฟังก์ชันและค่าในรูปแบบออบเจ็กต์ JSON

การแสดง JSON
{
  "name": string,
  "args": {
    object
  }
}

FunctionResponse

ผลลัพธ์ที่ได้จาก FunctionCall ที่มีสตริงที่แสดงถึง FunctionDeclaration.name และออบเจ็กต์ JSON ที่มีโครงสร้างที่มีเอาต์พุตจากฟังก์ชันจะใช้เป็นบริบทของโมเดล ควรมีผลลัพธ์ของ FunctionCall ที่สร้างขึ้นตามการคาดการณ์โมเดล

ช่อง
name string

ต้องระบุ ชื่อของฟังก์ชันที่จะเรียก ต้องเป็น a-z, A-Z, 0-9 หรือมีขีดล่างและขีดกลาง โดยมีความยาวไม่เกิน 63 อักขระ

response object (Struct format)

ต้องระบุ การตอบสนองของฟังก์ชันในรูปแบบออบเจ็กต์ JSON

การแสดง JSON
{
  "name": string,
  "response": {
    object
  }
}

FileData

ข้อมูลที่อิงตาม URI

ช่อง
mimeType string

ไม่บังคับ ประเภท MIME มาตรฐานของ IANA ของข้อมูลต้นทาง

fileUri string

ต้องระบุ URI

การแสดง JSON
{
  "mimeType": string,
  "fileUri": string
}

ExecutableCode

โค้ดที่โมเดลสร้างขึ้นที่จะทำงาน และส่งผลลัพธ์กลับไปยังโมเดล

สร้างขึ้นเฉพาะเมื่อใช้เครื่องมือ CodeExecution ซึ่งจะมีการเรียกใช้โค้ดโดยอัตโนมัติ และสร้าง CodeExecutionResult ที่เกี่ยวข้องด้วย

ช่อง
language enum (Language)

ต้องระบุ ภาษาโปรแกรมของ code

code string

ต้องระบุ โค้ดที่จะดำเนินการ

การแสดง JSON
{
  "language": enum (Language),
  "code": string
}

ภาษา

ภาษาโปรแกรมที่รองรับสำหรับโค้ดที่สร้างขึ้น

Enum
LANGUAGE_UNSPECIFIED ไม่ได้ระบุภาษา ไม่ควรใช้ค่านี้
PYTHON Python >= 3.10 โดยมี numpy และ simpy

CodeExecutionResult

ผลลัพธ์ของการเรียกใช้ ExecutableCode

สร้างเมื่อใช้ CodeExecution เท่านั้น และตามหลัง part ที่มี ExecutableCode เสมอ

ช่อง
outcome enum (Outcome)

ต้องระบุ ผลลัพธ์ของการเรียกใช้โค้ด

output string

ไม่บังคับ มี stdout เมื่อการเรียกใช้โค้ดสำเร็จ หรือ stderr หรือคำอธิบายอื่นเป็นอย่างอื่น

การแสดง JSON
{
  "outcome": enum (Outcome),
  "output": string
}

ผลลัพธ์

การชี้แจงผลลัพธ์ที่เป็นไปได้ของการเรียกใช้โค้ด

Enum
OUTCOME_UNSPECIFIED สถานะที่ไม่ได้ระบุ ไม่ควรใช้ค่านี้
OUTCOME_OK การเรียกใช้โค้ดเสร็จสมบูรณ์แล้ว
OUTCOME_FAILED ดำเนินการกับโค้ดเสร็จแล้วแต่ไม่สำเร็จ stderr ควรมีเหตุผล
OUTCOME_DEADLINE_EXCEEDED การเรียกใช้โค้ดทำงานนานเกินไปและถูกยกเลิก อาจมีหรือไม่มีเอาต์พุตบางส่วน

เครื่องมือ

รายละเอียดเครื่องมือที่โมเดลอาจใช้เพื่อสร้างคำตอบ

Tool คือโค้ดที่ช่วยให้ระบบโต้ตอบกับระบบภายนอกเพื่อดำเนินการหรือชุดการดำเนินการที่อยู่นอกเหนือความรู้และขอบเขตของโมเดลได้

ช่อง
functionDeclarations[] object (FunctionDeclaration)

ไม่บังคับ รายการ FunctionDeclarations ที่พร้อมใช้งานสำหรับโมเดลซึ่งใช้สำหรับการเรียกใช้ฟังก์ชันได้

โมเดลหรือระบบไม่ได้เรียกใช้ฟังก์ชัน แต่อาจส่งกลับฟังก์ชันที่กำหนดเป็น [FunctionCall][content.part.function_call] พร้อมอาร์กิวเมนต์ไปยังฝั่งไคลเอ็นต์เพื่อการดำเนินการ โมเดลอาจตัดสินใจเรียกใช้ชุดย่อยของฟังก์ชันเหล่านี้ด้วยการใส่ [FunctionCall][content.part.function_call] ในการตอบกลับ การเปลี่ยนบทสนทนาครั้งถัดไปอาจมี [FunctionResponse][content.part.function_response] พร้อม "ฟังก์ชั่น" [content.role] สำหรับการเปลี่ยนโมเดลถัดไป

codeExecution object (CodeExecution)

ไม่บังคับ อนุญาตให้โมเดลเรียกใช้โค้ดที่เป็นส่วนหนึ่งของการสร้าง

การแสดง JSON
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "codeExecution": {
    object (CodeExecution)
  }
}

FunctionDeclaration

การนำเสนอที่มีโครงสร้างของการประกาศฟังก์ชันตามที่กำหนดโดยข้อกำหนดของ OpenAPI 3.03 ชื่อฟังก์ชันและพารามิเตอร์จะรวมอยู่ในการประกาศนี้ Function Declaration นี้เป็นตัวแทนของบล็อกโค้ดที่โมเดลใช้เป็น Tool ได้และไคลเอ็นต์จะเรียกใช้

ช่อง
name string

ต้องระบุ ชื่อของฟังก์ชัน ต้องเป็น a-z, A-Z, 0-9 หรือมีขีดล่างและขีดกลาง โดยมีความยาวไม่เกิน 63 อักขระ

description string

ต้องระบุ คำอธิบายสั้นๆ เกี่ยวกับฟังก์ชัน

parameters object (Schema)

ไม่บังคับ อธิบายพารามิเตอร์ของฟังก์ชันนี้ แสดงถึงคีย์ออบเจ็กต์พารามิเตอร์ของ Open API 3.03 ซึ่งเป็นชื่อของพารามิเตอร์ ชื่อพารามิเตอร์คำนึงถึงตัวพิมพ์เล็กและตัวพิมพ์ใหญ่ ค่าของสคีมา: สคีมาที่กําหนดประเภทพารามิเตอร์

การแสดง JSON
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  }
}

สคีมา

ออบเจ็กต์ Schema อนุญาตการกำหนดประเภทข้อมูลอินพุตและเอาต์พุต ประเภทเหล่านี้อาจเป็นวัตถุ แต่ยังรวมถึงรูปทรงพื้นฐานและอาร์เรย์ แสดงชุดย่อยที่เลือกไว้ของออบเจ็กต์สคีมา OpenAPI 3.0

ช่อง
type enum (Type)

ต้องระบุ ประเภทข้อมูล

format string

ไม่บังคับ รูปแบบของข้อมูล โดยใช้สําหรับประเภทข้อมูลพื้นฐานเท่านั้น รูปแบบที่สนับสนุน: สำหรับประเภท NUMBER: ทศนิยม ประเภท INTEGER: int32, int64 สำหรับประเภท STRING: enum

description string

ไม่บังคับ คำอธิบายสั้นๆ เกี่ยวกับพารามิเตอร์ อาจมีตัวอย่างการใช้งาน คำอธิบายพารามิเตอร์อาจอยู่ในรูปแบบมาร์กดาวน์

nullable boolean

ไม่บังคับ ระบุว่าค่าอาจเป็น Null หรือไม่

enum[] string

ไม่บังคับ ค่าที่เป็นไปได้ขององค์ประกอบ Type.STRING ในรูปแบบ enum ตัวอย่างเช่น เราสามารถกำหนดทิศทาง Enum เป็น {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}

maxItems 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

items object (Schema)

ไม่บังคับ สคีมาขององค์ประกอบประเภท Type.ARRAY

การแสดง JSON
{
  "type": enum (Type),
  "format": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "items": {
    object (Schema)
  }
}

ประเภท

Type มีรายการประเภทข้อมูล OpenAPI ตามที่กำหนดโดย https://spec.openapis.org/oas/v3.0.3#data-types

Enum
TYPE_UNSPECIFIED ไม่ควรระบุ
STRING ประเภทสตริง
NUMBER ประเภทหมายเลข
INTEGER ประเภทจำนวนเต็ม
BOOLEAN ประเภทบูลีน
ARRAY ประเภทอาร์เรย์
OBJECT ประเภทออบเจ็กต์

CodeExecution

ประเภทนี้ไม่มีช่อง

เครื่องมือที่จะเรียกใช้โค้ดที่โมเดลสร้างขึ้น และส่งผลลัพธ์ไปยังโมเดลโดยอัตโนมัติ

รวมถึงดู ExecutableCode และ CodeExecutionResult ซึ่งสร้างขึ้นเฉพาะเมื่อใช้เครื่องมือนี้

ToolConfig

การกำหนดค่าเครื่องมือที่มีพารามิเตอร์สำหรับระบุการใช้ Tool ในคำขอ

ช่อง
functionCallingConfig object (FunctionCallingConfig)

ไม่บังคับ การกำหนดค่าการเรียกฟังก์ชัน

การแสดง JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

FunctionCallingConfig

การกำหนดค่าสำหรับการระบุพฤติกรรมการเรียกใช้ฟังก์ชัน

ช่อง
mode enum (Mode)

ไม่บังคับ ระบุโหมดที่การเรียกใช้ฟังก์ชันควรดำเนินการ หากไม่ระบุ ระบบจะตั้งค่าเริ่มต้นเป็น "อัตโนมัติ"

allowedFunctionNames[] string

ไม่บังคับ ชุดของชื่อฟังก์ชันที่จำกัดฟังก์ชันที่โมเดลจะเรียกใช้หากระบุไว้

ตั้งค่านี้ได้เฉพาะเมื่ออยู่ในโหมด "ใดก็ได้" ชื่อฟังก์ชันต้องตรงกับ [Functiondeclaration.name] เมื่อตั้งค่าเป็น "ใดๆ" โมเดลจะคาดการณ์การเรียกใช้ฟังก์ชันจากชุดของชื่อฟังก์ชันที่ระบุ

การแสดง JSON
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

โหมด

กำหนดลักษณะการดำเนินการสำหรับการเรียกฟังก์ชันโดยการกำหนดโหมดการดำเนินการ

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

UsageMetadata

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

ช่อง
totalTokenCount integer

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

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