> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript.md).

# 开始使用原生 TypeScript

在没有 UI 框架的项目中安装 Convai Web SDK，将客户端连接到角色，并添加可选的聊天小组件。

通过纯 TypeScript 或 JavaScript 连接到 Convai 角色，无需 React 或其他 UI 框架。首次在无框架项目中设置 SDK 时，请参考本页。完成后，页面中将包含一个已连接的客户端，以及可选的预构建聊天组件。

### 前提条件

* 一个使用包管理器且打包工具能够解析 npm 包的项目。
* 一个 Convai 账户、一个来自 <code class="expression">space.vars.dashboard\_url</code>的 API 密钥，以及一个角色 ID。

### 安装软件包

原生 API 属于单一的 `@convai/web-sdk` 包。无需安装单独的包。

{% tabs %}
{% tab title="npm" %}

```bash
npm install @convai/web-sdk @convai/web-widget
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @convai/web-sdk @convai/web-widget
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @convai/web-sdk @convai/web-widget
```

{% endtab %}
{% endtabs %}

从 `@convai/web-sdk/vanilla`导入。它导出了 `ConvaiClient`、SDK 自带的 `AudioRenderer` 类以及所有核心类型。预构建聊天 UI 中的 `createConvaiWidget` 和 `destroyConvaiWidget`也可通过 `@convai/web-widget/vanilla`. `ConvaiClient` 获取。也可以从 `@convai/web-sdk/core`.

### 创建并连接客户端

将配置传递给构造函数，订阅事件，然后调用 `connect()`。等待 `botReady` 后再发送第一条消息。

{% code title="src/main.ts" %}

```typescript
import { ConvaiClient } from '@convai/web-sdk/vanilla';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  endUserId: 'user-uuid', // 可选：启用长期记忆和按用户统计分析
});

client.on('stateChange', (state) => {
  console.log('Agent state:', state.agentState);
});

client.on('message', (message) => {
  console.log(message.type, message.content);
});

client.on('botReady', () => {
  client.sendUserTextMessage('Hello!');
});

try {
  await client.connect();
} catch (error) {
  console.error('Connect failed:', error);
}
```

{% endcode %}

`connect()` 需要 `characterId` 以及 `apiKey` 或 `authToken`。缺少这些参数时，它会抛出 `Either apiKey or authToken is required, and characterId is required`。你也可以省略构造函数参数，改为将配置传递给 `connect(config)` 。

设置 `enableVideo: true` 以开启支持摄像头和屏幕共享的视频连接。默认值为 `false`，此时连接仅支持音频。

{% hint style="danger" %}
客户端代码中的 API 密钥，任何打开页面的人都能读取。对于公开页面，请在服务器上创建一个短期有效的身份验证令牌，并传入 `authToken` 代替 API 密钥。请参阅 [使用身份验证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md).
{% endhint %}

### 播放角色的音频

聊天小组件会为你播放角色的语音。如果你基于默认的 WebRTC 传输方式构建自定义 UI，请为客户端的房间创建一个 `AudioRenderer` 。否则，角色的音频不会附加到页面上。

```typescript
import { AudioRenderer } from '@convai/web-sdk/vanilla';

client.on('connect', () => {
  const audioRenderer = new AudioRenderer(client.room);
  // Call audioRenderer.destroy() when you tear the session down.
});
```

请参阅 [使用 TypeScript 构建自定义 UI](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/building-a-custom-ui-typescript.md) ，了解完整实现方式，包括 WebSocket 传输方式。

### 添加聊天小组件

`createConvaiWidget(container, options)` 会将一个现成的聊天和语音 UI 挂载到 DOM 元素中，并返回一个小组件句柄。小组件会在首次点击时连接客户端；断开连接后再次打开时，则会使用 `reconnect()` 重新连接。

```typescript
import { ConvaiClient } from '@convai/web-sdk/vanilla';
import { createConvaiWidget } from '@convai/web-widget/vanilla';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableVideo: true,
});

const widget = createConvaiWidget(document.body, {
  convaiClient: client,
  showVideo: true,
  showScreenShare: true,
});

// When you remove the widget:
widget.destroy(); // or destroyConvaiWidget(widget)
```

传入一个现有的 `convaiClient`，或传入凭据和角色 ID，以便小组件自行创建客户端。如果两者都未提供， `createConvaiWidget` 会抛出异常： `Either convaiClient or (apiKey or authToken) and characterId must be provided`.

| 选项                                   | 类型                               | 默认值     | 说明                                |
| ------------------------------------ | -------------------------------- | ------- | --------------------------------- |
| `convaiClient`                       | `ConvaiClient`                   | 无       | 小组件所驱动的客户端。                       |
| `apiKey`, `authToken`, `characterId` | `string`                         | 无       | 仅当未提供 `convaiClient` 时使用，用于创建客户端。 |
| `enableVideo`, `startWithVideoOn`    | `boolean`                        | `false` | 转发给该组件创建的客户端。                     |
| `enableLipsync`, `enableEmotion`     | `boolean`                        | `false` | 转发给该组件创建的客户端。                     |
| `blendshapeConfig`                   | `object`                         | 无       | 转发给该组件创建的客户端。                     |
| `showVideo`                          | `boolean`                        | `true`  | 在设置中显示摄像头开关。仅适用于视频连接。             |
| `showScreenShare`                    | `boolean`                        | `true`  | 在设置中显示屏幕共享开关。仅适用于视频连接。            |
| `defaultVoiceMode`                   | `boolean`                        | `true`  | 以语音模式打开组件。                        |
| `onConnect`                          | `() => void`                     | 无       | 客户端连接后调用。                         |
| `onDisconnect`                       | `() => void`                     | 无       | 客户端断开连接后调用。                       |
| `onMessage`                          | `(message: ChatMessage) => void` | 无       | 收到最新聊天消息时调用。                      |

当组件自行创建客户端时，它只会转发表格中的选项。若要设置其他 `ConvaiConfig` 字段，请自行创建客户端并将其作为 `convaiClient`.

返回的句柄提供 `element` （组件的根元素）、 `client`和 `destroy()`.

### 验证连接

加载页面，然后打开组件或调用 `connect()`。 `stateChange` 处理程序会在会话建立后记录 `connected` ，角色会在 `botReady` 触发后回复第一条消息。

### 后续步骤

<table data-view="cards"><thead><tr><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>ConvaiClient 参考</strong><br>客户端的所有属性、方法和控制接口。</td><td><a href="https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md">ConvaiClient 参考</a></td></tr><tr><td><strong>在 TypeScript 中处理事件和消息</strong><br>订阅状态、消息和转录内容，并渲染对话。</td><td><a href="https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/events-and-message-handling.md">在 TypeScript 中处理事件和消息</a></td></tr><tr><td><strong>使用原生 TypeScript 添加唇形同步</strong><br>在 three.js 角色上播放流式 blendshape 帧。</td><td><a href="https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/real-time-lipsync.md">在原生 TypeScript 中添加口型同步</a></td></tr><tr><td><strong>使用 TypeScript 构建自定义 UI</strong><br>接入自定义聊天界面、音频播放和媒体控件。</td><td><a href="https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/building-a-custom-ui-typescript.md">在 TypeScript 中构建自定义 UI</a></td></tr><tr><td><strong>配置和类型参考</strong><br>所有配置字段、状态字段和导出的入口点。</td><td><a href="https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md">配置和类型参考</a></td></tr><tr><td><strong>Blendshape 通道顺序参考</strong><br>ARKit 和 MetaHuman blendshape 帧的通道顺序。</td><td><a href="https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/mappings-reference.md">Blendshape 声道顺序参考</a></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
