> 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).

# Web SDK 快速入门

使用来自 npm 的 Convai Web SDK 构建一个 React 页面，连接到 Convai 角色，向其发送文本消息，并显示回复。

在本快速入门中，我们将使用 Convai Web SDK 将一个 React 页面连接到 Convai 角色，向角色发送消息，并显示它的回复。完成后，你将拥有一个带有 **连接** 按钮和正在运行的对话的页面。

### 我们将构建什么

我们将构建一个 React 组件，使用 `useConvaiClient`创建客户端，并在你选择 **连接**时连接、发送问候语，并列出双方的消息。角色会以文本形式回复，且默认也会通过语音回复。

### 前提条件

* 一个使用打包工具的 React 18 或 19 项目。
* 一个 Convai 账户，以及从 <code class="expression">space.vars.dashboard\_url</code>.
* 你在 Convai 中创建的角色 ID。

### 安装 SDK

安装 `@convai/web-sdk`版本 <code class="expression">space.vars.web\_sdk\_version</code> 或更高版本：

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

### 创建客户端

我们使用 `useConvaiClient`在每个组件中创建一次客户端。配置会被保存，并在调用 `connect()`. `endUserId` 是使用该页面用户的稳定 ID；Convai 会将它用于长期记忆和分析。 `AudioRenderer`位于 `AudioContext` 提供程序内，并接收 `client.room`，用于播放角色的语音。

{% code title="src/App.tsx" %}

```tsx
import { useConvaiClient } from '@convai/web-sdk/react';
import { AudioRenderer, AudioContext } from '@convai/web-widget/react';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    endUserId: 'user-123',
  });

  const handleConnect = async () => {
    try {
      await client.connect();
    } catch (err) {
      // connect() 会因 Convai 返回的原因而拒绝。
      console.error('Connect failed:', err);
    }
  };

  const handleSend = () => {
    client.sendUserTextMessage('Hello. Who are you?');
  };

  return (
    <AudioContext.Provider value={client.room}>
      {/* 播放角色的语音 */}
      <AudioRenderer />
      <p>状态：{client.activity}</p>

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

      <ul>
        {client.chatMessages
          .filter(
            (m) =>
              m.type === 'user-llm-text' ||
              m.type === 'user-transcription' ||
              m.type === 'bot-llm-text' ||
              m.type === 'bot-output',
          )
          .map((m) => (
            <li key={m.id}>
              <strong>{m.type.startsWith('user') ? 'You' : 'Character'}:</strong> {m.content}
            </li>
          ))}
      </ul>
    </AudioContext.Provider>
  );
}
```

{% endcode %}

状态栏显示 `client.activity`，这是一个由 Hook 持续更新的字符串： `"Idle"` 首次连接前，然后是 `"Connecting..."`, `"Connected"`, `"Listening"`, `"Thinking"`, `"Speaking"`，或 `"Disconnected"`.

### 运行对话

启动开发服务器并打开页面。选择 **连接** 并等待，直到 **打招呼** 按钮启用。在 `client.isBotReady` 为 `true`之前，按钮会保持禁用状态；这与 `ConvaiWidget` 发送文本前执行的检查相同。

选择 **打招呼**。你的消息会立即作为一条 `user-llm-text` 消息出现在列表中，角色的回复则会以流式方式作为一条 `bot-llm-text` 消息传入。

{% hint style="success" %}
状态变为 `Thinking` ，随后变为 `Speaking`。回复文本会显示在你的消息下方，同时你会听到角色的声音。
{% endhint %}

{% hint style="danger" %}
此页面会将你的 API 密钥发送到浏览器。仅用于本地开发。若要创建他人也能打开的页面，请在服务器上创建一个短时有效的身份验证令牌，并传入 `authToken` 改为。请参阅 [使用身份验证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md).
{% endhint %}

### 后续步骤

{% content-ref url="/pages/582066e7524392f36f74e9cf6ee977b3a11c8c00" %}
[开始使用 React](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/react.md)
{% endcontent-ref %}

{% content-ref url="/pages/454c92abc7b09c6c632d94aa99c7adc9ccd49df0" %}
[开始使用原生 TypeScript](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript.md)
{% endcontent-ref %}

{% content-ref url="/pages/29f9aac19fcc2f8cd08338eeb8c9340da2c133cf" %}
[使用 blendshape 驱动面部动画](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/lipsync-and-blendshape.md)
{% endcontent-ref %}

{% content-ref url="/pages/1ef8009eea712d4c41fd7a2a07e473a277395698" %}
[处理错误和断开连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md)
{% endcontent-ref %}


---

# 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/quickstart.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.
