# 组合内置工具与函数调用

{% callout type="note" %}
该功能位于 [预览](/docs/models#preview) 并支持 [Gemini 4](/docs/models#gemini-4) 和 [Gemini 3](/docs/models#gemini-3) 模型。
{% /callout %}

Gemini 允许组合 [内置工具](/docs/tools)，例如 `google_search`, 和 [函数调用](/docs/function-calling)
（也称为 *定制工具*）通过保留和公开工具调用的上下文历史记录在单次交互中。内置和自定义工具组合可实现复杂、智能体的工作流程，例如，模型可以在调用特定业务逻辑之前将自身置于实时 Web 数据中。

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

{% tabs %}
{% tab label="Python" %}
```python
# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()

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

# The Interactions API manages context automatically across tool calls.
# The model will first use Google Search, then call getWeather.
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=[
        {"type": "google_search"},
        getWeather,
    ],
)

# Process steps: the interaction contains search results and a function call
for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function call: {step.name} with args: {step.arguments}")
        # In a real application, you would execute the function here
        # and provide the result back to the model.
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

// The Interactions API manages context automatically across tool calls.
// The model will first use Google Search, then call getWeather.
const interaction = await 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: [
        { type: "google_search" },
        {
            type: "function",
            name: "get_weather",
            description: "Get current weather",
            parameters: {
                type: "object",
                properties: { location: { type: "string" } },
                required: ["location"],
            },
        },
    ],
});

// Process steps: the interaction contains search results and a function call
for (const step of interaction.steps) {
    if (step.type === "function_call") {
        console.log(`Function call: ${step.name} with args: ${JSON.stringify(step.arguments)}`);
        // In a real application, you would execute the function here
        // and provide the result back to the model.
    }
}
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Function;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

Client client = new Client();

Map<String, Object> parameters = new HashMap<>();
parameters.put("type", "object");

Function customFunc =
    Function.builder()
        .name("get_user_location")
        .description("Retrieves user current location.")
        .parameters(parameters)
        .build();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-hydrogen"))
        .input(InteractionsInput.of("What is the weather like where I am right now?"))
        .tools(Arrays.asList(customFunc, new GoogleSearch()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    customFunc := interactions.NewTool(interactions.Function{
        Name:        genai.Ptr("get_user_location"),
        Description: genai.Ptr("Retrieves user current location."),
        Parameters: map[string]any{
            "type": "object",
        },
    })

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput("What is the weather like where I am right now?"),
            Tools: []interactions.Tool{
                customFunc,
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```bash
# Specifies the API revision to avoid breaking changes when they become default
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Api-Revision: 2026-05-20" \
-d '{
  "model": "gemini-4-hydrogen",
  "input": "What is the northernmost city in the United States? What'\''s the weather like there today?",
  "tools": [
    { "type": "google_search" },
    {
      "type": "function",
      "name": "getWeather",
      "description": "Get the weather in a given location",
      "parameters": {
          "type": "object",
          "properties": {
              "location": {
                  "type": "string",
                  "description": "The city and state, e.g. San Francisco, CA"
              }
          },
          "required": ["location"]
      }
    }
  ]
}'
```
{% /tab %}
{% /tabs %}

## 它是如何运作的  {% #how-it-works %}

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

### 启用工具组合  {% #enable %}

* 包括 [`function_declarations`](/docs/function-calling#function-declarations)，以及您想要使用的内置工具，以触发组合行为。

### API 返回步骤  {% #api-returns-steps %}

在交互响应中，API 返回内置工具调用和函数（自定义工具）调用的单独步骤：

* **内置工具步骤**：API 自动管理这些，保留各个回合的上下文。

* **函数调用步骤**：API 返回 `function_call` 自定义函数的步骤。您执行该函数并返回结果。

### 返回步骤中的关键字段  {% #critical-fields %}

返回步骤中的某些字段对于维护工具上下文和启用工具组合至关重要：

* **`id`**： 发现于 `function_call` 和 `function_response` 步骤。将调用映射到其响应的唯一标识符。
* **`signature`**： 发现于 `thought` 步骤以及所有工具调用（例如， `function_call`）和结果（例如， `function_response`) Gemini 3+ 型号的步骤。这种加密的上下文使得 **工具上下文循环** 跨互动。

**管理这些字段：**

* **有状态模式（推荐）**: 当你使用 `previous_interaction_id`，服务器自动处理两者 `id` 和 `signature` 字段。
* **无状态模式**：手动管理对话历史记录时，您必须确保通过 `id` 和 `signature` 在后续请求中将字段返回到模型以验证真实性并维护上下文。如果您将完整的响应对象传递回历史记录，官方 SDK 会自动处理此问题。

### 特定于工具的数据  {% #data %}

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

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
工具
{% /doc-cell %}

{% doc-cell %}
用户可见的工具调用参数（如果有）
{% /doc-cell %}

{% doc-cell %}
用户可见的工具响应（如果有）
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**谷歌搜索**
{% /doc-cell %}

{% doc-cell %}
`queries`
{% /doc-cell %}

{% doc-cell %}
`search_suggestions`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**谷歌地图**
{% /doc-cell %}

{% doc-cell %}
`queries`
{% /doc-cell %}

{% doc-cell %}
`places`

`google_maps_widget_context_token`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**网址上下文**
{% /doc-cell %}

{% doc-cell %}
`urls`

需要浏览的URL
{% /doc-cell %}

{% doc-cell %}
`status`：浏览状态

`retrieved_url`: 浏览过的网址
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**文件搜索**
{% /doc-cell %}

{% doc-cell %}
无
{% /doc-cell %}

{% doc-cell %}
无
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

## 代币和定价  {% #tokens %}

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

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

阅读 [token](/docs/tokens) 页面了解更多信息。

## 限制  {% #limitations %}

* 默认为 `validated` 模式（`auto` 当启用工具上下文循环时，不支持模式）。

* 内置工具如 `google_search` 依赖于位置和当前时间信息，所以如果您 `system_instruction` 或 `function_declaration.description` 位置和时间信息存在冲突，工具组合功能可能无法正常工作。

## 支持的工具  {% #supported-tools %}

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

| 工具                                | 执行方  | 上下文流通支持                                                 |
| --------------------------------- | ---- | ------------------------------------------------------- |
| [Google 搜索](/docs/google-search)  | 服务器端 | 支持                                                      |
| [Google 地图](/docs/maps-grounding) | 服务器端 | 支持                                                      |
| [URL上下文](/docs/url-context)       | 服务器端 | 支持                                                      |
| [文件搜索](/docs/file-search)         | 服务器端 | 支持                                                      |
| [代码执行](/docs/code-execution)      | 服务器端 | 支持（内置、使用 `code_execution` 和 `code_execution_result` 步骤） |
| [电脑使用](/docs/computer-use)        | 客户端  | 支持（内置、使用 `function_call` 和 `function_response` 步骤）      |
| [自定义功能](/docs/function-calling)   | 客户端  | 支持（内置、使用 `function_call` 和 `function_response` 步骤）      |

## 后续步骤  {% #whats-next %}

* 了解更多关于 [函数调用](/docs/function-calling) 在 Gemini API 中。
* 探索支持的工具：* [Google 搜索](/docs/google-search)
  * [Google 地图](/docs/maps-grounding)
  * [URL上下文](/docs/url-context)
  * [文件搜索](/docs/file-search)
