Caching

Bağlamı önbelleğe alma, önceden hesaplanmış ve tekrar tekrar kullanmak istediğiniz giriş parçalarını (ör. aynı medya dosyasıyla ilgili farklı sorular sorarken) kaydetmenize ve yeniden kullanmanıza olanak tanır. Bu, kullanıma bağlı olarak maliyet ve hız açısından tasarruf sağlayabilir. Ayrıntılı bir giriş için Bağlam önbelleğe alma kılavuzuna bakın.

Yöntem: cachedContents.create

CachedContent kaynağı oluşturur.

Uç nokta

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

İstek metni

İstek metni, CachedContent öğesinin bir örneğini içerir.

Alanlar
contents[] object (Content)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Önbelleğe alınacak içerik.

tools[] object (Tool)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Modelin bir sonraki yanıtı oluşturmak için kullanabileceği Tools listesi

expiration Union type
Bu kaynağın ne zaman sona ereceğini belirtir. expiration aşağıdakilerden yalnızca biri olabilir:
expireTime string (Timestamp format)

Bu kaynağın geçerliliğinin sona erdiği zamanı gösteren UTC zaman damgası. Bu, girişte ne gönderildiğinden bağımsız olarak her zaman çıkışta sağlanır.

Zaman damgasında RFC 3339 kullanılır. Yani oluşturulan çıkış her zaman Z ile normalleştirilir ve 0, 3, 6 veya 9 kesirli basamak kullanılır. "Z" dışındaki zaman farkları da kabul edilir. Örnekler: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" veya "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Yalnızca giriş. Bu kaynak için yeni TTL (yalnızca giriş).

En fazla dokuz kesirli basamak içeren ve "s" ile biten, saniye cinsinden süre. Örnek: "3.5s".

displayName string

İsteğe bağlı. Değiştirilemez. Önbelleğe alınmış içeriğin kullanıcı tarafından oluşturulan anlamlı görünen adı. En fazla 128 Unicode karakteri.

model string

Zorunlu. Değiştirilemez. Önbelleğe alınmış içerik için kullanılacak Model adı. Biçim: models/{model}

systemInstruction object (Content)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Geliştirici tarafından ayarlanan sistem talimatı. Şu anda yalnızca metin desteklenmektedir.

toolConfig object (ToolConfig)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Araç yapılandırması Bu yapılandırma tüm araçlar için paylaşılır.

Örnek istek

Temel

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)

kabuk

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

Gönderen adı

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)

Sohbetten

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

Yanıt metni

Başarılı olursa yanıt metni, yeni oluşturulan bir CachedContent örneğini içerir.

Yöntem: cachedContents.list

Önbelleğe alınmış içerikleri listeler.

Uç nokta

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

Sorgu parametreleri

pageSize integer

İsteğe bağlı. Döndürülecek maksimum önbelleğe alınmış içerik sayısı. Hizmet, bu değerden daha az sonuç döndürebilir. Belirtilmemişse varsayılan olarak (maksimum değerin altında) belirli sayıda öğe döndürülür. Maksimum değer 1.000'dir. 1.000'in üzerindeki değerler 1.000'e zorlanır.

pageToken string

İsteğe bağlı. Önceki bir cachedContents.list çağrısından alınan sayfa jetonu. Sonraki sayfayı almak için bunu sağlayın.

Sayfalara ayırma işlemi yapılırken cachedContents.list öğesine sağlanan diğer tüm parametreler, sayfa jetonunu sağlayan çağrıyla eşleşmelidir.

İstek metni

İstek metni boş olmalıdır.

Yanıt metni

CachedContents listesi içeren yanıt.

Başarılı olursa yanıt metni aşağıdaki yapıyla birlikte verileri içerir:

Alanlar
cachedContents[] object (CachedContent)

Önbelleğe alınan içeriklerin listesi.

nextPageToken string

Sonraki sayfayı almak için pageToken olarak gönderilebilen bir jeton. Bu alan atlanırsa sonraki sayfa yoktur.

JSON gösterimi
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Yöntem: cachedContents.get

CachedContent kaynağını okur.

Uç nokta

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

Yol parametreleri

name string

Zorunlu. İçerik önbelleği girişini ifade eden kaynak adı. Biçim: cachedContents/{id} cachedContents/{cachedcontent} biçimindedir.

İstek metni

İstek metni boş olmalıdır.

Örnek istek

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)

kabuk

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

Yanıt metni

Başarılıysa yanıt metni, CachedContent öğesinin bir örneğini içerir.

Yöntem: cachedContents.patch

CachedContent kaynağını günceller (yalnızca geçerlilik süresi güncellenebilir).

Uç nokta

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

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

Yol parametreleri

cachedContent.name string

Yalnızca çıkış. Tanımlayıcı. Önbelleğe alınan içeriğe atıfta bulunan kaynak adı. Biçim: cachedContents/{id} cachedContents/{cachedcontent} biçimindedir.

Sorgu parametreleri

updateMask string (FieldMask format)

Güncellenecek alanların listesi.

Bu, alanların tam nitelikli adlarının virgülle ayrılmış listesidir. Örnek: "user.displayName,photo".

İstek metni

İstek metni, CachedContent öğesinin bir örneğini içerir.

Alanlar
expiration Union type
Bu kaynağın ne zaman sona ereceğini belirtir. expiration aşağıdakilerden yalnızca biri olabilir:
expireTime string (Timestamp format)

Bu kaynağın geçerliliğinin sona erdiği zamanı gösteren UTC zaman damgası. Bu, girişte ne gönderildiğinden bağımsız olarak her zaman çıkışta sağlanır.

Zaman damgasında RFC 3339 kullanılır. Yani oluşturulan çıkış her zaman Z ile normalleştirilir ve 0, 3, 6 veya 9 kesirli basamak kullanılır. "Z" dışındaki zaman farkları da kabul edilir. Örnekler: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" veya "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Yalnızca giriş. Bu kaynak için yeni TTL (yalnızca giriş).

En fazla dokuz kesirli basamak içeren ve "s" ile biten, saniye cinsinden süre. Örnek: "3.5s".

Örnek istek

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)

kabuk

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

Yanıt metni

Başarılıysa yanıt metni, CachedContent öğesinin bir örneğini içerir.

Yöntem: cachedContents.delete

CachedContent kaynağını siler.

Uç nokta

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

Yol parametreleri

name string

Zorunlu. İçerik önbelleği girişine atıfta bulunan kaynak adı. Biçim: cachedContents/{id} cachedContents/{cachedcontent} biçimindedir.

İstek metni

İstek metni boş olmalıdır.

Örnek istek

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)

kabuk

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

Yanıt metni

Başarılı olursa yanıt gövdesi boş bir JSON nesnesi olur.

REST Kaynağı: cachedContents

Kaynak: CachedContent

Önceden işlenmiş ve GenerativeService'e yapılan sonraki isteklerde kullanılabilen içerik.

Önbelleğe alınmış içerik yalnızca oluşturulduğu modelle kullanılabilir.

Alanlar
contents[] object (Content)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Önbelleğe alınacak içerik.

tools[] object (Tool)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Modelin bir sonraki yanıtı oluşturmak için kullanabileceği Tools listesi

createTime string (Timestamp format)

Yalnızca çıkış. Önbellek girişinin oluşturulma zamanı.

Zaman damgasında RFC 3339 kullanılır. Yani oluşturulan çıkış her zaman Z ile normalleştirilir ve 0, 3, 6 veya 9 kesirli basamak kullanılır. "Z" dışındaki zaman farkları da kabul edilir. Örnekler: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" veya "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Yalnızca çıkış. Önbellek girişinin son güncellendiği zaman (UTC).

Zaman damgasında RFC 3339 kullanılır. Yani oluşturulan çıkış her zaman Z ile normalleştirilir ve 0, 3, 6 veya 9 kesirli basamak kullanılır. "Z" dışındaki zaman farkları da kabul edilir. Örnekler: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" veya "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

Yalnızca çıkış. Önbelleğe alınan içeriğin kullanımıyla ilgili meta veriler.

expiration Union type
Bu kaynağın ne zaman sona ereceğini belirtir. expiration aşağıdakilerden yalnızca biri olabilir:
expireTime string (Timestamp format)

Bu kaynağın geçerliliğinin sona erdiği zamanı gösteren UTC zaman damgası. Bu, girişte ne gönderildiğinden bağımsız olarak her zaman çıkışta sağlanır.

Zaman damgasında RFC 3339 kullanılır. Yani oluşturulan çıkış her zaman Z ile normalleştirilir ve 0, 3, 6 veya 9 kesirli basamak kullanılır. "Z" dışındaki zaman farkları da kabul edilir. Örnekler: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" veya "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Yalnızca giriş. Bu kaynak için yeni TTL (yalnızca giriş).

En fazla dokuz kesirli basamak içeren ve "s" ile biten, saniye cinsinden süre. Örnek: "3.5s".

name string

Yalnızca çıkış. Tanımlayıcı. Önbelleğe alınan içeriğe atıfta bulunan kaynak adı. Biçim: cachedContents/{id}

displayName string

İsteğe bağlı. Değiştirilemez. Önbelleğe alınmış içeriğin kullanıcı tarafından oluşturulan anlamlı görünen adı. En fazla 128 Unicode karakteri.

model string

Zorunlu. Değiştirilemez. Önbelleğe alınmış içerik için kullanılacak Model adı. Biçim: models/{model}

systemInstruction object (Content)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Geliştirici tarafından ayarlanan sistem talimatı. Şu anda yalnızca metin desteklenmektedir.

toolConfig object (ToolConfig)

İsteğe bağlı. Yalnızca giriş. Değiştirilemez. Araç yapılandırması Bu yapılandırma tüm araçlar için paylaşılır.

JSON gösterimi
{
  "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

İstek içinde Tool kullanımını belirten parametreleri içeren araç yapılandırması.

Alanlar
functionCallingConfig object (FunctionCallingConfig)

İsteğe bağlı. İşlev çağrısı yapılandırması.

retrievalConfig object (RetrievalConfig)

İsteğe bağlı. Alma yapılandırması.

includeServerSideToolInvocations boolean

İsteğe bağlı. Doğruysa API yanıtı, Content mesajında sunucu tarafı araç çağrılarını ve yanıtlarını içerir. Bu, istemcilerin sunucunun araç etkileşimlerini gözlemlemesine olanak tanır.

JSON gösterimi
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

İşlev çağrısı davranışını belirtmeye yönelik yapılandırma.

Alanlar
mode enum (Mode)

İsteğe bağlı. İşlev çağrısının yürütülmesi gereken modu belirtir. Belirtilmezse varsayılan değer AUTO olarak ayarlanır.

allowedFunctionNames[] string

İsteğe bağlı. Sağlandığında modelin çağıracağı işlevleri sınırlayan bir dizi işlev adı.

Bu özellik yalnızca Mod ANY veya VALIDATED olduğunda ayarlanmalıdır. İşlev adları [FunctionDeclaration.name] ile eşleşmelidir. Ayarlandığında model, yalnızca izin verilen işlev adlarından bir işlev çağrısı tahmin eder.

JSON gösterimi
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Mod

Yürütme modunu tanımlayarak işlev çağrısı için yürütme davranışını tanımlar.

Sıralamalar
MODE_UNSPECIFIED Belirtilmemiş işlev çağrısı modu. Bu değer kullanılmamalıdır.
AUTO Varsayılan model davranışı: Model, işlev çağrısı veya doğal dil yanıtı tahmin etmeye karar verir.
ANY Model, her zaman yalnızca bir işlev çağrısı tahmin etmeye zorlanır. "allowedFunctionNames" ayarlanırsa tahmin edilen işlev çağrısı, "allowedFunctionNames" değerlerinden biriyle sınırlanır. Aksi takdirde, tahmin edilen işlev çağrısı, sağlanan "functionDeclarations" değerlerinden biri olur.
NONE Model herhangi bir işlev çağrısını tahmin etmez. Model davranışı, herhangi bir işlev bildirimi iletilmediğinde olduğu gibidir.
VALIDATED Model, işlev çağrısı veya doğal dil yanıtı tahmin etmeye karar verir ancak işlev çağrılarını kısıtlanmış kod çözme ile doğrular. "allowedFunctionNames" ayarlanırsa tahmin edilen işlev çağrısı, "allowedFunctionNames" değerlerinden biriyle sınırlanır. Aksi takdirde, tahmin edilen işlev çağrısı, sağlanan "functionDeclarations" değerlerinden biri olur.

RetrievalConfig

Alma yapılandırması.

Alanlar
latLng object (LatLng)

İsteğe bağlı. Kullanıcının konumu.

languageCode string

İsteğe bağlı. Kullanıcının dil kodu. İçeriğin dil kodu. BCP47 tarafından tanımlanan dil etiketlerini kullanın.

JSON gösterimi
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

Bir enlem/boylam çiftini temsil eden nesne. Bu, enlem derecelerini ve boylam derecelerini temsil eden bir çift çift sayı olarak ifade edilir. Aksi belirtilmediği sürece bu nesne WGS84 standardına uygun olmalıdır. Değerler normalleştirilmiş aralıklar içinde olmalıdır.

Alanlar
latitude number

Enlem (derece cinsinden). [-90.0, +90.0] aralığında olmalıdır.

longitude number

Derece cinsinden boylam. [-180.0, +180.0] aralığında olmalıdır.

JSON gösterimi
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Önbelleğe alınan içeriğin kullanımıyla ilgili meta veriler.

Alanlar
totalTokenCount integer

Önbelleğe alınan içeriğin kullandığı toplam jeton sayısı.

JSON gösterimi
{
  "totalTokenCount": integer
}