Caching

कॉन्टेक्स्ट कैश मेमोरी की सुविधा की मदद से, पहले से कैलकुलेट किए गए उन इनपुट टोकन को सेव किया जा सकता है जिनका आपको बार-बार इस्तेमाल करना है. उदाहरण के लिए, एक ही मीडिया फ़ाइल के बारे में अलग-अलग सवाल पूछते समय. इस्तेमाल के आधार पर, इससे लागत कम हो सकती है और काम तेज़ी से हो सकता है. ज़्यादा जानकारी के लिए, कॉन्टेक्स्ट कैश मेमोरी गाइड देखें.

तरीका: cachedContents.create

यह CachedContent संसाधन बनाता है.

एंडपॉइंट

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

अनुरोध का मुख्य भाग

अनुरोध के मुख्य भाग में CachedContent का उदाहरण है.

फ़ील्ड
contents[] object (Content)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. कैश मेमोरी में सेव किया जाने वाला कॉन्टेंट.

tools[] object (Tool)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. Tools मॉडल, अगला जवाब जनरेट करने के लिए इनका इस्तेमाल कर सकता है

expiration Union type
इससे पता चलता है कि यह संसाधन कब खत्म होगा. expiration इनमें से सिर्फ़ एक हो सकता है:
expireTime string (Timestamp format)

यूटीसी में टाइमस्टैंप, जिससे पता चलता है कि यह संसाधन कब खत्म हो गया. यह जानकारी, इनपुट में भेजी गई जानकारी के बावजूद, आउटपुट में हमेशा दी जाती है.

यह आरएफ़सी 3339 का इस्तेमाल करता है. इसमें जनरेट किया गया आउटपुट हमेशा Z-नॉर्मलाइज़ किया जाएगा और इसमें 0, 3, 6 या 9 फ़्रैक्शनल अंक इस्तेमाल किए जाएंगे. "Z" के अलावा, अन्य ऑफ़सेट भी स्वीकार किए जाते हैं. उदाहरण: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" या "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

सिर्फ़ इनपुट के लिए. इस संसाधन के लिए नया टीटीएल, सिर्फ़ इनपुट करें.

यह सेकंड में अवधि होती है. इसमें नौ दशमलव अंक तक हो सकते हैं. इसके आखिर में 's' होता है. उदाहरण: "3.5s".

displayName string

ज़रूरी नहीं. इम्यूटेबल. कैश किए गए कॉन्टेंट का यूज़र जनरेटेड डिसप्ले नेम. ज़्यादा से ज़्यादा 128 यूनिकोड वर्ण.

model string

ज़रूरी है. इम्यूटेबल. कैश किए गए कॉन्टेंट के लिए इस्तेमाल किए जाने वाले Model का नाम फ़ॉर्मैट: models/{model}

systemInstruction object (Content)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. डेवलपर ने सिस्टम के लिए निर्देश सेट किए हैं. फ़िलहाल, सिर्फ़ टेक्स्ट के तौर पर उपलब्ध है.

toolConfig object (ToolConfig)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. टूल कॉन्फ़िगरेशन. यह कॉन्फ़िगरेशन सभी टूल के लिए शेयर किया जाता है.

अनुरोध का उदाहरण

सामान्य

Python

from google import genai
from google.genai import types

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

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

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

Node.js

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

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

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

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

ऐप पर जाएं

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

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

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

शेल

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

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

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

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

नाम

Python

from google import genai
from google.genai import types

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

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

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

Node.js

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

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

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

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

ऐप पर जाएं

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

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

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

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

चैट से

Python

from google import genai
from google.genai import types

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

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

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

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

Node.js

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

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

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

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

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

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

ऐप पर जाएं

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

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

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

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

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

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

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

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

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

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

जवाब का मुख्य भाग

अनुरोध पूरा होने पर, जवाब के मुख्य हिस्से में CachedContent का नया इंस्टेंस शामिल किया जाता है.

तरीका: cachedContents.list

Lists CachedContents.

एंडपॉइंट

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

क्वेरी पैरामीटर

pageSize integer

ज़रूरी नहीं. कैश किए गए ज़्यादा से ज़्यादा कॉन्टेंट वापस लाने की संख्या. ऐसा हो सकता है कि सेवा इस वैल्यू से कम नतीजे दिखाए. अगर इसे तय नहीं किया गया है, तो ज़्यादा से ज़्यादा संख्या के हिसाब से कुछ डिफ़ॉल्ट आइटम दिखाए जाएंगे. इसकी ज़्यादा से ज़्यादा वैल्यू 1,000 हो सकती है. इससे ज़्यादा वैल्यू डालने पर, उसे 1,000 पर सेट कर दिया जाएगा.

pageToken string

ज़रूरी नहीं. यह एक पेज टोकन है, जो पिछली cachedContents.list कॉल से मिला था. अगला पेज पाने के लिए, यह जानकारी दें.

पेज नंबर के हिसाब से डेटा दिखाने के दौरान, cachedContents.list को दिए गए अन्य सभी पैरामीटर, पेज टोकन देने वाले कॉल से मेल खाने चाहिए.

अनुरोध का मुख्य भाग

अनुरोध का मुख्य हिस्सा खाली होना चाहिए.

जवाब का मुख्य भाग

CacheContents की सूची के साथ जवाब.

अगर एपीआई सही से जुड़ जाता है, ताे जवाब के मुख्य भाग में नीचे दिए गए स्ट्रक्चर शामिल होता है.

Fields
cachedContents[] object (CachedContent)

कैश मेमोरी में सेव किए गए कॉन्टेंट की सूची.

nextPageToken string

यह एक टोकन है. इसका इस्तेमाल pageToken के तौर पर किया जा सकता है, ताकि अगला पेज वापस पाया जा सके. अगर इस फ़ील्ड को खाली छोड़ा जाता है, तो इसके बाद कोई पेज नहीं होता.

JSON के काेड में दिखाना
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

तरीका: cachedContents.get

यह CachedContent संसाधन को पढ़ता है.

एंडपॉइंट

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

पाथ पैरामीटर

name string

ज़रूरी है. कॉन्टेंट की कैश मेमोरी में सेव की गई एंट्री का रेफ़रंस देने वाला संसाधन का नाम. फ़ॉर्मैट: cachedContents/{id} यह cachedContents/{cachedcontent} के फ़ॉर्म में होता है.

अनुरोध का मुख्य भाग

अनुरोध का मुख्य हिस्सा खाली होना चाहिए.

अनुरोध का उदाहरण

Python

from google import genai

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

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

Node.js

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

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

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

ऐप पर जाएं

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

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

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

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

शेल

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

जवाब का मुख्य भाग

कामयाब रहने पर, जवाब के मुख्य हिस्से में CachedContent का एक इंस्टेंस शामिल किया जाता है.

तरीका: cachedContents.patch

यह CachedContent संसाधन को अपडेट करता है. सिर्फ़ खत्म होने की तारीख को अपडेट किया जा सकता है.

एंडपॉइंट

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

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

पाथ पैरामीटर

cachedContent.name string

सिर्फ़ आउटपुट के लिए. आइडेंटिफ़ायर. कैश मेमोरी में सेव किए गए कॉन्टेंट का संसाधन नाम. फ़ॉर्मैट: cachedContents/{id} यह cachedContents/{cachedcontent} के फ़ॉर्म में होता है.

क्वेरी पैरामीटर

updateMask string (FieldMask format)

अपडेट किए जाने वाले फ़ील्ड की सूची.

यह फ़ील्ड के पूरी तरह क्वालिफ़ाइड नामों की कॉमा लगाकर अलग की गई लिस्ट है. उदाहरण: "user.displayName,photo".

अनुरोध का मुख्य भाग

अनुरोध के मुख्य भाग में CachedContent का उदाहरण है.

फ़ील्ड
expiration Union type
इससे पता चलता है कि यह संसाधन कब खत्म होगा. expiration इनमें से सिर्फ़ एक हो सकता है:
expireTime string (Timestamp format)

यूटीसी में टाइमस्टैंप, जिससे पता चलता है कि यह संसाधन कब खत्म हो गया. यह जानकारी, इनपुट में भेजी गई जानकारी के बावजूद, आउटपुट में हमेशा दी जाती है.

यह आरएफ़सी 3339 का इस्तेमाल करता है. इसमें जनरेट किया गया आउटपुट हमेशा Z-नॉर्मलाइज़ किया जाएगा और इसमें 0, 3, 6 या 9 फ़्रैक्शनल अंक इस्तेमाल किए जाएंगे. "Z" के अलावा, अन्य ऑफ़सेट भी स्वीकार किए जाते हैं. उदाहरण: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" या "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

सिर्फ़ इनपुट के लिए. इस संसाधन के लिए नया टीटीएल, सिर्फ़ इनपुट करें.

यह सेकंड में अवधि होती है. इसमें नौ दशमलव अंक तक हो सकते हैं. इसके आखिर में 's' होता है. उदाहरण: "3.5s".

अनुरोध का उदाहरण

Python

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

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

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

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

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

Node.js

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

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

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

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

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

ऐप पर जाएं

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

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

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

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

शेल

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

जवाब का मुख्य भाग

कामयाब रहने पर, जवाब के मुख्य हिस्से में CachedContent का एक इंस्टेंस शामिल किया जाता है.

तरीका: cachedContents.delete

यह CachedContent संसाधन को मिटाता है.

एंडपॉइंट

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

पाथ पैरामीटर

name string

ज़रूरी है. कॉन्टेंट कैश मेमोरी की एंट्री का रेफ़रंस देने वाला संसाधन का नाम. फ़ॉर्मैट: cachedContents/{id} यह cachedContents/{cachedcontent} के फ़ॉर्म में होता है.

अनुरोध का मुख्य भाग

अनुरोध का मुख्य हिस्सा खाली होना चाहिए.

अनुरोध का उदाहरण

Python

from google import genai

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

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

Node.js

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

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

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

ऐप पर जाएं

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

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

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

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

शेल

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

जवाब का मुख्य भाग

अगर अनुरोध पूरा हो जाता है, तो जवाब के मुख्य हिस्से में एक खाली JSON ऑब्जेक्ट होता है.

REST रिसोर्स: cachedContents

संसाधन: CachedContent

ऐसा कॉन्टेंट जिसे पहले से प्रोसेस किया गया हो और जिसका इस्तेमाल, GenerativeService को किए जाने वाले अगले अनुरोध में किया जा सकता हो.

कैश किए गए कॉन्टेंट का इस्तेमाल सिर्फ़ उसी मॉडल के साथ किया जा सकता है जिसके लिए इसे बनाया गया था.

Fields
contents[] object (Content)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. कैश मेमोरी में सेव किया जाने वाला कॉन्टेंट.

tools[] object (Tool)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. Tools मॉडल, अगला जवाब जनरेट करने के लिए इस सूची का इस्तेमाल कर सकता है

createTime string (Timestamp format)

सिर्फ़ आउटपुट के लिए. कैश मेमोरी की एंट्री बनाए जाने का समय.

यह आरएफ़सी 3339 का इस्तेमाल करता है. इसमें जनरेट किया गया आउटपुट हमेशा Z-नॉर्मलाइज़ किया जाएगा और इसमें 0, 3, 6 या 9 फ़्रैक्शनल अंक इस्तेमाल किए जाएंगे. "Z" के अलावा, अन्य ऑफ़सेट भी स्वीकार किए जाते हैं. उदाहरण: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" या "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

सिर्फ़ आउटपुट के लिए. यूटीसी के मुताबिक, कैश मेमोरी की एंट्री को आखिरी बार कब अपडेट किया गया था.

यह आरएफ़सी 3339 का इस्तेमाल करता है. इसमें जनरेट किया गया आउटपुट हमेशा Z-नॉर्मलाइज़ किया जाएगा और इसमें 0, 3, 6 या 9 फ़्रैक्शनल अंक इस्तेमाल किए जाएंगे. "Z" के अलावा, अन्य ऑफ़सेट भी स्वीकार किए जाते हैं. उदाहरण: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" या "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

सिर्फ़ आउटपुट के लिए. कैश मेमोरी में सेव किए गए कॉन्टेंट के इस्तेमाल से जुड़ा मेटाडेटा.

expiration Union type
इससे पता चलता है कि यह संसाधन कब खत्म होगा. expiration इनमें से सिर्फ़ एक हो सकता है:
expireTime string (Timestamp format)

यूटीसी में टाइमस्टैंप, जिससे पता चलता है कि यह संसाधन कब खत्म हो गया. यह जानकारी, इनपुट में भेजी गई जानकारी के बावजूद, आउटपुट में हमेशा दी जाती है.

यह आरएफ़सी 3339 का इस्तेमाल करता है. इसमें जनरेट किया गया आउटपुट हमेशा Z-नॉर्मलाइज़ किया जाएगा और इसमें 0, 3, 6 या 9 फ़्रैक्शनल अंक इस्तेमाल किए जाएंगे. "Z" के अलावा, अन्य ऑफ़सेट भी स्वीकार किए जाते हैं. उदाहरण: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" या "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

सिर्फ़ इनपुट के लिए. इस संसाधन के लिए नया टीटीएल, सिर्फ़ इनपुट करें.

यह सेकंड में अवधि होती है. इसमें नौ दशमलव अंक तक हो सकते हैं. इसके आखिर में 's' होता है. उदाहरण: "3.5s".

name string

सिर्फ़ आउटपुट के लिए. आइडेंटिफ़ायर. कैश मेमोरी में सेव किए गए कॉन्टेंट का संसाधन नाम. फ़ॉर्मैट: cachedContents/{id}

displayName string

ज़रूरी नहीं. इम्यूटेबल. कैश किए गए कॉन्टेंट का यूज़र जनरेटेड डिसप्ले नेम. ज़्यादा से ज़्यादा 128 यूनिकोड वर्ण.

model string

ज़रूरी है. इम्यूटेबल. कैश किए गए कॉन्टेंट के लिए इस्तेमाल किए जाने वाले Model का नाम फ़ॉर्मैट: models/{model}

systemInstruction object (Content)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. डेवलपर ने सिस्टम के लिए निर्देश सेट किए हैं. फ़िलहाल, सिर्फ़ टेक्स्ट के तौर पर उपलब्ध है.

toolConfig object (ToolConfig)

ज़रूरी नहीं. सिर्फ़ इनपुट के लिए. इम्यूटेबल. टूल कॉन्फ़िगरेशन. यह कॉन्फ़िगरेशन सभी टूल के लिए शेयर किया जाता है.

JSON के काेड में दिखाना
{
  "contents": [
    {
      object (Content)
    }
  ],
  "tools": [
    {
      object (Tool)
    }
  ],
  "createTime": string,
  "updateTime": string,
  "usageMetadata": {
    object (UsageMetadata)
  },

  // expiration
  "expireTime": string,
  "ttl": string
  // Union type
  "name": string,
  "displayName": string,
  "model": string,
  "systemInstruction": {
    object (Content)
  },
  "toolConfig": {
    object (ToolConfig)
  }
}

ToolConfig

टूल कॉन्फ़िगरेशन में ऐसे पैरामीटर होते हैं जिनसे अनुरोध में Tool के इस्तेमाल के बारे में जानकारी मिलती है.

Fields
functionCallingConfig object (FunctionCallingConfig)

ज़रूरी नहीं. फ़ंक्शन कॉलिंग कॉन्फ़िगरेशन.

retrievalConfig object (RetrievalConfig)

ज़रूरी नहीं. डेटा वापस पाने का कॉन्फ़िगरेशन.

includeServerSideToolInvocations boolean

ज़रूरी नहीं. अगर यह वैल्यू सही है, तो एपीआई से मिले जवाब में सर्वर-साइड टूल कॉल और जवाब शामिल होंगे. ये जवाब, Content मैसेज में शामिल होंगे. इससे क्लाइंट, सर्वर के टूल इंटरैक्शन को देख सकते हैं.

JSON के काेड में दिखाना
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

फ़ंक्शन कॉल करने के तरीके के बारे में बताने के लिए कॉन्फ़िगरेशन.

Fields
mode enum (Mode)

ज़रूरी नहीं. यह बताता है कि फ़ंक्शन कॉलिंग किस मोड में काम करनी चाहिए. अगर कोई वैल्यू तय नहीं की जाती है, तो डिफ़ॉल्ट वैल्यू AUTO पर सेट हो जाएगी.

allowedFunctionNames[] string

ज़रूरी नहीं. फ़ंक्शन के नामों का एक सेट. इसे उपलब्ध कराने पर, मॉडल सिर्फ़ उन फ़ंक्शन को कॉल करेगा.

इसे सिर्फ़ तब सेट किया जाना चाहिए, जब मोड ANY या VALIDATED हो. फ़ंक्शन के नाम, [FunctionDeclaration.name] से मेल खाने चाहिए. इस विकल्प को सेट करने पर, मॉडल सिर्फ़ उन फ़ंक्शन के नाम से फ़ंक्शन कॉल का अनुमान लगाएगा जिनकी अनुमति दी गई है.

JSON के काेड में दिखाना
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

मोड

यह फ़ंक्शन कॉल करने के तरीके के बारे में बताता है. इसके लिए, यह फ़ंक्शन कॉल करने का मोड तय करता है.

Enums
MODE_UNSPECIFIED फ़ंक्शन कॉलिंग मोड की जानकारी नहीं दी गई है. इस वैल्यू का इस्तेमाल नहीं किया जाना चाहिए.
AUTO मॉडल का डिफ़ॉल्ट व्यवहार, मॉडल यह तय करता है कि फ़ंक्शन कॉल का अनुमान लगाना है या नैचुरल लैंग्वेज में जवाब देना है.
ANY मॉडल को हमेशा सिर्फ़ फ़ंक्शन कॉल का अनुमान लगाने के लिए सीमित किया जाता है. अगर "allowedFunctionNames" सेट किए गए हैं, तो अनुमानित फ़ंक्शन कॉल, "allowedFunctionNames" में से किसी एक तक सीमित रहेगा. ऐसा न होने पर, अनुमानित फ़ंक्शन कॉल, उपलब्ध कराए गए "functionDeclarations" में से कोई एक होगा.
NONE मॉडल, किसी भी फ़ंक्शन कॉल का अनुमान नहीं लगाएगा. मॉडल का व्यवहार वैसा ही होता है जैसा फ़ंक्शन के बारे में कोई जानकारी न देने पर होता है.
VALIDATED मॉडल यह तय करता है कि फ़ंक्शन कॉल का अनुमान लगाना है या नैचुरल लैंग्वेज में जवाब देना है. हालांकि, यह फ़ंक्शन कॉल की पुष्टि, सीमित डिकोडिंग की मदद से करेगा. अगर "allowedFunctionNames" सेट किए गए हैं, तो अनुमानित फ़ंक्शन कॉल, "allowedFunctionNames" में से किसी एक तक सीमित रहेगा. ऐसा न होने पर, अनुमानित फ़ंक्शन कॉल, दिए गए "functionDeclarations" में से कोई एक होगा.

RetrievalConfig

डेटा वापस पाने का कॉन्फ़िगरेशन.

Fields
latLng object (LatLng)

ज़रूरी नहीं. उपयोगकर्ता की जगह.

languageCode string

ज़रूरी नहीं. उपयोगकर्ता की भाषा का कोड. कॉन्टेंट के लिए भाषा कोड. BCP47 में तय किए गए भाषा टैग का इस्तेमाल करें.

JSON के काेड में दिखाना
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

यह ऑब्जेक्ट, अक्षांश/देशांतर की जोड़ी को दिखाता है. इसे डबल के तौर पर दिखाया जाता है, ताकि अक्षांश और देशांतर की डिग्री को दिखाया जा सके. जब तक अलग से कोई जानकारी न दी जाए, तब तक इस ऑब्जेक्ट को WGS84 स्टैंडर्ड के मुताबिक होना चाहिए. वैल्यू, सामान्य की गई रेंज में होनी चाहिए.

Fields
latitude number

डिग्री में अक्षांश. यह [-90.0, +90.0] की रेंज में होना चाहिए.

longitude number

डिग्री में देशांतर. यह [-180.0, +180.0] की रेंज में होना चाहिए.

JSON के काेड में दिखाना
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

कैश मेमोरी में सेव किए गए कॉन्टेंट के इस्तेमाल से जुड़ा मेटाडेटा.

Fields
totalTokenCount integer

कैश किए गए कॉन्टेंट के लिए इस्तेमाल किए गए टोकन की कुल संख्या.

JSON के काेड में दिखाना
{
  "totalTokenCount": integer
}