Gemini API 函数调用
函数调用可让您将模型连接到外部工具和 API。该模型不是生成文本响应,而是确定何时调用特定函数并提供执行实际操作所需的参数。这使得模型能够充当自然语言与现实世界的操作和数据之间的桥梁。 函数调用具有 3 主要用例:
- 采取行动: 使用 API 与外部系统交互,例如安排预约、创建发票、发送电子邮件或控制智能家居设备。
- 增长知识: 从数据库、API 和知识库等外部来源访问信息。
- 扩展能力: 使用外部工具执行计算并扩展模型的限制,例如使用计算器或创建图表。
您可以浏览下面这些用例的示例:
安排会议 #
此示例演示如何定义一个函数,在特定时间安排与与会者的会议,允许模型解析用户请求并返回结构化参数以触发外部系统中的操作。
from google import genai
from google.genai import types
# Define the function declaration for the model
schedule_meeting_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"},
"description": "List of people attending the meeting.",
},
"date": {
"type": "string",
"description": "Date of the meeting (e.g., '2024-07-29')",
},
"time": {
"type": "string",
"description": "Time of the meeting (e.g., '15:00')",
},
"topic": {
"type": "string",
"description": "The subject or topic of the meeting.",
},
},
"required": ["attendees", "date", "time", "topic"],
},
}
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[schedule_meeting_function])
config = types.GenerateContentConfig(tools=[tools])
# Send request with function declarations
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning.",
config=config,
)
# Check for a function call
if response.candidates[0].content.parts[0].function_call:
function_call = response.candidates[0].content.parts[0].function_call
print(f"Function to call: {function_call.name}")
print(f"ID: {function_call.id}")
print(f"Arguments: {function_call.args}")
# In a real app, you would call your function here:
# result = schedule_meeting(**function_call.args)
else:
print("No function call found in the response.")
print(response.text)
import { GoogleGenAI, Type } from '@google/genai';
// Configure the client
const ai = new GoogleGenAI({});
// Define the function declaration for the model
const scheduleMeetingFunctionDeclaration = {
name: 'schedule_meeting',
description: 'Schedules a meeting with specified attendees at a given time and date.',
parameters: {
type: Type.OBJECT,
properties: {
attendees: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: 'List of people attending the meeting.',
},
date: {
type: Type.STRING,
description: 'Date of the meeting (e.g., "2024-07-29")',
},
time: {
type: Type.STRING,
description: 'Time of the meeting (e.g., "15:00")',
},
topic: {
type: Type.STRING,
description: 'The subject or topic of the meeting.',
},
},
required: ['attendees', 'date', 'time', 'topic'],
},
};
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-4-hydrogen',
contents: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.',
config: {
tools: [{
functionDeclarations: [scheduleMeetingFunctionDeclaration]
}],
},
});
// Check for function calls in the response
if (response.functionCalls && response.functionCalls.length > 0) {
const functionCall = response.functionCalls[0]; // Assuming one function call
console.log(`Function to call: ${functionCall.name}`);
console.log(`ID: ${functionCall.id}`);
console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
// In a real app, you would call your actual function here:
// const result = await scheduleMeeting(functionCall.args);
} else {
console.log("No function call found in the response.");
console.log(response.text);
}
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Define the function declaration for the model
scheduleMeetingFunc := &genai.FunctionDeclaration{
Name: "schedule_meeting",
Description: "Schedules a meeting with specified attendees at a given time and date.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"attendees": {
Type: genai.TypeArray,
Items: &genai.Schema{Type: genai.TypeString},
Description: "List of people attending the meeting.",
},
"date": {
Type: genai.TypeString,
Description: "Date of the meeting (e.g., '2024-07-29')",
},
"time": {
Type: genai.TypeString,
Description: "Time of the meeting (e.g., '15:00')",
},
"topic": {
Type: genai.TypeString,
Description: "The subject or topic of the meeting.",
},
},
Required: []string{"attendees", "date", "time", "topic"},
},
}
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{FunctionDeclarations: []*genai.FunctionDeclaration{scheduleMeetingFunc}},
},
}
// Send request with function declarations
response, err := client.Models.GenerateContent(
ctx,
"gemini-4-hydrogen",
genai.Text("Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning."),
config,
)
if err != nil {
log.Fatal(err)
}
// Check for a function call
if len(response.FunctionCalls()) > 0 {
functionCall := response.FunctionCalls()[0]
fmt.Printf("Function to call: %s\n", functionCall.Name)
fmt.Printf("ID: %s\n", functionCall.ID)
fmt.Printf("Arguments: %v\n", functionCall.Args)
// In a real app, you would call your function here:
// result := scheduleMeeting(functionCall.Args)
} else {
fmt.Println("No function call found in the response.")
fmt.Println(response.Text())
}
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning."
}
]
}
],
"tools": [
{
"functionDeclarations": [
{
"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"},
"description": "List of people attending the meeting."
},
"date": {
"type": "string",
"description": "Date of the meeting (e.g., '2024-07-29')"
},
"time": {
"type": "string",
"description": "Time of the meeting (e.g., '15:00')"
},
"topic": {
"type": "string",
"description": "The subject or topic of the meeting."
}
},
"required": ["attendees", "date", "time", "topic"]
}
}
]
}
]
}'
获取天气 #
此示例演示如何定义一个函数来检索某个位置的温度数据,使模型能够调用外部 API 来回答需要实时或外部信息的查询。
from google import genai
from google.genai import types
# Define the function declaration for the model
weather_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"],
},
}
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[weather_function])
config = types.GenerateContentConfig(tools=[tools])
# Send request with function declarations
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="What's the temperature in London?",
config=config,
)
# Check for a function call
if response.candidates[0].content.parts[0].function_call:
function_call = response.candidates[0].content.parts[0].function_call
print(f"Function to call: {function_call.name}")
print(f"ID: {function_call.id}")
print(f"Arguments: {function_call.args}")
# In a real app, you would call your function here:
# result = get_current_temperature(**function_call.args)
else:
print("No function call found in the response.")
print(response.text)
import { GoogleGenAI, Type } from '@google/genai';
// Configure the client
const ai = new GoogleGenAI({});
// Define the function declaration for the model
const weatherFunctionDeclaration = {
name: 'get_current_temperature',
description: 'Gets the current temperature for a given location.',
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
description: 'The city name, e.g. San Francisco',
},
},
required: ['location'],
},
};
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-4-hydrogen',
contents: "What's the temperature in London?",
config: {
tools: [{
functionDeclarations: [weatherFunctionDeclaration]
}],
},
});
// Check for function calls in the response
if (response.functionCalls && response.functionCalls.length > 0) {
const functionCall = response.functionCalls[0]; // Assuming one function call
console.log(`Function to call: ${functionCall.name}`);
console.log(`ID: ${functionCall.id}`);
console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
// In a real app, you would call your actual function here:
// const result = await getCurrentTemperature(functionCall.args);
} else {
console.log("No function call found in the response.");
console.log(response.text);
}
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Define the function declaration for the model
weatherFunc := &genai.FunctionDeclaration{
Name: "get_current_temperature",
Description: "Gets the current temperature for a given location.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"location": {
Type: genai.TypeString,
Description: "The city name, e.g. San Francisco",
},
},
Required: []string{"location"},
},
}
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{FunctionDeclarations: []*genai.FunctionDeclaration{weatherFunc}},
},
}
// Send request with function declarations
response, err := client.Models.GenerateContent(
ctx,
"gemini-4-hydrogen",
genai.Text("What's the temperature in London?"),
config,
)
if err != nil {
log.Fatal(err)
}
// Check for a function call
if len(response.FunctionCalls()) > 0 {
functionCall := response.FunctionCalls()[0]
fmt.Printf("Function to call: %s\n", functionCall.Name)
fmt.Printf("ID: %s\n", functionCall.ID)
fmt.Printf("Arguments: %v\n", functionCall.Args)
// In a real app, you would call your function here:
// result := getCurrentTemperature(functionCall.Args)
} else {
fmt.Println("No function call found in the response.")
fmt.Println(response.Text())
}
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "What'\''s the temperature in London?"
}
]
}
],
"tools": [
{
"functionDeclarations": [
{
"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"]
}
}
]
}
]
}'
创建图表 #
此示例展示了如何定义一个从结构化数据生成条形图的函数,演示了模型如何使用外部工具来执行计算或创建可视化资产:
import os
from google import genai
from google.genai import types
# Define the function declaration for the model
create_chart_function = {
"name": "create_bar_chart",
"description": "Creates a bar chart given a title, labels, and corresponding values.",
"parameters": {
"type": "object",
"properties": {
"title": {
"type": "string",
"description": "The title for the chart.",
},
"labels": {
"type": "array",
"items": {"type": "string"},
"description": "List of labels for the data points (e.g., ['Q1', 'Q2', 'Q3']).",
},
"values": {
"type": "array",
"items": {"type": "number"},
"description": "List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).",
},
},
"required": ["title", "labels", "values"],
},
}
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[create_chart_function])
config = types.GenerateContentConfig(tools=[tools])
# Send request with function declarations
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000.",
config=config,
)
# Check for a function call
if response.candidates[0].content.parts[0].function_call:
function_call = response.candidates[0].content.parts[0].function_call
print(f"Function to call: {function_call.name}")
print(f"ID: {function_call.id}")
print(f"Arguments: {function_call.args}")
# In a real app, you would call your function here using a charting library:
# result = create_bar_chart(**function_call.args)
else:
print("No function call found in the response.")
print(response.text)
import { GoogleGenAI, Type } from '@google/genai';
// Configure the client
const ai = new GoogleGenAI({});
// Define the function declaration for the model
const createChartFunctionDeclaration = {
name: 'create_bar_chart',
description: 'Creates a bar chart given a title, labels, and corresponding values.',
parameters: {
type: Type.OBJECT,
properties: {
title: {
type: Type.STRING,
description: 'The title for the chart.',
},
labels: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: 'List of labels for the data points (e.g., ["Q1", "Q2", "Q3"]).',
},
values: {
type: Type.ARRAY,
items: { type: Type.NUMBER },
description: 'List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).',
},
},
required: ['title', 'labels', 'values'],
},
};
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-4-hydrogen',
contents: "Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000.",
config: {
tools: [{
functionDeclarations: [createChartFunctionDeclaration]
}],
},
});
// Check for function calls in the response
if (response.functionCalls && response.functionCalls.length > 0) {
const functionCall = response.functionCalls[0]; // Assuming one function call
console.log(`Function to call: ${functionCall.name}`);
console.log(`ID: ${functionCall.id}`);
console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
// In a real app, you would call your actual function here:
// const result = await createBarChart(functionCall.args);
} else {
console.log("No function call found in the response.");
console.log(response.text);
}
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Define the function declaration for the model
createChartFunc := &genai.FunctionDeclaration{
Name: "create_bar_chart",
Description: "Creates a bar chart given a title, labels, and corresponding values.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"title": {
Type: genai.TypeString,
Description: "The title for the chart.",
},
"labels": {
Type: genai.TypeArray,
Items: &genai.Schema{Type: genai.TypeString},
Description: "List of labels for the data points (e.g., ['Q1', 'Q2', 'Q3']).",
},
"values": {
Type: genai.TypeArray,
Items: &genai.Schema{Type: genai.TypeNumber},
Description: "List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000]).",
},
},
Required: []string{"title", "labels", "values"},
},
}
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{FunctionDeclarations: []*genai.FunctionDeclaration{createChartFunc}},
},
}
// Send request with function declarations
response, err := client.Models.GenerateContent(
ctx,
"gemini-4-hydrogen",
genai.Text("Create a bar chart titled 'Quarterly Sales' with data: Q1: 50000, Q2: 75000, Q3: 60000."),
config,
)
if err != nil {
log.Fatal(err)
}
// Check for a function call
if len(response.FunctionCalls()) > 0 {
functionCall := response.FunctionCalls()[0]
fmt.Printf("Function to call: %s\n", functionCall.Name)
fmt.Printf("ID: %s\n", functionCall.ID)
fmt.Printf("Arguments: %v\n", functionCall.Args)
// In a real app, you would call your function here using a charting library:
// result := createBarChart(functionCall.Args)
} else {
fmt.Println("No function call found in the response.")
fmt.Println(response.Text())
}
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Create a bar chart titled ''Quarterly Sales'' with data: Q1: 50000, Q2: 75000, Q3: 60000."
}
]
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "create_bar_chart",
"description": "Creates a bar chart given a title, labels, and corresponding values.",
"parameters": {
"type": "object",
"properties": {
"title": {
"type": "string",
"description": "The title for the chart."
},
"labels": {
"type": "array",
"items": {"type": "string"},
"description": "List of labels for the data points (e.g., [''Q1'', ''Q2'', ''Q3''])."
},
"values": {
"type": "array",
"items": {"type": "number"},
"description": "List of numerical values corresponding to the labels (e.g., [50000, 75000, 60000])."
}
},
"required": ["title", "labels", "values"]
}
}
]
}
]
}'
函数调用的工作原理 #

函数调用涉及应用程序、模型和外部函数之间的结构化交互。以下是该过程的详细说明:
- 定义函数声明: 在应用程序代码中定义函数声明。函数声明描述了函数的名称、参数和模型的用途。
- 使用函数声明调用 API: 将用户提示连同函数声明一起发送到模型。它分析请求并确定函数调用是否有帮助。如果是这样,它会返回一个结构化 JSON 对象,其中包含函数名称、参数和唯一的
id(这个id对于 Gemini 3 型号,现在始终由 API 返回*)。 - 执行功能代码(您的责任): 模型 不 执行函数本身。您的应用程序负责处理响应并检查函数调用。如果* 是的:提取名称、参数和
id该函数并在您的应用程序中执行相应的函数。
- 否: 该模型提供了对提示的直接文本响应(该流程在示例中不太强调,但是可能的结果)。
- 创建用户友好的响应: 如果执行了函数,则捕获结果并将其发送回模型,确保包含匹配的
id,在随后的对话中。它将使用结果生成最终的、用户友好的响应,其中包含来自函数调用的信息。
此过程可以重复多次,从而实现复杂的交互和工作流程。该模型还支持单轮调用多个函数(并联函数调用),依次(组合函数调用),以及内置的 Gemini 工具(多工具使用).
- 始终映射函数 ID: Gemini 3 现在始终返回唯一的
id与每一个functionCall。包括这个确切的id在你的functionResponse因此模型可以准确地将您的结果映射回原始请求。
步骤 1:定义函数声明 #
在应用程序代码中定义一个函数及其声明,允许用户设置光值并发出 API 请求。该函数可以调用外部服务或API。
# Define a function that the model can call to control smart lights
set_light_values_declaration = {
"name": "set_light_values",
"description": "Sets the brightness and color temperature of a light.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "integer",
"description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
},
"color_temp": {
"type": "string",
"enum": ["daylight", "cool", "warm"],
"description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
},
},
"required": ["brightness", "color_temp"],
},
}
# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
"""Set the brightness and color temperature of a room light. (mock API).
Args:
brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
Returns:
A dictionary containing the set brightness and color temperature.
"""
return {"brightness": brightness, "colorTemperature": color_temp}
import { Type } from '@google/genai';
// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
name: 'set_light_values',
description: 'Sets the brightness and color temperature of a light.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
},
color_temp: {
type: Type.STRING,
enum: ['daylight', 'cool', 'warm'],
description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
},
},
required: ['brightness', 'color_temp'],
},
};
/**
* Set the brightness and color temperature of a room light. (mock API)
* @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
* @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
* @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
return {
brightness: brightness,
colorTemperature: color_temp
};
}
package main
import "google.golang.org/genai"
// Define a function declaration that the model can call to control smart lights
var setLightValuesDeclaration = &genai.FunctionDeclaration{
Name: "set_light_values",
Description: "Sets the brightness and color temperature of a light.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"brightness": {
Type: genai.TypeInteger,
Description: "Light level from 0 to 100. Zero is off and 100 is full brightness",
},
"color_temp": {
Type: genai.TypeString,
Enum: []string{"daylight", "cool", "warm"},
Description: "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
},
},
Required: []string{"brightness", "color_temp"},
},
}
// This is the actual function that would be called based on the model's suggestion
func setLightValues(brightness int, colorTemp string) map[string]any {
return map[string]any{
"brightness": brightness,
"colorTemperature": colorTemp,
}
}
步骤 2:使用函数声明调用模型 #
定义函数声明后,您可以提示模型使用它们。它分析提示符和函数声明并决定是直接响应还是调用函数。如果调用函数,响应对象将包含函数调用建议。
from google.genai import types
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])
# Define user prompt
contents = [
types.Content(
role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
)
]
# Send request with function declarations
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents=contents,
config=config,
)
print(response.candidates[0].content.parts[0].function_call)
import { GoogleGenAI } from '@google/genai';
// Generation config with function declaration
const config = {
tools: [{
functionDeclarations: [setLightValuesFunctionDeclaration]
}]
};
// Configure the client
const ai = new GoogleGenAI({});
// Define user prompt
const contents = [
{
role: 'user',
parts: [{ text: 'Turn the lights down to a romantic level' }]
}
];
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-4-hydrogen',
contents: contents,
config: config
});
console.log(response.functionCalls[0]);
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Generation config with function declaration
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{FunctionDeclarations: []*genai.FunctionDeclaration{setLightValuesDeclaration}},
},
}
// Define user prompt
contents := []*genai.Content{
genai.NewContentFromText("Turn the lights down to a romantic level", genai.RoleUser),
}
// Send request with function declarations
response, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", contents, config)
if err != nil {
log.Fatal(err)
}
fmt.Println(response.FunctionCalls()[0])
然后模型返回一个 functionCall OpenAPI 兼容模式中的对象,指定如何调用一个或多个声明的函数以响应用户的问题。
id='8f2b1a3c' args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
{
id: '8f2b1a3c',
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
&{ID:8f2b1a3c Args:map[brightness:25 color_temp:warm] Name:set_light_values}
步骤3:执行set_light_values函数代码 #
从模型的响应中提取函数调用详细信息,解析参数,然后执行 set_light_values 功能。
# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call
if tool_call.name == "set_light_values":
result = set_light_values(**tool_call.args)
print(f"Function execution result: {result}")
// Extract tool call details
const tool_call = response.functionCalls[0]
let result;
if (tool_call.name === 'set_light_values') {
result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
console.log(`Function execution result: ${JSON.stringify(result)}`);
}
// Extract tool call details
toolCall := response.FunctionCalls()[0]
var result map[string]any
if toolCall.Name == "set_light_values" {
brightness := int(toolCall.Args["brightness"].(float64))
colorTemp := toolCall.Args["color_temp"].(string)
result = setLightValues(brightness, colorTemp)
fmt.Printf("Function execution result: %v\n", result)
}
步骤 4:使用函数结果创建用户友好的响应并再次调用模型 #
最后,将函数执行的结果发送回模型,以便模型可以将此信息合并到对用户的最终响应中。
from google import genai
from google.genai import types
# Create a function response part
function_response_part = types.Part.from_function_response(
name=tool_call.name,
response={"result": result},
id=tool_call.id,
)
# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response
client = genai.Client()
final_response = client.models.generate_content(
model="gemini-4-hydrogen",
config=config,
contents=contents,
)
print(final_response.text)
// Create a function response part
const function_response_part = {
name: tool_call.name,
response: { result },
id: tool_call.id
}
// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });
// Get the final response from the model
const final_response = await ai.models.generateContent({
model: 'gemini-4-hydrogen',
contents: contents,
config: config
});
console.log(final_response.text);
// Create a function response part
functionResponsePart := &genai.Part{
FunctionResponse: &genai.FunctionResponse{
ID: toolCall.ID,
Name: toolCall.Name,
Response: result,
},
}
// Append function call and result of the function execution to contents
contents = append(contents, response.Candidates[0].Content)
contents = append(contents, &genai.Content{
Role: genai.RoleUser,
Parts: []*genai.Part{functionResponsePart},
})
// Get the final response from the model
finalResponse, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", contents, config)
if err != nil {
log.Fatal(err)
}
fmt.Println(finalResponse.Text())
这样就完成了函数调用流程。该模型成功地使用了 set_light_values 函数来执行用户的请求操作。
函数声明 #
当您在提示中实现函数调用时,您创建了一个 tools 对象,其中包含一个或多个 function declarations。您可以使用 JSON 定义函数,特别是使用 选择子集 的 OpenAPI 架构 格式。单个函数声明可以包含以下参数:
name(字符串):函数的唯一名称(get_weather_forecast,send_email)。使用不带空格或特殊字符的描述性名称(使用下划线或驼峰命名法)。description(字符串):对该函数的用途和功能的清晰详细的解释。这对于模型了解何时使用该函数至关重要。请具体说明并提供示例(如果有帮助的话)(“根据位置和可选的当前正在影院播放的电影标题查找影院。”)。parameters(object):定义函数期望的输入参数。 *type(string): 指定整体数据类型,例如object.properties(对象):列出各个参数,每个参数带有:*type(string): 参数的数据类型,如string,integer,boolean, array.description(字符串):参数用途和格式的描述。提供示例和约束(“城市和州,例如“加利福尼亚州旧金山”或邮政编码,例如“95616”。”)。enum(数组,可选):如果参数值来自固定集合,请使用“enum”列出允许的值,而不是仅在说明中描述它们。这提高了准确性(“enum”:[“daylight”,“cool”,“warm”])。required(array):列出函数运行所必需的参数名称的字符串数组。
您还可以构建 FunctionDeclarations 直接使用Python函数 types.FunctionDeclaration.from_callable(client=client, callable=your_function).
函数调用带思维模型 #
Gemini 3和2.5系列型号使用内部 “思考” 通过请求进行推理的过程。这显着提高了函数调用的性能,使模型能够更好地确定何时调用函数以及使用哪些参数。由于 Gemini API 是无状态的,因此模型使用 思想签名 维持多轮对话的上下文。
本节介绍思想签名的高级管理,并且仅在您手动构建 API 请求(例如,通过 REST)或操作对话历史记录时才需要。
如果您正在使用 谷歌 GenAI SDK (我们的官方图书馆),您不需要管理这个过程。 SDK 自动处理必要的步骤,如前面所示 例子.
手动管理对话历史记录 #
如果您手动修改对话历史记录,而不是发送 完成之前的回复 你必须正确处理 thought_signature 包括在模型的回合中。
请遵循以下规则以确保保留模型的上下文:
- 始终发送
thought_signature回到原来的模型Part. - 始终包含准确的
id从function_call在你的function_response因此 API 可以将结果映射到正确的请求。 - 不要合并
Part包含一个签名,而另一个签名不包含签名。这打破了思想的位置背景。 - 不要将两个结合起来
Parts两者都包含签名,因为签名字符串无法合并。
Gemini 3 思想签名#
在 Gemini 3 中,任意 Part 模型响应的可能包含思想签名。虽然我们通常建议返回所有人的签名 Part 类型,回传思想签名对于函数调用是强制的。除非您手动操作对话历史记录,否则 Google GenAI SDK 将自动处理思想签名。
如果您手动操作对话历史记录,请参阅 想法签名 页面,了解有关处理 Gemini 3 思想签名的完整指南和详细信息。
检查思想签名 #
虽然对于实施来说不是必需的,但您可以检查响应以查看 thought_signature 用于调试或教育目的。
import base64
# After receiving a response from a model with thinking enabled
# response = client.models.generate_content(...)
# The signature is attached to the response part containing the function call
part = response.candidates[0].content.parts[0]
if part.thought_signature:
print(base64.b64encode(part.thought_signature).decode("utf-8"))
// After receiving a response from a model with thinking enabled
// const response = await ai.models.generateContent(...)
// The signature is attached to the response part containing the function call
const part = response.candidates[0].content.parts[0];
if (part.thoughtSignature) {
console.log(part.thoughtSignature);
}
// After receiving a response from a model with thinking enabled
// response, err := client.Models.GenerateContent(...)
// The signature is attached to the response part containing the function call
part := response.Candidates[0].Content.Parts[0]
if len(part.ThoughtSignature) > 0 {
fmt.Println(string(part.ThoughtSignature))
}
了解有关思维特征的限制和使用以及一般思维模型的更多信息,请访问 思考 页。
并行函数调用 #
除了单次调用函数调用外,还可以一次调用多个函数。并行函数调用允许您一次执行多个函数,并且在函数彼此不依赖时使用。这在从多个独立来源收集数据的场景中非常有用,例如从不同的数据库检索客户详细信息或检查各个仓库的库存水平或执行多个操作(例如将公寓改造成迪斯科舞厅)。
当模型单轮发起多个函数调用时,不需要返回 function_result 对象的顺序相同 function_call 收到了物品。 Gemini API 使用以下命令将每个结果映射回其相应的调用 id 从模型的输出。这使您可以异步执行函数并在完成时将结果附加到列表中。
power_disco_ball = {
"name": "power_disco_ball",
"description": "Powers the spinning disco ball.",
"parameters": {
"type": "object",
"properties": {
"power": {
"type": "boolean",
"description": "Whether to turn the disco ball on or off.",
}
},
"required": ["power"],
},
}
start_music = {
"name": "start_music",
"description": "Play some music matching the specified parameters.",
"parameters": {
"type": "object",
"properties": {
"energetic": {
"type": "boolean",
"description": "Whether the music is energetic or not.",
},
"loud": {
"type": "boolean",
"description": "Whether the music is loud or not.",
},
},
"required": ["energetic", "loud"],
},
}
dim_lights = {
"name": "dim_lights",
"description": "Dim the lights.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "number",
"description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
}
},
"required": ["brightness"],
},
}
import { Type } from '@google/genai';
const powerDiscoBall = {
name: 'power_disco_ball',
description: 'Powers the spinning disco ball.',
parameters: {
type: Type.OBJECT,
properties: {
power: {
type: Type.BOOLEAN,
description: 'Whether to turn the disco ball on or off.'
}
},
required: ['power']
}
};
const startMusic = {
name: 'start_music',
description: 'Play some music matching the specified parameters.',
parameters: {
type: Type.OBJECT,
properties: {
energetic: {
type: Type.BOOLEAN,
description: 'Whether the music is energetic or not.'
},
loud: {
type: Type.BOOLEAN,
description: 'Whether the music is loud or not.'
}
},
required: ['energetic', 'loud']
}
};
const dimLights = {
name: 'dim_lights',
description: 'Dim the lights.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
}
},
required: ['brightness']
}
};
package main
import "google.golang.org/genai"
var powerDiscoBall = &genai.FunctionDeclaration{
Name: "power_disco_ball",
Description: "Powers the spinning disco ball.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"power": {
Type: genai.TypeBoolean,
Description: "Whether to turn the disco ball on or off.",
},
},
Required: []string{"power"},
},
}
var startMusic = &genai.FunctionDeclaration{
Name: "start_music",
Description: "Play some music matching the specified parameters.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"energetic": {
Type: genai.TypeBoolean,
Description: "Whether the music is energetic or not.",
},
"loud": {
Type: genai.TypeBoolean,
Description: "Whether the music is loud or not.",
},
},
Required: []string{"energetic", "loud"},
},
}
var dimLights = &genai.FunctionDeclaration{
Name: "dim_lights",
Description: "Dim the lights.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"brightness": {
Type: genai.TypeNumber,
Description: "The brightness of the lights, 0.0 is off, 1.0 is full.",
},
},
Required: []string{"brightness"},
},
}
配置函数调用模式以允许使用所有指定的工具。要了解更多信息,您可以阅读 配置函数调用.
from google import genai
from google.genai import types
# Configure the client and tools
client = genai.Client()
house_tools = [
types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
tools=house_tools,
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
# Force the model to call 'any' function, instead of chatting.
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(mode='ANY')
),
)
chat = client.chats.create(model="gemini-4-hydrogen", config=config)
response = chat.send_message("Turn this place into a party!")
# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
print(f"{fn.name}({args}) - ID: {fn.id}")
import { GoogleGenAI } from '@google/genai';
// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];
const config = {
tools: [{
functionDeclarations: houseFns
}],
// Force the model to call 'any' function, instead of chatting.
toolConfig: {
functionCallingConfig: {
mode: 'any'
}
}
};
// Configure the client
const ai = new GoogleGenAI({});
// Create a chat session
const chat = ai.chats.create({
model: 'gemini-4-hydrogen',
config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});
// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
const args = Object.entries(fn.args)
.map(([key, val]) => `${key}=${val}`)
.join(', ');
console.log(`${fn.name}(${args}) - ID: ${fn.id}`);
}
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
houseTools := []*genai.Tool{
{FunctionDeclarations: []*genai.FunctionDeclaration{powerDiscoBall, startMusic, dimLights}},
}
config := &genai.GenerateContentConfig{
Tools: houseTools,
// Force the model to call 'any' function, instead of chatting.
ToolConfig: &genai.ToolConfig{
FunctionCallingConfig: &genai.FunctionCallingConfig{
Mode: genai.FunctionCallingConfigModeAny,
},
},
}
response, err := client.Models.GenerateContent(
ctx,
"gemini-4-hydrogen",
genai.Text("Turn this place into a party!"),
config,
)
if err != nil {
log.Fatal(err)
}
// Print out each of the function calls requested from this single call
fmt.Println("Example 1: Forced function calling")
for _, fn := range response.FunctionCalls() {
fmt.Printf("%s(%v) - ID: %s\n", fn.Name, fn.Args, fn.ID)
}
每个打印结果都反映了模型请求的单个函数调用。要发回结果,请按照请求的顺序包含响应。
Python SDK 支持 自动函数调用,它自动将Python函数转换为声明,为您处理函数调用执行和响应周期。以下是迪斯科用例的示例。
from google import genai
from google.genai import types
# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
"""Powers the spinning disco ball.
Args:
power: Whether to turn the disco ball on or off.
Returns:
A status dictionary indicating the current state.
"""
return {"status": f"Disco ball powered {'on' if power else 'off'}"}
def start_music_impl(energetic: bool, loud: bool) -> dict:
"""Play some music matching the specified parameters.
Args:
energetic: Whether the music is energetic or not.
loud: Whether the music is loud or not.
Returns:
A dictionary containing the music settings.
"""
music_type = "energetic" if energetic else "chill"
volume = "loud" if loud else "quiet"
return {"music_type": music_type, "volume": volume}
def dim_lights_impl(brightness: float) -> dict:
"""Dim the lights.
Args:
brightness: The brightness of the lights, 0.0 is off, 1.0 is full.
Returns:
A dictionary containing the new brightness setting.
"""
return {"brightness": brightness}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)
# Make the request
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="Do everything you need to this place into party!",
config=config,
)
print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!
组合函数调用 #
组合或顺序函数调用允许 Gemini 将多个函数调用链接在一起以满足复杂的请求。例如,要回答“获取我当前位置的温度”,Gemini API 可能首先调用 get_current_location() 函数后跟一个 get_weather() 将位置作为参数的函数。
以下示例演示如何使用 Python SDK 和自动函数调用实现组合函数调用。
此示例使用的自动函数调用功能 google-genai Python SDK。 SDK自动将Python函数转换为所需的模式,在模型请求时执行函数调用,并将结果发送回模型以完成任务。
import os
from google import genai
from google.genai import types
# Example Functions
def get_weather_forecast(location: str) -> dict:
"""Gets the current weather temperature for a given location."""
print(f"Tool Call: get_weather_forecast(location={location})")
# Make API call here
print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
return {"temperature": 25, "unit": "celsius"} # Dummy response
def set_thermostat_temperature(temperature: int) -> dict:
"""Sets the thermostat to a desired temperature."""
print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
# Interact with a thermostat API here
print("Tool Response: {'status': 'success'}")
return {"status": "success"}
# Configure the client and model
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_weather_forecast, set_thermostat_temperature]
)
# Make the request
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
config=config,
)
# Print the final, user-facing response
print(response.text)
预期输出
当您运行代码时,您将看到 SDK 编排函数调用。该模型首先调用 get_weather_forecast,接收温度,然后调用 set_thermostat_temperature 根据提示中的逻辑使用正确的值。
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.
此示例演示如何使用 JavaScript/TypeScript SDK 通过手动执行循环来执行组合函数调用。
import { GoogleGenAI, Type } from "@google/genai";
// Configure the client
const ai = new GoogleGenAI({});
// Example Functions
function get_weather_forecast({ location }) {
console.log(`Tool Call: get_weather_forecast(location=${location})`);
// Make API call here
console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
return { temperature: 25, unit: "celsius" };
}
function set_thermostat_temperature({ temperature }) {
console.log(
`Tool Call: set_thermostat_temperature(temperature=${temperature})`,
);
// Make API call here
console.log("Tool Response: {'status': 'success'}");
return { status: "success" };
}
const toolFunctions = {
get_weather_forecast,
set_thermostat_temperature,
};
const tools = [
{
functionDeclarations: [
{
name: "get_weather_forecast",
description:
"Gets the current weather temperature for a given location.",
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
},
},
required: ["location"],
},
},
{
name: "set_thermostat_temperature",
description: "Sets the thermostat to a desired temperature.",
parameters: {
type: Type.OBJECT,
properties: {
temperature: {
type: Type.NUMBER,
},
},
required: ["temperature"],
},
},
],
},
];
// Prompt for the model
let contents = [
{
role: "user",
parts: [
{
text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
},
],
},
];
// Loop until the model has no more function calls to make
while (true) {
const result = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents,
config: { tools },
});
if (result.functionCalls && result.functionCalls.length > 0) {
const functionCall = result.functionCalls[0];
const { name, args } = functionCall;
if (!toolFunctions[name]) {
throw new Error(`Unknown function call: ${name}`);
}
// Call the function and get the response.
const toolResponse = toolFunctions[name](args);
const functionResponsePart = {
name: functionCall.name,
response: {
result: toolResponse,
},
id: functionCall.id,
};
// Send the function response back to the model.
contents.push({
role: "model",
parts: [
{
functionCall: functionCall,
},
],
});
contents.push({
role: "user",
parts: [
{
functionResponse: functionResponsePart,
},
],
});
} else {
// No more function calls, break the loop.
console.log(result.text);
break;
}
}
预期输出
当您运行代码时,您将看到 SDK 编排函数调用。该模型首先调用 get_weather_forecast,接收温度,然后调用 set_thermostat_temperature 根据提示中的逻辑使用正确的值。
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.
此示例演示如何使用 Go SDK 通过手动执行循环来执行组合函数调用。
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func getWeatherForecast(location string) map[string]any {
fmt.Printf("Tool Call: get_weather_forecast(location=%s)\n", location)
fmt.Println("Tool Response: map[temperature:25 unit:celsius]")
return map[string]any{"temperature": 25, "unit": "celsius"}
}
func setThermostatTemperature(temperature float64) map[string]any {
fmt.Printf("Tool Call: set_thermostat_temperature(temperature=%v)\n", temperature)
fmt.Println("Tool Response: map[status:success]")
return map[string]any{"status": "success"}
}
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
tools := []*genai.Tool{
{
FunctionDeclarations: []*genai.FunctionDeclaration{
{
Name: "get_weather_forecast",
Description: "Gets the current weather temperature for a given location.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"location": {Type: genai.TypeString},
},
Required: []string{"location"},
},
},
{
Name: "set_thermostat_temperature",
Description: "Sets the thermostat to a desired temperature.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"temperature": {Type: genai.TypeNumber},
},
Required: []string{"temperature"},
},
},
},
},
}
config := &genai.GenerateContentConfig{Tools: tools}
contents := []*genai.Content{
genai.NewContentFromText("If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.", genai.RoleUser),
}
for {
result, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", contents, config)
if err != nil {
log.Fatal(err)
}
if len(result.FunctionCalls()) > 0 {
functionCall := result.FunctionCalls()[0]
var toolResponse map[string]any
switch functionCall.Name {
case "get_weather_forecast":
location := functionCall.Args["location"].(string)
toolResponse = getWeatherForecast(location)
case "set_thermostat_temperature":
temperature := functionCall.Args["temperature"].(float64)
toolResponse = setThermostatTemperature(temperature)
default:
log.Fatalf("Unknown function call: %s", functionCall.Name)
}
contents = append(contents, result.Candidates[0].Content)
contents = append(contents, &genai.Content{
Role: genai.RoleUser,
Parts: []*genai.Part{
{
FunctionResponse: &genai.FunctionResponse{
ID: functionCall.ID,
Name: functionCall.Name,
Response: toolResponse,
},
},
},
})
} else {
fmt.Println(result.Text())
break
}
}
}
预期输出
Tool Call: get_weather_forecast(location=London)
Tool Response: map[temperature:25 unit:celsius]
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: map[status:success]
OK. It's 25°C in London, so I've set the thermostat to 20°C.
组合函数调用是原生的 Live API 功能。这意味着 Live API 可以像 Python SDK 一样处理函数调用。
# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}
prompt = """
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
"""
tools = [
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]
await run(prompt, tools=tools, modality="AUDIO")
// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };
const prompt = `
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;
const tools = [
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];
await run(prompt, tools=tools, modality="AUDIO")
函数调用模式 #
Gemini API 允许您控制模型如何使用提供的工具(函数声明)。具体来说,您可以在中设置模式。function_calling_config.
VALIDATED:工具组合的默认模式(当还启用内置工具或结构化输出时)。该模型仅限于预测函数调用或自然语言,并确保函数模式的遵守。如果allowed_function_names未提供,模型会从所有可用的函数声明中进行选择。如果allowed_function_names提供后,模型从允许的函数集中进行选择。此模式减少了格式错误的函数调用(与AUTO模式)。AUTO:仅启用 function_declarations 工具时的默认模式。该模型决定是生成自然语言响应还是根据提示和上下文建议函数调用。ANY:模型被限制为始终预测函数调用并确保函数模式的遵守。如果allowed_function_names未指定,模型可以从任何提供的函数声明中进行选择。如果allowed_function_names作为列表提供,模型只能从该列表中的函数中进行选择。当您需要对每个提示(如果适用)进行函数调用响应时,请使用此模式。NONE: 型号是 禁止 从进行函数调用。这相当于发送一个没有任何函数声明的请求。使用此功能可以暂时禁用函数调用,而无需删除工具定义。
from google.genai import types
# Configure function calling mode
tool_config = types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode="ANY", allowed_function_names=["get_current_temperature"]
)
)
# Create the generation config
config = types.GenerateContentConfig(
tools=[tools], # not defined here.
tool_config=tool_config,
)
import { FunctionCallingConfigMode } from '@google/genai';
// Configure function calling mode
const toolConfig = {
functionCallingConfig: {
mode: FunctionCallingConfigMode.ANY,
allowedFunctionNames: ['get_current_temperature']
}
};
// Create the generation config
const config = {
tools: tools, // not defined here.
toolConfig: toolConfig,
};
// Configure function calling mode
toolConfig := &genai.ToolConfig{
FunctionCallingConfig: &genai.FunctionCallingConfig{
Mode: genai.FunctionCallingConfigModeAny,
AllowedFunctionNames: []string{"get_current_temperature"},
},
}
// Create the generation config
config := &genai.GenerateContentConfig{
Tools: tools, // not defined here.
ToolConfig: toolConfig,
}
自动函数调用(仅限 Python) #
使用Python SDK时,您可以直接提供Python函数作为工具。 SDK 将这些函数转换为声明,管理函数调用执行,并为您处理响应周期。使用类型提示和文档字符串定义您的函数。为了获得最佳结果,建议使用 Google 风格的文档字符串。 然后 SDK 将自动:
- 检测模型的函数调用响应。
- 在代码中调用相应的Python函数。
- 将函数的响应发送回模型。
- 返回模型的最终文本响应。
SDK 目前不会将参数描述解析到生成的函数声明的属性描述槽中。相反,它发送整个文档字符串作为顶级函数描述。
from google import genai
from google.genai import types
# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
"""Gets the current temperature for a given location.
Args:
location: The city and state, e.g. San Francisco, CA
Returns:
A dictionary containing the temperature and unit.
"""
# ... (implementation) ...
return {"temperature": 25, "unit": "Celsius"}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_current_temperature]
) # Pass the function itself
# Make the request
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="What's the temperature in Boston?",
config=config,
)
print(response.text) # The SDK handles the function call and returns the final text
您可以通过以下方式禁用自动函数调用:
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
自动函数模式声明 #
API 能够描述以下任何类型。 Pydantic 类型是允许的,只要其上定义的字段也由允许的类型组成。字典类型(例如 dict[str: int])在这里没有得到很好的支持,不要使用它们。
AllowedType = (
int | float | bool | str | list['AllowedType'] | pydantic.BaseModel)
要查看推断的架构是什么样子,您可以使用以下命令将其转换 from_callable:
from google import genai
from google.genai import types
def multiply(a: float, b: float):
"""Returns a * b."""
return a * b
client = genai.Client()
fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)
# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())
多工具使用:将内置工具与函数调用相结合 #
您可以启用多个工具,将内置工具与函数调用组合在同一请求中。
得益于工具上下文循环功能,Gemini 3 型号可以将内置工具与开箱即用的函数调用结合起来。阅读页面 结合内置工具和函数调用 了解更多。
循环功能在 Gemini 3 型号中处于预览状态。
from google import genai
from google.genai import types
client = genai.Client()
getWeather = {
"name": "getWeather",
"description": "Gets the weather for a requested city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city and state, e.g. Utqiaġvik, Alaska",
},
},
"required": ["city"],
},
}
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="What is the northernmost city in the United States? What's the weather like there today?",
config=types.GenerateContentConfig(
tools=[
types.Tool(
google_search=types.ToolGoogleSearch(), # Built-in tool
function_declarations=[getWeather] # Custom tool
),
],
include_server_side_tool_invocations=True
),
)
history = [
types.Content(
role="user",
parts=[types.Part(text="What is the northernmost city in the United States? What's the weather like there today?")]
),
response.candidates[0].content,
types.Content(
role="user",
parts=[types.Part(
function_response=types.FunctionResponse(
name="getWeather",
response={"response": "Very cold. 22 degrees Fahrenheit."},
id=response.candidates[0].content.parts[2].function_call.id
)
)]
)
]
response_2 = client.models.generate_content(
model="gemini-4-hydrogen",
contents=history,
config=types.GenerateContentConfig(
tools=[
types.Tool(
google_search=types.ToolGoogleSearch(),
function_declarations=[getWeather]
),
],
include_server_side_tool_invocations=True
),
)
import { GoogleGenAI, Type } from '@google/genai';
const client = new GoogleGenAI({});
const getWeather = {
name: "getWeather",
description: "Get the weather in a given location",
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
description: "The city and state, e.g. San Francisco, CA"
}
},
required: ["location"]
}
};
async function run() {
const tools = [
{ googleSearch: {} },
{ functionDeclarations: [getWeather] }
];
const toolConfig = { includeServerSideToolInvocations: true };
const response1 = await client.models.generateContent({
model: "gemini-4-hydrogen",
contents: [{role: "user", parts: [{text: "What is the northernmost city in the United States? What's the weather like there today?"}]}],
config: {
tools: tools,
toolConfig: toolConfig,
},
});
const functionCallId = response1.candidates[0].content.parts.find(p => p.functionCall)?.functionCall?.id;
const history = [
{
role: "user",
parts:[{text: "What is the northernmost city in the United States? What's the weather like there today?"}]
},
response1.candidates[0].content,
{
role: "user",
parts: [{
functionResponse: {
name: "getWeather",
response: {response: "Very cold. 22 degrees Fahrenheit."},
id: functionCallId
}
}]
}
];
const response2 = await client.models.generateContent({
model: "gemini-4-hydrogen",
contents: history,
config: {
tools: tools,
toolConfig: toolConfig,
},
});
}
await run();
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
getWeather := &genai.FunctionDeclaration{
Name: "getWeather",
Description: "Get the weather in a given location",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"location": {
Type: genai.TypeString,
Description: "The city and state, e.g. San Francisco, CA",
},
},
Required: []string{"location"},
},
}
tools := []*genai.Tool{
{GoogleSearch: &genai.GoogleSearch{}},
{FunctionDeclarations: []*genai.FunctionDeclaration{getWeather}},
}
config := &genai.GenerateContentConfig{
Tools: tools,
}
prompt := "What is the northernmost city in the United States? What's the weather like there today?"
response1, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", genai.Text(prompt), config)
if err != nil {
log.Fatal(err)
}
toolCall := response1.FunctionCalls()[0]
history := []*genai.Content{
genai.NewContentFromText(prompt, genai.RoleUser),
response1.Candidates[0].Content,
{
Role: genai.RoleUser,
Parts: []*genai.Part{
{
FunctionResponse: &genai.FunctionResponse{
ID: toolCall.ID,
Name: toolCall.Name,
Response: map[string]any{"response": "Very cold. 22 degrees Fahrenheit."},
},
},
},
},
}
response2, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", history, config)
if err != nil {
log.Fatal(err)
}
fmt.Println(response2.Text())
}
对于 Gemini 3 系列之前的型号,请使用 Live API.
多模态功能响应 #
模型。
对于 Gemini 3 系列模型,您可以在发送给模型的函数响应部分中包含多模态内容。该模型可以在下一轮处理这种多模态内容,以产生更明智的响应。函数响应中的多模态内容支持以下 MIME 类型:
- 图片:
image/png,image/jpeg,image/webp - 文档:
application/pdf,text/plain, 和 Office 和 OpenDocument 文件 (DOCX、DOC、DOTX、ODT、PPTX、PPT、ODP、XLSX、XLS、ODS) - 音频: 支持的音频格式
- 视频: 支持的视频格式
函数响应中的文件的处理方式与常规用户部分中的同一文件的处理方式相同。如果部件使用不受支持的 MIME 类型,则 API 返回 400 INVALID_ARGUMENT 命名字段并列出可接受的类型的错误。
要在函数响应中包含多模态数据,请将其作为嵌套在 functionResponse 部分。每个多式联运部分必须包含 inlineData (原始字节)或 fileData (文件 URI,例如 Files API URI)。参见 通过 URI 返回文件 举个例子。如果您从结构化中引用多模态零件 response 字段,它必须包含唯一的 displayName.
您还可以从结构化中引用多模态零件 response 的领域 functionResponse 部分使用 JSON 参考格式 {"$ref": "<displayName>"}。该模型在处理响应时用多模态内容替代参考。每个 displayName 只能在结构化中引用一次 response 场。
以下示例显示一条消息,其中包含 functionResponse 对于一个名为 get_image 以及包含图像数据的嵌套部分 displayName: "instrument.jpg"。的 functionResponse's response 字段引用此图像部分:
from google import genai
from google.genai import types
import requests
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., 'instrument')."
}
},
"required": ["item_name"],
},
)
tool_config = types.Tool(function_declarations=[get_image_declaration])
# 2. Send a message that triggers the tool
prompt = "Show me the instrument I ordered last month."
response_1 = client.models.generate_content(
model="gemini-4-hydrogen",
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": "instrument.jpg"},
}
image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content
function_response_multimodal_data = types.FunctionResponsePart(
inline_data=types.FunctionResponseBlob(
mime_type="image/jpeg",
display_name="instrument.jpg",
data=image_bytes,
)
)
# 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="user",
parts=[
types.Part(
function_response=types.FunctionResponse(
id=function_call.id,
name=function_call.name,
response=function_response_data,
parts=[function_response_multimodal_data],
)
)
],
)
]
response_2 = client.models.generate_content(
model="gemini-4-hydrogen",
contents=history,
config=types.GenerateContentConfig(
tools=[tool_config],
thinking_config=types.ThinkingConfig(include_thoughts=True)
),
)
print(f"\nFinal model response: {response_2.text}")
import { GoogleGenAI, Type } from '@google/genai';
const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// This is a manual, two turn multimodal function calling workflow:
// 1. Define the function tool
const getImageDeclaration = {
name: 'get_image',
description: 'Retrieves the image file reference for a specific order item.',
parameters: {
type: Type.OBJECT,
properties: {
item_name: {
type: Type.STRING,
description: "The name or description of the item ordered (e.g., 'instrument').",
},
},
required: ['item_name'],
},
};
const toolConfig = {
functionDeclarations: [getImageDeclaration],
};
// 2. Send a message that triggers the tool
const prompt = 'Show me the instrument I ordered last month.';
const response1 = await client.models.generateContent({
model: 'gemini-4-hydrogen',
contents: prompt,
config: {
tools: [toolConfig],
},
});
// 3. Handle the function call
const functionCall = response1.functionCalls[0];
const requestedItem = functionCall.args.item_name;
console.log(`Model wants to call: ${functionCall.name}`);
// Execute your tool (e.g., call an API)
// (This is a mock response for the example)
console.log(`Calling external tool for: ${requestedItem}`);
const functionResponseData = {
image_ref: { $ref: 'instrument.jpg' },
};
const imageUrl = "https://goo.gle/instrument-img";
const response = await fetch(imageUrl);
const imageArrayBuffer = await response.arrayBuffer();
const base64ImageData = Buffer.from(imageArrayBuffer).toString('base64');
const functionResponseMultimodalData = {
inlineData: {
mimeType: 'image/jpeg',
displayName: 'instrument.jpg',
data: base64ImageData,
},
};
// 4. Send the tool's result back
// Append this turn's messages to history for a final response.
const history = [
{ role: 'user', parts: [{ text: prompt }] },
response1.candidates[0].content,
{
role: 'user',
parts: [
{
functionResponse: {
id: functionCall.id,
name: functionCall.name,
response: functionResponseData,
parts: [functionResponseMultimodalData]
},
},
],
},
];
const response2 = await client.models.generateContent({
model: 'gemini-4-hydrogen',
contents: history,
config: {
tools: [toolConfig],
thinkingConfig: { includeThoughts: true },
},
});
console.log(`\nFinal model response: ${response2.text}`);
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// 1. Define the function tool
getImageDeclaration := &genai.FunctionDeclaration{
Name: "get_image",
Description: "Retrieves the image file reference for a specific order item.",
Parameters: &genai.Schema{
Type: genai.TypeObject,
Properties: map[string]*genai.Schema{
"item_name": {
Type: genai.TypeString,
Description: "The name or description of the item ordered (e.g., 'instrument').",
},
},
Required: []string{"item_name"},
},
}
tools := []*genai.Tool{
{FunctionDeclarations: []*genai.FunctionDeclaration{getImageDeclaration}},
}
// 2. Send a message that triggers the tool
prompt := "Show me the instrument I ordered last month."
response1, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", genai.Text(prompt), &genai.GenerateContentConfig{
Tools: tools,
})
if err != nil {
log.Fatal(err)
}
// 3. Handle the function call
functionCall := response1.FunctionCalls()[0]
requestedItem := functionCall.Args["item_name"]
fmt.Printf("Model wants to call: %s\n", functionCall.Name)
fmt.Printf("Calling external tool for: %v\n", requestedItem)
resp, err := http.Get("https://goo.gle/instrument-img")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
imageBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
functionResponseData := map[string]any{
"image_ref": map[string]any{"$ref": "instrument.jpg"},
}
functionResponseMultimodalData := &genai.FunctionResponsePart{
InlineData: &genai.FunctionResponseBlob{
MIMEType: "image/jpeg",
DisplayName: "instrument.jpg",
Data: imageBytes,
},
}
// 4. Send the tool's result back
history := []*genai.Content{
genai.NewContentFromText(prompt, genai.RoleUser),
response1.Candidates[0].Content,
{
Role: genai.RoleUser,
Parts: []*genai.Part{
{
FunctionResponse: &genai.FunctionResponse{
ID: functionCall.ID,
Name: functionCall.Name,
Response: functionResponseData,
Parts: []*genai.FunctionResponsePart{functionResponseMultimodalData},
},
},
},
},
}
response2, err := client.Models.GenerateContent(ctx, "gemini-4-hydrogen", history, &genai.GenerateContentConfig{
Tools: tools,
ThinkingConfig: &genai.ThinkingConfig{
IncludeThoughts: true,
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("\nFinal model response: %s\n", response2.Text())
}
IMG_URL="https://goo.gle/instrument-img"
MIME_TYPE=$(curl -sIL "$IMG_URL" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\r$//' | head -n 1)
if [[ -z "$MIME_TYPE" || ! "$MIME_TYPE" == image/* ]]; then
MIME_TYPE="image/jpeg"
fi
# Check for macOS
if [[ "$(uname)" == "Darwin" ]]; then
IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -b 0)
elif [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
IMAGE_B64=$(curl -sL "$IMG_URL" | base64)
else
IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -w0)
fi
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
...,
{
"role": "user",
"parts": [
{
"functionResponse": {
"name": "get_image",
"id": "UNIQUE_CALL_ID_HERE",
"response": {
"image_ref": {
"$ref": "instrument.jpg"
}
},
"parts": [
{
"inlineData": {
"displayName": "instrument.jpg",
"mimeType":"'"$MIME_TYPE"'",
"data": "'"$IMAGE_B64"'"
}
}
]
}
}
]
}
]
}'
通过 URI 返回文件 #
内联数据计入请求大小限制。对于大文件,例如视频、长音频或多页文档,请使用 Files API 并返回其 URI fileData 而不是内联字节。 fileData 接受函数响应中支持的每种 MIME 类型。
以下示例显示了一个 view_file 通过 Files API URI 返回 PowerPoint 演示文稿的工具:
from google import genai
from google.genai import types
client = genai.Client()
# `function_call` is the function call from the model's previous response.
# Your tool uploads the file and returns its URI.
deck = client.files.upload(
file="deck.pptx",
config={"mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
)
function_response_part = types.Part(
function_response=types.FunctionResponse(
id=function_call.id,
name=function_call.name,
response={"status": "ok", "file": {"$ref": "deck.pptx"}},
parts=[
types.FunctionResponsePart(
file_data=types.FunctionResponseFileData(
file_uri=deck.uri,
mime_type=deck.mime_type,
display_name="deck.pptx",
)
)
],
)
)
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// `functionCall` is the function call from the model's previous response.
// Your tool uploads the file and returns its URI.
const deck = await client.files.upload({
file: 'deck.pptx',
config: { mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' },
});
const functionResponsePart = {
functionResponse: {
id: functionCall.id,
name: functionCall.name,
response: { status: 'ok', file: { $ref: 'deck.pptx' } },
parts: [
{
fileData: {
fileUri: deck.uri,
mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
displayName: 'deck.pptx',
},
},
],
},
};
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
...,
{
"role": "user",
"parts": [
{
"functionResponse": {
"name": "view_file",
"id": "UNIQUE_CALL_ID_HERE",
"response": {
"status": "ok",
"file": {"$ref": "deck.pptx"}
},
"parts": [
{
"fileData": {
"fileUri": "https://generativelanguage.googleapis.com/v1beta/files/FILE_ID",
"mimeType": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"displayName": "deck.pptx"
}
}
]
}
}
]
}
]
}'
设置视频的处理模式 #
对于函数响应中的视频部分,您可以设置 mediaProcessing 选择模型处理视频的方式: STATIC 或 AGENTIC。如果您不设置它,则应用与常规部分中的视频相同的默认值。仅在视频部分设置此字段。有关每种模式的详细信息,请参见 智能体视频理解.
以下示例通过 URI 返回安全摄像头剪辑,并要求模型以代理方式检查它:
clip = client.files.upload(file="backdoor_1410.mp4", config={"mime_type": "video/mp4"})
function_response_part = types.Part(
function_response=types.FunctionResponse(
id=function_call.id,
name=function_call.name,
response={"status": "recording_found", "clip": {"$ref": "backdoor_1410.mp4"}},
parts=[
types.FunctionResponsePart(
file_data=types.FunctionResponseFileData(
file_uri=clip.uri,
mime_type="video/mp4",
display_name="backdoor_1410.mp4",
),
media_processing=types.MediaProcessing.AGENTIC,
)
],
)
)
const clip = await client.files.upload({
file: 'backdoor_1410.mp4',
config: { mimeType: 'video/mp4' },
});
const functionResponsePart = {
functionResponse: {
id: functionCall.id,
name: functionCall.name,
response: { status: 'recording_found', clip: { $ref: 'backdoor_1410.mp4' } },
parts: [
{
fileData: {
fileUri: clip.uri,
mimeType: 'video/mp4',
displayName: 'backdoor_1410.mp4',
},
mediaProcessing: 'AGENTIC',
},
],
},
};
{
"functionResponse": {
"name": "fetch_security_recording",
"id": "UNIQUE_CALL_ID_HERE",
"response": {
"status": "recording_found",
"clip": {"$ref": "backdoor_1410.mp4"}
},
"parts": [
{
"fileData": {
"fileUri": "https://generativelanguage.googleapis.com/v1beta/files/FILE_ID",
"mimeType": "video/mp4",
"displayName": "backdoor_1410.mp4"
},
"mediaProcessing": "AGENTIC"
}
]
}
}
当模型处理工具返回的视频时 AGENTIC 模式,响应包含相同的 MEDIA_PROCESSING 对于用户提供的视频,工具调用和工具响应部分。在下一轮中将完整响应作为历史记录传回。
函数调用具有结构化输出 #
对于 Gemini 4 和 Gemini 3 系列型号,您可以将函数调用与 结构化输出。这使得模型可以预测符合特定模式的函数调用或输出。因此,当模型不生成函数调用时,您会收到格式一致的响应。
模型上下文协议 (MCP) #
Model Context Protocol (MCP) 是一个用于将人工智能应用程序与外部工具和数据连接起来的开放标准。 MCP 为模型提供访问上下文的通用协议,例如函数(工具)、数据源(资源)或预定义提示。
Gemini SDK 内置了对 MCP 的支持,减少了样板代码并提供 自动工具调用 适用于 MCP 工具。当模型生成 MCP 工具调用时,Python 和 JavaScript 客户端 SDK 可以自动执行 MCP 工具,并在后续请求中将响应发送回模型,继续此循环,直到模型不再进行工具调用。
在这里,您可以找到如何将本地 MCP 服务器与 Gemini 一起使用的示例,以及 mcp SDK。
确保最新版本 mcp SDK 安装在您选择的平台上。
pip install mcp
注意:Python支持自动调用工具,通过传入 ClientSession 进入 tools 参数。如果你想禁用它,你可以提供 automatic_function_calling 与残疾人 True.
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai
client = genai.Client()
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=["-y", "@philschmid/weather-mcp"], # MCP Server
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Prompt to get the weather for the current day in London.
prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"
# Initialize the connection between client and server
await session.initialize()
# Send request to the model with MCP function declarations
response = await client.aio.models.generate_content(
model="gemini-4-hydrogen",
contents=prompt,
config=genai.types.GenerateContentConfig(
tools=[session], # uses the session, will automatically call the tool
# Uncomment if you **don't** want the SDK to automatically call the tool
# automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
# disable=True
# ),
),
)
print(response.text)
# Start the asyncio event loop and run the main function
asyncio.run(run())
确保最新版本 mcp SDK 安装在您选择的平台上。
npm install @modelcontextprotocol/sdk
注意:JavaScript 通过包装来支持自动工具调用 client 使用 mcpToTool。如果你想禁用它,你可以提供 automaticFunctionCalling 与残疾人 true.
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
command: "npx", // Executable
args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});
const client = new Client(
{
name: "example-client",
version: "1.0.0"
}
);
// Configure the client
const ai = new GoogleGenAI({});
// Initialize the connection between client and server
await client.connect(serverParams);
// Send request to the model with MCP tools
const response = await ai.models.generateContent({
model: "gemini-4-hydrogen",
contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
config: {
tools: [mcpToTool(client)], // uses the session, will automatically call the tool
// Uncomment if you **don't** want the sdk to automatically call the tool
// automaticFunctionCalling: {
// disable: true,
// },
},
});
console.log(response.text)
// Close the connection
await client.close();
内置 MCP 支持的限制 #
内置 MCP 支持 实验性的 我们的 SDK 中包含此功能,并且具有以下限制:
- 仅支持工具,不支持资源或提示
- 它可用于 Python 和 JavaScript/TypeScript SDK。
- 未来版本中可能会发生重大更改。
如果 MCP 服务器的手动集成限制了您正在构建的内容,那么手动集成始终是一种选择。
支持的模型 #
本节列出了型号及其函数调用功能。不包括实验模型。您可以在以下位置找到全面的功能概述: 型号概览 页。
| 模型 | 函数调用 | 并行函数调用 | 组合函数调用 |
|---|---|---|---|
| Gemini 4 Carbon | ✔️ | ✔️ | ✔️ |
| Gemini 4 Argon | ✔️ | ✔️ | ✔️ |
| Gemini 4 Hydrogen | ✔️ | ✔️ | ✔️ |
| Gemini 3.8 Flash | ✔️ | ✔️ | ✔️ |
| Gemini 3.6 Flash | ✔️ | ✔️ | ✔️ |
| Gemini 3.5 Flash-Lite | ✔️ | ✔️ | ✔️ |
| Gemini 3.1 Pro Preview | ✔️ | ✔️ | ✔️ |
| Gemini 3.1 Flash-Lite | ✔️ | ✔️ | ✔️ |
| Gemini 2.5 Pro | ✔️ | ✔️ | ✔️ |
| Gemini 2.5 Flash | ✔️ | ✔️ | ✔️ |
| Gemini 2.5 Flash-Lite | ✔️ | ✔️ | ✔️ |
最佳实践 #
功能及参数说明: 您的描述要极其清晰和具体。该模型依靠这些来选择正确的函数并提供适当的参数。
命名: 使用描述性函数名称(不含空格、句点或破折号)。
强类型: 使用特定类型(整数、字符串、枚举)作为参数以减少错误。如果参数的有效值有限,请使用枚举。
工具选择: 虽然模型可以使用任意数量的工具,但提供太多工具会增加选择不正确或次优工具的风险。为了获得最佳结果,旨在仅提供与上下文或任务相关的工具,理想情况下将活动集保持在 10-20. 的最大值。如果您拥有大量工具,请考虑基于对话上下文进行动态工具选择。
及时工程:
提供上下文:告诉模型其角色(例如,“你是一位有用的天气助手。”)。
给出说明:指定如何以及何时使用函数(例如,“不要猜测日期;始终使用未来日期进行预测。”)。
鼓励澄清:指示模型在需要时提出澄清问题。
温度: 使用低温(例如 0)可实现更具确定性和可靠性的函数调用。
验证: 如果函数调用具有重大后果(例如,下订单),请在执行之前与用户验证该调用。
检查完成原因: 始终检查
finishReason在模型的响应中处理模型无法生成有效函数调用的情况。错误处理:在函数中实现强大的错误处理,以优雅地处理意外输入或 API 故障。返回信息丰富的错误消息,模型可以使用这些消息来生成对用户有用的响应。
安全性: 调用外部API时请注意安全。使用适当的身份验证和授权机制。避免在函数调用中暴露敏感数据。
代币限制: 功能描述和参数计入您的输入 token 限制。如果您达到了 token 限制,请考虑限制函数的数量或描述的长度,将复杂的任务分解为更小、更集中的函数集。
bash 和自定义工具的混合 对于那些混合使用 bash 和自定义工具进行构建的人来说,Gemini 3.1 Pro Preview 附带了一个单独的端点,可通过 API 访问,称为
gemini-3.1-pro-preview-customtools.
工具前文本要求的解决方法 #
问题: 如果您的提示要求模型输出结构化文本(XML、YAML、JSON 等)(例如, <UPDATE>...</UPDATE>) 在进行工具调用之前,工具调用有时可能会失败,并显示 Malformed_Function_Call.
解决方案: 以下解决方法可以解决此问题:
- 首选: 指示模型将其预工具注释放入专用的
update()函数调用而不是原始文本(详细信息如下)。 - 指示模型将注释写入 Markdown 标题(
# UPDATE,## PLAN) 而不是结构化文本。 - 不要求模型在工具调用之前输出文本。
首选解决方法:将工作笔记包含在专用函数调用中 #
而不是原来的指令:
Before calling a tool, in every response you MUST first output a single `<UPDATE>` part as specified, don't skip this part or any of required sub-tags within `<UPDATE>`.
使用此更新的说明:
Before calling any other tool, in every response you MUST first call `update` with all required parameters (previous_step, plan, next_step, external).
并更新所有对旧版本的引用 <UPDATE> 客户要求的 XML 格式。然后为更新函数添加相应的函数声明:
{
"name": "update",
"description": "Update working notes (previous step analysis, plan, next step, external note).",
"parameters": {
"type": "OBJECT",
"properties": {
"previous_step": {
"type": "STRING",
"description": "Key findings and outcomes since the previous step."
},
"plan": {
"type": "STRING",
"description": "The current status of the plan."
},
"next_step": {
"type": "STRING",
"description": "Brief explanation of the immediate next action according to the plan."
},
"external": {
"type": "STRING",
"description": "A short, plain-language note shown to the User about what you are ABOUT TO DO next."
}
},
"required": [
"previous_step",
"plan",
"next_step",
"external"
]
}
}
然后模型将在同一步骤中进行两次调用: update() 替换结构化 XML 的调用以及它想要进行的实际函数调用。
注意事项和限制 #
- 函数调用部分的定位:使用自定义函数声明时 与内置工具一起 (如 Google 搜索),该模型可能会返回以下内容的混合
functionCall,toolCall, 和toolResponse单圈零件。因此,不要假设functionCall将始终是零件数组中的最后一项。如果您手动解析 JSON 响应,请始终迭代部件数组,而不是依赖位置。 - 只有一个 OpenAPI 模式的子集 是支持的。
- 对于
ANY模式,非常大或深度嵌套的模式可能会被拒绝。 - Python 中支持的参数类型是有限的。
- 自动函数调用仅是 Python SDK 功能。
简化复杂的函数模式 #
当你使用 ANY 模式或定义复杂参数和响应模式,API 将您的函数声明编译到约束 token 生成的状态机中。该状态机强制限制总状态、分支路径和嵌套深度。如果您的工具的综合复杂性超出了这些限制,API 将拒绝该请求,并显示 400 INVALID_ARGUMENT 错误。
要修复模式拒绝错误,请减少声明的结构深度和分支因子。您可以通过多种方式简化复杂的函数模式:
- 拆分大型工具集并将规则移至描述: 约束解码会一起评估所有声明的工具。限制单个请求中的功能数量,并将整体功能拆分为更小的、集中的工具。将复杂的格式规则移至字段中
description属性或系统指令,指导模型而不扩展语法。 - 展平嵌套对象和绑定递归: 用更扁平的结构替换深度嵌套的对象层次结构。如果你使用
$defs和$ref对于递归类型,使递归引用可选或可为空。避免通过所需的属性或数组进行递归minItems大于零。 - 减少可选字段、枚举和联合的分支: 可选属性,
enum价值观,以及anyOf分支乘以输出语法中的分支路径。将属性标记为required在可能的情况下并允许null当字段可以为空时的值。修剪大enum列出并简化anyOf联合,或在提示中包含约束(例如,使用 Pydantic 架构)作为较软的限制。 - 缩短属性名称并删除数组边界: 属性键消耗与其字符长度成比例的状态。数组边界例如
minItems和maxItems还为每个计数位置复制项目架构。使用简洁的属性名称,删除未使用的字段,并在提示中包含数组边界(例如,使用 Pydantic 架构)作为更软的限制,或者检查应用程序代码中的数组长度。