فراخوانی تابع به شما امکان میدهد مدلها را به ابزارها و 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.8-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.8-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)}`);
}
}
جاوا
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.FunctionCallStep;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Client client = new Client();
Map<String, Object> attendeesProp = new HashMap<>();
attendeesProp.put("type", "array");
Map<String, Object> itemsMap = new HashMap<>(); itemsMap.put("type", "string"); attendeesProp.put("items", itemsMap);
Map<String, Object> dateProp = new HashMap<>();
dateProp.put("type", "string");
dateProp.put("description", "Date (e.g., \"2024-07-29\")");
Map<String, Object> timeProp = new HashMap<>();
timeProp.put("type", "string");
timeProp.put("description", "Time (e.g., \"15:00\")");
Map<String, Object> topicProp = new HashMap<>();
topicProp.put("type", "string");
topicProp.put("description", "The meeting topic.");
Map<String, Object> properties = new HashMap<>();
properties.put("attendees", attendeesProp);
properties.put("date", dateProp);
properties.put("time", timeProp);
properties.put("topic", topicProp);
Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");
parameters.put("properties", properties);
parameters.put("required", Arrays.asList("attendees", "date", "time", "topic"));
Function scheduleMeetingFunction =
Function.builder()
.name("schedule_meeting")
.description("Schedules a meeting with specified attendees at a given time and date.")
.parameters(parameters)
.build();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.6-flash"))
.input(InteractionsInput.of("Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about Q3 planning."))
.tools(Arrays.asList(scheduleMeetingFunction))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof FunctionCallStep) {
FunctionCallStep functionCall = (FunctionCallStep) step;
System.out.println("Function to call: " + functionCall.name().orElse(""));
System.out.println("Arguments: " + functionCall.arguments().orElse(null));
}
}
}
استراحت
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.8-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.8-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.8-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)}`);
}
}
جاوا
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.FunctionCallStep;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Client client = new Client();
Map<String, Object> locationProp = new HashMap<>();
locationProp.put("type", "string");
locationProp.put("description", "The city name, e.g. San Francisco");
Map<String, Object> properties = new HashMap<>();
properties.put("location", locationProp);
Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");
parameters.put("properties", properties);
parameters.put("required", Arrays.asList("location"));
Function weatherFunction =
Function.builder()
.name("get_current_temperature")
.description("Gets the current temperature for a given location.")
.parameters(parameters)
.build();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.6-flash"))
.input(InteractionsInput.of("What's the temperature in London?"))
.tools(Arrays.asList(weatherFunction))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof FunctionCallStep) {
FunctionCallStep functionCall = (FunctionCallStep) step;
System.out.println("Function to call: " + functionCall.name().orElse(""));
System.out.println("Arguments: " + functionCall.arguments().orElse(null));
}
}
}
استراحت
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.8-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.8-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.8-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)})`);
}
}
جاوا
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.FunctionCallStep;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Client client = new Client();
Map<String, Object> properties = new HashMap<>();
Map<String, Object> titleMap = new HashMap<>(); titleMap.put("type", "string"); titleMap.put("description", "The title for the chart."); properties.put("title", titleMap);
Map<String, Object> labelsMap = new HashMap<>(); labelsMap.put("type", "array"); labelsMap.put("items", Collections.singletonMap("type", "string")); properties.put("labels", labelsMap);
Map<String, Object> valuesMap = new HashMap<>(); valuesMap.put("type", "array"); valuesMap.put("items", Collections.singletonMap("type", "number")); properties.put("values", valuesMap);
Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");
parameters.put("properties", properties);
parameters.put("required", Arrays.asList("title", "labels", "values"));
Function createChartFunction =
Function.builder()
.name("create_bar_chart")
.description("Creates a bar chart given a title, labels, and values.")
.parameters(parameters)
.build();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.6-flash"))
.input(InteractionsInput.of("Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000."))
.tools(Arrays.asList(createChartFunction))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof FunctionCallStep) {
FunctionCallStep functionCall = (FunctionCallStep) step;
System.out.println(functionCall.name().orElse("") + "(" + functionCall.arguments().orElse(null) + ")");
}
}
}
استراحت
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.8-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 };
}
جاوا
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.FunctionCallStep;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Client client = new Client();
Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");
Function function = Function.builder()
.name("custom_function")
.description("A custom function.")
.parameters(parameters)
.build();
CreateModelInteraction params = CreateModelInteraction.builder()
.model(Model.of("gemini-3.6-flash"))
.input(InteractionsInput.of("Call the function."))
.tools(Arrays.asList(function))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof FunctionCallStep) {
FunctionCallStep fc = (FunctionCallStep) step;
System.out.println("Function: " + fc.name().orElse(""));
}
}
}
مرحله ۲: فراخوانی مدل با اعلان توابع
پایتون
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-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.8-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);
جاوا
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.FunctionCallStep;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Client client = new Client();
Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");
Function function = Function.builder()
.name("custom_function")
.description("A custom function.")
.parameters(parameters)
.build();
CreateModelInteraction params = CreateModelInteraction.builder()
.model(Model.of("gemini-3.6-flash"))
.input(InteractionsInput.of("Call the function."))
.tools(Arrays.asList(function))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof FunctionCallStep) {
FunctionCallStep fc = (FunctionCallStep) step;
System.out.println("Function: " + fc.name().orElse(""));
}
}
}
این مدل یک مرحله 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)}`);
}
جاوا
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.FunctionCallStep;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Client client = new Client();
Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");
Function function = Function.builder()
.name("custom_function")
.description("A custom function.")
.parameters(parameters)
.build();
CreateModelInteraction params = CreateModelInteraction.builder()
.model(Model.of("gemini-3.6-flash"))
.input(InteractionsInput.of("Call the function."))
.tools(Arrays.asList(function))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof FunctionCallStep) {
FunctionCallStep fc = (FunctionCallStep) step;
System.out.println("Function: " + fc.name().orElse(""));
}
}
}
مرحله ۴: ارسال نتیجه به مدل
پایتون
final_interaction = client.interactions.create(
model="gemini-3.8-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.8-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