קריאה להפעלת פונקציות, שנקראת גם שימוש בכלים, מספקת למודל ה-LLM הגדרות של כלים חיצוניים (לדוגמה, פונקציית get_current_weather).
כשהמודל מעבד הנחיה, הוא קובע בצורה חכמה אם נדרש כלי, ואם כן, הוא מוציא נתונים מובְנים שמציינים את הכלי שצריך להפעיל ואת הפרמטרים שלו (לדוגמה, get_current_weather(location='Boston')). לאחר מכן, האפליקציה מפעילה את הכלי הזה, מזינה את התוצאה בחזרה למודל, ומאפשרת לו להשלים את התשובה שלו עם מידע דינמי מהעולם האמיתי או עם תוצאה של פעולה. כך אפשר לגשר ביעילות בין ה-LLM למערכות שלכם ולהרחיב את היכולות שלו.
קריאה להפעלת פונקציות מאפשרת שני תרחישי שימוש עיקריים:
אחזור נתונים: אחזור מידע עדכני לתשובות של המודל, כמו מזג האוויר הנוכחי, המרת מטבע או נתונים ספציפיים ממאגרי ידע ומממשקי API (RAG).
ביצוע פעולות: ביצוע פעולות חיצוניות כמו שליחת טפסים, עדכון מצב האפליקציה או תזמור של תהליכי עבודה מבוססי-סוכנים (למשל, העברת שיחות).
לתרחישי שימוש ודוגמאות נוספות שמתבססים על קריאה להפעלת פונקציות, ראו תרחישי שימוש.
תכונות ומגבלות
המודלים הבאים תומכים בקריאה להפעלת פונקציות:
- מודלים של Gemini:
לחצו כדי להרחיב את רשימת המודלים הנתמכים
- Gemini Robotics ER 2
- Gemini 4 Argon Cyber Permissive
- Gemini 4 Argon
- Gemini 3.8 במצב לייב
- Gemini 3.8 Flash
- Gemini 3.7 Flash
- Gemini 3.6 Flash
- Gemini 3.5 Flash-Lite
- Gemini 3.5 Flash
- Gemini 3.1 Pro
- Gemini 3.1 Flash-Lite
- Gemini 3 Flash
- Gemini 2.5 Pro
- Gemini 2.5 Flash-Lite
- Gemini 2.5 Flash עם אודיו מקורי של Gemini Live API
- Gemini 2.5 Flash
מודלים פתוחים:
מגדירים את הפונקציות בפורמט OpenAPI schema.
במודלים של Gemini 3 ואילך, אתם יכולים לכלול תוכן בכמה אופנים (תמונות וקובצי PDF) בהודעות של
functionResponseשאתם שולחים בחזרה למודל. מידע נוסף זמין במאמר תגובות של פונקציות מולטי-מודאליות.במודלים של Gemini 3 ואילך, אפשר להציג באופן שוטף ארגומנטים של קריאה להפעלת פונקציות בזמן שהם נוצרים, על ידי הגדרת
streamFunctionCallArgumentsל-trueב-functionCallingConfig. מידע נוסף זמין במאמר ארגומנטים של קריאה להפעלת פונקציות בסטרימינג.בקטע שיטות מומלצות מפורטות שיטות מומלצות שקשורות להצהרות על פונקציות, כולל טיפים לשמות ולתיאורים.
במודלים פתוחים, פועלים לפי המדריך למשתמש הזה.
איך יוצרים אפליקציה עם קריאה להפעלת פונקציות
כדי להשתמש בקריאה להפעלת פונקציות, מבצעים את המשימות הבאות:
שלב 1: שולחים למודל את ההנחיה ואת הצהרות הפונקציות
מצהירים על Tool בפורמט סכימה שתואם לסכימת OpenAPI. מידע נוסף זמין במאמר דוגמאות לסכימות.
בדוגמאות הבאות נשלחים פרומפט והצהרת פונקציה למודלים של Gemini:
REST
PROJECT_ID=myproject
LOCATION=us-central1
MODEL_ID=gemini-2.5-flash
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [{
"role": "user",
"parts": [{
"text": "What is the weather in Boston?"
}]
}],
"tools": [{
"functionDeclarations": [
{
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name of the location for which to get the weather.",
"default": {
"string_value": "Boston, MA"
}
}
},
"required": [
"location"
]
}
}
]
}]
}'
Google Gen AI SDK ל-Python
from google import genai
from google.genai.types import GenerateContentConfig, Part
# The project and location are passed directly to the client,
# and vertexai=True is added to specify the use of the Agent Platform backend.
client = genai.Client(vertexai=True, project="PROJECT_ID", location="global")
def get_current_weather(location: str) -> str:
"""Returns the current weather.
Args:
location: The city and state, e.g. San Francisco, CA
"""
return 'sunny'
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What is the weather in boston?",
config=GenerateContentConfig(tools=[get_current_weather]),
)
Agent Platform SDK
אתם יכולים לציין את הסכימה באופן ידני באמצעות מילון Python, או באופן אוטומטי באמצעות פונקציית העזר from_func. בדוגמה הבאה אפשר לראות איך להצהיר על פונקציה באופן ידני:
import vertexai
from vertexai.generative_models import (
Content,
FunctionDeclaration,
GenerationConfig,
GenerativeModel,
Part,
Tool,
ToolConfig
)
# Initialize Agent Platform
# TODO(developer): Update the project
vertexai.init(project="PROJECT_ID", location="us-central1")
# Initialize Gemini model
model = GenerativeModel(model_name="gemini-2.5-flash")
# Manual function declaration
get_current_weather_func = FunctionDeclaration(
name="get_current_weather",
description="Get the current weather in a given location",
# Function parameters are specified in JSON schema format
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name of the location for which to get the weather.",
"default": {
"string_value": "Boston, MA"
}
}
},
},
)
response = model.generate_content(
contents = [
Content(
role="user",
parts=[
Part.from_text("What is the weather like in Boston?"),
],
)
],
generation_config = GenerationConfig(temperature=0),
tools = [
Tool(
function_declarations=[get_current_weather_func],
)
]
)
לחלופין, אפשר להצהיר על הפונקציה באופן אוטומטי באמצעות פונקציית העזר from_func, כמו בדוגמה הבאה:
def get_current_weather(location: str = "Boston, MA"):
"""
Get the current weather in a given location
Args:
location: The city name of the location for which to get the weather.
"""
# This example uses a mock implementation.
# You can define a local function or import the requests library to call an API
return {
"location": "Boston, MA",
"temperature": 38,
"description": "Partly Cloudy",
"icon": "partly-cloudy",
"humidity": 65,
"wind": {
"speed": 10,
"direction": "NW"
}
}
get_current_weather_func = FunctionDeclaration.from_func(get_current_weather)
Node.js
הדוגמה הזו ממחישה תרחיש של טקסט עם פונקציה אחת והנחיה אחת.
Node.js
לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js שמפורטות במאמר התחלה מהירה של Agent Platform באמצעות ספריות לקוח.
כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.
המשך
הדוגמה הזו ממחישה תרחיש טקסט עם פונקציה אחת והנחיה אחת.
מידע נוסף זמין ב מאמרי העזרה של ה-SDK.
מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_ENTERPRISE=True
C#
הדוגמה הזו ממחישה תרחיש טקסט עם פונקציה אחת והנחיה אחת.
C#
לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של C# שמפורטות במאמר התחלה מהירה של Agent Platform באמצעות ספריות לקוח.
כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.
Java
Java
לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java שמפורטות במאמר התחלה מהירה של Agent Platform באמצעות ספריות לקוח.
כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.
אם המודל קובע שהוא צריך את הפלט של פונקציה מסוימת, התגובה שהאפליקציה מקבלת מהמודל מכילה את שם הפונקציה ואת ערכי הפרמטרים שצריך לקרוא לפונקציה איתם.
הדוגמה הבאה היא תשובה של מודל להנחיה של המשתמש "What is the weather like in Boston?". המודל מציע להפעיל את הפונקציה get_current_weather עם הפרמטר Boston, MA.
candidates {
content {
role: "model"
parts {
function_call {
name: "get_current_weather"
args {
fields {
key: "location"
value {
string_value: "Boston, MA"
}
}
}
}
}
}
...
}
שלב 2: מספקים למודל את הפלט של ה-API
להפעיל את ה-API החיצוני ולהעביר את הפלט של ה-API בחזרה למודל.
בדוגמה הבאה נעשה שימוש בנתונים סינתטיים כדי לדמות מטען ייעודי (payload) של תגובה מ-API חיצוני, והפלט נשלח בחזרה למודל:
REST
PROJECT_ID=myproject
MODEL_ID=gemini-2.5-flash
LOCATION="us-central1"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [
{
"role": "user",
"parts": {
"text": "What is the weather in Boston?"
}
},
{
"role": "model",
"parts": [
{
"functionCall": {
"name": "get_current_weather",
"args": {
"location": "Boston, MA"
}
}
}
]
},
{
"role": "user",
"parts": [
{
"functionResponse": {
"name": "get_current_weather",
"response": {
"temperature": 20,
"unit": "C"
}
}
}
]
}
],
"tools": [
{
"function_declarations": [
{
"name": "get_current_weather",
"description": "Get the current weather in a specific location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name of the location for which to get the weather."
}
},
"required": [
"location"
]
}
}
]
}
]
}'
Agent Platform SDK
function_response_contents = []
function_response_parts = []
# Iterates through the function calls in the response in case there are parallel function call requests
for function_call in response.candidates[0].function_calls:
print(f"Function call: {function_call.name}")
# In this example, we'll use synthetic data to simulate a response payload from an external API
if (function_call.args['location'] == "Boston, MA"):
api_response = { "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy" }
if (function_call.args['location'] == "San Francisco, CA"):
api_response = { "location": "San Francisco, CA", "temperature": 58, "description": "Sunny" }
function_response_parts.append(
Part.from_function_response(
name=function_call.name,
response={"contents": api_response}
)
)
# Add the function call response to the contents
function_response_contents = Content(role="user", parts=function_response_parts)
# Submit the User's prompt, model's response, and API output back to the model
response = model.generate_content(
[
Content( # User prompt
role="user",
parts=[
Part.from_text("What is the weather like in Boston?"),
],
),
response.candidates[0].content, # Function call response
function_response_contents # API output
],
tools=[
Tool(
function_declarations=[get_current_weather_func],
)
],
)
# Get the model summary response
print(response.text)
במאמר שיטות מומלצות – הפעלת API מפורטות שיטות מומלצות שקשורות להפעלת API.
אם המודל הציע כמה קריאות להפעלת פונקציות במקביל, האפליקציה צריכה לספק את כל התשובות בחזרה למודל. מידע נוסף זמין במאמר דוגמה לקריאה להפעלת פונקציות במקביל.
יכול להיות שהמודל יקבע שהפלט של פונקציה אחרת נדרש כדי להגיב להנחיה. במקרה כזה, התשובה שהאפליקציה מקבלת מהמודל מכילה שם פונקציה אחר וקבוצה אחרת של ערכי פרמטרים.
אם המודל קובע שהתגובה מה-API מספיקה כדי לענות להנחיה של המשתמש, הוא יוצר תשובה בשפה טבעית ומחזיר אותה לאפליקציה. במקרה כזה, האפליקציה צריכה להעביר את התשובה בחזרה למשתמש. הדוגמה הבאה היא של תשובה בשפה טבעית:
It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies.
קריאה להפעלת פונקציות עם תהליך חשיבה
כשמפעילים פונקציות עם חשיבה, צריך לקבל את thought_signature מאובייקט התגובה של המודל ולהחזיר אותו כששולחים את תוצאת הפעלת הפונקציה בחזרה למודל. לדוגמה:
Python
# 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 not part.text:
continue
if part.thought and part.thought_signature:
print("Thought signature:")
print(part.thought_signature)
לא חובה להציג חתימות מחשבה, אבל תצטרכו לשנות את שלב 2 כדי להחזיר אותן יחד עם תוצאת הפעלת הפונקציה, כדי שהמודל יוכל לשלב את המחשבות בתשובה הסופית שלו:
Python
# 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)
כשאתה מחזיר חתימות של מחשבות, פעל לפי ההנחיות הבאות:
- המודל מחזיר חתימות בחלקים אחרים בתשובה, למשל בחלקים של קריאה להפעלת פונקציות, טקסט או סיכומי מחשבות. להחזיר את כל התשובה עם כל החלקים למודל בסבבים הבאים.
- אל תמזגו חלק עם חתימה אחת עם חלק אחר שגם מכיל חתימה. אי אפשר לשרשר חתימות.
- אל תמזגו חלק עם חתימה עם חלק אחר בלי חתימה. זה פוגע במיקום הנכון של הרעיון שמיוצג על ידי החתימה.
מידע נוסף על המגבלות והשימוש בחתימות חשיבה ועל מודלים של חשיבה
קריאה להפעלת פונקציות במקביל
בהנחיות כמו "Get weather details in Boston and San Francisco?", המודל עשוי להציע כמה קריאות להפעלת פונקציות במקביל. רשימת המודלים שתומכים בקריאה להפעלת פונקציות במקביל מופיעה בקטע מודלים נתמכים.
כשהמודל מחזיר כמה חלקים של functionCall בתשובה אחת, צריך להחזיר את כל החלקים התואמים של functionResponse ביחד באובייקט Content אחד בתור הבא. אל תשלבו בין החלקים של functionCall ו-functionResponse בתורות נפרדים.
כדי לוודא שכל functionResponse מותאם ל-functionCall הנכון, צריך להחזיר את החלקים של functionResponse במערך parts באותו סדר בדיוק כמו החלקים של functionCall שהמודל החזיר, כשכל functionResponse.name מוגדר ל-functionCall.name התואם. הסדר הזה לפי מיקום פועל בכל המודלים של Gemini ובכל הגרסאות של ה-API שנתמכים.
במודלים של Gemini 3 ואילך, ה-API תומך גם בהתאמה של תשובות לפונקציות מקבילות לקריאות להפעלת פונקציות, לפי סדר הקדימויות הבא:
- לפי
id: אםidמאוכלס ב-functionCall(נתמך ב-API שלv1beta1למודלים של Gemini 3 ואילך) ואתם כוללים את הערך התואם שלidב-functionResponse, ה-API מתאים את התשובה לקריאה עם אותו ערך שלid, בלי קשר לסדר במערךparts. הערך שלfunctionResponse.nameעדיין צריך להתאים לערך שלfunctionCall.name, אחרת הבקשה תיכשל ותוצג השגיאה400. - לפי
nameובסדר עוקב: אם לא צויןid(למשל ב-API שלv1), ה-API מתאים כלfunctionResponseל-functionCallשלא הותאם עם אותוname. כשהמודל מבצע כמה קריאות מקבילות לאותו שם פונקציה בסבב אחד, התגובות עם ה-nameהזה מותאמות ברצף לפי הסדר שבו הן מופיעות במערךparts.
REST
בדוגמה הזו מוצג תרחיש עם פונקציה אחת של get_current_weather.
ההנחיה של המשתמש היא "Get weather details in Boston and San Francisco?". המודל מציע שתי קריאות מקבילות לפונקציה get_current_weather: אחת עם הפרמטר Boston והשנייה עם הפרמטר San Francisco.
{
"candidates": [
{
"content": {
"role": "model",
"parts": [
{
"functionCall": {
"name": "get_current_weather",
"args": {
"location": "Boston"
}
}
},
{
"functionCall": {
"name": "get_current_weather",
"args": {
"location": "San Francisco"
}
}
}
]
},
...
}
],
...
}
הפקודה הבאה מדגימה איך אפשר לספק את פלט הפונקציה למודל. מחליפים את my-project בשם הפרויקט ב- Google Cloud .
בקשה למודל
PROJECT_ID=my-project
MODEL_ID=gemini-2.5-flash
LOCATION="us-central1"
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
"contents": [
{
"role": "user",
"parts": {
"text": "What is difference in temperature in Boston and San Francisco?"
}
},
{
"role": "model",
"parts": [
{
"functionCall": {
"name": "get_current_weather",
"args": {
"location": "Boston"
}
}
},
{
"functionCall": {
"name": "get_current_weather",
"args": {
"location": "San Francisco"
}
}
}
]
},
{
"role": "user",
"parts": [
{
"functionResponse": {
"name": "get_current_weather",
"response": {
"temperature": 30.5,
"unit": "C"
}
}
},
{
"functionResponse": {
"name": "get_current_weather",
"response": {
"temperature": 20,
"unit": "C"
}
}
}
]
}
],
"tools": [
{
"function_declarations": [
{
"name": "get_current_weather",
"description": "Get the current weather in a specific location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name of the location for which to get the weather."
}
},
"required": [
"location"
]
}
}
]
}
]
}'
התשובה בשפה טבעית שנוצרה על ידי המודל דומה לזו:
תשובה מהמודל
[
{
"candidates": [
{
"content": {
"parts": [
{
"text": "The temperature in Boston is 30.5C and the temperature in San Francisco is 20C. The difference is 10.5C. \n"
}
]
},
"finishReason": "STOP",
...
}
]
...
}
]
Python
בדוגמה הזו מוצג תרחיש עם פונקציה אחת של get_current_weather.
ההנחיה של המשתמש היא "What is the weather like in Boston and San Francisco?".
מחליפים את my-project בשם הפרויקט ב- Google Cloud .
import vertexai
from vertexai.generative_models import (
Content,
FunctionDeclaration,
GenerationConfig,
GenerativeModel,
Part,
Tool,
ToolConfig
)
# Initialize Agent Platform
# TODO(developer): Update the project
vertexai.init(project="my-project", location="us-central1")
# Initialize Gemini model
model = GenerativeModel(model_name="gemini-2.5-flash")
# Manual function declaration
get_current_weather_func = FunctionDeclaration(
name="get_current_weather",
description="Get the current weather in a given location",
# Function parameters are specified in JSON schema format
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name of the location for which to get the weather.",
"default": {
"string_value": "Boston, MA"
}
}
},
},
)
response = model.generate_content(
contents = [
Content(
role="user",
parts=[
Part.from_text("What is the weather like in Boston and San Francisco?"),
],
)
],
generation_config = GenerationConfig(temperature=0),
tools = [
Tool(
function_declarations=[get_current_weather_func],
)
]
)
הפקודה הבאה מדגימה איך אפשר לספק את פלט הפונקציה למודל.
function_response_contents = []
function_response_parts = []
# You can have parallel function call requests for the same function type.
# For example, 'location_to_lat_long("London")' and 'location_to_lat_long("Paris")'
# In that case, collect API responses in parts and send them back to the model
for function_call in response.candidates[0].function_calls:
print(f"Function call: {function_call.name}")
# In this example, we'll use synthetic data to simulate a response payload from an external API
if (function_call.args['location'] == "Boston, MA"):
api_response = { "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy" }
if (function_call.args['location'] == "San Francisco, CA"):
api_response = { "location": "San Francisco, CA", "temperature": 58, "description": "Sunny" }
function_response_parts.append(
Part.from_function_response(
name=function_call.name,
response={"contents": api_response}
)
)
# Add the function call response to the contents
function_response_contents = Content(role="user", parts=function_response_parts)
function_response_contents
response = model.generate_content(
contents = [
Content(
role="user",
parts=[
Part.from_text("What is the weather like in Boston and San Francisco?"),
],
), # User prompt
response.candidates[0].content, # Function call response
function_response_contents, # Function response
],
tools = [
Tool(
function_declarations=[get_current_weather_func],
)
]
)
# Get the model summary response
print(response.text)
המשך
תשובות מולטי-מודאליות של פונקציות
ב-Gemini 3 ובמודלים מתקדמים יותר, אתם יכולים לכלול תוכן מולטימודלי בחלקים של התגובה מהפונקציה שאתם שולחים למודל. המודל יכול לעבד את התוכן המולטי-מודאלי הזה בסבב הבא כדי ליצור תשובה מושכלת יותר. אלה סוגי ה-MIME שנתמכים בתוכן מולטי-מודאלי בתגובות לפונקציות:
- תמונות:
image/png,image/jpeg,image/webp - מסמכים:
application/pdf,text/plain
כדי לכלול נתונים ממספר סוגים בתשובה של פונקציה, צריך לכלול אותם כחלק אחד או יותר שמוטמע בתוך החלק functionResponse. כל חלק מולטימודלי חייב להכיל את inlineData או את fileData. אם אתם מפנים לחלק מולטימודלי מתוך השדה המובנה response, הוא חייב להכיל displayName ייחודי.
אפשר גם להפנות לחלק מולטימודלי מתוך השדה המובנה response של החלק functionResponse באמצעות פורמט ההפניה של JSON {"$ref": "<displayName>"}. המודל מחליף את ההפניה בתוכן המולטי-מודאלי כשהוא מעבד את התשובה. אפשר להפנות לכל displayName רק פעם אחת בשדה המובנה response.
בדוגמה הבאה מוצגת הודעה שמכילה functionResponse לפונקציה בשם get_image וחלק בתצורה של עץ שמכיל נתוני תמונה. השדה response של functionResponse מפנה לחלק הזה בתמונה:
Python
from google import genai
from google.genai import types
client = genai.Client()
# This is a manual, two turn multimodal function calling workflow:
# 1. Define the function tool
get_image_declaration = types.FunctionDeclaration(
name="get_image",
description="Retrieves the image file reference for a specific order item.",
parameters={
"type": "object",
"properties": {
"item_name": {
"type": "string",
"description": "The name or description of the item ordered (e.g., 'green shirt')."
}
},
"required": ["item_name"],
},
)
tool_config = types.Tool(function_declarations=[get_image_declaration])
# 2. Send a message that triggers the tool
prompt = "Show me the green shirt I ordered last month."
response_1 = client.models.generate_content(
model="gemini-3.5-flash",
contents=[prompt],
config=types.GenerateContentConfig(
tools=[tool_config],
)
)
# 3. Handle the function call
function_call = response_1.function_calls[0]
requested_item = function_call.args["item_name"]
print(f"Model wants to call: {function_call.name}")
# Execute your tool (e.g., call an API)
# (This is a mock response for the example)
print(f"Calling external tool for: {requested_item}")
function_response_data = {
"image_ref": {"$ref": "dress.jpg"},
}
function_response_multimodal_data = types.FunctionResponsePart(
file_data=types.FunctionResponseFileData(
mime_type="image/png",
display_name="dress.jpg",
file_uri="gs://cloud-samples-data/generative-ai/image/dress.jpg",
)
)
# 4. Send the tool's result back
# Append this turn's messages to history for a final response.
history = [
types.Content(role="user", parts=[types.Part(text=prompt)]),
response_1.candidates[0].content,
types.Content(
role="tool",
parts=[
types.Part.from_function_response(
name=function_call.name,
response=function_response_data,
parts=[function_response_multimodal_data]
)
],
)
]
response_2 = client.models.generate_content(
model="gemini-3.5-flash",
contents=history,
config=types.GenerateContentConfig(
tools=[tool_config],
thinking_config=types.ThinkingConfig(include_thoughts=True)
),
)
print(f"\nFinal model response: {response_2.text}")
REST
"contents": [
...,
{
"role": "user",
"parts": [
{
"functionResponse": {
"name": "get_image",
"response": {
"image_ref": {
"$ref": "wakeupcat.jpg"
}
},
"parts": [
{
"fileData": {
"displayName": "wakeupcat.jpg",
"mimeType": "image/jpeg",
"fileUri": "gs://cloud-samples-data/vision/label/wakeupcat.jpg"
}
}
]
}
}
]
}
]
ארגומנטים של בקשות להפעלת פונקציות בסטרימינג
במודלים של Gemini 3 ואילך, אתם יכולים לבקש שהארגומנטים של בקשה להפעלת פונקציה יועברו בסטרימינג בזמן שהמודל יוצר אותם, במקום לחכות שהמודל ייצור את כל קבוצת הארגומנטים. ההגדרה הזו שימושית כדי לצמצם את זמן האחזור הנתפס כשצריך להפעיל פונקציות.
לתכונה הזו יש את המגבלות הבאות:
- התכונה הזו זמינה גם בגרסה
v1וגם בגרסהv1beta1של ה-API.
כדי להפעיל סטרימינג של ארגומנטים של בקשה להפעלת פונקציה, מגדירים את streamFunctionCallArguments ל-true בתוך toolConfig.functionCallingConfig כשקוראים ל-streamGenerateContent.
כשהאפשרות streamFunctionCallArguments מופעלת, התגובות החלקיות יכילו אובייקט functionCall עם השדות partialArgs ו-willContinue.
השדה partialArgs מכיל קטעי ארגומנטים כפי שהם נוצרים, והשדה willContinue מציין אם צפויים קטעים נוספים לבקשה להפעלת פונקציה.
-
partialArgs: מערך של אובייקטים מסוגPartialArg, שכל אחד מהם מכיל:-
jsonPath: מחרוזת JSONPath שמציינת את הנתיב לקטע הזה בתוך אובייקט הפרמטרים של הפונקציה. הנתיב יכול להצביע על ארגומנט (למשל$.location) או על רכיב בתוך ארגומנט אם הארגומנט הוא אובייקט (למשל$.location.latitude). - ערך לקטע, שיכול להיות
numberValue,stringValue,boolValueאוnullValue. -
willContinue: ערך בוליאני בתוך אובייקטpartialArgs. השדה הזה הוא רקtrueעבור קטעיstringValueכאשר ערך המחרוזת מועבר בסטרימינג בחלקים וצפויים חלקים נוספים עבור הארגומנט הזה.
-
-
willContinue: ערך בוליאני בתוך האובייקטfunctionCall. אםtrue, צפויים עודpartialArgsלקריאה הכוללת לפונקציה בתגובות הבאות בסטרימינג. אם הערך הואfalseאו שהשדה לא קיים, זו התגובה הסופית בסטרימינג לקריאה הנוכחית להפעלת פונקציה.
בדוגמה הבאה מוצג רצף של קטעי generateContent בסטרימינג, שבהם הארגומנטים של בקשה להפעלת פונקציה אחת מועברים בסטרימינג:
{
"parts": [
{
"functionCall": {
"name": "controlLight",
"partialArgs": [
{
"jsonPath": "$.brightness",
"numberValue": 50
}
],
"willContinue": true
}
}
],
"role": "model"
}
{
"parts": [
{
"functionCall": {
"partialArgs": [
{
"jsonPath": "$.colorTemperature",
"stringValue": "warm",
"willContinue": true
}
],
"willContinue": true
}
}
],
"role": "model"
}
{
"parts": [
{
"functionCall": {
"partialArgs": [
{
"jsonPath": "$.colorTemperature"
}
],
"willContinue": true
}
}
],
"role": "model"
}
{
"parts": [
{
"functionCall": {}
}
],
"role": "model"
}
בדוגמה הבאה מוצג איך ארגומנטים לקריאות להפעלת פונקציות במקביל עשויים להישלח בכמה תשובות להנחיה "What is difference in temperature in New Delhi and San Francisco?":
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
"name": "get_current_weather",
"willContinue": true
},
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
"partialArgs": [{
"jsonPath": "$.location",
"stringValue": "New Delhi",
"willContinue": true
}],
"willContinue": true
}
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
"partialArgs": [{
"jsonPath": "$.location",
"stringValue": ""
}],
"willContinue": true
}
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
}
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
"name": "get_current_weather",
"willContinue": true
},
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
"partialArgs": [{
"jsonPath": "$.location",
"stringValue": "San Francisco",
"willContinue": true
}],
"willContinue": true
}
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
"partialArgs": [{
"jsonPath": "$.location",
"stringValue": ""
}],
"willContinue": true
}
}]
}
}],
}
{
"candidates": [{
"content": {
"role": "model",
"parts": [{
"functionCall": {
}
}]
}
}],
}
Python
from google import genai
from google.genai import types
client = genai.Client()
get_weather_declaration = types.FunctionDeclaration(
name="get_weather",
description="Gets the current weather temperature for a given location.",
parameters={
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
)
get_weather_tool = types.Tool(function_declarations=[get_weather_declaration])
for chunk in client.models.generate_content_stream(
model="gemini-3.5-flash",
contents="What's the weather in London and New York?",
config=types.GenerateContentConfig(
tools=[get_weather_tool],
tool_config = types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode=types.FunctionCallingConfigMode.AUTO,
stream_function_call_arguments=True,
)
),
),
):
function_call = chunk.function_calls[0]
if function_call and function_call.name:
print(f"{function_call.name}")
print(f"will_continue={function_call.will_continue}")
מצבי קריאה להפעלת פונקציות
אתם יכולים לקבוע איך המודל ישתמש בכלים שסופקו (הצהרות על פונקציות) על ידי הגדרת המצב ב-function_calling_config.
| מצב | תיאור |
|---|---|
AUTO |
התנהגות ברירת המחדל של המודל. המודל מחליט אם לחזות בקשות להפעלת פונקציות או להגיב בשפה טבעית על סמך ההקשר. זהו המצב הגמיש ביותר והוא מומלץ לרוב התרחישים. |
VALIDATED |
המודל מוגבל לחיזוי של בקשות להפעלת פונקציות או של שפה טבעית, ומבטיח עמידה בסכימה של הפונקציה. אם לא מציינים את allowed_function_names, המודל בוחר מכל הצהרות הפונקציות הזמינות. אם מציינים את allowed_function_names, המודל בוחר מתוך קבוצת הפונקציות המותרות. החל מ-Gemini 3, המצב הזה גם אוכף את הנוכחות של פרמטרים נדרשים. |
ANY |
המודל מוגבל כך שהוא תמיד חוזה קריאה אחת או יותר להפעלת פונקציות, ומבטיח שהסכימה של הפונקציה תישמר. אם לא מציינים את allowed_function_names, המודל בוחר מכל הצהרות הפונקציות הזמינות. אם מציינים את allowed_function_names, המודל בוחר מתוך קבוצת הפונקציות המותרות. השתמשו במצב הזה כשאתם רוצים לקבל תשובה עם בקשה להפעלת פונקציה לכל פרומפט (אם רלוונטי). |
NONE |
למודל אסור לבצע קריאות לפונקציות. זה שווה ערך לשליחת בקשה בלי הצהרות על פונקציות. אתם יכולים להשתמש במצב הזה כדי להשבית זמנית את הקריאה להפעלת פונקציות בלי להסיר את הגדרות הכלים. |
קריאה מאולצת להפעלת פונקציות
במקום לאפשר למודל לבחור בין תשובה בשפה טבעית לבין בקשה להפעלת פונקציה, אתם יכולים לאלץ אותו לחזות רק בקשות להפעלת פונקציות. זה נקרא קריאה מאולצת להפעלת פונקציות. אפשר גם לספק למודל קבוצה מלאה של הצהרות על פונקציות, אבל להגביל את התשובות שלו לקבוצת משנה של הפונקציות האלה.
בדוגמה הבאה, המודל נאלץ לחזות רק קריאות להפעלת פונקציות של get_weather.
Python
response = model.generate_content(
contents = [
Content(
role="user",
parts=[
Part.from_text("What is the weather like in Boston?"),
],
)
],
generation_config = GenerationConfig(temperature=0),
tools = [
Tool(
function_declarations=[get_weather_func, some_other_function],
)
],
tool_config=ToolConfig(
function_calling_config=ToolConfig.FunctionCallingConfig(
# ANY mode forces the model to predict only function calls
mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
# Allowed function calls to predict when the mode is ANY. If empty, any of
# the provided function calls will be predicted.
allowed_function_names=["get_weather"],
)
)
)
דוגמאות לסכימות של פונקציות
הצהרות על פונקציות תואמות לסכימה של OpenAPI. אנחנו תומכים במאפיינים הבאים: type, nullable, required, format, description, properties, items, enum, anyOf, $ref ו-$defs. אין תמיכה במאפיינים אחרים.
פונקציה עם פרמטרים של אובייקטים ומערכים
בדוגמה הבאה נעשה שימוש במילון Python כדי להצהיר על פונקציה שמקבלת גם פרמטרים של אובייקטים וגם פרמטרים של מערכים:
extract_sale_records_func = FunctionDeclaration( name="extract_sale_records", description="Extract sale records from a document.", parameters={ "type": "object", "properties": { "records": { "type": "array", "description": "A list of sale records", "items": { "description": "Data for a sale record", "type": "object", "properties": { "id": {"type": "integer", "description": "The unique id of the sale."}, "date": {"type": "string", "description": "Date of the sale, in the format of MMDDYY, e.g., 031023"}, "total_amount": {"type": "number", "description": "The total amount of the sale."}, "customer_name": {"type": "string", "description": "The name of the customer, including first name and last name."}, "customer_contact": {"type": "string", "description": "The phone number of the customer, e.g., 650-123-4567."}, }, "required": ["id", "date", "total_amount"], }, }, }, "required": ["records"], }, )
פונקציה עם פרמטר enum
בדוגמה הבאה נעשה שימוש במילון Python כדי להצהיר על פונקציה שמקבלת פרמטר של מספר שלם enum:
set_status_func = FunctionDeclaration( name="set_status", description="set a ticket's status field", # Function parameters are specified in JSON schema format parameters={ "type": "object", "properties": { "status": { "type": "integer", "enum": [ "10", "20", "30" ], # Provide integer (or any other type) values as strings. } }, }, )
פונקציה עם ref ו-def
הצהרת הפונקציה הבאה ב-JSON משתמשת במאפיינים ref ו-defs:
{ "contents": ..., "tools": [ { "function_declarations": [ { "name": "get_customer", "description": "Search for a customer by name", "parameters": { "type": "object", "properties": { "first_name": { "ref": "#/defs/name" }, "last_name": { "ref": "#/defs/name" } }, "defs": { "name": { "type": "string" } } } } ] } ] }
הערות לגבי השימוש:
- בניגוד לסכימת OpenAPI, צריך לציין את
refו-defsבלי הסמל$. -
refחייב להפנות לצאצא ישיר שלdefs; אין הפניות חיצוניות. - העומק המקסימלי של סכימה בתצוגת עץ הוא 32.
- עומק הרקורסיה ב-
defs(הפניה עצמית) מוגבל לשניים.
from_func עם פרמטר מערך
בדוגמת הקוד הבאה מוגדרת פונקציה שמכפילה מערך של מספרים, ומשתמשת ב-from_func כדי ליצור את הסכימה של FunctionDeclaration.
from typing import List # Define a function. Could be a local function or you can import the requests library to call an API def multiply_numbers(numbers: List[int] = [1, 1]) -> int: """ Calculates the product of all numbers in an array. Args: numbers: An array of numbers to be multiplied. Returns: The product of all the numbers. If the array is empty, returns 1. """ if not numbers: # Handle empty array return 1 product = 1 for num in numbers: product *= num return product multiply_number_func = FunctionDeclaration.from_func(multiply_numbers) """ multiply_number_func contains the following schema: {'name': 'multiply_numbers', 'description': 'Calculates the product of all numbers in an array.', 'parameters': {'properties': {'numbers': {'items': {'type': 'INTEGER'}, 'description': 'list of numbers', 'default': [1.0, 1.0], 'title': 'Numbers', 'type': 'ARRAY'}}, 'description': 'Calculates the product of all numbers in an array.', 'title': 'multiply_numbers', 'property_ordering': ['numbers'], 'type': 'OBJECT'}} """
שיטות מומלצות לקריאה להפעלת פונקציות
כדי לשפר את התוצאות כשמשתמשים בקריאה להפעלת פונקציות, כדאי לפעול לפי השיטות המומלצות הבאות:
לכתוב שמות פונקציות, תיאורי פרמטרים והוראות ברורים ומפורטים
שמות של פונקציות צריכים להתחיל באות או בקו תחתון, ויכולים להכיל רק את התווים a-z, A-Z, 0-9, קווים תחתונים, נקודות או מקפים. האורך המקסימלי הוא 64 תווים.
התיאורים של הפונקציות והפרמטרים צריכים להיות ברורים וספציפיים מאוד. המודל מסתמך על התיאורים האלה כדי לבחור את הפונקציה הנכונה ולספק ארגומנטים מתאימים. לדוגמה, לפונקציה
book_flight_ticketיכול להיות התיאורbook flight tickets after confirming users' specific requirements, such as time, departure, destination, party size and preferred airline
שימוש בפרמטרים עם סוגים מוגדרים היטב
אם ערכי הפרמטרים הם מקבוצה סופית, צריך להוסיף שדה enum במקום להזין את קבוצת הערכים בתיאור. אם ערך הפרמטר הוא תמיד מספר שלם, צריך להגדיר את הסוג בתור integer ולא בתור number.
בחירת כלי
המודל יכול להשתמש במספר שרירותי של כלים, אבל אם מספקים יותר מדי כלים, יש סיכון גבוה יותר לבחירה בכלי שגוי או לא אופטימלי. כדי לקבל את התוצאות הכי טובות, מומלץ לספק רק את הכלים שרלוונטיים להקשר או למשימה, ורצוי להגביל את מספר הכלים הפעילים ל-10 עד 20 לכל היותר. אם יש לכם מספר גדול של כלים, כדאי לשקול בחירת כלים דינמית על סמך ההקשר של השיחה.
אם תספקו כלים כלליים ברמה נמוכה (כמו bash), יכול להיות שהמודל ישתמש בכלי לעיתים קרובות יותר, אבל ברמת דיוק נמוכה יותר. אם תספקו כלי ספציפי ברמה גבוהה (כמו get_weather), המודל יוכל להשתמש בכלי בצורה מדויקת יותר, אבל יכול להיות שהוא לא ישתמש בו לעיתים קרובות.
שימוש בהוראות המערכת
כשמשתמשים בפונקציות עם פרמטרים של תאריך, שעה או מיקום, צריך לכלול בהוראות למערכת את התאריך והשעה הנוכחיים או את פרטי המיקום הרלוונטיים (לדוגמה, עיר ומדינה). כך המודל מקבל את ההקשר שדרוש לו כדי לעבד את הבקשה בצורה מדויקת, גם אם חסרים פרטים בהנחיה של המשתמש.
הנדסת פרומפטים
כדי לקבל את התוצאות הכי טובות, כדאי להוסיף את הפרטים הבאים לפני הנחיית המשתמש:
- הקשר נוסף למודל – לדוגמה,
You are a flight API assistant to help with searching flights based on user preferences. - פרטים או הוראות לגבי אופן השימוש בפונקציות ומתי להשתמש בהן, לדוגמה
Don't make assumptions on the departure or destination airports. Always use a future date for the departure or destination time. - הוראות לשאול שאלות הבהרה אם השאילתות של המשתמשים לא ברורות, למשל:
Ask clarifying questions if not enough information is available.
שימוש בהגדרות ליצירת תוכן
בפרמטר הטמפרטורה, משתמשים ב-0 או בערך נמוך אחר. כך המודל מקבל הוראה ליצור תוצאות ודאיות יותר, וזה מפחית את ההזיות.
שימוש בפלט מובנה
אפשר להשתמש בקריאה להפעלת פונקציות יחד עם פלט מובנה כדי לאפשר למודל לחזות תמיד קריאות להפעלת פונקציות או פלטים שתואמים לסכימה ספציפית, כך שתקבלו תשובות בפורמט עקבי כשהמודל לא יוצר קריאות להפעלת פונקציות.
אימות הקריאה ל-API
אם המודל מציע להפעיל פונקציה שתשלח הזמנה, תעדכן מסד נתונים או תגרום לתוצאות משמעותיות אחרות, צריך לאמת את הקריאה להפעלת הפונקציה עם המשתמש לפני שמפעילים אותה.
שימוש בחתימות מחשבה
כדי לקבל את התוצאות הכי טובות, תמיד כדאי להשתמש בחתימות חשיבה עם קריאה להפעלת פונקציות.
תמחור
התמחור של קריאה להפעלת פונקציות מבוסס על מספר התווים בקלט ובפלט של הטקסט. מידע נוסף על התמחור של Gemini Enterprise Agent Platform
כאן, קלט טקסט (הנחיה) מתייחס להנחיית המשתמש בתור הנוכחי בשיחה, להצהרות על הפונקציות בתור הנוכחי בשיחה ולהיסטוריית השיחה. היסטוריית השיחה כוללת את השאילתות, בקשות להפעלת פונקציות והתשובות של הפונקציות מהשלבים הקודמים בשיחה. פלטפורמת הסוכנים של Gemini Enterprise מקצרת את היסטוריית השיחה ל-32,000 תווים.
פלט הטקסט (תשובה) מתייחס לקריאות להפעלת פונקציות ולתשובות בטקסט של התור הנוכחי בשיחה.
תרחישים לדוגמה של קריאה להפעלת פונקציות
אתם יכולים להשתמש בקריאה להפעלת פונקציות למשימות הבאות:
| תרחיש לדוגמה | תיאור לדוגמה | קישור לדוגמה |
|---|---|---|
| שילוב עם ממשקי API חיצוניים | קבלת מידע על מזג האוויר באמצעות API מטאורולוגי | מדריך ל-Notebook |
| המרת כתובות לקואורדינטות של קווי רוחב ואורך | מדריך ל-Notebook | |
| המרת מטבעות באמצעות API להמרת מטבעות | Codelab | |
| פיתוח צ'אט בוטים מתקדמים | מענה על שאלות של לקוחות לגבי מוצרים ושירותים | מדריך ל-Notebook |
| יצירת עוזר דיגיטלי שיענה על שאלות פיננסיות וחדשותיות לגבי חברות | מדריך ל-Notebook | |
| מבנה ובקרה של קריאות להפעלת פונקציות | חילוץ ישויות מובְנות מנתוני יומן גולמיים | מדריך ל-Notebook |
| חילוץ פרמטר אחד או כמה פרמטרים מהקלט של המשתמש | מדריך ל-Notebook | |
| טיפול ברשימות ובמבני נתונים מקוננים בקריאות להפעלת פונקציות | מדריך ל-Notebook | |
| טיפול בהתנהגות של קריאה להפעלת פונקציות | טיפול בקריאות להפעלת פונקציות במקביל ובתגובות שלהן | מדריך ל-Notebook |
| לנהל את המועד שבו המודל יכול להפעיל פונקציות ואת הפונקציות שהוא יכול להפעיל | מדריך ל-Notebook | |
| שליחת שאילתות למסדי נתונים בשפה טבעית | המרת שאלות בשפה טבעית לשאילתות SQL ב-BigQuery | אפליקציה לדוגמה |
| קריאה להפעלת פונקציות מולטי-מודאליות | שימוש בתמונות, בסרטונים, בקובצי אודיו ובקובצי PDF כקלט להפעלת פונקציות | מדריך ל-Notebook |
הנה עוד כמה תרחישי שימוש:
לפרש פקודות קוליות: ליצור פונקציות שתואמות למשימות ברכב. לדוגמה, אתם יכולים ליצור פונקציות שמפעילות את הרדיו או את מיזוג האוויר. שולחים למודל קובצי אודיו של הפקודות הקוליות של המשתמש, ומבקשים מהמודל להמיר את האודיו לטקסט ולזהות את הפונקציה שהמשתמש רוצה להפעיל.
אוטומציה של תהליכי עבודה על סמך טריגרים סביבתיים: יצירת פונקציות שמייצגות תהליכים שאפשר להפוך לאוטומטיים. מספקים למודל נתונים מחיישנים סביבתיים ומבקשים ממנו לנתח ולעבד את הנתונים כדי לקבוע אם צריך להפעיל אחד או יותר מתהליכי העבודה. לדוגמה, מודל יכול לעבד נתוני טמפרטורה במחסן ולהחליט להפעיל פונקציה של ממטרה.
הקצאה אוטומטית של כרטיסי תמיכה: מספקים למודל כרטיסי תמיכה, יומנים וכללים שמותאמים להקשר. מבקשים מהמודל לעבד את כל המידע הזה כדי לקבוע למי צריך להקצות את הפנייה. קוראים לפונקציה כדי להקצות את הכרטיס לאדם שהמודל הציע.
אחזור מידע ממאגר ידע: יוצרים פונקציות שמאחזרות מאמרים אקדמיים בנושא מסוים ומסכמות אותם. המודל יכול לענות על שאלות בנושאים אקדמיים ולספק ציטוטים לתשובות שלו.