Caching

שמירת מטמון של הקשר מאפשרת לכם לשמור ולעשות שימוש חוזר בטוקנים של קלט שחושבו מראש שאתם רוצים להשתמש בהם שוב ושוב, למשל כשאתם שואלים שאלות שונות לגבי אותו קובץ מדיה. השימוש ב-CDN יכול להוביל לחיסכון בעלויות ולשיפור המהירות, בהתאם לשימוש. למידע נוסף, אפשר לעיין במדריך בנושא שמירת הקשר במטמון.

שיטה: cachedContents.create

יוצר משאב CachedContent.

נקודת קצה

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

גוף הבקשה

גוף הבקשה מכיל מופע של CachedContent.

Fields
contents[] object (Content)

אופציונלי. קלט בלבד. אי אפשר לשנות. התוכן שרוצים לשמור במטמון.

tools[] object (Tool)

אופציונלי. קלט בלבד. אי אפשר לשנות. רשימה של Tools שהמודל יכול להשתמש בהם כדי ליצור את התשובה הבאה

expiration Union type
השדה הזה מציין מתי יפוג התוקף של המשאב. הערך expiration יכול להיות רק אחד מהבאים:
expireTime string (Timestamp format)

חותמת זמן בשעון UTC שמציינת מתי המשאב הזה נחשב כמשאב שתוקפו פג. הערך הזה תמיד מופיע בפלט, לא משנה מה נשלח בקלט.

הפלט שנוצר תמיד יהיה בפורמט RFC 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)

קלט בלבד. ערך חדש של TTL למשאב הזה, קלט בלבד.

משך זמן בשניות עם עד תשע ספרות אחרי הנקודה העשרונית, שמסתיים ב-'s'. דוגמה: "3.5s".

displayName string

אופציונלי. אי אפשר לשנות. שם התצוגה המשמעותי של התוכן שבמטמון, שנוצר על ידי המשתמש. מקסימום 128 תווים ב-Unicode.

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

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)

קונכייה

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

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)

מצ'אט

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

גוף התשובה

אם הפעולה בוצעה ללא שגיאות, גוף התגובה יכיל מופע חדש של CachedContent.

שיטה: cachedContents.list

רשימות CachedContents.

נקודת קצה

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

פרמטרים של שאילתה

pageSize integer

אופציונלי. המספר המקסימלי של תכנים שמאוחסנים במטמון שיוחזרו. יכול להיות שהשירות יחזיר פחות מהערך הזה. אם לא מציינים ערך, יוחזר מספר ברירת מחדל של פריטים (מתחת למקסימום). הערך המקסימלי הוא 1,000. ערכים גבוהים יותר יומרו ל-1,000.

pageToken string

אופציונלי. טוקן של דף שהתקבל מקריאה קודמת של cachedContents.list. צריך להזין את הטוקן כדי לאחזר את הדף הבא.

כשמבצעים חלוקה לעמודים, כל הפרמטרים האחרים שסופקו ל-cachedContents.list חייבים להיות זהים לקריאה שסיפקה את הטוקן של הדף.

גוף הבקשה

גוף הבקשה צריך להיות ריק.

גוף התשובה

תגובה עם רשימת CachedContents.

אם הפעולה בוצעה ללא שגיאות, גוף התגובה יכיל נתונים במבנה הבא:

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

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)

קונכייה

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

גוף התשובה

אם הפעולה בוצעה ללא שגיאות, גוף התגובה יכיל מופע של CachedContent.

‫Method: 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)

חותמת זמן בשעון UTC שמציינת מתי המשאב הזה נחשב כמשאב שתוקפו פג. הערך הזה תמיד מופיע בפלט, לא משנה מה נשלח בקלט.

הפלט שנוצר תמיד יהיה בפורמט RFC 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)

קלט בלבד. ערך חדש של TTL למשאב הזה, קלט בלבד.

משך זמן בשניות עם עד תשע ספרות אחרי הנקודה העשרונית, שמסתיים ב-'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);

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)

קונכייה

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

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)

קונכייה

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)

פלט בלבד. זמן היצירה של רשומת המטמון.

הפלט שנוצר תמיד יהיה בפורמט RFC 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)

פלט בלבד. הזמן שבו רשומת המטמון עודכנה בפעם האחרונה לפי שעון UTC.

הפלט שנוצר תמיד יהיה בפורמט RFC 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)

חותמת זמן בשעון UTC שמציינת מתי המשאב הזה נחשב כמשאב שתוקפו פג. הערך הזה תמיד מופיע בפלט, לא משנה מה נשלח בקלט.

הפלט שנוצר תמיד יהיה בפורמט RFC 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)

קלט בלבד. ערך חדש של TTL למשאב הזה, קלט בלבד.

משך זמן בשניות עם עד תשע ספרות אחרי הנקודה העשרונית, שמסתיים ב-'s'. דוגמה: "3.5s".

name string

פלט בלבד. מזהה. שם המשאב שאליו מתייחס התוכן שנשמר במטמון. פורמט: cachedContents/{id}

displayName string

אופציונלי. אי אפשר לשנות. שם התצוגה המשמעותי של התוכן שבמטמון, שנוצר על ידי המשתמש. מקסימום 128 תווים ב-Unicode.

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

אופציונלי. אם הערך הוא true, התשובה של ה-API תכלול את הקריאות לכלים ואת התשובות בצד השרת בהודעה 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
  ]
}

מצב

הגדרת אופן הביצוע של קריאות לפונקציות על ידי הגדרת מצב הביצוע.

טיפוסים בני מנייה (enum)
MODE_UNSPECIFIED מצב לא מוגדר של הפעלת פונקציות. אין להשתמש בערך הזה.
AUTO התנהגות ברירת המחדל של המודל, המודל מחליט לחזות קריאה לפונקציה או תגובה בשפה טבעית.
ANY המודל מוגבל לחיזוי של קריאה לפונקציה בלבד. אם מוגדרים שמות של פונקציות מותרות (allowedFunctionNames), הקריאה החזויה לפונקציה תוגבל לאחד מהשמות האלה. אחרת, הקריאה החזויה לפונקציה תהיה אחת מההצהרות על הפונקציות (functionDeclarations) שסופקו.
NONE המודל לא יבצע חיזוי של הפעלת פונקציה. התנהגות המודל זהה למצב שבו לא מעבירים הצהרות פונקציה.
VALIDATED המודל מחליט אם לחזות קריאה לפונקציה או תשובה בשפה טבעית, אבל הוא יאמת קריאות לפונקציה באמצעות פענוח מוגבל. אם מוגדרים שמות הפונקציות המותרות, הקריאה החזויה לפונקציה תוגבל לאחד משמות הפונקציות המותרות. אחרת, הקריאה החזויה לפונקציה תהיה אחת מהצהרות הפונקציות שסופקו.

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
}