Caching

Context caching memungkinkan Anda menyimpan dan menggunakan kembali token input yang telah dihitung sebelumnya dan ingin Anda gunakan berulang kali, misalnya saat mengajukan pertanyaan yang berbeda tentang file media yang sama. Hal ini dapat menghemat biaya dan waktu, bergantung pada penggunaannya. Untuk pengantar mendetail, lihat panduan Penyimpanan dalam cache konteks.

Metode: cachedContents.create

Membuat resource CachedContent.

Endpoint

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

Isi permintaan

Isi permintaan memuat instance CachedContent.

Kolom
contents[] object (Content)

Opsional. Hanya input. Tidak dapat diubah. Konten yang akan di-cache.

tools[] object (Tool)

Opsional. Hanya input. Tidak dapat diubah. Daftar Tools yang dapat digunakan model untuk menghasilkan respons berikutnya

expiration Union type
Menentukan kapan resource ini akan berakhir. expiration hanya dapat berupa salah satu dari hal berikut:
expireTime string (Timestamp format)

Stempel waktu dalam UTC saat resource ini dianggap habis masa berlakunya. Ini selalu diberikan pada output, terlepas dari apa yang dikirimkan pada input.

Menggunakan RFC 3339 yang outputnya akan selalu dinormalisasi Z dan menggunakan 0, 3, 6, atau 9 digit pecahan. Offset selain "Z" juga diterima. Contoh: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z", atau "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Hanya input. TTL baru untuk resource ini, hanya input.

Durasi dalam detik dengan maksimal sembilan digit pecahan, yang diakhiri dengan 's'. Contoh: "3.5s".

displayName string

Opsional. Tidak dapat diubah. Nama tampilan bermakna buatan pengguna dari konten yang di-cache. Maksimum 128 karakter Unicode.

model string

Wajib. Tidak dapat diubah. Nama Model yang akan digunakan untuk konten yang di-cache Format: models/{model}

systemInstruction object (Content)

Opsional. Hanya input. Tidak dapat diubah. Petunjuk sistem yang ditetapkan developer. Saat ini hanya berupa teks.

toolConfig object (ToolConfig)

Opsional. Hanya input. Tidak dapat diubah. Konfigurasi alat. Konfigurasi ini dibagikan untuk semua alat.

Contoh permintaan

Dasar

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'"
    }'

Nama pengirim

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)

Dari chat

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

Isi respons

Jika berhasil, isi respons akan memuat instance CachedContent yang baru dibuat.

Metode: cachedContents.list

Mencantumkan CachedContents.

Endpoint

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

Parameter kueri

pageSize integer

Opsional. Jumlah maksimum konten yang di-cache untuk ditampilkan. Layanan mungkin menampilkan lebih sedikit dari nilai ini. Jika tidak ditentukan, beberapa item default (di bawah maksimum) akan ditampilkan. Nilai maksimum adalah 1.000; nilai di atas 1.000 akan dikonversi menjadi 1.000.

pageToken string

Opsional. Token halaman, yang diterima dari panggilan cachedContents.list sebelumnya. Berikan ini untuk mengambil halaman selanjutnya.

Saat melakukan penomoran halaman, semua parameter lain yang disediakan untuk cachedContents.list harus sesuai dengan panggilan yang memberikan token halaman.

Isi permintaan

Isi permintaan harus kosong.

Isi respons

Respons dengan daftar CachedContents.

Jika berhasil, isi respons memuat data dengan struktur berikut:

Kolom
cachedContents[] object (CachedContent)

Daftar konten yang di-cache.

nextPageToken string

Token yang dapat dikirim sebagai pageToken untuk mengambil halaman berikutnya. Jika kolom ini dihilangkan, tidak akan ada halaman berikutnya.

Representasi JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Metode: cachedContents.get

Membaca resource CachedContent.

Endpoint

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

Parameter jalur

name string

Wajib. Nama resource yang merujuk ke entri cache konten. Format: cachedContents/{id} Formatnya adalah cachedContents/{cachedcontent}.

Isi permintaan

Isi permintaan harus kosong.

Contoh permintaan

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"

Isi respons

Jika berhasil, isi respons memuat instance CachedContent.

Metode: cachedContents.patch

Memperbarui resource CachedContent (hanya waktu habis masa berlaku yang dapat diperbarui).

Endpoint

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

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

Parameter jalur

cachedContent.name string

Hanya output. ID. Nama resource yang merujuk ke konten yang di-cache. Format: cachedContents/{id} Formatnya adalah cachedContents/{cachedcontent}.

Parameter kueri

updateMask string (FieldMask format)

Daftar kolom yang akan diperbarui.

Ini adalah comma-separated list berisi nama kolom yang sepenuhnya memenuhi syarat. Contoh: "user.displayName,photo".

Isi permintaan

Isi permintaan memuat instance CachedContent.

Kolom
expiration Union type
Menentukan kapan resource ini akan berakhir. expiration hanya dapat berupa salah satu dari hal berikut:
expireTime string (Timestamp format)

Stempel waktu dalam UTC saat resource ini dianggap habis masa berlakunya. Ini selalu diberikan pada output, terlepas dari apa yang dikirimkan pada input.

Menggunakan RFC 3339 yang outputnya akan selalu dinormalisasi Z dan menggunakan 0, 3, 6, atau 9 digit pecahan. Offset selain "Z" juga diterima. Contoh: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z", atau "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Hanya input. TTL baru untuk resource ini, hanya input.

Durasi dalam detik dengan maksimal sembilan digit pecahan, yang diakhiri dengan 's'. Contoh: "3.5s".

Contoh permintaan

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"}'

Isi respons

Jika berhasil, isi respons memuat instance CachedContent.

Metode: cachedContents.delete

Menghapus resource CachedContent.

Endpoint

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

Parameter jalur

name string

Wajib. Nama resource yang merujuk ke entri cache konten Format: cachedContents/{id} Berbentuk cachedContents/{cachedcontent}.

Isi permintaan

Isi permintaan harus kosong.

Contoh permintaan

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"

Isi respons

Jika berhasil, isi respons adalah objek JSON kosong.

REST Resource: cachedContents

Resource: CachedContent

Konten yang telah diproses sebelumnya dan dapat digunakan dalam permintaan berikutnya ke GenerativeService.

Konten yang di-cache hanya dapat digunakan dengan model yang digunakan untuk membuatnya.

Kolom
contents[] object (Content)

Opsional. Hanya input. Tidak dapat diubah. Konten yang akan di-cache.

tools[] object (Tool)

Opsional. Hanya input. Tidak dapat diubah. Daftar Tools yang dapat digunakan model untuk menghasilkan respons berikutnya

createTime string (Timestamp format)

Hanya output. Waktu pembuatan entri cache.

Menggunakan RFC 3339 yang outputnya akan selalu dinormalisasi Z dan menggunakan 0, 3, 6, atau 9 digit pecahan. Offset selain "Z" juga diterima. Contoh: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z", atau "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Hanya output. Kapan entri cache terakhir diperbarui dalam waktu UTC.

Menggunakan RFC 3339 yang outputnya akan selalu dinormalisasi Z dan menggunakan 0, 3, 6, atau 9 digit pecahan. Offset selain "Z" juga diterima. Contoh: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z", atau "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

Hanya output. Metadata tentang penggunaan konten yang di-cache.

expiration Union type
Menentukan kapan resource ini akan berakhir. expiration hanya dapat berupa salah satu dari hal berikut:
expireTime string (Timestamp format)

Stempel waktu dalam UTC saat resource ini dianggap habis masa berlakunya. Ini selalu diberikan pada output, terlepas dari apa yang dikirimkan pada input.

Menggunakan RFC 3339 yang outputnya akan selalu dinormalisasi Z dan menggunakan 0, 3, 6, atau 9 digit pecahan. Offset selain "Z" juga diterima. Contoh: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z", atau "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Hanya input. TTL baru untuk resource ini, hanya input.

Durasi dalam detik dengan maksimal sembilan digit pecahan, yang diakhiri dengan 's'. Contoh: "3.5s".

name string

Hanya output. ID. Nama resource yang merujuk ke konten yang di-cache. Format: cachedContents/{id}

displayName string

Opsional. Tidak dapat diubah. Nama tampilan bermakna buatan pengguna dari konten yang di-cache. Maksimum 128 karakter Unicode.

model string

Wajib. Tidak dapat diubah. Nama Model yang akan digunakan untuk konten yang di-cache Format: models/{model}

systemInstruction object (Content)

Opsional. Hanya input. Tidak dapat diubah. Petunjuk sistem yang ditetapkan developer. Saat ini hanya berupa teks.

toolConfig object (ToolConfig)

Opsional. Hanya input. Tidak dapat diubah. Konfigurasi alat. Konfigurasi ini dibagikan untuk semua alat.

Representasi 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

Konfigurasi Alat yang berisi parameter untuk menentukan penggunaan Tool dalam permintaan.

Kolom
functionCallingConfig object (FunctionCallingConfig)

Opsional. Konfigurasi panggilan fungsi.

retrievalConfig object (RetrievalConfig)

Opsional. Konfigurasi pengambilan.

includeServerSideToolInvocations boolean

Opsional. Jika benar (true), respons API akan menyertakan panggilan dan respons alat sisi server dalam pesan Content. Hal ini memungkinkan klien mengamati interaksi alat server.

Representasi JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

Konfigurasi untuk menentukan perilaku panggilan fungsi.

Kolom
mode enum (Mode)

Opsional. Menentukan mode saat panggilan fungsi harus dieksekusi. Jika tidak ditentukan, nilai default akan disetel ke AUTO.

allowedFunctionNames[] string

Opsional. Kumpulan nama fungsi yang, jika diberikan, akan membatasi fungsi yang akan dipanggil model.

Kolom ini hanya boleh ditetapkan jika Mode adalah ANY atau VALIDATED. Nama fungsi harus cocok dengan [FunctionDeclaration.name]. Jika disetel, model akan memprediksi panggilan fungsi hanya dari nama fungsi yang diizinkan.

Representasi JSON
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Mode

Menentukan perilaku eksekusi untuk panggilan fungsi dengan menentukan mode eksekusi.

Enum
MODE_UNSPECIFIED Mode panggilan fungsi tidak ditentukan. Nilai ini tidak boleh digunakan.
AUTO Perilaku model default, model memutuskan untuk memprediksi panggilan fungsi atau respons bahasa alami.
ANY Model dibatasi untuk selalu memprediksi panggilan fungsi saja. Jika "allowedFunctionNames" ditetapkan, panggilan fungsi yang diprediksi akan dibatasi ke salah satu dari "allowedFunctionNames", jika tidak, panggilan fungsi yang diprediksi akan menjadi salah satu dari "functionDeclarations" yang diberikan.
NONE Model tidak akan memprediksi panggilan fungsi apa pun. Perilaku model sama seperti saat tidak meneruskan deklarasi fungsi apa pun.
VALIDATED Model memutuskan untuk memprediksi panggilan fungsi atau respons bahasa alami, tetapi akan memvalidasi panggilan fungsi dengan decoding terbatas. Jika "allowedFunctionNames" ditetapkan, panggilan fungsi yang diprediksi akan dibatasi ke salah satu "allowedFunctionNames", jika tidak, panggilan fungsi yang diprediksi akan menjadi salah satu "functionDeclarations" yang diberikan.

RetrievalConfig

Konfigurasi pengambilan.

Kolom
latLng object (LatLng)

Opsional. Lokasi pengguna.

languageCode string

Opsional. Kode bahasa pengguna. Kode bahasa untuk konten. Gunakan tag bahasa yang ditentukan oleh BCP47.

Representasi JSON
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

Objek yang merepresentasikan pasangan garis lintang/bujur. Objek ini dinyatakan sebagai pasangan nilai ganda untuk mewakili derajat lintang dan derajat bujur. Kecuali jika ditentukan lain, objek ini harus sesuai dengan standar WGS84. Nilai harus berada dalam rentang yang dinormalisasi.

Kolom
latitude number

Lintang dalam derajat. Harus dalam rentang [-90.0, +90.0].

longitude number

Bujur dalam derajat. Harus dalam rentang [-180.0, +180.0].

Representasi JSON
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Metadata tentang penggunaan konten yang di-cache.

Kolom
totalTokenCount integer

Jumlah total token yang digunakan konten yang di-cache.

Representasi JSON
{
  "totalTokenCount": integer
}