Gemini 中文指南
获取 API 密钥 ↗

Gemini API 函数调用

↓ 下载 Markdown

函数调用可让您将模型连接到外部工具和 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-4-hydrogen",
    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}")

获取天气 #

此示例演示如何定义一个函数来检索某个位置的温度数据,使模型能够调用外部 API 来回答需要实时或外部信息的查询。

python
from google import genai

weather_function = {
    "type": "function",
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What's the temperature in London?",
    tools=[weather_function],
)

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

创建图表 #

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

python
from google import genai

create_chart_function = {
    "type": "function",
    "name": "create_bar_chart",
    "description": "Creates a bar chart given a title, labels, and values.",
    "parameters": {
        "type": "object",
        "properties": {
            "title": {"type": "string", "description": "The title for the chart."},
            "labels": {"type": "array", "items": {"type": "string"}},
            "values": {"type": "array", "items": {"type": "number"}},
        },
        "required": ["title", "labels", "values"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Create a bar chart titled 'Quarterly Sales' with Q1: 50000, Q2: 75000, Q3: 60000.",
    tools=[create_chart_function],
)

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

函数调用的工作原理 #

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

  1. 定义函数声明: 定义模型的函数名称、参数和用途。
  2. 使用函数声明调用 LLM: 将用户提示连同函数声明一起发送到模型。
  3. 执行功能代码(您的责任): 型号 不 执行函数本身。提取名称和参数并在您的应用程序中执行。
  4. 创建用户友好的响应: 将结果发送回模型以获得最终的、用户友好的响应。

这个过程可以重复多轮。该模型支持单轮调用多个函数(并联函数调用) 并依次 (组合函数调用).

步骤 1:定义函数声明 #

python
set_light_values_declaration = {
    "type": "function",
    "name": "set_light_values",
    "description": "Sets the brightness and color temperature of a light.",
    "parameters": {
        "type": "object",
        "properties": {
            "brightness": {
                "type": "integer",
                "description": "Light level from 0 to 100",
            },
            "color_temp": {
                "type": "string",
                "enum": ["daylight", "cool", "warm"],
                "description": "Color temperature",
            },
        },
        "required": ["brightness", "color_temp"],
    },
}

def set_light_values(brightness: int, color_temp: str) -> dict:
    """Set the brightness and color temperature of a room light."""
    return {"brightness": brightness, "colorTemperature": color_temp}

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

python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Turn the lights down to a romantic level",
    tools=[set_light_values_declaration],
)

fc_step = next(s for s in interaction.steps if s.type == "function_call")
print(fc_step)

该模型返回一个 function_call 步与 type, name, 和 arguments:

python
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"Function execution result: {result}")

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

python
final_interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    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)

无状态函数调用 #

您还可以通过在客户端管理会话历史记录并设置在无状态模式下使用函数调用 store=false.

在无状态模式下,您必须在 input 每个后续请求的字段。这段历史必须包括:

  1. 最初的 user_input 步骤。
  2. Turn 1 中返回的所有模型生成的步骤(包括 thought 和 function_call 步骤)与收到的完全一样。
  3. 该 function_result 步骤包含已执行函数的输出。
python
from google import genai
import json

client = genai.Client()

history = [
    {
        "type": "user_input",
        "content": [{"type": "text", "text": "Turn the lights down to a romantic level"}]
    }
]

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    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-4-hydrogen",
    store=False,
    input=history,
    tools=[set_light_values_declaration],
)

print(final_interaction.output_text)

函数声明 #

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

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

函数调用带思维模型 #

Gemini 3系列型号采用内部 “思考” 改进函数调用的过程。 SDK 自动处理 思想签名 为了你。

并行函数调用 #

当多个函数独立时,一次调用它们:

python
power_disco_ball = {"type": "function", "name": "power_disco_ball", "description": "Powers the disco ball.",
    "parameters": {"type": "object", "properties": {"power": {"type": "boolean"}}, "required": ["power"]}}
start_music = {"type": "function", "name": "start_music", "description": "Play music.",
    "parameters": {"type": "object", "properties": {"energetic": {"type": "boolean"}, "loud": {"type": "boolean"}}, "required": ["energetic", "loud"]}}
dim_lights = {"type": "function", "name": "dim_lights", "description": "Dim the lights.",
    "parameters": {"type": "object", "properties": {"brightness": {"type": "number"}}, "required": ["brightness"]}}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Turn this place into a party!",
    tools=[power_disco_ball, start_music, dim_lights],
    generation_config={"tool_choice": "any"},
)

for step in interaction.steps:
    if step.type == "function_call":
        args = ", ".join(f"{key}={val}" for key, val in step.arguments.items())
        print(f"{step.name}({args})")

组合函数调用 #

将多个函数调用链接在一起以实现复杂的请求(例如,首先获取位置,然后获取该位置的天气)。

python
get_weather_forecast_declaration = {
    "type": "function",
    "name": "get_weather_forecast",
    "description": "Gets the current weather temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "The location"},
        },
        "required": ["location"],
    },
}

set_thermostat_temperature_declaration = {
    "type": "function",
    "name": "set_thermostat_temperature",
    "description": "Sets the thermostat to a desired temperature.",
    "parameters": {
        "type": "object",
        "properties": {
            "temperature": {
                "type": "integer",
                "description": "The temperature in Celsius",
            },
        },
        "required": ["temperature"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise 18°C.",
    tools=[
        get_weather_forecast_declaration,
        set_thermostat_temperature_declaration,
    ],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function to call: {step.name}")
        print(f"Arguments: {step.arguments}")
    elif hasattr(step, "content") and step.content:
         for part in step.content:
             if hasattr(part, "text"):
                 print(part.text)

函数调用模式 #

控制模型如何使用工具 tool_choice 在 generation_config:

  • auto (默认):模型决定是调用函数还是直接响应。
  • any:模型被限制为始终预测函数调用。
  • none:模型禁止进行函数调用。
  • validated:模型确保功能架构的一致性。
python
generation_config = {
    "tool_choice": {
        "allowed_tools": {
            "mode": "any",
            "tools": ["get_current_temperature"]
        }
    }
}

多工具使用 #

您可以启用多个工具,将内置工具与函数调用组合在同一请求中。 Gemini 4 和 Gemini 3 型号可以在交互中将内置工具与开箱即用的函数调用相结合。路过 previous_interaction_id 自动循环内置工具上下文。

python
from google import genai
import json

client = genai.Client()

get_weather = {
    "type": "function",
    "name": "get_weather",
    "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"],
    },
}

tools = [
    {"type": "google_search"},
    get_weather
]

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What is the northernmost city in the United States? What's the weather like there today?",
    tools=tools
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function call: {step.name} (ID: {step.id})")
        result = {"response": "Very cold. 22 degrees Fahrenheit."}
        interaction_2 = client.interactions.create(
            model="gemini-4-hydrogen",
            previous_interaction_id=interaction.id,
            tools=tools,
            input=[{
                "type": "function_result",
                "name": step.name,
                "call_id": step.id,
                "result": [{"type": "text", "text": json.dumps(result)}]
            }]
        )

        print(interaction_2.output_text)

多模态功能响应 #

对于 Gemini 3 系列模型,您可以在发送给模型的函数响应部分中包含多模态内容。该模型可以在下一轮处理这种多模态内容,以产生更明智的响应。

要在函数响应中包含多模态数据,请将其作为一个或多个内容块包含在 result 的领域 function_result 步骤。每个内容块必须指定其 type。支持以下类型:

每个媒体块接受 base64 编码 data 或一个 uri,比如一个 Files API URI。函数结果中的文件的处理方式与常规输入中的同一文件的处理方式相同。参见 通过 URI 返回文件 举个例子。

如果块使用不支持的 MIME 类型,则 API 返回 400 INVALID_ARGUMENT 命名字段并列出可接受的类型的错误。

以下示例演示如何在交互中将包含图像数据的函数响应发送回模型:

python
import base64
from google import genai
import requests

client = genai.Client()

tool_call = next(s for s in interaction.steps if s.type == "function_call")

image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content

base64_image_data = base64.b64encode(image_bytes).decode("utf-8")

final_interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    previous_interaction_id=interaction.id,
    input=[
        {
            "type": "function_result",
            "name": tool_call.name,
            "call_id": tool_call.id,
            "result": [
                {"type": "text", "text": "instrument.jpg"},
                {
                    "type": "image",
                    "mime_type": "image/jpeg",
                    "data": base64_image_data,
                },
            ],
        }
    ],
)

print(final_interaction.output_text)

通过 URI 返回文件 #

内联数据计入请求大小限制。对于大文件,例如视频、长音频或多页文档,请使用 Files API 并返回其 uri 而不是内联 data.

以下示例显示了一个 view_file 通过 Files API URI 返回 Excel 电子表格和视频的工具。对于 video 块,您可以设置 processing 到 "static" 或 "agentic"。如果您不设置它,则应用与输入视频相同的默认值。详细信息请参见 智能体视频理解.

python
from google import genai

client = genai.Client()

tool_call = next(s for s in interaction.steps if s.type == "function_call")

# Your tool uploads the files and returns their URIs.
sheet = client.files.upload(
    file="q3_sales.xlsx",
    config={"mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
)
clip = client.files.upload(file="store_walkthrough.mp4")

final_interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    previous_interaction_id=interaction.id,
    input=[
        {
            "type": "function_result",
            "name": tool_call.name,
            "call_id": tool_call.id,
            "result": [
                {"type": "text", "text": "{\"status\": \"ok\"}"},
                {
                    "type": "document",
                    "uri": sheet.uri,
                    "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                },
                {
                    "type": "video",
                    "uri": clip.uri,
                    "mime_type": "video/mp4",
                    "processing": "agentic",
                },
            ],
        }
    ],
)

print(final_interaction.output_text)

函数调用具有结构化输出 #

对于 Gemini 3 系列型号,将函数调用与 结构化输出 以获得格式一致的响应。

远程 MCP (Model Context Protocol) #

Interactions API 支持连接到远程 MCP 服务器,使模型能够访问外部工具和服务。您提供服务器 name 和 url 在工具配置中。

使用远程 MCP 时,请注意以下限制:

  • 服务器类型:远程 MCP 仅适用于 Streamable HTTP 服务器。不支持 SSE(服务器发送事件)服务器。
  • 命名:MCP 服务器名称不应包含 - 性格。使用 snake_case 而是服务器名称。
领域类型必填说明
typestring是的必须是 "mcp_server".
namestring否MCP 服务器的显示名称。
urlstring否MCP 服务器端点的完整 URL。
headersobject否键值对作为 HTTP 标头随每个请求发送到服务器(例如,身份验证 token)。
allowed_toolsarray否限制智能体可以调用服务器上的哪些工具。

示例#

python
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Check the weather in San Francisco.",
    tools=[
        {
            "type": "mcp_server",
            "name": "weather",
            "url": "https://gemini-api-demos.uc.r.appspot.com/mcp",
        }
    ]
)

流工具调用 #

当使用流式处理工具时,模型会生成一系列函数调用 step.delta 流上的事件。工具参数可以使用以下方式作为部分参数进行流式传输 arguments。在执行工具调用之前,您必须聚合这些增量以重建完整的工具调用。

python
import json
from google import genai

client = genai.Client()

weather_tool = {
    "type": "function",
    "name": "get_weather",
    "description": "Gets the weather for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "The city and state"}
        },
        "required": ["location"]
    }
}

stream = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What is the weather in Paris?",
    tools=[weather_tool],
    stream=True
)

current_calls = {}
tool_calls = []

for event in stream:
    if event.event_type == "step.start":
        if event.step.type == "function_call":
            current_calls[event.index] = {
                "id": event.step.id,
                "name": event.step.name,
                "arguments": ""
            }
            if hasattr(event.step, "arguments") and event.step.arguments:
                if isinstance(event.step.arguments, dict):
                    current_calls[event.index]["arguments"] = json.dumps(event.step.arguments)
                else:
                    current_calls[event.index]["arguments"] = event.step.arguments
    elif event.event_type == "step.delta":
        if event.delta.type == "arguments":
            if event.index in current_calls:
                current_calls[event.index]["arguments"] += event.delta.partial_arguments
        elif event.delta.type == "text":
            print(event.delta.text, end="", flush=True)

    elif event.event_type == "interaction.completed":
        for index, call in current_calls.items():
            args = call["arguments"]
            if args:
                args = json.loads(args)
            else:
                args = {}

            tool_calls.append({
                "type": "function_call",
                "id": call["id"],
                "name": call["name"],
                "arguments": args
            })

        print(f"\nFinal tool calls ready to execute:")
        print(json.dumps(tool_calls, indent=2))

最佳实践 #

  • 功能及参数说明: 明确且具体。
  • 命名: 使用不带空格或特殊字符的描述性名称。
  • 强类型: 使用特定类型(整数、字符串、枚举)。
  • 工具选择: 保持活动设置为 10-20 工具最大值。
  • 及时工程: 提供上下文和说明。
  • 验证: 在执行之前验证函数调用。
  • 错误处理: 实施强大的错误处理。
  • 安全性: 对外部 API 使用适当的身份验证。

工具前文本要求的解决方法 #

问题: 如果您的提示要求模型输出结构化文本(XML、YAML、JSON 等)(例如, <UPDATE>...</UPDATE>) 在进行工具调用之前,工具调用有时可能会失败,并显示 Malformed_Function_Call.

解决方案: 以下解决方法可以解决此问题:

  • 首选: 指示模型将其预工具注释放入专用的 update() 函数调用而不是原始文本(详细信息如下)。
  • 指示模型将注释写入 Markdown 标题(# UPDATE, ## PLAN) 而不是结构化文本。
  • 不要求模型在工具调用之前输出文本。

首选解决方法:将工作笔记包含在专用函数调用中 #

而不是原来的指令:

html
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>`.

使用此更新的说明:

html
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 格式。然后为更新函数添加相应的函数声明:

json
{
  "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 的调用以及它想要进行的实际函数调用。

注意事项和限制 #

  • 只有一个 OpenAPI 模式的子集 是支持的。
  • 对于 any 模式,非常大或深度嵌套的模式可能会被拒绝。
  • Python 中支持的参数类型是有限的。

简化复杂的函数模式 #

当你使用 any 模式或定义复杂参数模式,API 将您的函数声明编译到约束 token 生成的状态机中。该状态机强制限制总状态、分支路径和嵌套深度。如果您的工具的综合复杂性超出了这些限制,API 将拒绝该请求,并显示 400 INVALID_ARGUMENT 错误。

要修复模式拒绝错误,请减少声明的结构深度和分支因子。您可以通过多种方式简化复杂的函数模式:

  • 拆分大型工具集并将规则移至描述: 约束解码会一起评估所有声明的工具。限制单个请求中的功能数量,并将整体功能拆分为更小的、集中的工具。将复杂的格式规则移至字段中 description 属性或系统指令,指导模型而不扩展语法。
  • 展平嵌套对象和绑定递归: 用更扁平的结构替换深度嵌套的对象层次结构。如果你使用 $defs 和 $ref 对于递归类型,使递归引用可选或可为空。避免通过所需的属性或数组进行递归 minItems 大于零。
  • 减少可选字段、枚举和联合的分支: 可选属性, enum 价值观,以及 anyOf 分支乘以输出语法中的分支路径。将属性标记为 required 在可能的情况下并允许 null 当字段可以为空时的值。修剪大 enum 列出并简化 anyOf 联合,或在提示中包含约束(例如,使用 Pydantic 架构)作为较软的限制。
  • 缩短属性名称并删除数组边界: 属性键消耗与其字符长度成比例的状态。数组边界例如 minItems 和 maxItems 还为每个计数位置复制项目架构。使用简洁的属性名称,删除未使用的字段,并在提示中包含数组边界(例如,使用 Pydantic 架构)作为更软的限制,或者检查应用程序代码中的数组长度。

搜索标题、API 名称或正文内容