# 连接到自定义工具

自定义工具可让 GitBook Assistant 在 [Docs Embed](https://gitbook-v2-q67etdj25-gitbook.vercel.app/url/gitbook.com/docs/documentation/zh/publishing-documentation/embedding) 中执行真实操作。

你可以将它连接到 *任何* 你的应用可以访问的工具。这包括你的后端 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 服务器](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/mcp-servers-for-published-docs) 在 **设置 → AI 与 MCP**.
{% endhint %}

### 工具运行的位置

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

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

因此你可以：

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

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

### 添加工具

定义工具：

* 通过 `window.GitBook("configure", …)` 用于 [script 标签](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/embedding/implementation/script) 实现
* 通过 `tools` 用于 [Node.js/NPM](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/embedding/implementation/nodejs) package 和 [React](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/embedding/implementation/react) 组件的

{% 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` 接受：

* `label` （必需）：按钮文本。
* `icon` （可选）：一个 [Font Awesome](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" %}
将其与始终可见的 **联系支持** 操作一起放在嵌入侧边栏中。你可以按照以下方式配置操作 [自定义嵌入](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/embedding/configuration/customizing-docs-embed).
{% endhint %}

### 后续步骤

* 需要完整的 embed API 能力面？请参阅 [API 参考](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/embedding/configuration/reference).
* 想要更多 UI 控件（问候语、建议、操作）？请参阅 [自定义嵌入](https://app.gitbook.com/s/NkEGS7hzeqa35sMXQZ4X/publishing-documentation/embedding/configuration/customizing-docs-embed).
