فراخوانی تابع به شما امکان میدهد مدلها را به ابزارها و APIهای خارجی متصل کنید. به جای تولید پاسخهای متنی، مدل زمان فراخوانی توابع خاص را تعیین میکند و پارامترهای لازم را برای اجرای اقدامات دنیای واقعی فراهم میکند. این امر به مدل اجازه میدهد تا به عنوان پلی بین زبان طبیعی و اقدامات و دادههای دنیای واقعی عمل کند. فراخوانی تابع دارای ۳ مورد استفاده اصلی است:
- اقدامات لازم: با استفاده از APIها با سیستمهای خارجی تعامل داشته باشید، مانند برنامهریزی قرار ملاقاتها، ایجاد فاکتورها، ارسال ایمیل یا کنترل دستگاههای خانه هوشمند.
- افزایش دانش: دسترسی به اطلاعات از منابع خارجی مانند پایگاههای داده، APIها و پایگاههای دانش.
- گسترش قابلیتها: از ابزارهای خارجی برای انجام محاسبات و گسترش محدودیتهای مدل، مانند استفاده از ماشین حساب یا ایجاد نمودار، استفاده کنید.
میتوانید نمونههایی از این موارد استفاده را در زیر مرور کنید:
برنامه جلسه
این مثال نشان میدهد که چگونه میتوان تابعی تعریف کرد که جلسهای را با شرکتکنندگان در یک زمان مشخص برنامهریزی میکند و به مدل اجازه میدهد درخواستهای کاربر را تجزیه و تحلیل کرده و آرگومانهای ساختاریافته را برای ایجاد اقدامات در سیستمهای خارجی بازگرداند.
پایتون
from google import genai
schedule_meeting_function = {
"type": "function",
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {"type": "array", "items": {"type": "string"}},
"date": {"type": "string", "description": "Date (e.g., '2024-07-29')"},
"time": {"type": "string", "description": "Time (e.g., '15:00')"},
"topic": {"type": "string", "description": "The meeting topic."},
},
"required": ["attendees", "date", "time", "topic"],
},
}
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.7-flash",
input="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.",
tools=[{"type": "function", **schedule_meeting_function}],
)
for step in interaction.steps:
if step.type == "function_call":
print(f"Function to call: {step.name}")
print(f"Arguments: {step.arguments}")
جاوا اسکریپت
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const scheduleMeetingFunction = {
type: 'function',
name: 'schedule_meeting',
description: 'Schedules a meeting with specified attendees at a given time and date.',
parameters: {
type: 'object',
properties: {
attendees: { type: 'array', items: { type: 'string' } },
date: { type: 'string', description: 'Date (e.g., "2024-07-29")' },
time: { type: 'string', description: 'Time (e.g., "15:00")' },
topic: { type: 'string', description: 'The meeting topic.' },
},
required: ['attendees', 'date', 'time', 'topic'],
},
};
const interaction = await client.interactions.create({
model: 'gemini-3.7-flash',
input: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.',
tools: [scheduleMeetingFunction],
});
for (const step of interaction.steps) {
if (step.type === 'function_call') {
console.log(`Function to call: ${step.name}`);
console.log(`Arguments: ${JSON.stringify(step.arguments)}`);
}
}
استراحت
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.7-flash",
"input": "Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning.",
"tools": [{
"type": "function",
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {"type": "array", "items": {"type": "string"}},
"date": {"type": "string"},
"time": {"type": "string"},
"topic": {"type": "string"}
},
"required": ["attendees", "date", "time", "topic"]
}
}]
}'
دریافت آب و هوا
این مثال نشان میدهد که چگونه میتوان تابعی تعریف کرد که دادههای دما را برای یک مکان بازیابی میکند و مدل را قادر میسازد تا APIهای خارجی را برای پاسخ به پرسوجوهایی که به اطلاعات بلادرنگ یا خارجی نیاز دارند، فراخوانی کند.
پایتون
from google import genai
weather_function = {
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.7-flash",
input="What's the temperature in London?",
tools=[weather_function],
)
for step in interaction.steps:
if step.type == "function_call":
print(f"Function to call: {step.name}")
print(f"Arguments: {step.arguments}")
جاوا اسکریپت
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const weatherFunctionDeclaration = {
type: 'function',
name: 'get_current_temperature',
description: 'Gets the current temperature for a given location.',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The city name, e.g. San Francisco',
},
},
required: ['location'],
},
};
const interaction = await client.interactions.create({
model: 'gemini-3.7-flash',
input: "What's the temperature in London?",
tools: [weatherFunctionDeclaration],
});
for (const step of interaction.steps) {
if (step.type === 'function_call') {
console.log(`Function to call: ${step.name}`);
console.log(`Arguments: ${JSON.stringify(step.arguments)}`);
}
}
استراحت
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.7-flash",
"input": "What'\''s the temperature in London?",
"tools": [{
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city name"}
},
"required": ["location"]
}
}]
}'
ایجاد نمودار
این مثال نحوه تعریف تابعی را نشان میدهد که یک نمودار میلهای از دادههای ساختاریافته تولید میکند و نشان میدهد که چگونه مدل میتواند از ابزارهای خارجی برای انجام محاسبات یا ایجاد داراییهای بصری استفاده کند:
پایتون
from google import genai
create_chart_function = {
"type": "function",
"name": "create_bar_chart",
"description": "Creates a bar chart given a title, labels, and values.",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string", "description": "The title for the chart."},
"labels": {"type": "array", "items": {"type": "string"}},
"values": {"type": "array", "items": {"type": "number"}},
},
"required": ["title", "labels", "values"],
},
}
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.7-flash",
input="Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.",
tools=[create_chart_function],
)
for step in interaction.steps:
if step.type == "function_call":
print(f"Function to call: {step.name}")
print(f"Arguments: {step.arguments}")
جاوا اسکریپت
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const createChartFunctionDeclaration = {
type: 'function',
name: 'create_bar_chart',
description: 'Creates a bar chart given a title, labels, and values.',
parameters: {
type: 'object',
properties: {
title: { type: 'string', description: 'The title for the chart.' },
labels: { type: 'array', items: { type: 'string' } },
values: { type: 'array', items: { type: 'number' } },
},
required: ['title', 'labels', 'values'],
},
};
const interaction = await client.interactions.create({
model: 'gemini-3.7-flash',
input: "Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.",
tools: [createChartFunctionDeclaration],
});
for (const step of interaction.steps) {
if (step.type === 'function_call') {
console.log(`${step.name}(${JSON.stringify(step.arguments)})`);
}
}
استراحت
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3.7-flash",
"input": "Create a bar chart titled '\''Quarterly Sales'\'' with Q1: 50000, Q2: 75000, Q3: 60000.",
"tools": [{
"type": "function",
"name": "create_bar_chart",
"description": "Creates a bar chart given a title, labels, and values.",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"labels": {"type": "array", "items": {"type": "string"}},
"values": {"type": "array", "items": {"type": "number"}}
},
"required": ["title", "labels", "values"]
}
}]
}'
نحوه فراخوانی تابع

فراخوانی تابع شامل یک تعامل ساختاریافته بین برنامه شما، مدل و توابع خارجی است:
- تعریف اعلان تابع: نام، پارامترها و هدف تابع را برای مدل تعریف کنید.
- فراخوانی LLM با اعلان توابع: ارسال اعلان کاربر به همراه اعلان(های) تابع به مدل.
- اجرای کد تابع (مسئولیت شما): مدل خود تابع را اجرا نمیکند . نام و آرگومانها را استخراج کرده و در برنامه خود اجرا کنید.
- ایجاد پاسخ کاربرپسند: نتیجه را برای دریافت پاسخ نهایی و کاربرپسند به مدل ارسال کنید.
این فرآیند میتواند در چندین نوبت تکرار شود. این مدل از فراخوانی چندین تابع در یک نوبت ( فراخوانی تابع موازی ) و به ترتیب ( فراخوانی تابع ترکیبی ) پشتیبانی میکند.
مرحله ۱: تعریف یک تابع
پایتون
set_light_values_declaration = {
"type": "function",
"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",
},
"color_temp": {
"type": "string",
"enum": ["daylight", "cool", "warm"],
"description": "Color temperature",
},
},
"required": ["brightness", "color_temp"],
},
}
def set_light_values(brightness: int, color_temp: str) -> dict:
"""Set the brightness and color temperature of a room light."""
return {"brightness": brightness, "colorTemperature": color_temp}
جاوا اسکریپت
const setLightValuesTool = {
type: 'function',
name: 'set_light_values',
description: 'Sets the brightness and color temperature of a light.',
parameters: {
type: 'object',
properties: {
brightness: { type: 'number', description: 'Light level from 0 to 100' },
color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] },
},
required: ['brightness', 'color_temp'],
},
};
function setLightValues(brightness, color_temp) {
return { brightness: brightness, colorTemperature: color_temp };
}
مرحله ۲: فراخوانی مدل با اعلان توابع
پایتون
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.7-flash",
input="Turn the lights down to a romantic level",
tools=[set_light_values_declaration],
)
fc_step = next(s for s in interaction.steps if s.type == "function_call")
print(fc_step)
جاوا اسکریپت
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3.7-flash',
input: 'Turn the lights down to a romantic level',
tools: [setLightValuesTool],
});
const fcStep = interaction.steps.find(s => s.type === 'function_call');
console.log(fcStep);
این مدل یک مرحله function_call به همراه type ، name و arguments را برمیگرداند:
type='function_call'
name='set_light_values'
arguments={'color_temp': 'warm', 'brightness': 25}
مرحله ۳: اجرای تابع
پایتون
fc_step = next(s for s in interaction.steps if s.type == "function_call")
if fc_step.name == "set_light_values":
result = set_light_values(**fc_step.arguments)
print(f"Function execution result: {result}")
جاوا اسکریپت
const fcStep = interaction.steps.find(s => s.type === 'function_call');
let result;
if (fcStep.name === 'set_light_values') {
result = setLightValues(fcStep.arguments.brightness, fcStep.arguments.color_temp);
console.log(`Function execution result: ${JSON.stringify(result)}`);
}
مرحله ۴: ارسال نتیجه به مدل
پایتون
final_interaction = client.interactions.create(
model="gemini-3.7-flash",
input=[
{
"type": "function_result",
"name": fc_step.name,
"call_id": fc_step.id,
"result": [{"type": "text", "text": json.dumps(result)}],
}
],
tools=[set_light_values_declaration],
previous_interaction_id=interaction.id,
)
print(final_interaction.output_text)
جاوا اسکریپت
const finalInteraction = await client.interactions.create({
model: 'gemini-3.7-flash',
input: [{
type: 'function_result',
name: fcStep.name,
call_id: fcStep.id,
result: [{ type: 'text', text: JSON.stringify(result) }]
}],
tools: [setLightValuesTool],
previous_interaction_id: interaction.id,
});
console.log(finalInteraction.output_text);
فراخوانی تابع بدون وضعیت
همچنین میتوانید با مدیریت تاریخچه مکالمات در سمت کلاینت و تنظیم store=false ، از فراخوانی تابع در حالت بدون وضعیت (stateless) استفاده کنید.
در حالت بدون وضعیت، شما باید تاریخچه کامل مکالمه را در فیلد input هر درخواست بعدی ارسال کنید. این تاریخچه باید شامل موارد زیر باشد: ۱. مرحله اولیه user_input . ۲. تمام مراحل تولید شده توسط مدل که در نوبت ۱ (از جمله مراحل thought و function_call ) دقیقاً همانطور که دریافت شدهاند، برگردانده شوند. ۳. مرحله function_result که شامل خروجی تابع اجرا شده شما است.
پایتون
from google import genai
import json
client = genai.Client()
history = [
{
"type": "user_input",
"content": [{"type": "text", "text": "Turn the lights down to a romantic level"}]
}
]
interaction = client.interactions.create(
model="gemini-3.7-flash",
store=False,
input=history,
tools=[set_light_values_declaration],
)
for step in interaction.steps:
history.append(step.model_dump())
fc_step = next(s for s in interaction.steps if s.type == "function_call")
if fc_step.name == "set_light_values":
result = set_light_values(**fc_step.arguments)
history.append({
"type": "function_result",
"name": fc_step.name,
"call_id": fc_step.id,
"result": [{"type": "text", "text": json.dumps(result)}],
})
final_interaction = client.interactions.create(
model="gemini-3.7-flash",
store=False,
input=history,
tools=[set_light_values_declaration],
)
print(final_interaction.output_text)
جاوا اسکریپت
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
async function main() {
const history = [
{
type: "user_input",
content: [{ type: "text",