> 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/quickstart.md).

# 快速入门

### 先决条件

* 一个带 API 密钥的 Convai 账号——可在以下网址获取： [convai.com](https://convai.com)
* 来自你 Convai 仪表板的角色 ID
* Node.js 18+ 和一个 React 项目（Vite、Next.js 或 CRA）

### 安装

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

### 你的第一段对话（React）

这是连接到角色并交换文本消息所需的最少代码。

```tsx
import { useConvaiClient } from '@convai/web-sdk';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    // 推荐：为每个终端用户使用一个稳定的 id。它会为该用户建立角色的
    // 跨会话长期记忆。
    endUserId: 'user-123',
  });

  const handleConnect = async () => {
    try {
      await client.connect();
    } catch (err) {
      // connect() 会因服务器原因而拒绝——要展示出来，不要吞掉。
      // 例如，“LTM speaker limit reached” 表示此 API 密钥已达到其
      // 面向新 endUserId 的长期记忆说话者上限。
      console.error('连接失败：', err);
    }
  };

  const handleSend = () => {
    client.sendUserTextMessage('你好！你是谁？');
  };

  return (
    <div>
      <p>状态：{client.activity}</p>

      {!client.state.isConnected ? (
        <button onClick={handleConnect}>连接</button>
      ) : (
        <button onClick={handleSend}>打个招呼</button>
      )}

      <ul>
        {client.chatMessages
          .filter(m => m.type === 'bot-output' || m.type === 'user-llm-text')
          .map(m => (
            <li key={m.id}>
              <strong>{m.type.startsWith('user') ? '你' : '机器人'}：</strong> {m.content}
            </li>
          ))}
      </ul>
    </div>
  );
}
```

#### 这是做什么的

1. `useConvaiClient` 创建一个持久的客户端实例，并连接 React 状态。
2. `client.connect()` 会打开一个 WebRTC 会话。角色在以下条件满足后就已准备就绪： `client.isBotReady` 为 `true`.
3. `client.sendUserTextMessage` 向角色发送文本；回复会以 `chatMessages`.
4. `client.activity` 是一个显示当前状态的字符串： `“空闲”`, `“连接中...”`, `“已连接”`, `“聆听中”`, `“思考中”`，或者 `“说话中”`.

### 即插即用组件

如果你想要一个完整构建好的聊天界面（语音 + 文本），请使用 `ConvaiWidget`:

```tsx
import { useConvaiClient } from '@convai/web-sdk';
import { ConvaiWidget } from '@convai/web-sdk/react';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    startWithAudioOn: false, // 仅在用户进入语音模式时请求麦克风权限
  });

  return <ConvaiWidget convaiClient={client} />;
}
```

该组件开箱即用地处理连接、麦克风、语音模式和消息显示。

### 添加一个会说话的 3D 角色

两行配置即可为 3D 头像开启面部动画流：

```tsx
const client = useConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableLipsync: true,
  blendshapeConfig: { format: 'mha' }, // 'mha'（MetaHuman 251）或 'arkit'（61）
});

// client.blendshapeQueue 现在会缓冲每帧的 blendshape 值，
// 并与机器人语音同步——将它们传给你的渲染器。
```

有关渲染循环集成、角色映射，以及让它更自然的模式（淡入淡出、眨眼归属、按通道增益），请参阅 Lipsync & Blendshapes。 `examples/react-three-fiber` 演示是一个完整的生产风格参考：在带灯光的房间里，一个类 MetaHuman 角色具备唇形同步、程序化眨眼/凝视/头部跟踪、身体动画、SDK 驱动的动作，以及一个脚本化的开场场景。

### 首次连接故障排查

| 症状                                            | 原因 / 修复                                                                                                                  |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `connect()` 拒绝并返回 `LTM speaker limit reached` | 该 API 密钥已达到其长期记忆说话者上限；请复用现有的 `endUserId` ，或在仪表板中提高限制。                                                                    |
| 角色已连接，但在触发器上保持静默                              | `sendTriggerMessage` 通过其 **仪表板名称** （例如 `“Welcome”`）来解析触发器，而不是触发器的 UUID——未知名称会被静默忽略。                                      |
| 没有 blendshape 帧                               | `enableLipsync: true` 缺失，或者是在配置更改前就启动了组件/会话——请在修改配置后重新加载。                                                                |
| 自定义聊天界面中的机器人文本重复/乱码                           | 渲染 `bot-llm-text` 消息； `bot-output` 事件是 TTS 进度滴答（相同的 `segment_id` 会在每个滴答中重新发送）——SDK 自 v1.5 起会去重。 `chatMessages` 自 v1.5 起。 |

### 原生 JavaScript

不用 React？直接使用 `ConvaiClient` ：

```ts
import { ConvaiClient } from '@convai/web-sdk/core';
import { AudioRenderer } from '@convai/web-sdk/vanilla';

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

// 通过扬声器播放机器人音频
const audio = new AudioRenderer(client.room);

client.on('botReady', () => {
  console.log('角色已准备就绪');
  client.sendUserTextMessage('你好！');
});

client.on('message', (msg) => {
  if (msg.type === 'bot-output') {
    console.log('机器人：', msg.content);
  }
});

await client.connect();
```

### 后续步骤

* 配置参考——全部 `ConvaiConfig` 选项
* React 集成——hooks、组件、定制 UI
* 唇形同步与 blendshape——驱动 3D 角色的面部
* 动作与触发器——让角色执行动作，并用 `sendTriggerMessage`
* 事件参考——客户端发出的每一个事件
* 语音与音频控制——麦克风、摄像头、屏幕共享


---

# 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 dynamically by asking a question.

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

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
