API 参考Google 兼容
函数调用
Gemini Function Calling API - 让 Gemini Pro 调用外部工具和 API。构建 AI Agent,实现自动化工作流和集成。
函数调用(工具)
函数调用允许 Gemini 模型通过生成结构化的函数调用来与外部系统交互。模型不会直接执行函数——它只生成参数,由您的代码来执行。
支持的模型: 所有 Gemini 1.5+ 模型都支持函数调用。
工作原理
- 使用 JSON Schema 定义函数
- 将定义与请求一起发送
- 模型决定是否/调用哪个函数
- 模型生成函数参数
- 您的代码执行函数
- 将结果发送回模型
定义函数
curl -X POST "https://api.uniterouter.ai/v1beta/models/gemini-2.0-flash:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $UNITEROUTER_API_KEY" \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "东京的天气怎么样?"}]
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "获取某个位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如东京、纽约"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["location"]
}
}
]
}
]
}'import google.generativeai as genai
genai.configure(
api_key="your_uniterouter_api_key",
transport="rest",
client_options={"api_endpoint": "api.uniterouter.ai"}
)
# 定义函数
def get_weather(location: str, unit: str = "celsius") -> dict:
"""获取某个位置的天气(模拟实现)"""
return {
"location": location,
"temperature": 22,
"unit": unit,
"condition": "晴天"
}
# 创建带工具的模型
model = genai.GenerativeModel(
"gemini-2.0-flash",
tools=[get_weather]
)
# 开始对话
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message("东京的天气怎么样?")
print(response.text)import { GoogleGenerativeAI, FunctionDeclarationSchemaType } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("your_uniterouter_api_key", {
baseUrl: "https://api.uniterouter.ai"
});
const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash",
tools: [{
functionDeclarations: [{
name: "get_weather",
description: "获取某个位置的当前天气",
parameters: {
type: FunctionDeclarationSchemaType.OBJECT,
properties: {
location: {
type: FunctionDeclarationSchemaType.STRING,
description: "城市名称"
},
unit: {
type: FunctionDeclarationSchemaType.STRING,
enum: ["celsius", "fahrenheit"]
}
},
required: ["location"]
}
}]
}]
});
const result = await model.generateContent("东京的天气怎么样?");
const call = result.response.functionCalls()?.[0];
if (call) {
console.log("函数:", call.name);
console.log("参数:", call.args);
}函数调用响应
当模型决定调用函数时:
{
"candidates": [
{
"content": {
"parts": [
{
"functionCall": {
"name": "get_weather",
"args": {
"location": "东京",
"unit": "celsius"
}
}
}
],
"role": "model"
}
}
]
}发送函数结果
执行函数后,将结果发送回模型:
# 执行函数
result = get_weather("东京", "celsius")
# 发送结果回模型
response = chat.send_message(
genai.protos.Content(
parts=[
genai.protos.Part(
function_response=genai.protos.FunctionResponse(
name="get_weather",
response={"result": result}
)
)
]
)
)
print(response.text) # "东京的天气是22°C,晴天。"工具配置
控制函数调用行为:
{
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO",
"allowedFunctionNames": ["get_weather", "get_time"]
}
}
}| 模式 | 描述 |
|---|---|
AUTO | 模型决定何时调用函数 |
ANY | 模型必须至少调用一个函数 |
NONE | 禁用函数调用 |
多个函数
tools = [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "获取当前天气",
"parameters": {...}
},
{
"name": "get_time",
"description": "获取某个时区的当前时间",
"parameters": {...}
},
{
"name": "search_web",
"description": "搜索网络信息",
"parameters": {...}
}
]
}
]并行函数调用
Gemini 可以并行调用多个函数:
{
"candidates": [{
"content": {
"parts": [
{
"functionCall": {
"name": "get_weather",
"args": {"location": "东京"}
}
},
{
"functionCall": {
"name": "get_weather",
"args": {"location": "纽约"}
}
}
]
}
}]
}最佳实践
- 清晰的描述 - 编写详细的函数和参数描述
- 使用枚举 - 尽可能约束参数值
- 处理错误 - 始终优雅地处理函数执行错误
- 验证输入 - 执行函数前验证参数
- 保持简单 - 少量专注的函数比许多通用函数效果更好
相关文档
How is this guide?