התכונה 'הפעלת פונקציות' מאפשרת לכם לקשר מודלים לכלים ולממשקי API חיצוניים. במקום ליצור תשובות טקסטואליות, המודל קובע מתי להפעיל פונקציות ספציפיות ומספק את הפרמטרים הדרושים לביצוע פעולות בעולם האמיתי. כך המודל יכול לשמש כגשר בין שפה טבעית לבין פעולות ונתונים בעולם האמיתי. יש 3 תרחישי שימוש עיקריים לקריאה לפונקציה:
- העשרת הידע: גישה למידע ממקורות חיצוניים כמו מסדי נתונים, ממשקי API ומאגרי ידע.
- הרחבת היכולות: אפשר להשתמש בכלים חיצוניים כדי לבצע חישובים ולהרחיב את המגבלות של המודל, למשל באמצעות מחשבון או יצירת תרשימים.
- ביצוע פעולות: אינטראקציה עם מערכות חיצוניות באמצעות ממשקי API, כמו קביעת פגישות, יצירת חשבוניות, שליחת אימיילים או שליטה במכשירים חכמים לבית.
איך פועלת התקשרות לפונקציות
קריאה לפונקציה היא אינטראקציה מובנית בין האפליקציה, המודל ופונקציות חיצוניות. פירוט התהליך:
- הגדרת הצהרת פונקציה: מגדירים את הצהרת הפונקציה בקוד האפליקציה. הצהרות על פונקציות מתארות למודל את שם הפונקציה, הפרמטרים והמטרה שלה.
- הפעלת LLM עם הצהרות פונקציה: שליחת הנחיה למשתמש יחד עם הצהרות הפונקציה למודל. הוא מנתח את הבקשה וקובע אם כדאי להשתמש בקריאה לפונקציה. אם כן, הוא משיב עם אובייקט JSON מובנה.
- הפעלת קוד הפונקציה (באחריותכם): המודל לא מפעיל את הפונקציה בעצמו. באחריות האפליקציה שלכם לעבד את התשובה ולבדוק אם יש בה קריאה לפונקציה, אם
- כן: חילוץ השם והארגומנטים של הפונקציה והפעלת הפונקציה התואמת באפליקציה.
- לא: המודל סיפק תגובה ישירה של טקסט להנחיה (התרחיש הזה פחות מודגש בדוגמה, אבל הוא אפשרי).
- יצירת תשובה ידידותית למשתמש: אם בוצעה פונקציה, צריך לתעד את התוצאה ולשלוח אותה בחזרה למודל בתור הבא של השיחה. הוא ישתמש בתוצאה כדי ליצור תשובה סופית וידידותית למשתמש, שתכלול את המידע מהקריאה לפונקציה.
אפשר לחזור על התהליך הזה כמה פעמים, וכך ליצור אינטראקציות ותהליכי עבודה מורכבים. המודל תומך גם בהפעלת כמה פונקציות בתור אחד (הפעלת פונקציות במקביל) וברצף (הפעלת פונקציות בהרכבה).
שלב 1: מגדירים הצהרה על פונקציה
מגדירים פונקציה והצהרה שלה בקוד האפליקציה, שמאפשרות למשתמשים להגדיר ערכי תאורה ולשלוח בקשת API. הפונקציה הזו יכולה להפעיל שירותים חיצוניים או ממשקי API.
Python
# Define a function that the model can call to control smart lights
set_light_values_declaration = {
"name": "set_light_values",
"description": "Sets the brightness and color temperature of a light.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "integer",
"description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
},
"color_temp": {
"type": "string",
"enum": ["daylight", "cool", "warm"],
"description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
},
},
"required": ["brightness", "color_temp"],
},
}
# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
"""Set the brightness and color temperature of a room light. (mock API).
Args:
brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
Returns:
A dictionary containing the set brightness and color temperature.
"""
return {"brightness": brightness, "colorTemperature": color_temp}
JavaScript
import { Type } from '@google/genai';
// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
name: 'set_light_values',
description: 'Sets the brightness and color temperature of a light.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
},
color_temp: {
type: Type.STRING,
enum: ['daylight', 'cool', 'warm'],
description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
},
},
required: ['brightness', 'color_temp'],
},
};
/**
* Set the brightness and color temperature of a room light. (mock API)
* @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
* @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
* @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
return {
brightness: brightness,
colorTemperature: color_temp
};
}
שלב 2: קוראים למודל עם הצהרות על פונקציות
אחרי שמגדירים את הצהרות הפונקציות, אפשר להנחות את המודל להשתמש בהן. הוא מנתח את ההנחיה ואת הצהרות הפונקציה ומחליט אם להשיב ישירות או להפעיל פונקציה. אם מתבצעת קריאה לפונקציה, אובייקט התשובה יכיל הצעה לקריאה לפונקציה.
Python
from google.genai import types
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])
# Define user prompt
contents = [
types.Content(
role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
)
]
# Send request with function declarations
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=contents
config=config,
)
print(response.candidates[0].content.parts[0].function_call)
JavaScript
import { GoogleGenAI } from '@google/genai';
// Generation config with function declaration
const config = {
tools: [{
functionDeclarations: [setLightValuesFunctionDeclaration]
}]
};
// Configure the client
const ai = new GoogleGenAI({});
// Define user prompt
const contents = [
{
role: 'user',
parts: [{ text: 'Turn the lights down to a romantic level' }]
}
];
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(response.functionCalls[0]);
לאחר מכן המודל מחזיר אובייקט functionCall
בסכימה שתואמת ל-OpenAPI, שמציין איך להפעיל אחת או יותר מהפונקציות שהוצהרו כדי להשיב על השאלה של המשתמש.
Python
id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
JavaScript
{
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
שלב 3: מריצים את הקוד של הפונקציה set_light_values
לחלץ את פרטי הקריאה לפונקציה מהתשובה של המודל, לנתח את הארגומנטים ולהפעיל את הפונקציה set_light_values
.
Python
# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call
if tool_call.name == "set_light_values":
result = set_light_values(**tool_call.args)
print(f"Function execution result: {result}")
JavaScript
// Extract tool call details
const tool_call = response.functionCalls[0]
let result;
if (tool_call.name === 'set_light_values') {
result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
console.log(`Function execution result: ${JSON.stringify(result)}`);
}
שלב 4: יצירת תשובה ידידותית למשתמש עם תוצאת הפונקציה והפעלת המודל שוב
לבסוף, שולחים את התוצאה של הפעלת הפונקציה בחזרה למודל כדי שהוא יוכל לשלב את המידע הזה בתשובה הסופית למשתמש.
Python
# Create a function response part
function_response_part = types.Part.from_function_response(
name=tool_call.name,
response={"result": result},
)
# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response
final_response = client.models.generate_content(
model="gemini-2.5-flash",
config=config,
contents=contents,
)
print(final_response.text)
JavaScript
// Create a function response part
const function_response_part = {
name: tool_call.name,
response: { result }
}
// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });
// Get the final response from the model
const final_response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(final_response.text);
כך מסתיים תהליך השימוש בפונקציות. המודל השתמש בהצלחה בפונקציה set_light_values
כדי לבצע את פעולת הבקשה של המשתמש.
הצהרות על פונקציות
כשמטמיעים קריאה לפונקציה בהנחיה, יוצרים אובייקט tools
שמכיל פונקציה אחת או יותר function declarations
. מגדירים פונקציות באמצעות JSON, באופן ספציפי עם קבוצת משנה נבחרת של פורמט סכימת OpenAPI. הצהרה על פונקציה יחידה יכולה לכלול את הפרמטרים הבאים:
-
name
(מחרוזת): שם ייחודי לפונקציה (get_weather_forecast
,send_email
). מומלץ להשתמש בשמות תיאוריים ללא רווחים או תווים מיוחדים (אפשר להשתמש בקו תחתון או בשיטת CamelCase). -
description
(string): הסבר ברור ומפורט על המטרה והיכולות של הפונקציה. ההסבר הזה חיוני כדי שהמודל יבין מתי להשתמש בפונקציה. כדאי להיות ספציפיים ולספק דוגמאות אם זה עוזר ("מוצא בתי קולנוע על סמך המיקום ואופציונלית על סמך שם הסרט שמוקרן כרגע בבתי הקולנוע"). -
parameters
(object): הגדרה של פרמטרי הקלט שהפונקציה מצפה לקבל.-
type
(מחרוזת): מציין את סוג הנתונים הכולל, כמוobject
. -
properties
(אובייקט): רשימה של פרמטרים נפרדים, כל אחד עם:-
type
(string): סוג הנתונים של הפרמטר, כמוstring
,integer
, boolean, array
. -
description
(מחרוזת): תיאור של מטרת הפרמטר והפורמט שלו. צריך לספק דוגמאות ואילוצים ("העיר והמדינה, למשל, 'San Francisco, CA' או מיקוד, למשל, '95616'."). -
enum
(מערך, אופציונלי): אם ערכי הפרמטרים הם מתוך קבוצה קבועה, צריך להשתמש ב-enum כדי לפרט את הערכים המותרים במקום רק לתאר אותם בתיאור. כך משפרים את הדיוק ("enum": ["daylight", "cool", "warm"]).
-
-
required
(array): מערך של מחרוזות שכולל את שמות הפרמטרים שחובה להשתמש בהם כדי שהפונקציה תפעל.
-
בקשות להפעלת פונקציות עם חשיבה
הפעלת התכונה 'חשיבה' יכולה לשפר את הביצועים של קריאות לפונקציות, כי היא מאפשרת למודל להסיק מסקנות לגבי בקשה לפני שהוא מציע קריאות לפונקציות.
עם זאת, מכיוון ש-Gemini API הוא חסר מצב (stateless), ההקשר של הנימוקים הזה אובד בין תורות, מה שעלול להפחית את האיכות של הקריאות לפונקציות, כי הן דורשות בקשות מרובות.
כדי לשמור על ההקשר הזה, אפשר להשתמש בחתימות מחשבה. חתימת מחשבה היא ייצוג מוצפן של תהליך החשיבה הפנימי של המודל, שמעבירים בחזרה למודל בתורות הבאות.
כדי להשתמש בחתימות מחשבה:
- קבלת החתימה: כשהתכונה 'חשיבה' מופעלת, תגובת ה-API תכלול את השדה thought_signature שמכיל ייצוג מוצפן של הנימוקים של המודל.
- החזרת החתימה: כששולחים את תוצאת ההפעלה של הפונקציה בחזרה לשרת, צריך לכלול את החתימה thought_signature שקיבלתם.
כך המודל יכול לשחזר את הקשר החשיבה הקודם שלו, וסביר להניח שזה ישפר את הביצועים של הפעלת הפונקציות.
קבלת חתימות מהשרת
החתימות מוחזרות בחלק שאחרי שלב החשיבה של המודל, שבדרך כלל הוא טקסט או קריאה לפונקציה.
ריכזנו כאן כמה דוגמאות לחתימות מחשבה שמוחזרות בכל סוג של חלק, בתגובה לבקשה 'מה מזג האוויר באגם טאהו?' באמצעות הדוגמה Get Weather:
חלק מהטקסט
[{
"candidates": [
{
"content": {
"parts": [
{
"text": "Here's what the weather in Lake Tahoe is today",
"thoughtSignature": "ClcBVKhc7ru7KzUI7SrdUoIdAYLm/+i93aHjfIt4xHyAoO/G70tApxnK2ujBhOhC1PrRy1pkQa88fqFvpHNVd1HDjNLO7mkp6/hFwE+SPPEB3fh0hs4oM8MKhgIBVKhc7uIGvrS7i/T4HpfbnYrluFfWNjZ62gewqe4cVdR/Dlh+zbjtYmDD0gPZ+SuBO7vvHQdzsjePRP+2Y5XddX6LEf/cGGgakq8EhVvw/a6IVzUO6XmpHg2Ag1sl8E9+VFH/lC0R0ZuYdFWligtDuYwp5p5q3o59G0TtWeU2MC1y2MJfE9u/KWd313ldka80/X2W/xF2O/4djMp5G2WKcULfve75zeRCy0mc5iS3SB9mTH0cT6x0vtKjeBx50gcg+CQWtJcRuwTVzz54dmvmK9xvnqA8gKGw3DuaM9wfy5hyY7Qg0z3iyyWdP8T/lbjKim8IEQOk7O1vVwP1Ko7oMYH8JgA1CsoBAVSoXO6v4c5RSyd1cn6EIU0pEFQsjW7rYWPuZdOFq/tsGJT9BCfW7KGkPGwlNSq8jTJFvbcJ/DjtndISQYXwiXd2kGa5JfdS2Kh4zOxCxiWtOk+2nCc3+XQk2nonhO+esGJpkDdbbHZSqRgcUtYKq7q28iPFOQvOFyCiZNB7K86Z/6Hnagu2snSlN/BcTMaFGaWpcCClSUo4foRZn3WbNCoM8rcpD7qEJMp4a5baaSxyyeL1ZTGd2HLpFys/oiW6e3oAnhxuIysCwg=="
}
],
"role": "model"
},
"index": 0
}
],
# Remainder of response...
החלק של בקשה להפעלת פונקציה
[{
"candidates": [
{
"content": {
"parts": [
{
"functionCall": {
"name": "getWeather",
"args": {
"city": "Lake Tahoe"
}
},
"thoughtSignature": "CiwBVKhc7nRyTi3HmggPD9iQiRc261f5jwuMdw3H/itDH0emsb9ZVo3Nwx9p6wpsAVSoXO5i8fDV4jBSBLoaWxB5zUdlGY6aIGp+I0oEnwRRSRQ1LOvrDlojEH8JE8HjiKXALdJrvNPiG+HY3GZEO8pZjEZtc3UoBUh7+SVyjK7Xolu7aRYYeUyzrCapoETWypER1jbrJXnFV23hCosBAVSoXO6oIPNJSmbuEDfGafOhuCSHkpr1yjTp35RXYqmCESzRzWf5+nFXLqncqeFo4ohoxbiYQVpVQbOZF81p8o9zg6xeRE7qMeOv+XN7enXGJ4/s3qNFQpfkSMqRdBITN1VpX7jyfEAjvxBNc7PDfDJZmEPY338ZIY5nFFcmzJSWjVrboFt2sMFv+A=="
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 0
}
],
# Remainder of response...
כדי לוודא שקיבלתם חתימה ולראות איך היא נראית, אפשר להשתמש בקוד הבא:
# Step 2: Call the model with function declarations
# ...Generation config, Configure the client, and Define user prompt (No changes)
# Send request with declarations (using a thinking model)
response = client.models.generate_content(
model="gemini-2.5-flash", config=config, contents=contents)
# See thought signatures
for part in response.candidates[0].content.parts:
if part.thought_signature:
print("Thought signature:")
print(part.thought_signature)
החזרת החתימות לשרת
כדי להחזיר את החתימות:
- צריך להחזיר חתימות יחד עם החלקים שמכילים אותן בחזרה לשרת
- אסור למזג חלק עם חתימה עם חלק אחר שמכיל גם הוא חתימה. אי אפשר לשרשר את מחרוזת החתימה
- אסור למזג חלק אחד עם חתימה עם חלק אחר בלי חתימה. הפעולה הזו משבשת את המיקום הנכון של המחשבה שמיוצגת על ידי החתימה.
הקוד יישאר זהה לזה שמופיע בשלב 4 בסעיף הקודם. אבל במקרה הזה (כפי שמצוין בתגובה שלמטה) תחזירו חתימות למודל יחד עם התוצאה של הפעלת הפונקציה, כדי שהמודל יוכל לשלב את המחשבות בתגובה הסופית שלו:
Python
# Step 4: Create user friendly response with function result and call the model again
# ...Create a function response part (No change)
# Append thought signatures, function call and result of the function execution to contents
function_call_content = response.candidates[0].content
# Append the model's function call message, which includes thought signatures
contents.append(function_call_content)
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response
final_response = client.models.generate_content(
model="gemini-2.5-flash",
config=config,
contents=contents,
)
print(final_response.text)
JavaScript
// Step 4: Create user friendly response with function result and call the model again
// ...Create a function response part (No change)
// Append thought signatures, function call and result of the function execution to contents
const function_response_content = response.candidates[0].content;
contents.push(function_response_content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });
const final_response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(final_response.text);
כך נראית בקשה שמחזירה חתימת מחשבה:
[{
"contents": [
{
"role": "user",
"parts": [
{
"text": "what is the weather in Lake Tahoe?"
}
]
},
{
"parts": [
{
"functionCall": {
"name": "getWeather",
"args": {
"city": "Lake Tahoe"
}
},
"thoughtSignature": "CiIBVKhc7oDPpCaXyJKKssjqr4g3JNOSgJ/M2V+1THC1icsWCmwBVKhc7pBABbZ+zR3e9234WnWWS6GFXmf8IVwpnzjd5KYd7vyJbn/4vTorWBGayj/vbd9JPaZQjxdAIXhoE5mX/MDsQ7M9N/b0qJjHm39tYIBvS4sIWkMDHqTJqXGLzhhKtrTkfbV3RbaJEkQKmwEBVKhc7qVUgC3hfTXZLo9R3AJzUUIx50NKvJTb9B+UU+LBqgg7Nck1x5OpjWVS2R+SsveprIuYOruk2Y0H53J2OJF8qsxTdIq2si8DGW2V7WK8xyoJH5kbqd7drIw1jLb44b6lx4SMyB0VaULuTBki4d+Ljjg1tJTwR0IYMKqDLDZt9mheINsi0ZxcNjfpnDydRXdWbcSwzmK/wgqJAQFUqFzuKgNVElxs3cbO+xebr2IwcOro84nKTisi0tTp9bICPC9fTUhn3L+rvQWA+d3J1Za8at2bakrqiRj7BTh+CVO9fWQMAEQAs3ni0Z2hfaYG92tOD26E4IoZwyYEoWbfNudpH1fr5tEkyqnEGtWIh7H+XoZQ2DXeiOa+br7Zk88SrNE+trJMCogBAVSoXO5e9fBLg7hnbkmKsrzNLnQtLsQm1gNzjcjEC7nJYklYPp0KI2uGBE1PkM8XNsfllAfHVn7LzHcHNlbQ9pJ7QZTSIeG42goS971r5wNZwxaXwCTphClQh826eqJWo6A/28TtAVQWLhTx5ekbP7qb4nh1UblESZ1saxDQAEo4OKPbDzx5BgqKAQFUqFzuVyjNm5i0wN8hTDnKjfpDroEpPPTs531iFy9BOX+xDCdGHy8D+osFpaoBq6TFekQQbz4hIoUR1YEcP4zI80/cNimEeb9IcFxZTTxiNrbhbbcv0969DSMWhB+ZEqIz4vuw4GLe/xcUvqhlChQwFdgIbdOQHSHpatn5uDlktnP/bi26nKuXIwo0AVSoXO7US22OUH7d1f4abNPI0IyAvhqkPp12rbtWLx9vkOtojE8IP+xCfYtIFuZIzRNZqA=="
}
],
"role": "model"
},
{
"role": "user",
"parts": [
{
"functionResponse": {
"name": "getWeather",
"response": {
"response": {
"stringValue": "Sunny and hot. 90 degrees Fahrenheit"
}
}
}
}
]
}
],
# Remainder of request...
מידע נוסף על מגבלות ושימוש בחתימות מחשבה, ועל מודלים של חשיבה באופן כללי, זמין בדף חשיבה.
בקשות מקבילות להפעלת פונקציות
בנוסף לקריאה לפונקציה אחת, אפשר גם לקרוא לכמה פונקציות בו-זמנית. התכונה 'הפעלת פונקציות במקביל' מאפשרת להפעיל כמה פונקציות בו-זמנית, והיא שימושית כשהפונקציות לא תלויות זו בזו. האפשרות הזו שימושית בתרחישים כמו איסוף נתונים מכמה מקורות עצמאיים, למשל אחזור פרטי לקוחות ממסדי נתונים שונים או בדיקת רמות המלאי בכמה מחסנים, או ביצוע כמה פעולות כמו הפיכת הדירה לדיסקוטק.
Python
power_disco_ball = {
"name": "power_disco_ball",
"description": "Powers the spinning disco ball.",
"parameters": {
"type": "object",
"properties": {
"power": {
"type": "boolean",
"description": "Whether to turn the disco ball on or off.",
}
},
"required": ["power"],
},
}
start_music = {
"name": "start_music",
"description": "Play some music matching the specified parameters.",
"parameters": {
"type": "object",
"properties": {
"energetic": {
"type": "boolean",
"description": "Whether the music is energetic or not.",
},
"loud": {
"type": "boolean",
"description": "Whether the music is loud or not.",
},
},
"required": ["energetic", "loud"],
},
}
dim_lights = {
"name": "dim_lights",
"description": "Dim the lights.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "number",
"description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
}
},
"required": ["brightness"],
},
}
JavaScript
import { Type } from '@google/genai';
const powerDiscoBall = {
name: 'power_disco_ball',
description: 'Powers the spinning disco ball.',
parameters: {
type: Type.OBJECT,
properties: {
power: {
type: Type.BOOLEAN,
description: 'Whether to turn the disco ball on or off.'
}
},
required: ['power']
}
};
const startMusic = {
name: 'start_music',
description: 'Play some music matching the specified parameters.',
parameters: {
type: Type.OBJECT,
properties: {
energetic: {
type: Type.BOOLEAN,
description: 'Whether the music is energetic or not.'
},
loud: {
type: Type.BOOLEAN,
description: 'Whether the music is loud or not.'
}
},
required: ['energetic', 'loud']
}
};
const dimLights = {
name: 'dim_lights',
description: 'Dim the lights.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
}
},
required: ['brightness']
}
};
מגדירים את מצב קריאת הפונקציות כדי לאפשר שימוש בכל הכלים שצוינו. מידע נוסף זמין במאמר בנושא הגדרת קריאות לפונקציות.
Python
from google import genai
from google.genai import types
# Configure the client and tools
client = genai.Client()
house_tools = [
types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
tools=house_tools,
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
# Force the model to call 'any' function, instead of chatting.
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(mode='ANY')
),
)
chat = client.chats.create(model="gemini-2.5-flash", config=config)
response = chat.send_message("Turn this place into a party!")
# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
print(f"{fn.name}({args})")
JavaScript
import { GoogleGenAI } from '@google/genai';
// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];
const config = {
tools: [{
functionDeclarations: houseFns
}],
// Force the model to call 'any' function, instead of chatting.
toolConfig: {
functionCallingConfig: {
mode: 'any'
}
}
};
// Configure the client
const ai = new GoogleGenAI({});
// Create a chat session
const chat = ai.chats.create({
model: 'gemini-2.5-flash',
config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});
// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
const args = Object.entries(fn.args)
.map(([key, val]) => `${key}=${val}`)
.join(', ');
console.log(`${fn.name}(${args})`);
}
כל אחת מהתוצאות המודפסות משקפת קריאה יחידה לפונקציה שהמודל ביקש. כדי לשלוח את התוצאות בחזרה, צריך לכלול את התשובות באותו סדר שבו הן התבקשו.
Python SDK תומך בקריאה אוטומטית לפונקציות, שממירה אוטומטית פונקציות של Python להצהרות, ומטפלת במחזור הביצוע והתגובה של הקריאה לפונקציה בשבילכם. הנה דוגמה לתרחיש השימוש ב-disco.
Python
from google import genai
from google.genai import types
# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
"""Powers the spinning disco ball.
Args:
power: Whether to turn the disco ball on or off.
Returns:
A status dictionary indicating the current state.
"""
return {"status": f"Disco ball powered {'on' if power else 'off'}"}
def start_music_impl(energetic: bool, loud: bool) -> dict:
"""Play some music matching the specified parameters.
Args:
energetic: Whether the music is energetic or not.
loud: Whether the music is loud or not.
Returns:
A dictionary containing the music settings.
"""
music_type = "energetic" if energetic else "chill"
volume = "loud" if loud else "quiet"
return {"music_type": music_type, "volume": volume}
def dim_lights_impl(brightness: float) -> dict:
"""Dim the lights.
Args:
brightness: The brightness of the lights, 0.0 is off, 1.0 is full.
Returns:
A dictionary containing the new brightness setting.
"""
return {"brightness": brightness}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Do everything you need to this place into party!",
config=config,
)
print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!
בקשות להפעלת פונקציות שכוללות קומפוזיציה
התכונה 'קריאה לפונקציות בהרכב או ברצף' מאפשרת ל-Gemini לשרשר כמה קריאות לפונקציות כדי למלא בקשה מורכבת. לדוגמה, כדי לענות על השאלה 'מה הטמפרטורה במיקום הנוכחי שלי?', יכול להיות ש-Gemini API יפעיל קודם פונקציית get_current_location()
ואחריה פונקציית get_weather()
שמקבלת את המיקום כפרמטר.
בדוגמה הבאה אפשר לראות איך מטמיעים קריאות לפונקציות מורכבות באמצעות Python SDK וקריאות אוטומטיות לפונקציות.
Python
בדוגמה הזו נעשה שימוש בתכונה של קריאה אוטומטית לפונקציה של google-genai
Python SDK. ה-SDK ממיר באופן אוטומטי את פונקציות Python לסכימה הנדרשת, מריץ את הקריאות לפונקציות כשמתקבלת בקשה מהמודל ושולח את התוצאות בחזרה למודל כדי להשלים את המשימה.
import os
from google import genai
from google.genai import types
# Example Functions
def get_weather_forecast(location: str) -> dict:
"""Gets the current weather temperature for a given location."""
print(f"Tool Call: get_weather_forecast(location={location})")
# TODO: Make API call
print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
return {"temperature": 25, "unit": "celsius"} # Dummy response
def set_thermostat_temperature(temperature: int) -> dict:
"""Sets the thermostat to a desired temperature."""
print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
# TODO: Interact with a thermostat API
print("Tool Response: {'status': 'success'}")
return {"status": "success"}
# Configure the client and model
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_weather_forecast, set_thermostat_temperature]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
config=config,
)
# Print the final, user-facing response
print(response.text)
הפלט הצפוי
כשמריצים את הקוד, אפשר לראות את ה-SDK מתזמן את הקריאות לפונקציה. קודם המודל קורא ל-get_weather_forecast
, מקבל את הטמפרטורה ואז קורא ל-set_thermostat_temperature
עם הערך הנכון על סמך הלוגיקה בהנחיה.
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.
JavaScript
בדוגמה הזו מוסבר איך להשתמש ב-SDK של JavaScript/TypeScript כדי לבצע קריאות לפונקציות מורכבות באמצעות לולאת ביצוע ידנית.
import { GoogleGenAI, Type } from "@google/genai";
// Configure the client
const ai = new GoogleGenAI({});
// Example Functions
function get_weather_forecast({ location }) {
console.log(`Tool Call: get_weather_forecast(location=${location})`);
// TODO: Make API call
console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
return { temperature: 25, unit: "celsius" };
}
function set_thermostat_temperature({ temperature }) {
console.log(
`Tool Call: set_thermostat_temperature(temperature=${temperature})`,
);
// TODO: Make API call
console.log("Tool Response: {'status': 'success'}");
return { status: "success" };
}
const toolFunctions = {
get_weather_forecast,
set_thermostat_temperature,
};
const tools = [
{
functionDeclarations: [
{
name: "get_weather_forecast",
description:
"Gets the current weather temperature for a given location.",
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
},
},
required: ["location"],
},
},
{
name: "set_thermostat_temperature",
description: "Sets the thermostat to a desired temperature.",
parameters: {
type: Type.OBJECT,
properties: {
temperature: {
type: Type.NUMBER,
},
},
required: ["temperature"],
},
},
],
},
];
// Prompt for the model
let contents = [
{
role: "user",
parts: [
{
text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
},
],
},
];
// Loop until the model has no more function calls to make
while (true) {
const result = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents,
config: { tools },
});
if (result.functionCalls && result.functionCalls.length > 0) {
const functionCall = result.functionCalls[0];
const { name, args } = functionCall;
if (!toolFunctions[name]) {
throw new Error(`Unknown function call: ${name}`);
}
// Call the function and get the response.
const toolResponse = toolFunctions[name](args);
const functionResponsePart = {
name: functionCall.name,
response: {
result: toolResponse,
},
};
// Send the function response back to the model.
contents.push({
role: "model",
parts: [
{
functionCall: functionCall,
},
],
});
contents.push({
role: "user",
parts: [
{
functionResponse: functionResponsePart,
},
],
});
} else {
// No more function calls, break the loop.
console.log(result.text);
break;
}
}
הפלט הצפוי
כשמריצים את הקוד, אפשר לראות את ה-SDK מתזמן את הקריאות לפונקציה. קודם המודל קורא ל-get_weather_forecast
, מקבל את הטמפרטורה ואז קורא ל-set_thermostat_temperature
עם הערך הנכון על סמך הלוגיקה בהנחיה.
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.
קריאה לפונקציות מורכבות היא תכונה מקורית של Live API. כלומר, Live API יכול לטפל בקריאות לפונקציות באופן דומה ל-Python SDK.
Python
# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}
prompt = """
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
"""
tools = [
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]
await run(prompt, tools=tools, modality="AUDIO")
JavaScript
// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };
const prompt = `
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;
const tools = [
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];
await run(prompt, tools=tools, modality="AUDIO")
מצבים של בקשות להפעלת פונקציה
Gemini API מאפשר לכם לשלוט באופן שבו המודל משתמש בכלים שסופקו (הצהרות פונקציה). באופן ספציפי, אתם יכולים להגדיר את המצב בתוך.function_calling_config
.
-
AUTO (Default)
: המודל מחליט אם ליצור תשובה בשפה טבעית או להציע קריאה לפונקציה על סמך ההנחיה וההקשר. זהו המצב הגמיש ביותר והוא מומלץ לרוב התרחישים. -
ANY
: המודל מוגבל כך שתמיד יחזה קריאה לפונקציה, ומבטיח הקפדה על סכימת הפונקציה. אם לא מציינים אתallowed_function_names
, המודל יכול לבחור מתוך כל הצהרות הפונקציות שסופקו. אםallowed_function_names
מסופק כרשימה, המודל יכול לבחור רק מתוך הפונקציות ברשימה הזו. משתמשים במצב הזה כשרוצים לקבל תגובה לקריאה לפונקציה לכל הנחיה (אם רלוונטי).
NONE
: אסור למודל לבצע קריאות לפונקציות. זה שווה ערך לשליחת בקשה בלי הצהרות על פונקציות. אפשר להשתמש בזה כדי להשבית זמנית את השימוש בפונקציות בלי להסיר את ההגדרות של כלי העזר.
Python
from google.genai import types
# Configure function calling mode
tool_config = types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode="ANY", allowed_function_names=["get_current_temperature"]
)
)
# Create the generation config
config = types.GenerateContentConfig(
tools=[tools], # not defined here.
tool_config=tool_config,
)
JavaScript
import { FunctionCallingConfigMode } from '@google/genai';
// Configure function calling mode
const toolConfig = {
functionCallingConfig: {
mode: FunctionCallingConfigMode.ANY,
allowedFunctionNames: ['get_current_temperature']
}
};
// Create the generation config
const config = {
tools: tools, // not defined here.
toolConfig: toolConfig,
};
הפעלת פונקציות אוטומטית (ב-Python בלבד)
כשמשתמשים ב-Python SDK, אפשר לספק פונקציות Python ישירות ככלים. ה-SDK ממיר אוטומטית את פונקציית Python להצהרות, ומטפל בהרצת הקריאה לפונקציה ובמחזור התגובה בשבילכם. Python SDK אז באופן אוטומטי:
- מזהה תגובות של קריאות לפונקציות מהמודל.
- מפעילים את פונקציית Python המתאימה בקוד.
- שולחת את התשובה של הפונקציה בחזרה למודל.
- הפונקציה מחזירה את תשובת הטקסט הסופית של המודל.
כדי להשתמש בזה, מגדירים את הפונקציה עם רמזים לגבי סוגים ומחרוזת תיעוד, ואז מעבירים את הפונקציה עצמה (לא הצהרת JSON) ככלי:
Python
from google import genai
from google.genai import types
# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
"""Gets the current temperature for a given location.
Args:
location: The city and state, e.g. San Francisco, CA
Returns:
A dictionary containing the temperature and unit.
"""
# ... (implementation) ...
return {"temperature": 25, "unit": "Celsius"}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_current_temperature]
) # Pass the function itself
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the temperature in Boston?",
config=config,
)
print(response.text) # The SDK handles the function call and returns the final text
כדי להשבית את ההפעלה האוטומטית של פונקציות, משתמשים בפקודה:
Python
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
הצהרה אוטומטית על סכימת פונקציות
חילוץ סכימה אוטומטי מפונקציות Python לא פועל בכל המקרים. לדוגמה, הוא לא מטפל במקרים שבהם מתארים את השדות של אובייקט מילון מוטמע. ה-API יכול לתאר כל אחד מהסוגים הבאים:
Python
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])
כדי לראות איך נראית הסכימה שהמערכת הסיקה, אפשר להמיר אותה באמצעות from_callable
:
Python
def multiply(a: float, b: float):
"""Returns a * b."""
return a * b
fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)
# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())
שימוש בכמה כלים: שילוב של כלים מקוריים עם קריאות לפונקציות
אפשר להפעיל כמה כלים בו-זמנית, ולשלב בין כלים מקוריים לבין קריאות לפונקציות. הנה דוגמה להפעלת שני כלים, הארקה באמצעות חיפוש Google והרצת קוד, בבקשה באמצעות Live API.
Python
# Multiple tasks example - combining lights, code execution, and search
prompt = """
Hey, I need you to do three things for me.
1. Turn on the lights.
2. Then compute the largest prime palindrome under 100000.
3. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.
Thanks!
"""
tools = [
{'google_search': {}},
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]
# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")
JavaScript
// Multiple tasks example - combining lights, code execution, and search
const prompt = `
Hey, I need you to do three things for me.
1. Turn on the lights.
2. Then compute the largest prime palindrome under 100000.
3. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.
Thanks!
`;
const tools = [
{ googleSearch: {} },
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];
// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});
מפתחי Python יכולים לנסות את זה במחברת השימוש בכלי API בזמן אמת.
פרוטוקול הקשר של המודל (MCP)
Model Context Protocol (MCP) הוא תקן פתוח לחיבור אפליקציות AI עם כלים ונתונים חיצוניים. פרוטוקול MCP מספק למודלים פרוטוקול משותף לגישה להקשר, כמו פונקציות (כלים), מקורות נתונים (משאבים) או הנחיות מוגדרות מראש.
Gemini SDK כולל תמיכה מובנית ב-MCP, שמצמצמת את קוד ה-boilerplate ומציעה קריאה אוטומטית לכלים לכלים של MCP. כשהמודל יוצר קריאה לכלי MCP, ערכת ה-SDK של לקוח Python ו-JavaScript יכולה להפעיל את כלי ה-MCP באופן אוטומטי ולשלוח את התגובה בחזרה למודל בבקשה הבאה. התהליך הזה נמשך עד שהמודל לא יוצר יותר קריאות לכלי.
כאן אפשר למצוא דוגמה לאופן השימוש בשרת מקומי של MCP עם Gemini ועם mcp
SDK.
Python
חשוב לוודא שהגרסה העדכנית של mcp
SDK מותקנת בפלטפורמה שבחרתם.
pip install mcp
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai
client = genai.Client()
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=["-y", "@philschmid/weather-mcp"], # MCP Server
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Prompt to get the weather for the current day in London.
prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"
# Initialize the connection between client and server
await session.initialize()
# Send request to the model with MCP function declarations
response = await client.aio.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
config=genai.types.GenerateContentConfig(
temperature=0,
tools=[session], # uses the session, will automatically call the tool
# Uncomment if you **don't** want the SDK to automatically call the tool
# automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
# disable=True
# ),
),
)
print(response.text)
# Start the asyncio event loop and run the main function
asyncio.run(run())
JavaScript
מוודאים שמותקנת בפלטפורמה שבחרתם הגרסה העדכנית ביותר של mcp
SDK.
npm install @modelcontextprotocol/sdk
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
command: "npx", // Executable
args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});
const client = new Client(
{
name: "example-client",
version: "1.0.0"
}
);
// Configure the client
const ai = new GoogleGenAI({});
// Initialize the connection between client and server
await client.connect(serverParams);
// Send request to the model with MCP tools
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
config: {
tools: [mcpToTool(client)], // uses the session, will automatically call the tool
// Uncomment if you **don't** want the sdk to automatically call the tool
// automaticFunctionCalling: {
// disable: true,
// },
},
});
console.log(response.text)
// Close the connection
await client.close();
מגבלות בתמיכה המובנית ב-MCP
תמיכה מובנית ב-MCP היא תכונה ניסיונית בערכות ה-SDK שלנו, ויש לה את המגבלות הבאות:
- יש תמיכה רק בכלים, לא במשאבים או בהנחיות
- היא זמינה ב-Python וב-JavaScript/TypeScript SDK.
- יכול להיות שיהיו שינויים שעלולים לשבור את התאימות בגרסאות עתידיות.
אם המגבלות האלה משפיעות על מה שאתם בונים, תמיד אפשר לשלב את שרתי MCP באופן ידני.
מודלים נתמכים
בקטע הזה מפורטים המודלים והיכולות שלהם להפעלת פונקציות. לא נכללים מודלים ניסיוניים. בדף הסקירה הכללית של הדגם אפשר למצוא סקירה מקיפה של היכולות.
דגם | בקשה להפעלת פונקציה | בקשות מקבילות להפעלת פונקציות | בקשות להפעלת פונקציות מורכבות |
---|---|---|---|
Gemini 2.5 Pro | ✔️ | ✔️ | ✔️ |
Gemini 2.5 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.5 Flash-Lite | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | X | X | X |
שיטות מומלצות
- תיאורי פונקציות ופרמטרים: התיאורים צריכים להיות ברורים וספציפיים מאוד. המודל מסתמך על הנתונים האלה כדי לבחור את הפונקציה הנכונה ולספק את הארגומנטים המתאימים.
- שם: צריך להשתמש בשמות פונקציות תיאוריים (ללא רווחים, נקודות או מקפים).
- הקלדה חזקה: כדי לצמצם את מספר השגיאות, כדאי להשתמש בסוגים ספציפיים (מספר שלם, מחרוזת, enum) לפרמטרים. אם לפרמטר יש קבוצה מוגבלת של ערכים תקינים, צריך להשתמש ב-enum.
- בחירת כלי: המודל יכול להשתמש במספר כלים שרירותי, אבל אם מספקים לו יותר מדי כלים, הסיכון שהוא יבחר בכלי לא נכון או לא אופטימלי גדל. כדי להשיג את התוצאות הכי טובות, מומלץ לספק רק את הכלים הרלוונטיים להקשר או למשימה, ובאופן אידיאלי להגביל את הסט הפעיל ל-10 עד 20 כלים. אם יש לכם מספר גדול של כלים, כדאי לשקול בחירה דינמית של כלים על סמך הקשר של השיחה.
- Prompt Engineering:
- להוסיף הקשר: צריך להגדיר למודל את התפקיד שלו (למשל, "אתה עוזר מזג אוויר מועיל").
- לתת הוראות: לציין איך ומתי להשתמש בפונקציות (למשל, אל תנחשו תאריכים, תמיד צריך להשתמש בתאריך עתידי לתחזיות").
- עידוד הבהרה: נותנים למודל הוראה לשאול שאלות הבהרה אם צריך.
- טמפרטורה: מומלץ להשתמש בטמפרטורה נמוכה (למשל, 0) כדי לקבל קריאות פונקציה דטרמיניסטיות ואמינות יותר.
- אימות: אם לקריאה לפונקציה יש השלכות משמעותיות (למשל, ביצוע הזמנה), כדאי לאמת את הקריאה עם המשתמש לפני שמבצעים אותה.
- טיפול בשגיאות: צריך להטמיע טיפול חזק בשגיאות בפונקציות כדי לטפל בצורה נאותה בקלט לא צפוי או בכשלים ב-API. החזרת הודעות שגיאה אינפורמטיביות שהמודל יכול להשתמש בהן כדי ליצור תשובות מועילות למשתמש.
- אבטחה: חשוב לשים לב לאבטחה כשמתקשרים לממשקי API חיצוניים. שימוש במנגנוני אימות והרשאה מתאימים. אל תחשפו נתונים רגישים בקריאות לפונקציות.
- מגבלות על טוקנים: תיאורי פונקציות ופרמטרים נספרים במגבלת הטוקנים של הקלט. אם אתם מגיעים למגבלות האסימונים, כדאי להגביל את מספר הפונקציות או את אורך התיאורים, ולחלק משימות מורכבות לקבוצות קטנות יותר של פונקציות ממוקדות יותר.
הערות ומגבלות
- יש תמיכה רק בקבוצת משנה של סכימת OpenAPI.
- יש מגבלות על סוגי הפרמטרים הנתמכים ב-Python.
- התכונה 'הפעלת פונקציות אוטומטית' זמינה רק ב-Python SDK.