Tính năng gọi hàm cho phép bạn kết nối các mô hình với các công cụ và API bên ngoài. Thay vì tạo phản hồi bằng văn bản, mô hình sẽ xác định thời điểm gọi các hàm cụ thể và cung cấp các tham số cần thiết để thực thi các hành động trong thế giới thực. Điều này cho phép mô hình đóng vai trò là cầu nối giữa ngôn ngữ tự nhiên và các hành động cũng như dữ liệu trong thế giới thực. Tính năng gọi hàm có 3 trường hợp sử dụng chính:
- Thực hiện hành động: Tương tác với các hệ thống bên ngoài bằng API, chẳng hạn như lên lịch hẹn, tạo hoá đơn, gửi email hoặc điều khiển các thiết bị nhà thông minh.
- Tăng cường kiến thức: Truy cập thông tin từ các nguồn bên ngoài như cơ sở dữ liệu, API và cơ sở kiến thức.
- Mở rộng khả năng: Sử dụng các công cụ bên ngoài để thực hiện phép tính và mở rộng các giới hạn của mô hình, chẳng hạn như sử dụng máy tính hoặc tạo biểu đồ.
Bạn có thể duyệt xem ví dụ về các trường hợp sử dụng này bên dưới:
Lên lịch họp
Ví dụ này cho thấy cách xác định một hàm lên lịch cuộc họp với người tham dự vào một thời điểm cụ thể, cho phép mô hình phân tích cú pháp các yêu cầu của người dùng và trả về các đối số có cấu trúc để kích hoạt các hành động trong hệ thống bên ngoài.
Python
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.6-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}")
JavaScript
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.6-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)}`);
}
}
REST
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.6-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"]
}
}]
}'
Nhận thông tin thời tiết
Ví dụ này cho thấy cách xác định một hàm truy xuất dữ liệu nhiệt độ cho một vị trí, cho phép mô hình gọi các API bên ngoài để trả lời những truy vấn yêu cầu thông tin theo thời gian thực hoặc thông tin bên ngoài.
Python
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.6-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}")
JavaScript
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.6-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)}`);
}
}
REST
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.6-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"]
}
}]
}'
Tạo biểu đồ
Ví dụ này cho thấy cách xác định một hàm tạo biểu đồ thanh từ dữ liệu có cấu trúc, minh hoạ cách mô hình có thể sử dụng các công cụ bên ngoài để thực hiện các phép tính hoặc tạo tài sản trực quan:
Python
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.6-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}")
JavaScript
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.6-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)})`);
}
}
REST
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.6-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"]
}
}]
}'
Cách hoạt động của tính năng gọi hàm

Gọi hàm là một hoạt động tương tác có cấu trúc giữa ứng dụng, mô hình và các hàm bên ngoài:
- Xác định khai báo hàm: Xác định tên, tham số và mục đích của hàm cho mô hình.
- Gọi LLM bằng khai báo hàm: Gửi câu lệnh của người dùng cùng với(các) khai báo hàm đến mô hình.
- Thực thi mã hàm (Trách nhiệm của bạn): Mô hình không tự thực thi hàm. Trích xuất tên và đối số rồi thực thi trong ứng dụng của bạn.
- Tạo câu trả lời thân thiện với người dùng: Gửi kết quả trở lại mô hình để có câu trả lời cuối cùng, thân thiện với người dùng.
Quá trình này có thể được lặp lại nhiều lần. Mô hình này hỗ trợ việc gọi nhiều hàm trong một lượt (gọi hàm song song) và theo trình tự (gọi hàm kết hợp).
Bước 1: Xác định một khai báo hàm
Python
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&>quot;, "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}
JavaScript
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 };
}
Bước 2: Gọi mô hình bằng các khai báo hàm
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.6-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)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3.6-flash',
input: 'Turn the lights down to a romantic level',
tools: [setLightValuesTool],
});
const fcStep = in>teraction.steps.find(s = s.type === 'function_call');
console.log(fcStep);
Mô hình này trả về một bước function_call với type, name và arguments:
type='function_call'
name='set_light_values'
arguments={'color_temp': 39;warm', 'brightness': 25}
Bước 3: Thực thi hàm
Python
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}")
JavaScript
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)}`);
}
Bước 4: Gửi kết quả về mô hình
Python
final_interaction = client.interactions.create(
model="gemini-3.6-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)
JavaScript
const finalInteraction = await client.interactions.create({
model: 'gemini-3.6-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);
Gọi hàm không trạng thái
Bạn cũng có thể sử dụng tính năng gọi hàm ở chế độ không trạng thái bằng cách quản lý nhật ký trò chuyện ở phía máy khách và đặt store=false.
Ở chế độ không trạng thái, bạn phải truyền toàn bộ nhật ký cuộc trò chuyện trong trường input của mỗi yêu cầu tiếp theo. Nhật ký này phải bao gồm:
1. Bước user_input ban đầu.
2. Tất cả các bước do mô hình tạo được trả về trong Lượt 1 (bao gồm cả các bước thought và function_call) chính xác như đã nhận.
3. Bước function_result chứa kết quả của hàm mà bạn đã thực thi.
Python
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.6-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.6-flash",
store=False,
input=history,
tools=[set_light_values_declaration],
)
print(final_interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
async function main() {
const history = [
{
type: "user_input",
content: [{ type: "text", text: "Turn the lights down to a romantic level" }]
}
];
const interaction = await client.interactions.create({
model: "gemini-3.6-flash",
store: false,
input: history,
tools: [setLightValuesTool],
});
history.push(...interaction.st>eps);
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);
}
history.push({
type: 'function_result',
name: fcStep.name,
call_id: fcStep.id,
result: [{ type: 'text', text: JSON.stringify(result) }]
});
const finalInteraction = await client.interactions.create({
model: 'gemini-3.6-flash',
store: false,
input: history,
tools: [setLightValuesTool],
});
console.log(finalInteraction.output_text);
}
await main();
REST
# Turn 1: Send request with tools and store: false
RESPONSE1=$(curl -s -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.6-flash",
"store": false,
"input": [
{
"type": "user_input",
"content": "Turn the lights down to a romantic level"
}
],
"tools": [{
"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"]}
},
"required": ["brightness", "color_temp"]
}
}]
}')
# Extract model steps (thought, function_call)
MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')
# Extract function call details to execute
FC_NAME=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .name')
FC_ID=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .id')
# Assume local execution returns: {"brightness": 25, "colorTemperature": "warm"}
RESULT="{\"brightness\": 25, \"colorTemperature\": \"warm\"}"
# Reconstruct history for Turn 2
HISTORY=$(jq -n \
--argjson first_input '[{"type": "user_input", "content": "Turn the lights down to a romantic level"}]' \
--argjson model_steps "$MODEL_STEPS" \
--arg fc_name "$FC_NAME" \
--arg fc_id "$FC_ID" \
--arg result "$RESULT" \
'$first_input + $model_steps + [{"type": "function_result", "name": $fc_name, "call_id": $fc_id, "result": [{"type": "text", "text": $result}]}]')
# Turn 2: Send the full history
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.6-flash\",
\"store\": false,
\"input\": $HISTORY,
\"tools\": [{
\"type\": \"function\",
\"name\": \"set_light_values\",
\"description\": \"Sets the brightness and color temperature of a light.\",
\"parameters\": {
\"type\": \"object\",
\"properties\": {
\"brightness\": {\"type\": \"integer\"},
\"color_temp\": {\"type\": \"string\"}
},
\"required\": [\"brightness\", \"color_temp\"]
}
}]
}"
Khai báo hàm
Khai báo hàm được truyền dưới dạng một công cụ và bao gồm:
type(chuỗi): Phải là"function"đối với các hàm tuỳ chỉnh.name(chuỗi): Tên hàm riêng biệt (sử dụng dấu gạch dưới hoặc quy tắc viết hoa chữ cái đầu của từ thứ hai).description(chuỗi): Giải thích rõ ràng về mục đích của hàm.parameters(đối tượng): Các thông số đầu vào mà hàm này yêu cầu.type(chuỗi): Loại dữ liệu tổng thể, chẳng hạn nhưobject.properties(đối tượng): Các tham số riêng lẻ có loại và nội dung mô tả.required(mảng): Tên tham số bắt buộc.
Gọi hàm bằng mô hình tư duy
Các mô hình Gemini 3 sử dụng quy trình "tư duy" nội bộ giúp cải thiện chức năng gọi. Các SDK sẽ tự động xử lý chữ ký ý tưởng cho bạn.
Gọi hàm song song
Gọi nhiều hàm cùng lúc khi chúng độc lập:
Python
power_disco_ball = {"type": "function", "name": "power_disco_ball", "description": "Powers the disco ball.",
"parameters": {"type": "object", "properties": {"power": {"type": "boolean"}}, "required": ["power"]}}
start_music = {"type": "function", "name": "start_music", "description": "Play music.",
"parameters": {"type": "object", "properties": {"energetic": {"type": "boolean"}, "loud": {"type": "boolean"}}, "required": ["energetic", "loud"]}}
dim_lights = {"type": "function", "name": "dim_lights", "description": "Dim the lights.",
"parameters": {"type": "object", "properties": {"brightness": {"type": "number"}}, "required": ["brightness"]}}
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.6-flash",
input="Turn this place into a party!",
tools=[power_disco_ball, start_music, dim_lights],
generation_config={"tool_choice": "any"},
)
for step in interaction.steps:
if step.type == "function_call":
args = ", ".join(f"{key}={val}" for key, val in step.arguments.items())
print(f"{step.name}({args})")
JavaScript
const powerDiscoBall = { type: 'function', name: 'power_disco_ball', description: 'Powers the disco ball.',
parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } };
const startMusic = { type: 'function', name: 'start_music', description: 'Play music.',
parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } };
const dimLights = { type: 'function', name: 'dim_lights', description: 'Dim the lights.',
parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } };
const interaction = await client.interactions.create({
model: 'gemini-3.6-flash',
input: 'Turn this place into a party!',
tools: [powerDiscoBall, startMusic, dimLights],
generation_config: { tool_choice: 'any' },
});
for (const step of interaction.steps) {
if (step.type === 'function_call') {
console.log(`${step.name}(${JSON.stringify(step.arguments)})`);
}
}
REST
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.6-flash",
"input": "Turn this place into a party!",
"tools": [
{
"type": "function",
"name": "power_disco_ball",
"description": "Powers the disco ball.",
"parameters": {
"type": "object",
"properties": {
"power": {"type": "boolean"}
},
"required": ["power"]
}
},
{
"type": "function",
"name": "start_music",
"description": "Play music.",
"parameters": {
"type": "object",
"properties": {
"energetic": {"type": "boolean"},
"loud": {"type": "boolean"}
},
"required": ["energetic", "loud"]
}
},
{
"type": "function",
"name": "dim_lights",
"description": "Dim the lights.",
"parameters": {
"type": "object",
"properties": {
"brightness": {"type": "number"}
},
"required": ["brightness"]
}
}
]
}'
Gọi hàm thành phần
Nối nhiều lệnh gọi hàm với nhau cho các yêu cầu phức tạp (ví dụ: trước tiên, hãy lấy vị trí, sau đó lấy thông tin thời tiết cho vị trí đó).
Python
get_weather_forecast_declaration = {
"type": "function",
"name": "get_weather_forecast",
"description": "Gets the current weather temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The location"},
},
"required": ["location"],
},
}
set_thermostat_temperature_declaration = {
"type": "function",
"name": "set_thermostat_temperature",
"description": "Sets the thermostat to a desired temperature.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature in Celsius",
},
},
"required": ["temperature"],
},
}
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.6-flash",
input="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.",
tools=[
get_weather_forecast_declaration,
set_thermostat_temperature_declaration,
],
)
for step in interaction.steps:
if step.type == "function_call":
print(f"Function to call: {step.name}")
print(f"Arguments: {step.arguments}")
elif hasattr(step, "content") and step.content:
for part in step.content: