Gemini 中文指南
获取 API 密钥 ↗

组合内置工具与函数调用

↓ 下载 Markdown

Gemini 允许组合 内置工具,例如 google_search, 和 函数调用 (也称为 定制工具)通过保留和公开工具调用的上下文历史记录,在单代中完成。内置和自定义工具组合可实现复杂、智能体的工作流程,例如,模型可以在调用特定业务逻辑之前将自身置于实时 Web 数据中。

这是一个启用内置和自定义工具组合的示例 google_search 和一个自定义函数 getWeather:

python
  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"],
      },
  }

  # Turn 1: Initial request with Google Search (built-in) and getWeather (custom) tools enabled
  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.GoogleSearch(), # Built-in tool
                  function_declarations=[getWeather] # Custom tool
              ),
          ],
          tool_config=types.ToolConfig(
              include_server_side_tool_invocations=True
          )
      ),
  )
  function_call_id = None
  for part in response.candidates[0].content.parts:
      if part.function_call:
          print(f"Function call: {part.function_call.name} (ID: {part.function_call.id})")
          function_call_id = part.function_call.id

  # Turn 2: Manually build history to circulate both tool and function context
  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 from Turn 1 includes tool_call, tool_response, and thought_signatures
      response.candidates[0].content,
      # Return the function_response
      types.Content(
          role="user",
          parts=[types.Part(
              function_response=types.FunctionResponse(
                  name="getWeather",
                  response={"response": "Very cold. 22 degrees Fahrenheit."},
                  id=function_call_id # Match the ID from the function_call
              )
          )]
      )
  ]

  response_2 = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=history,
      config=types.GenerateContentConfig(
          tools=[
              types.Tool(
                  google_search=types.GoogleSearch(),
                  function_declarations=[getWeather]
              ),
          ],
          # This flag needs to be enabled for built-in tool context circulation and tool combination
          tool_config=types.ToolConfig(
              include_server_side_tool_invocations=True
          )
      ),
  )

  for part in response_2.candidates[0].content.parts:
      if part.text:
          print(part.text)

它是如何运作的 #

Gemini 3型号使用 工具上下文循环 启用内置和自定义工具组合。工具上下文循环使得可以保存和公开内置工具的上下文,并在同一次调用中与自定义工具共享它。

启用工具组合 #

  • 您必须设置 include_server_side_tool_invocations 标记为 true 启用工具上下文循环。

  • 包括 function_declarations,以及您想要使用的内置工具,以触发组合行为。

  • 如果你不包括 function_declarations,只要设置了该标志,工具上下文循环仍然会作用于包含的内置工具。

API 退回零件 #

在单个响应中,API 返回 toolCall 和 toolResponse 内置工具调用的部分。对于函数(自定义工具)调用,API 返回 functionCall 调用部分,用户向其提供 functionResponse 参与下一轮。

  • toolCall 和 toolResponse:API 返回这些部分,以保留在服务器端运行的工具的上下文及其执行结果,以供下一轮使用。

  • functionCall 和 functionResponse:API将函数调用发送给用户填写,用户将结果在函数响应中返回(这些部分是所有标准的) 函数调用 在Gemini API中,不是工具组合功能所独有的)。

  • (代码执行 仅工具) executableCode 和 codeExecutionResult:使用代码执行工具时,而不是 functionCall 和 functionResponse,API 返回 executableCode (模型生成的要执行的代码)和 codeExecutionResult (可执行代码的结果)。

您必须退回所有部件,包括所有 领域 它们包含在每个回合中返回模型以维护上下文并启用工具组合。

退回零件中的关键字段 #

某些 API 返回的部件 将包括 id, tool_type, 和 thought_signature 字段。这些字段对于维护工具上下文至关重要(因此对于工具组合也至关重要);您需要退回所有零件 正如回复中给出的 在您后续的请求中。

  • id:将调用映射到其响应的唯一标识符。 id 是 设置所有函数调用响应,无论工具上下文循环如何。你 必须 提供相同的 id 在 API 在函数调用中提供的函数响应中。内置工具自动共享 id 工具调用和工具响应之间。

    • 在所有与工具相关的部分中找到: toolCall, toolResponse, functionCall, functionResponse, executableCode, codeExecutionResult
  • tool_type:标识正在使用的特定工具;字面上的内置工具或(例如 URL_CONTEXT)或函数(例如 getWeather)名称。

    • 发现于 toolCall 和 toolResponse 零件。
  • thought_signature:嵌入的实际加密上下文 API 返回的每个部分。没有思想签名就无法重建语境;如果您不每次都返回所有部件的思想签名,模型就会出错。

    • 发现于 全部 零件。

特定于工具的数据 #

一些内置工具返回特定于工具类型的用户可见数据参数。

工具

用户可见的工具调用参数(如果有)

用户可见的工具响应(如果有)

GOOGLE_SEARCH

queries

search_suggestions

GOOGLE_MAPS

queries

places

google_maps_widget_context_token

URL_CONTEXT

urls

需要浏览的URL

url_metadata

retrieved_url: 浏览过的网址

url_retrieval_status:浏览状态

FILE_SEARCH

无

无

工具组合请求结构示例 #

以下请求结构显示了提示的请求结构:“美国最北端的城市是哪座?今天那里的天气怎么样?”。它结合了三个工具:内置 Gemini 工具 google_search 和 code_execution,和一个自定义函数 get_weather.

json
{
  "model": "models/gemini-4-hydrogen",
  "contents": [{
    "parts": [{
      "text": "What is the northernmost city in the United States? What's the weather like there today?"
    }],
    "role": "user"
  }, {
    "parts": [{
      "thoughtSignature": "...",
      "toolCall": {
        "toolType": "GOOGLE_SEARCH_WEB",
        "args": {
          "queries": ["northernmost city in the United States"]
        },
        "id": "a7b3k9p2"
      }
    }, {
      "thoughtSignature": "...",
      "toolResponse": {
        "toolType": "GOOGLE_SEARCH_WEB",
        "response": {
          "search_suggestions": "..."
        },
        "id": "a7b3k9p2"
      }
    }, {
      "functionCall": {
        "name": "getWeather",
        "args": {
          "city": "Utqiaġvik, Alaska"
        },
        "id": "m4q8z1v6"
      },
      "thoughtSignature": "..."
    }],
    "role": "model"
  }, {
    "parts": [{
      "functionResponse": {
        "name": "getWeather",
        "response": {
          "response": "Very cold. 22 degrees Fahrenheit."
        },
        "id": "m4q8z1v6"
      }
    }],
    "role": "user"
  }],
  "tools": [{
    "functionDeclarations": [{
      "name": "getWeather"
    }]
  }, {
    "googleSearch": {
    }
  }, {
    "codeExecution": {
    }
  }],
  "toolConfig": {
    "includeServerSideToolInvocations": true
  }
}

代币和定价 #

请注意 toolCall 和 toolResponse 请求中的部分计入 prompt_token_count。由于这些中间工具步骤现在可见并返回给您,因此它们是对话历史记录的一部分。这仅适用于 要求, 不 回应.

Google 搜索工具是此规则的一个例外。 Google 搜索已经在查询级别应用了自己的定价模型,因此 token 不会重复收费(请参阅 价格 页)。

阅读 token 页面了解更多信息。

限制 #

  • 默认为 VALIDATED 模式(AUTO 模式不支持)时 include_server_side_tool_invocations 标志已启用
  1. 内置工具如 google_search 依赖于位置和当前时间信息,所以如果您 system_instruction 或 function_declaration.description 位置和时间信息存在冲突,工具组合功能可能无法正常工作。

支持的工具 #

标准工具上下文循环适用于服务器端(内置)工具。代码执行也是一个服务器端工具,但有自己内置的上下文循环解决方案。 Computer Use和函数调用是客户端工具,也有内置的上下文循环解决方案。

工具执行方上下文流通支持
Google 搜索服务器端支持
Google 地图服务器端支持
URL上下文服务器端支持
文件搜索服务器端支持
代码执行服务器端支持(内置、使用 executableCode 和 codeExecutionResult 零件)
电脑使用客户端支持(内置、使用 functionCall 和 functionResponse 零件)
自定义功能客户端支持(内置、使用 functionCall 和 functionResponse 零件)

后续步骤 #

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