> 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` provider，该 provider 接收 `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('连接失败：', 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') ? '你' : '角色'}:</strong> {m.content}
            </li>
          ))}
      </ul>
    </AudioContext.Provider>
  );
}
```

{% endcode %}

状态行显示 `client.activity`，这是 hook 持续更新的字符串： `"空闲"` 在第一次连接之前，然后 `"连接中..."`, `"已连接"`, `"聆听中"`, `"思考中"`, `"说话中"`，或 `"已断开"`.

### 运行对话

启动你的开发服务器并打开页面。选择 **连接** 并等待直到 **打个招呼** 按钮启用。该按钮在以下情况之前一直处于禁用状态： `client.isBotReady` 是 `true`，同样的检查 `ConvaiWidget` 在发送文本之前也适用。

选择 **打个招呼**。你的消息会立即以一条 `user-llm-text` 消息出现在列表中，而角色的回复会以一条 `bot-llm-text` 消息流式显示。

{% hint style="success" %}
状态变为 `思考中` 然后 `说话中`，回复文本会显示在你的消息下方，你还能听到角色的声音。
{% endhint %}

{% hint style="danger" %}
此页面会将你的 API 密钥发送到浏览器。仅用于本地开发。对于其他人可以打开的页面，请在你的服务器上创建一个短期有效的认证令牌，并传递 `authToken` 而不是。参见 [使用认证令牌连接](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md).
{% endhint %}

### 后续步骤

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

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

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

{% content-ref url="/pages/1ef8009eea712d4c41fd7a2a07e473a277395698" %}
[处理错误和断开连接](/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.
