Caching

Tính năng lưu vào bộ nhớ đệm theo bối cảnh cho phép bạn lưu và sử dụng lại các mã thông báo đầu vào được tính toán trước mà bạn muốn sử dụng nhiều lần, chẳng hạn như khi đặt nhiều câu hỏi về cùng một tệp đa phương tiện. Điều này có thể giúp bạn tiết kiệm chi phí và thời gian, tuỳ thuộc vào mức sử dụng. Để biết thông tin giới thiệu chi tiết, hãy xem hướng dẫn về Lưu vào bộ nhớ đệm theo bối cảnh.

Phương thức: cachedContents.create

Tạo tài nguyên CachedContent.

Điểm cuối

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

Nội dung yêu cầu

Nội dung yêu cầu chứa một bản sao của CachedContent.

Trường
contents[] object (Content)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Nội dung cần lưu vào bộ nhớ đệm.

tools[] object (Tool)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Danh sách Tools mà mô hình có thể dùng để tạo câu trả lời tiếp theo

expiration Union type
Chỉ định thời điểm tài nguyên này sẽ hết hạn. expiration chỉ có thể là một trong những trạng thái sau:
expireTime string (Timestamp format)

Dấu thời gian theo giờ UTC cho biết thời điểm tài nguyên này được xem là đã hết hạn. Tham số này luôn được cung cấp trên đầu ra, bất kể tham số nào được gửi trên đầu vào.

Hãy dùng RFC 3339, trong đó dữ liệu đầu ra được tạo sẽ luôn được chuẩn hoá theo múi giờ và sử dụng 0, 3, 6 hoặc 9 chữ số thập phân. Các khoảng lệch khác ngoài "Z" cũng được chấp nhận. Ví dụ: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" hoặc "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Chỉ có đầu vào. TTL mới cho tài nguyên này, chỉ có thể nhập.

Thời lượng tính bằng giây, có tối đa 9 chữ số thập phân và kết thúc bằng "s". Ví dụ: "3.5s".

displayName string

Không bắt buộc. Không thể thay đổi. Tên hiển thị có ý nghĩa do người dùng tạo của nội dung được lưu vào bộ nhớ đệm. Tối đa 128 ký tự Unicode.

model string

Bắt buộc. Không thể thay đổi. Tên của Model cần dùng cho nội dung được lưu vào bộ nhớ đệm Định dạng: models/{model}

systemInstruction object (Content)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Nhà phát triển đặt chỉ dẫn hệ thống. Hiện chỉ có văn bản.

toolConfig object (ToolConfig)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Cấu hình công cụ. Cấu hình này được dùng chung cho tất cả các công cụ.

Ví dụ về yêu cầu

Cơ bản

Python

from google import genai
from google.genai import types

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

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
print(cache)

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

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

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

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

const response = await ai.models.generateContent({
  model: modelName,
  contents: "Please summarize this transcript",
  config: { cachedContent: cache.name },
});
console.log("Response text:", response.text);

Go

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

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

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

Shell

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

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

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

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

Tên người gửi

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)

Từ cuộc trò chuyện

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

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một thực thể mới tạo của CachedContent.

Phương thức: cachedContents.list

Lists CachedContents.

Điểm cuối

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

Tham số truy vấn

pageSize integer

Không bắt buộc. Số lượng nội dung được lưu vào bộ nhớ đệm tối đa cần trả về. Dịch vụ có thể trả về ít hơn giá trị này. Nếu không được chỉ định, một số lượng mặt hàng mặc định (dưới mức tối đa) sẽ được trả về. Giá trị tối đa là 1.000; các giá trị trên 1.000 sẽ được chuyển đổi thành 1.000.

pageToken string

Không bắt buộc. Mã thông báo trang nhận được từ một lệnh gọi cachedContents.list trước đó. Cung cấp thông tin này để truy xuất trang tiếp theo.

Khi phân trang, tất cả các tham số khác được cung cấp cho cachedContents.list phải khớp với lệnh gọi đã cung cấp mã thông báo trang.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Nội dung phản hồi

Phản hồi bằng danh sách CachedContents.

Nếu thành công, phần nội dung phản hồi sẽ chứa dữ liệu có cấu trúc sau:

Trường
cachedContents[] object (CachedContent)

Danh sách nội dung được lưu vào bộ nhớ đệm.

nextPageToken string

Một mã thông báo có thể được gửi dưới dạng pageToken để truy xuất trang tiếp theo. Nếu bạn bỏ qua trường này, thì sẽ không có các trang tiếp theo.

Biểu diễn dưới dạng JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Phương thức: cachedContents.get

Đọc tài nguyên CachedContent.

Điểm cuối

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

Tham số đường dẫn

name string

Bắt buộc. Tên tài nguyên đề cập đến mục nhập bộ nhớ đệm nội dung. Định dạng: cachedContents/{id} Tên này có dạng cachedContents/{cachedcontent}.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Ví dụ về yêu cầu

Python

from google import genai

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

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

Node.js

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

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

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

Go

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

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

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

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

Shell

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

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một thực thể của CachedContent.

Phương thức: cachedContents.patch

Cập nhật tài nguyên CachedContent (bạn chỉ có thể cập nhật thời gian hết hạn).

Điểm cuối

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

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

Tham số đường dẫn

cachedContent.name string

Chỉ có đầu ra. Giá trị nhận dạng. Tên tài nguyên đề cập đến nội dung được lưu vào bộ nhớ đệm. Định dạng: cachedContents/{id} Tên này có dạng cachedContents/{cachedcontent}.

Tham số truy vấn

updateMask string (FieldMask format)

Danh sách các trường cần cập nhật.

Đây là danh sách tên đủ điều kiện của các trường được phân tách bằng dấu phẩy. Ví dụ: "user.displayName,photo"

Nội dung yêu cầu

Nội dung yêu cầu chứa một bản sao của CachedContent.

Trường
expiration Union type
Chỉ định thời điểm tài nguyên này sẽ hết hạn. expiration chỉ có thể là một trong những trạng thái sau:
expireTime string (Timestamp format)

Dấu thời gian theo giờ UTC cho biết thời điểm tài nguyên này được xem là đã hết hạn. Tham số này luôn được cung cấp trên đầu ra, bất kể tham số nào được gửi trên đầu vào.

Hãy dùng RFC 3339, trong đó dữ liệu đầu ra được tạo sẽ luôn được chuẩn hoá theo múi giờ và sử dụng 0, 3, 6 hoặc 9 chữ số thập phân. Các khoảng lệch khác ngoài "Z" cũng được chấp nhận. Ví dụ: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" hoặc "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Chỉ có đầu vào. TTL mới cho tài nguyên này, chỉ có thể nhập.

Thời lượng tính bằng giây, có tối đa 9 chữ số thập phân và kết thúc bằng "s". Ví dụ: "3.5s".

Ví dụ về yêu cầu

Python

from google import genai
from google.genai import types
import datetime

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

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

# Update the cache's time-to-live (ttl)
ttl = f"{int(datetime.timedelta(hours=2).total_seconds())}s"
client.caches.update(
    name=cache.name, config=types.UpdateCachedContentConfig(ttl=ttl)
)
print(f"After update:\n {cache}")

# Alternatively, update the expire_time directly
# Update the expire_time directly in valid RFC 3339 format (UTC with a "Z" suffix)
expire_time = (
    (
        datetime.datetime.now(datetime.timezone.utc)
        + datetime.timedelta(minutes=15)
    )
    .isoformat()
    .replace("+00:00", "Z")
)
client.caches.update(
    name=cache.name,
    config=types.UpdateCachedContentConfig(expire_time=expire_time),
)

Node.js

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

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

let cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});

// Update the cache's time-to-live (ttl)
const ttl = `${2 * 3600}s`; // 2 hours in seconds
cache = await ai.caches.update({
  name: cache.name,
  config: { ttl },
});
console.log("After update (TTL):", cache);

// Alternatively, update the expire_time directly (in RFC 3339 format with a "Z" suffix)
const expireTime = new Date(Date.now() + 15 * 60000)
  .toISOString()
  .replace(/\.\d{3}Z$/, "Z");
cache = await ai.caches.update({
  name: cache.name,
  config: { expireTime: expireTime },
});
console.log("After update (expire_time):", cache);

Go

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

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

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

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

Shell

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

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một thực thể của CachedContent.

Phương thức: cachedContents.delete

Xoá tài nguyên CachedContent.

Điểm cuối

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

Tham số đường dẫn

name string

Bắt buộc. Tên tài nguyên đề cập đến mục nhập bộ nhớ đệm nội dung Định dạng: cachedContents/{id} Tên này có dạng cachedContents/{cachedcontent}.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Ví dụ về yêu cầu

Python

from google import genai

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

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

Node.js

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

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

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

Go

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

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

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

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

Shell

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

Nội dung phản hồi

Nếu thành công, phần nội dung phản hồi sẽ là một đối tượng JSON trống.

Tài nguyên REST: cachedContents

Tài nguyên: CachedContent

Nội dung đã được xử lý trước và có thể được dùng trong yêu cầu tiếp theo tới GenerativeService.

Bạn chỉ có thể dùng nội dung trong bộ nhớ đệm với mô hình mà nội dung đó được tạo ra.

Trường
contents[] object (Content)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Nội dung cần lưu vào bộ nhớ đệm.

tools[] object (Tool)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Danh sách Tools mà mô hình có thể dùng để tạo câu trả lời tiếp theo

createTime string (Timestamp format)

Chỉ có đầu ra. Thời gian tạo mục nhập trong bộ nhớ đệm.

Hãy dùng RFC 3339, trong đó dữ liệu đầu ra được tạo sẽ luôn được chuẩn hoá theo múi giờ và sử dụng 0, 3, 6 hoặc 9 chữ số thập phân. Các khoảng lệch khác ngoài "Z" cũng được chấp nhận. Ví dụ: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" hoặc "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Chỉ có đầu ra. Thời điểm mục nhập trong bộ nhớ đệm được cập nhật lần gần đây nhất theo giờ UTC.

Hãy dùng RFC 3339, trong đó dữ liệu đầu ra được tạo sẽ luôn được chuẩn hoá theo múi giờ và sử dụng 0, 3, 6 hoặc 9 chữ số thập phân. Các khoảng lệch khác ngoài "Z" cũng được chấp nhận. Ví dụ: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" hoặc "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

Chỉ có đầu ra. Siêu dữ liệu về việc sử dụng nội dung được lưu vào bộ nhớ đệm.

expiration Union type
Chỉ định thời điểm tài nguyên này sẽ hết hạn. expiration chỉ có thể là một trong những trạng thái sau:
expireTime string (Timestamp format)

Dấu thời gian theo giờ UTC cho biết thời điểm tài nguyên này được xem là đã hết hạn. Tham số này luôn được cung cấp trên đầu ra, bất kể tham số nào được gửi trên đầu vào.

Hãy dùng RFC 3339, trong đó dữ liệu đầu ra được tạo sẽ luôn được chuẩn hoá theo múi giờ và sử dụng 0, 3, 6 hoặc 9 chữ số thập phân. Các khoảng lệch khác ngoài "Z" cũng được chấp nhận. Ví dụ: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" hoặc "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Chỉ có đầu vào. TTL mới cho tài nguyên này, chỉ có thể nhập.

Thời lượng tính bằng giây, có tối đa 9 chữ số thập phân và kết thúc bằng "s". Ví dụ: "3.5s".

name string

Chỉ có đầu ra. Giá trị nhận dạng. Tên tài nguyên đề cập đến nội dung được lưu vào bộ nhớ đệm. Định dạng cachedContents/{id}

displayName string

Không bắt buộc. Không thể thay đổi. Tên hiển thị có ý nghĩa do người dùng tạo của nội dung được lưu vào bộ nhớ đệm. Tối đa 128 ký tự Unicode.

model string

Bắt buộc. Không thể thay đổi. Tên của Model cần dùng cho nội dung được lưu vào bộ nhớ đệm Định dạng: models/{model}

systemInstruction object (Content)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Nhà phát triển đặt chỉ dẫn hệ thống. Hiện chỉ có văn bản.

toolConfig object (ToolConfig)

Không bắt buộc. Chỉ có đầu vào. Không thể thay đổi. Cấu hình công cụ. Cấu hình này được dùng chung cho tất cả các công cụ.

Biểu diễn dưới dạng 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

Cấu hình Công cụ chứa các tham số để chỉ định việc sử dụng Tool trong yêu cầu.

Trường
functionCallingConfig object (FunctionCallingConfig)

Không bắt buộc. Cấu hình gọi hàm.

retrievalConfig object (RetrievalConfig)

Không bắt buộc. Cấu hình truy xuất.

includeServerSideToolInvocations boolean

Không bắt buộc. Nếu đúng, phản hồi của API sẽ bao gồm các lệnh gọi và phản hồi của công cụ phía máy chủ trong thông báo Content. Điều này cho phép các ứng dụng quan sát các hoạt động tương tác của công cụ trên máy chủ.

Biểu diễn dưới dạng JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

Cấu hình để chỉ định hành vi gọi hàm.

Trường
mode enum (Mode)

Không bắt buộc. Chỉ định chế độ mà tính năng gọi hàm sẽ thực thi. Nếu bạn không chỉ định, giá trị mặc định sẽ được đặt thành AUTO.

allowedFunctionNames[] string

Không bắt buộc. Một tập hợp tên hàm. Khi được cung cấp, tập hợp này sẽ giới hạn các hàm mà mô hình sẽ gọi.

Bạn chỉ nên đặt thuộc tính này khi Chế độ là BẤT KỲ hoặc ĐƯỢC XÁC THỰC. Tên hàm phải khớp với [FunctionDeclaration.name]. Khi được đặt, mô hình sẽ dự đoán một lệnh gọi hàm chỉ từ những tên hàm được phép.

Biểu diễn dưới dạng JSON
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Chế độ

Xác định hành vi thực thi cho lệnh gọi hàm bằng cách xác định chế độ thực thi.

Enum
MODE_UNSPECIFIED Chế độ gọi hàm không xác định. Bạn không nên sử dụng giá trị này.
AUTO Hành vi mặc định của mô hình, mô hình quyết định dự đoán một lệnh gọi hàm hoặc một câu trả lời bằng ngôn ngữ tự nhiên.
ANY Mô hình bị hạn chế chỉ dự đoán một lệnh gọi hàm. Nếu bạn đặt "allowedFunctionNames", lệnh gọi hàm được dự đoán sẽ bị giới hạn ở một trong các "allowedFunctionNames", nếu không, lệnh gọi hàm được dự đoán sẽ là một trong các "functionDeclarations" được cung cấp.
NONE Mô hình sẽ không dự đoán bất kỳ lệnh gọi hàm nào. Hành vi của mô hình giống như khi không truyền bất kỳ khai báo hàm nào.
VALIDATED Mô hình quyết định dự đoán một lệnh gọi hàm hoặc một câu trả lời bằng ngôn ngữ tự nhiên, nhưng sẽ xác thực các lệnh gọi hàm bằng tính năng giải mã có ràng buộc. Nếu bạn đặt "allowedFunctionNames", lệnh gọi hàm được dự đoán sẽ bị giới hạn ở một trong các "allowedFunctionNames", nếu không, lệnh gọi hàm được dự đoán sẽ là một trong các "functionDeclarations" được cung cấp.

RetrievalConfig

Cấu hình truy xuất.

Trường
latLng object (LatLng)

Không bắt buộc. Vị trí của người dùng.

languageCode string

Không bắt buộc. Mã ngôn ngữ của người dùng. Mã ngôn ngữ của nội dung. Sử dụng thẻ ngôn ngữ do BCP47 xác định.

Biểu diễn dưới dạng JSON
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

Một đối tượng đại diện cho cặp vĩ độ/kinh độ. Thông tin này được biểu thị dưới dạng một cặp số thực có độ chính xác kép để biểu thị vĩ độ và kinh độ theo độ. Trừ phi có quy định khác, đối tượng này phải tuân thủ tiêu chuẩn WGS84. Giá trị phải nằm trong phạm vi được chuẩn hoá.

Trường
latitude number

Vĩ độ tính bằng độ. Giá trị này phải nằm trong khoảng [-90.0, +90.0].

longitude number

Kinh độ tính bằng độ. Giá trị này phải nằm trong phạm vi [-180.0, +180.0].

Biểu diễn dưới dạng JSON
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Siêu dữ liệu về việc sử dụng nội dung được lưu vào bộ nhớ đệm.

Trường
totalTokenCount integer

Tổng số mã thông báo mà nội dung được lưu vào bộ nhớ đệm tiêu thụ.

Biểu diễn dưới dạng JSON
{
  "totalTokenCount": integer
}