使用 Gemini API 进行函数调用

借助函数调用,您可以将模型连接到外部工具和 API。 模型不会生成文本回答,而是会确定何时调用特定函数,并提供执行实际操作所需的参数。这使得模型能够充当自然语言与实际操作和数据之间的桥梁。函数调用有 3 个主要应用场景:

  • 执行操作使用 API 与外部系统互动,例如安排预约、创建账单、发送电子邮件或控制智能家居设备。
  • 扩充知识从数据库、API 和知识库等外部来源获取信息。
  • 扩展功能使用外部工具执行计算,并扩展模型的功能限制,例如使用计算器或创建图表。

您可以浏览以下示例,了解这些使用情形:

安排会议

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

Python

from google import genai

schedule_meeting_function = {
    "type": "function",
    "name": "schedule_meeting",
    "description": "Schedules a meeting with specified attendees at a given time and date.",
    "parameters": {
        "type": "object",
        "properties": {
            "attendees": {"type": "array", "items": {"type": "string"}},
            "date": {"type": "string", "description": "Date (e.g., '2024-07-29')"},
            "time": {"type": "string", "description": "Time (e.g., '15:00')"},
            "topic": {"type": "string", "description": "The meeting topic."},
        },
        "required": ["attendees", "date", "time", "topic"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.6-flash",
    input="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.",
    tools=[{"type": "function", **schedule_meeting_function}],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function to call: {step.name}")
        print(f"Arguments: {step.arguments}")

JavaScript

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

const client = new GoogleGenAI({});

const scheduleMeetingFunction = {
  type: 'function',
  name: 'schedule_meeting',
  description: 'Schedules a meeting with specified attendees at a given time and date.',
  parameters: {
    type: 'object',
    properties: {
      attendees: { type: 'array', items: { type: 'string' } },
      date: { type: 'string', description: