---
title: "安装"
description: "Server AI 工具包的安装指南。了解如何安装、配置认证，并开始使用 Server AI 工具包云服务。"
canonical_url: "https://tiptap.zhcndoc.com/content-ai/capabilities/server-ai-toolkit/install"
---

# 安装

Server AI 工具包的安装指南。了解如何安装、配置认证，并开始使用 Server AI 工具包云服务。

- **1. 请求访问权限**

  通过
  联系我们的团队
  来请求访问 Server AI 工具包。
- **2. 安装该包**

  Server AI 工具包包是开源的。请使用 npm 或您偏好的包管理器从公共 npm 注册表安装。
- **3. 认证到该服务**

  配置一个

  Tiptap 访问控制 JWT

  以访问 Server AI Toolkit 服务。

首先，联系我们的团队 以获取 Server AI 工具包的访问权限。

然后，安装开源的 Server AI 工具包包：

```bash
npm install @tiptap/server-ai-toolkit
```

## 获取编辑器上下文

首先，在编辑器中安装 `ServerAiToolkit` 扩展。这将修改您的编辑器架构，使您的文档与 Server AI 工具包兼容。

要使用 Server AI 工具包 API，请从您的 Tiptap 编辑器中获取编辑器上下文。这个 JSON 对象包含编辑器 schema 以及 AI 服务器理解有效文档内容所需的其他数据。

```tsx
import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'
import { getEditorContext, ServerAiToolkit } from '@tiptap/server-ai-toolkit'

const editor = new Editor({
  extensions: [StarterKit, ServerAiToolkit],
})

// 从编辑器获取编辑器上下文
const editorContext = getEditorContext(editor)
```

在您向 Server AI 工具包发送的每个请求中都传递 `editorContext`。

> **存储编辑器上下文:**
>
> `getEditorContext` 返回的编辑器上下文是可 JSON 序列化的。您可以将其存储在数据库中，并且只在编辑器扩展或 schema 发生变化时更新它。

> **使用自定义节点？:**
>
> 如果您的编辑器包含自定义节点或标记，请使用 `addJsonSchemaAwareness` 进行配置。请参阅
> [自定义节点指南](https://tiptap.zhcndoc.com/content-ai/capabilities/server-ai-toolkit/advanced-guides/custom-nodes.md)。

更多详情请参阅 [编辑器上下文 API 参考](https://tiptap.zhcndoc.com/content-ai/capabilities/server-ai-toolkit/api-reference/editor-context.md)。

## 配置授权

Server AI 工具包是一个云端或本地服务。需认证后方可访问其 REST API。

1. **创建密钥** in the Tiptap Cloud dashboard. Go to `Authentication > Secrets > Add Secret`. The dashboard generates an ES256 key pair and shows you the **private key** once. Store the private key.
2. **复制你的环境 ID** from the dashboard. Go to `Authentication > Environment ID`. Use it as the JWT `iss` claim.
3. **在你的服务器上生成 Tiptap Access Control JWT**. See the [JWT token guide](#create-a-jwt-token) below.
4. **在 API 请求中使用 JWT**. Pass it in the `Authorization: Bearer JWT` header.

For the full JWT format and signing examples, see the [Authentication reference](https://tiptap.zhcndoc.com/authentication.md).

### 环境变量

配置以下环境变量：

```sh
# .env
TIPTAP_CLOUD_AI_API_URL=https://api.tiptap.dev
TIPTAP_ENVIRONMENT_ID=your-environment-hash-id
TIPTAP_PRIVATE_KEY=your-private-key-pem
```

- **TIPTAP\_CLOUD\_AI\_API\_URL**: Server AI 工具包 API 的基础 URL。
- **TIPTAP\_ENVIRONMENT\_ID**: 来自 Tiptap 仪表板的环境哈希 ID。签发令牌时用作 `iss` 声明。
- **TIPTAP\_PRIVATE\_KEY**: 来自 Tiptap 仪表板的 ES256 私钥（PKCS#8 PEM）。用于在服务器端签署令牌。

### 创建 JWT 令牌

`createJwtToken` 函数为 Server AI 工具包 API 签发令牌。当 AI 工具包需要读取和编辑 Tiptap Cloud 文档时，请传入 `documentId`。

```ts
// lib/server-ai-toolkit/create-jwt-token.ts
import { SignJWT, importPKCS8 } from 'jose'

/**
 * 签发用于与 Server AI 工具包 API 进行身份验证的 JWT
 */
export async function createJwtToken(documentId?: string): Promise<string> {
  const privateKey = await importPKCS8(process.env.TIPTAP_PRIVATE_KEY!, 'ES256')

  const permissions: { action: string; resource: string }[] = [
    { action: 'AI:Toolkit', resource: '*' },
  ]

  if (documentId) {
    permissions.push({ action: 'Documents:Write', resource: documentId })
  }

  return new SignJWT({ permissions })
    .setProtectedHeader({ alg: 'ES256' })
    .setIssuer(process.env.TIPTAP_ENVIRONMENT_ID!)
    .setAudience(documentId ? ['AI', 'Documents'] : ['AI'])
    .setIssuedAt()
    .setExpirationTime('30m')
    .sign(privateKey)
}
```

### 获取身份验证头

此函数返回 Server AI 工具包 API 请求所需的身份验证头。它是异步的，因为它会签发一个新的 JWT，因此所有示例都使用 `await getAuthHeaders(...)`。

```ts
// lib/server-ai-toolkit/get-auth-headers.ts
import { createJwtToken } from './create-jwt-token'

/**
 * 返回 Server AI 工具包 API 的身份验证头
 */
export async function getAuthHeaders(documentId?: string): Promise<Record<string, string>> {
  return {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${await createJwtToken(documentId)}`,
  }
}
```

> **Alternative: provide documents directly:**
>
> 如果你在自己的存储中管理文档，而不是使用 Tiptap Cloud，则省略 `documentId` 选项
> 并在 API 请求中通过 `document` 字段直接传递文档。此时令牌只需要
> `AI:Toolkit` 权限。

> **Maintaining an existing integration?:**
>
> 之前的 App ID 和 secret（HS256）流程会将 App ID 发送到 `X-App-Id`，并将
> 文档服务器凭据嵌入为 JWT 声明，该流程记录在 [Legacy
> authentication](https://tiptap.zhcndoc.com/authentication/legacy.md) 中。

## 调用 API 端点

完成身份验证后，使用 `getAuthHeaders` 函数调用 Server AI 工具包 API 端点：

```ts
import { getAuthHeaders } from './lib/server-ai-toolkit/get-auth-headers'

const apiBaseUrl = process.env.TIPTAP_CLOUD_AI_API_URL || 'https://api.tiptap.dev'

const response = await fetch(`${apiBaseUrl}/v4/ai/toolkit/fetch-tools`, {
  method: 'POST',
  headers: await getAuthHeaders(),
  body: JSON.stringify({
    editorContext,
    tools: {
      tiptapRead: true,
      tiptapEdit: true,
    },
  }),
})

const tools = await response.json()
```

完整的 API 文档请参见 [REST API 参考](https://tiptap.zhcndoc.com/content-ai/capabilities/server-ai-toolkit/api-reference/rest-api.md)。

## 后续步骤

现在您已配置好 Server AI 工具包，开始构建您的 AI 集成：

[AI 代理聊天机器人
了解更多 →构建一个能够通过聊天交互并编辑文档的对话式 AI。](https://tiptap.zhcndoc.com/content-ai/capabilities/server-ai-toolkit/agents/ai-agent-chatbot.md)
