Caching

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

שיטה: cachedContents.create

יצירת משאב CachedContent.

נקודת קצה

פוסט https://generativelanguage.googleapis.com/v1beta/cachedContents

גוף הבקשה

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

שדות
contents[] object (Content)

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

tools[] object (Tool)

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

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

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

הפורמט הזה משתמש ב-RFC 3339, שבו הפלט שנוצר תמיד יהיה מנורמלי לפי Z וישמש בספרות עשרוניות של 0, 3, 6 או 9. אפשר להשתמש גם בשינויים (offsets) אחרים מלבד '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)

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

בקשה לדוגמה

from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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'"
    }'
from google import genai
from google.genai import types

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

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)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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)
from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-1.5-flash-001"
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)
// 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-1.5-flash-001";
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-1.5-flash-001"
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, "user"),
}, 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, "user"),
})
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.

נקודת קצה

קבלה https://generativelanguage.googleapis.com/v1beta/cachedContents

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

pageSize integer

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

pageToken string

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

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

גוף הבקשה

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

גוף התשובה

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

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

שדות
cachedContents[] object (CachedContent)

רשימת התוכן שנשמר במטמון.

nextPageToken string

אסימון שאפשר לשלוח כ-pageToken כדי לאחזר את הדף הבא. אם השדה הזה לא יצוין, לא יהיו דפים נוספים.

ייצוג ב-JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

שיטה: cachedContents.get

קריאת המשאב CachedContent.

נקודת קצה

קבלה https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

פרמטרים של נתיב

name string

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

גוף הבקשה

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

בקשה לדוגמה

from google import genai

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

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))
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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 (אפשר לעדכן רק את התוקף).

נקודת קצה

תיקון 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. אפשר להשתמש גם בשינויים (offsets) אחרים מלבד '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}

בקשה לדוגמה

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-1.5-flash-001"

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),
)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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.

נקודת קצה

מחיקה https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

פרמטרים של נתיב

name string

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

גוף הבקשה

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

בקשה לדוגמה

from google import genai

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

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)
// 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-1.5-flash-001";

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-1.5-flash-001"
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, "user"),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", "user",
	),
})
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.

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

שדות
contents[] object (Content)

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

tools[] object (Tool)

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

createTime string (Timestamp format)

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

הפורמט הזה משתמש ב-RFC 3339, שבו הפלט שנוצר תמיד יהיה מנורמלי לפי Z וישמש בספרות עשרוניות של 0, 3, 6 או 9. אפשר להשתמש גם בשינויים (offsets) אחרים מלבד '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. אפשר להשתמש גם בשינויים (offsets) אחרים מלבד '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. אפשר להשתמש גם בשינויים (offsets) אחרים מלבד '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)
  }
}

תוכן

סוג הנתונים המובנה הבסיסי שמכיל תוכן של הודעה שמחולק לכמה חלקים.

Content כולל שדה role שמציין את היוצר של Content ושדה parts שמכיל נתונים בכמה חלקים שמכילים את תוכן תור ההודעה.

שדות
parts[] object (Part)

Parts מסודרים שמרכיבים הודעה אחת. לחלקים יכולים להיות סוגים שונים של MIME.

role string

אופציונלי. היוצר של התוכן. הערך חייב להיות 'משתמש' או 'מודל'.

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

ייצוג ב-JSON
{
  "parts": [
    {
      object (Part)
    }
  ],
  "role": string
}

חלק

טיפוס נתונים שמכיל מדיה שחלק מתוך הודעה Content שמכילה כמה חלקים.

Part מורכב מנתונים שיש להם סוג נתונים משויך. השדה Part יכול להכיל רק אחד מהסוגים הקבילים ב-Part.data.

אם השדה inlineData מלא ביטים גולמיים, ל-Part חייב להיות סוג MIME קבוע של IANA שמזהה את הסוג ואת תת-הסוג של המדיה.

שדות
thought boolean

אופציונלי. מציין אם החלק נחשב לדגם.

data Union type
הערך של data יכול להיות רק אחת מהאפשרויות הבאות:
text string

טקסט בשורת הטקסט.

inlineData object (Blob)

בייטים של מדיה בתוך הטקסט.

functionCall object (FunctionCall)

הערך המשוער של FunctionCall שהמודל מחזיר, ומכיל מחרוזת שמייצגת את FunctionDeclaration.name עם הארגומנטים והערכים שלהם.

functionResponse object (FunctionResponse)

הפלט של התוצאה של FunctionCall שמכיל מחרוזת שמייצגת את FunctionDeclaration.name ואובייקט JSON מובנה שמכיל את כל הפלט מהפונקציה משמשים כהקשר של המודל.

fileData object (FileData)

נתונים שמבוססים על URI.

executableCode object (ExecutableCode)

קוד שנוצר על ידי המודל והוא מיועד להרצה.

codeExecutionResult object (CodeExecutionResult)

התוצאה של הפעלת ExecutableCode.

ייצוג ב-JSON
{
  "thought": boolean,

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  }
  // Union type
}

Blob

בייטים של מדיה גולמית.

אין לשלוח טקסט כבייט גולמיים, צריך להשתמש בשדה 'text'.

שדות
mimeType string

סוג ה-MIME הסטנדרטי של IANA של נתוני המקור. דוגמאות: ‎- image/png ‎- image/jpeg אם מציינים סוג MIME שאינו נתמך, תוחזר שגיאה. רשימה מלאה של הסוגים הנתמכים זמינה במאמר פורמטים נתמכים של קבצים.

data string (bytes format)

ביטים גולמיים לפורמטים של מדיה.

מחרוזת בקידוד Base64.

ייצוג ב-JSON
{
  "mimeType": string,
  "data": string
}

FunctionCall

הערך המשוער של FunctionCall שהמודל מחזיר, ומכיל מחרוזת שמייצגת את FunctionDeclaration.name עם הארגומנטים והערכים שלהם.

שדות
id string

אופציונלי. המזהה הייחודי של קריאת הפונקציה. אם הוא מאוכלס, הלקוח יבצע את functionCall ויחזיר את התשובה עם id התואם.

name string

חובה. שם הפונקציה שרוצים להפעיל. המזהה חייב להכיל את התווים a-z,‏ A-Z,‏ 0-9 או קווים תחתונים ומקפים, באורך מקסימלי של 63 תווים.

args object (Struct format)

אופציונלי. הפרמטרים והערכים של הפונקציה בפורמט אובייקט JSON.

ייצוג ב-JSON
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

FunctionResponse

הפלט של התוצאה מ-FunctionCall שמכיל מחרוזת שמייצגת את FunctionDeclaration.name ואובייקט JSON מובנה שמכיל את כל הפלט מהפונקציה משמשים כהקשר של המודל. השדה הזה אמור להכיל את התוצאה של FunctionCall שנוצרה על סמך תחזית המודל.

שדות
id string

אופציונלי. המזהה של קריאת הפונקציה שהתגובה הזו מיועדת לה. הלקוח מאכלס את השדה הזה בהתאם לקריאה התואמת לפונקציה id.

name string

חובה. שם הפונקציה שרוצים להפעיל. המזהה חייב להכיל את התווים a-z,‏ A-Z,‏ 0-9 או קווים תחתונים ומקפים, באורך מקסימלי של 63 תווים.

response object (Struct format)

חובה. תגובת הפונקציה בפורמט של אובייקט JSON.

ייצוג ב-JSON
{
  "id": string,
  "name": string,
  "response": {
    object
  }
}

FileData

נתונים שמבוססים על URI.

שדות
mimeType string

אופציונלי. סוג ה-MIME הסטנדרטי של IANA של נתוני המקור.

fileUri string

חובה. URI.

ייצוג ב-JSON
{
  "mimeType": string,
  "fileUri": string
}

ExecutableCode

קוד שנוצר על ידי המודל ונועד לביצוע, והתוצאה שמוחזרת למודל.

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

שדות
language enum (Language)

חובה. שפת התכנות של ה-code.

code string

חובה. הקוד שרוצים להריץ.

ייצוג ב-JSON
{
  "language": enum (Language),
  "code": string
}

שפה

שפות התכנות הנתמכות לקוד שנוצר.

טיפוסים בני מנייה (enum)
LANGUAGE_UNSPECIFIED לא נבחרה שפה. לא צריך להשתמש בערך הזה.
PYTHON Python מגרסה 3.10 ואילך, עם numpy ו-simpy זמינים.

CodeExecutionResult

התוצאה של הפעלת ExecutableCode.

הקוד הזה נוצר רק כשמשתמשים ב-CodeExecution, ותמיד מופיע אחרי part שמכיל את ExecutableCode.

שדות
outcome enum (Outcome)

חובה. התוצאה של הרצת הקוד.

output string

אופציונלי. הפונקציה מכילה את stdout כשהקוד מבוצע בהצלחה, את stderr או תיאור אחר במקרה אחר.

ייצוג ב-JSON
{
  "outcome": enum (Outcome),
  "output": string
}

תוצאה

ספירה של התוצאות האפשריות של הרצת הקוד.

טיפוסים בני מנייה (enum)
OUTCOME_UNSPECIFIED הסטטוס לא צוין. לא צריך להשתמש בערך הזה.
OUTCOME_OK ביצוע הקוד הושלם בהצלחה.
OUTCOME_FAILED ביצוע הקוד הסתיים, אבל עם כשל. השדה stderr צריך להכיל את הסיבה.
OUTCOME_DEADLINE_EXCEEDED ביצוע הקוד נמשך זמן רב מדי והוא בוטל. יכול להיות שיופיע פלט חלקי או לא.

כלי

פרטי הכלי שהמודל עשוי להשתמש בהם כדי ליצור תשובה.

Tool הוא קטע קוד שמאפשר למערכת לקיים אינטראקציה עם מערכות חיצוניות כדי לבצע פעולה או קבוצת פעולות מחוץ לידע ולהיקף של המודל.

שדות
functionDeclarations[] object (FunctionDeclaration)

אופציונלי. רשימה של FunctionDeclarations שזמינים למודל ואפשר להשתמש בהם לקריאה לפונקציות.

המודל או המערכת לא מריצים את הפונקציה. במקום זאת, הפונקציה שהוגדרה עשויה להוחזר כ-FunctionCall עם ארגומנטים לצד הלקוח לצורך ביצוע. המודל עשוי להחליט לקרוא לקבוצת משנה של הפונקציות האלה על ידי אכלוס FunctionCall בתגובה. תור השיחה הבא עשוי לכלול FunctionResponse עם ההקשר ליצירת Content.role 'פונקציה' לתור הבא של המודל.

googleSearchRetrieval object (GoogleSearchRetrieval)

אופציונלי. כלי אחזור שמבוסס על חיפוש Google.

codeExecution object (CodeExecution)

אופציונלי. מאפשרת למודל להריץ קוד כחלק מהיצירה.

ייצוג ב-JSON
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  }
}

FunctionDeclaration

ייצוג מובנה של הצהרת פונקציה כפי שמוגדר במפרט OpenAPI 3.03. ההצהרה הזו כוללת את שם הפונקציה ואת הפרמטרים שלה. FunctionDeclaration הזה מייצג בלוק קוד שאפשר להשתמש בו כ-Tool על ידי המודל ולהריץ אותו על ידי הלקוח.

שדות
name string

חובה. שם הפונקציה. המזהה חייב להכיל את התווים a-z,‏ A-Z,‏ 0-9 או קווים תחתונים ומקפים, באורך מקסימלי של 63 תווים.

description string

חובה. תיאור קצר של הפונקציה.

parameters object (Schema)

אופציונלי. תיאור הפרמטרים של הפונקציה הזו. משקף את מפתח המחרוזת של אובייקט הפרמטר ב-Open API 3.03: שם הפרמטר. השמות של הפרמטרים הם תלויי אותיות רישיות. ערך הסכימה: הסכימה שמגדירה את הסוג שבו נעשה שימוש בפרמטר.

response object (Schema)

אופציונלי. תיאור הפלט של הפונקציה הזו בפורמט JSON Schema. משקף את אובייקט התגובה של Open API 3.03. ה-Schema מגדיר את הסוג שמשמש לערך התגובה של הפונקציה.

ייצוג ב-JSON
{
  "name": string,
  "description": string,
  "parameters": {
    object (Schema)
  },
  "response": {
    object (Schema)
  }
}

סכימה

האובייקט Schema מאפשר להגדיר את סוגי הנתונים של הקלט והפלט. הסוגים האלה יכולים להיות אובייקטים, אבל גם פריימים ומערכים. מייצג קבוצת משנה נבחרת של אובייקט הסכימה של OpenAPI 3.0.

שדות
type enum (Type)

חובה. סוג הנתונים.

format string

אופציונלי. הפורמט של הנתונים. האפשרות הזו משמשת רק לסוגי נתונים פרימיטיביים. הפורמטים הנתמכים: לסוג NUMBER: float, ‏ double לסוג INTEGER: int32, ‏ int64 לסוג STRING: enum, ‏ date-time

title string

אופציונלי. שם הסכימה.

description string

אופציונלי. תיאור קצר של הפרמטר. המידע הזה יכול לכלול דוגמאות לשימוש. הפורמט של תיאור הפרמטר יכול להיות Markdown.

nullable boolean

אופציונלי. מציין אם הערך יכול להיות null.

enum[] string

אופציונלי. ערכים אפשריים של המרכיב מסוג Type.STRING בפורמט enum. לדוגמה, אפשר להגדיר כיוון של Enum כך : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]}

maxItems string (int64 format)

אופציונלי. המספר המקסימלי של הרכיבים של Type.ARRAY.

minItems string (int64 format)

אופציונלי. מספר המינימום של הרכיבים עבור Type.ARRAY.

properties map (key: string, value: object (Schema))

אופציונלי. מאפיינים של Type.OBJECT.

אובייקט שמכיל רשימה של זוגות "key": value. דוגמה: { "name": "wrench", "mass": "1.3kg", "count": "3" }.

required[] string

אופציונלי. המאפיינים הנדרשים של Type.OBJECT.

minProperties string (int64 format)

אופציונלי. המספר המינימלי של המאפיינים עבור Type.OBJECT.

maxProperties string (int64 format)

אופציונלי. המספר המקסימלי של המאפיינים של Type.OBJECT.

minLength string (int64 format)

אופציונלי. שדות SCHEMA לסוג STRING אורך מינימלי של Type.STRING

maxLength string (int64 format)

אופציונלי. האורך המקסימלי של Type.STRING

pattern string

אופציונלי. דפוס של Type.STRING כדי להגביל מחרוזת לביטוי רגולרי.

example value (Value format)

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

anyOf[] object (Schema)

אופציונלי. צריך לאמת את הערך מול כל אחד (אחד או יותר) מהסכמות המשניות ברשימה.

propertyOrdering[] string

אופציונלי. הסדר של הנכסים. לא שדה סטנדרטי במפרט של Open API. משמש לקביעת הסדר של המאפיינים בתגובה.

default value (Value format)

אופציונלי. ערך ברירת המחדל של השדה. בהתאם ל-JSON Schema, השדה הזה מיועד ליצירת מסמכי עזרה, והוא לא משפיע על האימות. לכן הוא נכלל כאן ומתעלם ממנו, כדי שמפתחים ששולחים סכימות עם שדה default לא יקבלו שגיאות של שדות לא מוכרים.

items object (Schema)

אופציונלי. הסכימה של הרכיבים של Type.ARRAY.

minimum number

אופציונלי. שדות הסכימה לסוג INTEGER ו-NUMBER הערך המינימלי של Type.INTEGER ו-Type.NUMBER

maximum number

אופציונלי. הערך המקסימלי של Type.INTEGER ו-Type.NUMBER

ייצוג ב-JSON
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

סוג

Type מכיל את רשימת סוגי הנתונים של OpenAPI כפי שהוגדרו ב-https://spec.openapis.org/oas/v3.0.3#data-types

טיפוסים בני מנייה (enum)
TYPE_UNSPECIFIED לא צוין, אין להשתמש בו.
STRING טיפוס מחרוזת.
NUMBER סוג המספר.
INTEGER טיפוס של מספר שלם.
BOOLEAN טיפוס בוליאני.
ARRAY סוג המערך.
OBJECT סוג האובייקט.
NULL סוג Null.

GoogleSearchRetrieval

כלי לאחזור נתונים ציבוריים מהאינטרנט לצורך אימות, שמופעל על ידי Google.

שדות
dynamicRetrievalConfig object (DynamicRetrievalConfig)

קובעת את הגדרת אחזור הנתונים הדינמיים של המקור הנתון.

ייצוג ב-JSON
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

DynamicRetrievalConfig

תיאור האפשרויות להתאמה אישית של אחזור דינמי.

שדות
mode enum (Mode)

המצב של החזוי שישמש לאחזור דינמי.

dynamicThreshold number

הסף לשימוש באחזור דינמי. אם לא מגדירים את הערך, המערכת תשתמש בערך ברירת המחדל שלה.

ייצוג ב-JSON
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

מצב

המצב של החזוי שישמש לאחזור דינמי.

טיפוסים בני מנייה (enum)
MODE_UNSPECIFIED תמיד מפעילים אחזור.
MODE_DYNAMIC המערכת מריצה אחזור רק כשהיא מחליטה שזה נחוץ.

CodeExecution

אין שדות לסוג הזה.

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

אפשר לעיין גם ב-ExecutableCode וב-CodeExecutionResult, שנוצרים רק כשמשתמשים בכלי הזה.

GoogleSearch

אין שדות לסוג הזה.

סוג הכלי של חיפוש Google. כלי לתמיכה בחיפוש Google במודל. מופעל על ידי Google.

ToolConfig

הגדרת הכלי שמכילה פרמטרים לציון השימוש ב-Tool בבקשה.

שדות
functionCallingConfig object (FunctionCallingConfig)

אופציונלי. הגדרה של קריאה לפונקציה.

ייצוג ב-JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  }
}

FunctionCallingConfig

הגדרה של התנהגות קריאה לפונקציה.

שדות
mode enum (Mode)

אופציונלי. מציין את המצב שבו צריך להפעיל את קריאת הפונקציה. אם לא יצוין ערך, ערך ברירת המחדל יהיה AUTO.

allowedFunctionNames[] string

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

צריך להגדיר את האפשרות הזו רק כשהערך של Mode הוא ANY. שמות הפונקציות צריכים להתאים ל-[FunctionDeclaration.name]. כשהמצב מוגדר ל-ANY, המודל ינבא קריאה לפונקציה מתוך קבוצת שמות הפונקציות שסופקו.

ייצוג ב-JSON
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

מצב

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

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

UsageMetadata

מטא-נתונים על השימוש בתוכן שנשמר במטמון.

שדות
totalTokenCount integer

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

ייצוג ב-JSON
{
  "totalTokenCount": integer
}