Phase 1 · Agent 基础

Gemini API 函数调用 | Google AI 开发者

其他·2026/7/21·8 阅读

Gemini API 函数调用 | Google AI 开发者

来源 (中文翻译版): https://ai.google.dev/gemini-api/docs/function-calling 抓取时间: 2026-07-21 16:19:00


Interactions API现在已经正式发布。我们建议使用此 API 来访问所有最新功能和模型。

发送反馈

Gemini API 函数调用

注意: 本页版本涵盖了 Interactions API。你可以使用本页上的切换按钮切换到本页的 generateContent API 版本

函数调用允许你将模型连接到外部工具和 API。模型不是生成文本响应,而是决定何时调用特定函数,并提供执行现实世界操作所需的必要参数。这允许模型充当自然语言和现实世界操作与数据之间的桥梁。函数调用有 3 个主要用例:

  • 采取行动: 使用 API 与外部系统交互,如安排会议、创建发票、发送电子邮件或控制智能家居设备。
  • 增强知识: 从数据库、API 和知识库等外部来源访问信息。
  • 扩展功能: 使用外部工具执行计算并扩展模型的局限性,如使用计算器或创建图表。

你可以浏览以下这些用例的示例:

安排会议

此示例显示如何定义一个在特定时间与与会者安排会议的函数,允许模型解析用户请求并返回结构化参数以触发外部系统中的操作。

Python

from google import genai

schedule_meeting_function = {
    "type": "function",
    "name": "schedule_meeting",
    "description": "在给定时间安排有指定与会者的会议。",
    "parameters": {
        "type": "object",
        "properties": {
            "attendees": {"type": "array", "items": {"type": "string"}},
            "date": {"type": "string", "description": "日期(如 '2024-07-29')"},
            "time": {"type": "string", "description": "时间(如 '15:00')"},
            "topic": {"type": "string", "description": "会议主题。"},
        },
        "required": ["attendees", "date", "time", "topic"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.5-flash",
    input="安排 Bob 和 Alice 在 2025 年 3 月 14 日上午 10 点讨论第三季度计划。",
    tools=[{"type": "function", **schedule_meeting_function}],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"要调用的函数: {step.name}")
        print(f"参数: {step.arguments}")

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const scheduleMeetingFunction = {
  type: 'function',
  name: 'schedule_meeting',
  description: '在给定时间安排有指定与会者的会议。',
  parameters: {
    type: 'object',
    properties: {
      attendees: { type: 'array', items: { type: 'string' } },
      date: { type: 'string', description: '日期(如 "2024-07-29")' },
      time: { type: 'string', description: '时间(如 "15:00")' },
      topic: { type: 'string', description: '会议主题。' },
    },
    required: ['attendees', 'date', 'time', 'topic'],
  },
};

const interaction = await client.interactions.create({
  model: 'gemini-3.5-flash',
  input: '安排 Bob 和 Alice 在 2025 年 3 月 27 日上午 10 点讨论第三季度计划。',
  tools: [scheduleMeetingFunction],
});

for (const step of interaction.steps) {
  if (step.type === 'function_call') {
    console.log(`要调用的函数: ${step.name}`);
    console.log(`参数: ${JSON.stringify(step.arguments)}`);
  }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "安排 Bob 和 Alice 在 2025 年 3 月 27 日上午 10 点讨论第三季度计划。",
    "tools": [{
        "type": "function",
        "name": "schedule_meeting",
        "description": "在给定时间安排有指定与会者的会议。",
        "parameters": {
          "type": "object",
          "properties": {
            "attendees": {"type": "array", "items": {"type": "string"}},
            "date": {"type": "string"},
            "time": {"type": "string"},
            "topic": {"type": "string"}
          },
          "required": ["attendees", "date", "time", "topic"]
        }
    }]
  }'

获取天气

此示例显示如何定义一个获取位置温度数据的函数,允许模型调用外部 API 来回答需要实时或外部信息的查询。

Python

from google import genai

weather_function = {
    "type": "function",
    "name": "get_current_temperature",
    "description": "获取给定位置的当前温度。",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "城市名称,如旧金山",
            },
        },
        "required": ["location"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.5-flash",
    input="伦敦的温度是多少?",
    tools=[weather_function],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"要调用的函数: {step.name}")
        print(f"参数: {step.arguments}")

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const weatherFunctionDeclaration = {
  type: 'function',
  name: 'get_current_temperature',
  description: '获取给定位置的当前温度。',
  parameters: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: '城市名称,如旧金山',
      },
    },
    required: ['location'],
  },
};

const interaction = await client.interactions.create({
  model: 'gemini-3.5-flash',
  input: "伦敦的温度是多少?",
  tools: [weatherFunctionDeclaration],
});

for (const step of interaction.steps) {
  if (step.type === 'function_call') {
    console.log(`要调用的函数: ${step.name}`);
    console.log(`参数: ${JSON.stringify(step.arguments)}`);
  }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "伦敦的温度是多少?",
    "tools": [{
      "type": "function",
      "name": "get_current_temperature",
      "description": "获取给定位置的当前温度。",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "城市名称"}
        },
        "required": ["location"]
      }
    }]
  }'

创建图表

此示例显示如何定义一个从结构化数据生成条形图的函数,演示模型如何使用外部工具执行计算或创建视觉资产:

Python

from google import genai

create_chart_function = {
    "type": "function",
    "name": "create_bar_chart",
    "description": "根据标题、标签和值创建条形图。",
    "parameters": {
        "type": "object",
        "properties": {
            "title": {"type": "string", "description": "图表的标题。"},
            "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.5-flash",
    input="创建一个标题为 '季度销售额' 的条形图,Q1: 50000,Q2: 75000,Q3: 60000。",
    tools=[create_chart_function],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"要调用的函数: {step.name}")
        print(f"参数: {step.arguments}")

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const createChartFunctionDeclaration = {
  type: 'function',
  name: 'create_bar_chart',
  description: '根据标题、标签和值创建条形图。',
  parameters: {
    type: 'object',
    properties: {
      title: { type: 'string', description: '图表的标题。' },
      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.5-flash',
  input: "创建一个标题为 '季度销售额' 的条形图,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: ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "创建一个标题为 '\''季度销售额'\'' 的条形图,Q1: 50000,Q2: 75000,Q3: 60000。",
    "tools": [{
        "type": "function",
        "name": "create_bar_chart",
        "description": "根据标题、标签和值创建条形图。",
        "parameters": {
          "type": "object",
          "properties": {
            "title": {"type": "string"},
            "labels": {"type": "array", "items": {"type": "string"}},
            "values": {"type": "array", "items": {"type": "number"}}
          },
          "required": ["title", "labels", "values"]
        }
    }]
  }'

函数调用的工作原理

函数调用概述

函数调用涉及你的应用程序、模型和外部函数之间的结构化交互:

  1. 定义函数声明: 为模型定义函数的名称、参数和用途。
  2. 用函数声明调用大语言模型: 发送用户提示以及函数声明给模型。
  3. 执行函数代码(你的责任): 模型不会自己执行函数。提取名称和参数并在你的应用程序中执行。
  4. 创建友好的用户响应: 将结果发送回模型以获得最终的用户友好响应。

这个过程可以在多个回合中重复。模型支持在单个回合中(并行函数调用)和按顺序(组合函数调用)调用多个函数。

步骤 1:定义函数声明

Python

set_light_values_declaration = {
    "type": "function",
    "name": "set_light_values",
    "description": "设置灯光的亮度和色温。",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "integer",
                "description": "亮度级别从 0 到 100",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "色温",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

def set_light_values(brightness: int, color_temp: str) -> dict:
    """设置房间灯光的亮度和色温。"""
    return {"brightness": brightness, "colorTemperature": color_temp}

JavaScript

const setLightValuesTool = {
  type: 'function',
  name: 'set_light_values',
  description: '设置灯光的亮度和色温。',
  parameters: {
    type: 'object',
    properties: {
      brightness: { type: 'number', description: '亮度级别从 0 到 100' },
      color_temp: { type: 'string', enum: ['daylight', 'cool', 'warm'] },
    },
    required: ['brightness', 'color_temp'],
  },
};

function setLightValues(brightness, color_temp) {
  return { brightness: brightness, colorTemperature: color_temp };
}

步骤 2:用函数声明调用模型

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.5-flash",
    input="把灯光调暗到浪漫的水平",
    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.5-flash',
  input: '把灯光调暗到浪漫的水平',
  tools: [setLightValuesTool],
});

const fcStep = interaction.steps.find(s => s.type === 'function_call');
console.log(fcStep);

模型返回带有 typenameargumentsfunction_call 步骤:

type='function_call'
name='set_light_values'
arguments={'color_temp': 'warm', 'brightness': 25}

步骤 3:执行函数

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"函数执行结果: {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(`函数执行结果: ${JSON.stringify(result)}`);
}

步骤 4:将结果发送回模型

Python

final_interaction = client.interactions.create(
    model="gemini-3.5-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.5-flash',
  input: [{
    type: 'function_result',
    name: fcStep.name,
    call_id: fcStep.id,
    result: [{ type: 'text', text: JSON.stringify(result) }]
  }],
  tools: [setLightValuesTool],
  previous_interaction_id: interaction.id,
});

console.log(finalInteraction.output_text);

无状态函数调用

你也可以通过在客户端管理对话历史并设置 store: false 来使用无状态模式的函数调用。

在无状态模式下,你必须在每个后续请求的 input 字段中传递完整的对话历史。此历史必须包括:1. 初始的 user_input 步骤。2. 在第 1 回合中返回的所有模型生成步骤(包括 thoughtfunction_call 步骤),完全按照接收的方式。3. 包含你执行的函数输出的 function_result 步骤。

Python

from google import genai
import json

client = genai.Client()

history = [
    {
        "type": "user_input",
        "content": [{"type": "text", "text": "把灯光调暗到浪漫的水平"}]
    }
]

interaction = client.interactions.create(
    model="gemini-3.5-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.5-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: "把灯光调暗到浪漫的水平" }]
    }
  ];

  const interaction = await client.interactions.create({
    model: "gemini-3.5-flash",
    store: false,
    input: history,
    tools: [setLightValuesTool],
  });

  history.push(...interaction.steps);

  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.5-flash',
    store: false,
    input: history,
    tools: [setLightValuesTool],
  });

  console.log(finalInteraction.output_text);
}

await main();

REST

# 第 1 回合:发送带有工具的请求并设置 store: false
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.5-flash",
    "store": false,
    "input": [
      {
        "type": "user_input",
        "content": "把灯光调暗到浪漫的水平"
      }
    ],
    "tools": [{
      "type": "function",
      "name": "set_light_values",
      "description": "设置灯光的亮度和色温。",
      "parameters": {
        "type": "object",
        "properties": {
          "brightness": {"type": "integer", "description": "亮度级别从 0 到 100"},
          "color_temp": {"type": "string", "enum": ["daylight", "cool", "warm"]}
        },
        "required": ["brightness", "color_temp"]
      }
    }]
  }')

# 提取模型步骤(thought, function_call)
MODEL_STEPS=$(echo "$RESPONSE1" | jq '.steps')

# 提取要执行的函数调用详情
FC_NAME=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .name')
FC_ID=$(echo "$RESPONSE1" | jq -r '.steps[] | select(.type=="function_call") | .id')

# 假设本地执行返回:{"brightness": 25, "colorTemperature": "warm"}
RESULT="{\"brightness\": 25, \"colorTemperature\": \"warm\"}"

# 重建第 2 回合的历史记录
HISTORY=$(jq -n \
  --argjson first_input '[{"type": "user_input", "content": "把灯光调暗到浪漫的水平"}]' \
  --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}]}]')

# 第 2 回合:发送完整历史记录
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: ***" \
  -H 'Content-Type: application/json' \
  -d "{
    \"model\": \"gemini-3.5-flash\",
    \"store\": false,
    \"input\": $HISTORY,
    \"tools\": [{
      \"type\": \"function\",
      \"name\": \"set_light_values\",
      \"description\": \"设置灯光的亮度和色温。\",
      \"parameters\": {
        \"type\": \"object\",
        \"properties\": {
          \"brightness\": {\"type\": \"integer\"},
          \"color_temp\": {\"type\": \"string\"}
        },
        \"required\": [\"brightness\", \"color_temp\"]
      }
    }]
  }"

函数声明

函数声明作为工具传递,包括:

  • type(字符串):自定义函数必须是 "function"
  • name(字符串):唯一函数名称(使用下划线或驼峰命名)。
  • description(字符串):函数用途的清晰解释。
  • parameters(对象):函数期望的输入参数。
    • type(字符串):整体数据类型,如 object
    • properties(对象):带有类型和描述的单个参数。
    • required(数组):必需参数名称。

思考模型的函数调用

Gemini 3 系列模型使用内部"思考"过程来改进函数调用。SDK 会自动为你处理思考签名

并行函数调用

当函数独立时,可以同时调用多个函数:

Python

power_disco_ball = {"type": "function", "name": "power_disco_ball", "description": "启动迪斯科球。",
    "parameters": {"type": "object", "properties": {"power": {"type": "boolean"}}, "required": ["power"]}}
start_music = {"type": "function", "name": "start_music", "description": "播放音乐。",
    "parameters": {"type": "object", "properties": {"energetic": {"type": "boolean"}, "loud": {"type": "boolean"}}, "required": ["energetic", "loud"]}}
dim_lights = {"type": "function", "name": "dim_lights", "description": "调暗灯光。",
    "parameters": {"type": "object", "properties": {"brightness": {"type": "number"}}, "required": ["brightness"]}}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.5-flash",
    input="把这里变成派对现场!",
    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: '启动迪斯科球。',
  parameters: { type: 'object', properties: { power: { type: 'boolean' } }, required: ['power'] } };
const startMusic = { type: 'function', name: 'start_music', description: '播放音乐。',
  parameters: { type: 'object', properties: { energetic: { type: 'boolean' }, loud: { type: 'boolean' } }, required: ['energetic', 'loud'] } };
const dimLights = { type: 'function', name: 'dim_lights', description: '调暗灯光。',
  parameters: { type: 'object', properties: { brightness: { type: 'number' } }, required: ['brightness'] } };

const interaction = await client.interactions.create({
  model: 'gemini-3.5-flash',
  input: '把这里变成派对现场!',
  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: ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "把这里变成派对现场!",
    "tools": [
      {
        "type": "function",
        "name": "power_disco_ball",
        "description": "启动迪斯科球。",
        "parameters": {
          "type": "object",
          "properties": {
            "power": {"type": "boolean"}
          },
          "required": ["power"]
        }
      },
      {
        "type": "function",
        "name": "start_music",
        "description": "播放音乐。",
        "parameters": {
          "type": "object",
          "properties": {
            "energetic": {"type": "boolean"},
            "loud": {"type": "boolean"}
          },
          "required": ["energetic", "loud"]
        }
      },
      {
        "type": "function",
        "name": "dim_lights",
        "description": "调暗灯光。",
        "parameters": {
          "type": "object",
          "properties": {
            "brightness": {"type": "number"}
          },
          "required": ["brightness"]
        }
      }
    ],
    "generation_config": {"tool_choice": "any"}
  }'

本文档提供了使用 Gemini API 进行函数调用的完整指南,涵盖基本概念、各种编程语言示例以及高级功能,如并行调用和无状态模式。

评论 (0)

暂无评论,快来抢沙发吧!

91学AI

© 2026 91学AI · 按岗位学 AI 与大数据. All rights reserved.