# 连接自定义工具

自定义工具让 GitBook Assistant 可以在 [Docs Embed](/docs/documentation/zh/docs-site/embedding.md) 中执行实际操作。

你可以将它连接到 *任何* 你的应用可以访问的工具。这包括你的后端 API、第三方 SDK 和内部系统。

如果你的应用能调用它，Assistant 就能调用它。

常见示例：

* 代表用户创建或更新支持工单
* 通过打开带有预填消息的支持聊天，将用户转接给支持团队

  <div data-gb-custom-block data-tag="hint" data-style="success" class="hint hint-success"><p><strong>支持转接</strong> 是开始使用自定义工具的绝佳方式。这是帮助用户快速脱困的最快办法。</p></div>
* 触发产品操作（重置 MFA、重新发送邀请、启用功能开关）
* 在你的后端中查找账户状态
* 在 Jira、Linear、Slack 或 Zendesk 等工具中启动工作流

{% hint style="info" %}
除了你在 Embed 配置中定义的工具外，Assistant 还可以使用任何 [你设置的 MCP 服务器](/docs/documentation/zh/ai-yu-sou-suo/mcp-servers-for-published-docs.md) 在 **设置 → AI 与 MCP**.
{% endhint %}

### 工具运行的位置

工具的 `execute` 函数会在与你的嵌入集成相同的环境中运行。

这通常意味着它会在用户的浏览器中、你的应用内运行。

因此你可以：

* 调用你自己的后端端点
* 调用你应用中已加载的任何第三方 SDK（例如 Intercom）
* 打开模态窗口、深度链接或产品内 UI

{% hint style="warning" %}
避免在客户端代码中放置密钥——改为调用你的后端。
{% endhint %}

### 添加工具

定义工具：

* 通过 `window.GitBook("configure", …)` 用于 [script 标签](/docs/documentation/zh/docs-site/embedding/implementation/script.md) 实现
* 通过 `tools` 用于 [Node.js/NPM](/docs/documentation/zh/docs-site/embedding/implementation/nodejs.md) package 和 [React](/docs/documentation/zh/docs-site/embedding/implementation/react.md) 组件的 prop

{% hint style="info" %}
工具并不等同于 **actions**.

* 使用 **actions** 供用户点击的按钮。
* 当你希望 Assistant 选择并运行代码时，请使用工具。
  {% endhint %}

#### 工具模板（重新发送邀请邮件）

让我们看一个示例：

```javascript
window.GitBook("configure", {
  tools: [
    {
      // 使用名称和描述注册工具。
      name: "resend_invite",
      description:
        "当用户找不到邀请邮件或表示它已过期时，重新发送邀请邮件。",

      // 输入 schema 是可在 execute 函数中访问的数据。
      inputSchema: {
        type: "object",
        properties: {
          email: {
            type: "string",
            description:
              "要重新发送邀请的电子邮件地址。如果未知，请先询问用户。",
          },
        },
        required: ["email"],
      },

      // 一个可选的确认按钮，在执行 execute 函数之前显示。
      confirmation: { icon: "paper-plane", label: "重新发送邀请？" },

      // execute 函数是在使用工具时将被调用的函数。
      execute: async (input) => {
        const { email } = input;

        const result = await fetch("/api/invites/resend", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email }),
        }).then((r) => r.json());

        return {
          // 输出会传回给 AI。
          output: {
            recipient: email,
            status: result.status ?? "success",
          },
          // 摘要会显示给用户。
          summary: {
            icon: "check",
            text: "已重新发送邀请邮件。",
          },
        };
      },
    },
  ],
});
```

### 工具如何被使用

一旦你注册了工具，Assistant 就可以根据用户的问题和你的工具自动选择它们 `描述`.

如果缺少必填字段，Assistant 应该继续提问。

如果你添加 `confirmation`，用户必须在工具运行前批准。

### 工具字段

* `name`：唯一标识符。
* `描述`：Assistant 的“何时使用此工具”提示。
* `inputSchema`：工具输入的 JSON Schema。
* `confirmation` （可选）：在工具运行前显示的确认按钮。
* `execute(input)`：执行该操作的异步函数。
  * 返回 `{ output, summary }`.
  * `output` 会返回给 Assistant。
  * `summary` 会显示给用户。

#### 确认

使用 `confirmation` 用于你希望用户批准某个操作时。它有助于防止意外的副作用。

`confirmation` 接受：

* `标签` （必填）：按钮文本。
* `icon` （可选）：一个 [访问](https://fontawesome.com/search) 图标名称。

### 支持工作流

支持是工具最具价值的使用场景。

你可以让 Assistant：

* 收集缺失的信息
* 在你的系统中创建工单
* 打开一个带有预填上下文的人类支持渠道

#### 模板：打开带有预填消息的支持聊天

当你想要顺畅地转接给真人时，请使用此方式。

```javascript
window.GitBook("configure", {
  tools: [
    {
      name: "open_support_chat",
      description:
        "打开支持聊天并预填消息，以便用户快速联系支持。",
      inputSchema: {
        type: "object",
        properties: {
          message: {
            type: "string",
            description:
              "发送给支持团队的消息。如果缺少，请先询问用户。",
          },
        },
      },
      confirmation: { icon: "circle-question", label: "打开支持聊天" },
      execute: (input) => {
        // 关闭 GitBook Assistant
        window.GitBook('close');
     
        // 示例：
        // - Intercom: Intercom('showNewMessage', input.message);
        // - Zendesk: zE('messenger', 'open');
        
        return {
          output: {
            status: "success",
          },
          summary: { icon: 'check', text: "已转交支持团队。" },
        };
      },
    },
  ],
});
```

{% hint style="info" %}
将此与始终可见的 **联系支持** 操作配合使用，放在嵌入侧边栏中。你可以按照以下方式配置操作 [自定义嵌入](/docs/documentation/zh/docs-site/embedding/configuration/customizing-docs-embed.md).
{% endhint %}

### 下一步

* 需要完整的嵌入 API 表面吗？请参见 [API 参考](/docs/documentation/zh/docs-site/embedding/configuration/reference.md).
* 想要更多 UI 控件（问候语、建议、操作）？请参见 [自定义嵌入](/docs/documentation/zh/docs-site/embedding/configuration/customizing-docs-embed.md).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.com/docs/documentation/zh/docs-site/embedding/configuration/creating-custom-tools.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
