> 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/react/useconvaiclient-hook.md).

# useConvaiClient Hook 参考

负责管理 Convai 客户端的 React Hook 参考，包括其参数、返回的每个字段，以及它为渲染所维护的状态。

`useConvaiClient` 是从以下内容导出的 React Hook `@convai/web-sdk/react`。它会创建一个 `ConvaiClient` 在组件的整个生命周期内，订阅其事件，并返回客户端的 API 以及 React 状态；当对话发生变化时，该状态会重新渲染组件。

### 签名

```ts
function useConvaiClient(config?: ConvaiConfig): IConvaiClient & {
  connectWithPublicationGrant: (
    launchToken: string,
    options?: PublishedChatConnectOptions,
  ) => Promise<void>;
  activity: string;
  chatMessages: ChatMessage[];
  isAudioMuted: boolean;
  isVideoEnabled: boolean;
  isScreenShareActive: boolean;
};
```

| 参数       | 类型             | 默认值 | 描述                                                                                                                                                                                             |
| -------- | -------------- | --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config` | `ConvaiConfig` | 无   | 首次渲染时存储的连接配置，并由 `connect()` 在不传入参数时使用。之后对该参数的更改会被忽略。每个字段都列在 [配置与类型参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md). |

该 hook 仅创建一次客户端，使用 `useState`。组件卸载时会移除监听器，并移除隐藏的 WebSocket 音频元素。该 hook 不会在卸载时断开连接；请调用 `disconnect()` 在会话应结束时自行调用。

### React 状态

这些字段是 React 状态。在 render 中读取它们可使组件与对话保持同步。

| 字段                    | 类型                  | 在以下情况更新                                                                        |
| --------------------- | ------------------- | ------------------------------------------------------------------------------ |
| `状态`                  | `ConvaiClientState` | 客户端会发出 `stateChange`, `connect`，或 `disconnect`.                                |
| `activity`            | `字符串`               | 客户端会发出 `stateChange`, `botReady`，或 `disconnect`时发送。参见 [活动值](#activity-values). |
| `chatMessages`        | `ChatMessage[]`     | 客户端会发出 `messagesChange`。清除为 `[]` 在 `disconnect`.                               |
| `userTranscription`   | `字符串`               | 客户端会发出 `userTranscriptionChange`。保存你语音的实时、非最终转写。                               |
| `isBotReady`          | `布尔值`               | 设置为 `true` 在 `botReady` 并设置为 `false` 在 `disconnect`.                           |
| `isAudioMuted`        | `布尔值`               | `audioControls` 发出 `audioStateChange`。设置为 `true` 在 `disconnect`.               |
| `isVideoEnabled`      | `布尔值`               | `videoControls` 发出 `videoStateChange`。设置为 `false` 在 `disconnect`.              |
| `isScreenShareActive` | `布尔值`               | `screenShareControls` 发出 `screenShareStateChange`。设置为 `false` 在 `disconnect`.  |

`activity`, `isAudioMuted`, `isVideoEnabled`，以及 `isScreenShareActive` 仅存在于该 hook 的返回值中。 `ConvaiClient` 直接创建的对象没有这些属性。

### 活动值

`activity` 初始为 `"空闲"`。之后，hook 会按以下优先级顺序从客户端状态中设置它：

| 值          | 在以下情况设置                            |
| ---------- | ---------------------------------- |
| `"连接中..."` | `state.isConnecting` 为 `true`.     |
| `"已断开"`    | 未连接且未在连接中，或者客户端发出 `disconnect`.    |
| `"说话中"`    | 角色正在说话。                            |
| `"聆听中"`    | 你正在说话。                             |
| `"思考中"`    | 角色正在准备回复。                          |
| `"已连接"`    | 已连接，但不属于上述任何情况，或者当 `botReady` 触发时。 |

### 客户端值

每次组件渲染时都会从客户端读取这些字段。它们本身不会触发渲染。

| 字段                       | 类型                                     | 描述                                                    |
| ------------------------ | -------------------------------------- | ----------------------------------------------------- |
| `connectionType`         | `'audio' \| 'video' \| 'text' \| null` | 当前会话的连接类型。 `null` 在未连接时。                              |
| `isPublishedChatSession` | `布尔值`                                  | `true` 当客户端上次使用以下方式连接时 `connectWithPublicationGrant`. |
| `apiKey`                 | `字符串`                                  | 当前连接的 API 密钥。仅在使用过时才会存在。                              |
| `authToken`              | `字符串`                                  | 当前连接的身份验证令牌。仅在使用过时才会存在。                               |
| `characterId`            | `字符串 \| null`                          | 当前连接的角色 ID。                                           |
| `characterSessionId`     | `字符串 \| null`                          | Convai 为当前对话返回的会话 ID。                                 |
| `requestTraceId`         | `字符串 \| null`                          | 最近一次连接请求的跟踪 ID（如果 Convai 提供了）。                        |
| `conversationSessionId`  | `数值`                                   | 由以下内容使用的轮次计数器： `conversationStart` 和 `turnEnd` 事件。    |
| `room`                   | `Room`                                 | LiveKit 房间。将其传递给 `AudioContext.Provider` 用于自定义 UI。    |
| `audioControls`          | `AudioControls`                        | 麦克风控制。                                                |
| `videoControls`          | `VideoControls`                        | 摄像头和视觉源控制。                                            |
| `screenShareControls`    | `ScreenShareControls`                  | 屏幕共享控制。                                               |
| `blendshapeQueue`        | `BlendshapeQueue`                      | 已缓冲的口型同步帧。                                            |
| `memoryManager`          | `MemoryManager \| null`                | 长期记忆 API。 `null` 直到使用以下方式连接： `endUserId`.             |

### 方法

每个方法都绑定到该 hook 的客户端，因此你可以将其直接作为事件处理器传入。其行为、参数和错误记录在 [ConvaiClient 参考文档](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md).

| 方法                                                   | 注意                                                                                                   |
| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `connect(config?)`                                   | 使用以下方式连接： `config`，或者使用传递给该 hook 的配置。抛出 `未提供配置。请将 config 传给 useConvaiClient() 或 connect()` 当两者都不存在时。 |
| `connectWithPublicationGrant(launchToken, options?)` | 使用一次性 launch token 连接到已发布的文本聊天。                                                                      |
| `disconnect()`                                       | 结束会话。                                                                                                |
| `reconnect()`                                        | 使用上次保存的配置重新连接。                                                                                       |
| `resetSession()`                                     | 清除对话，并在下次连接时启动新会话。在实时连接中，请先调用 `disconnect()` ，然后 `connect()` 再次调用。                                   |
| `sendUserTextMessage(text, options?)`                | 发送文本消息。                                                                                              |
| `sendTriggerMessage(triggerName?, triggerMessage?)`  | 触发一个触发器。                                                                                             |
| `sendInterruptMessage()`                             | 中断角色当前的回复。                                                                                           |
| `sendActionResult(result)`                           | 返回客户端工具调用的结果。                                                                                        |
| `resetIdleTimer()`                                   | 重置会话的空闲计时器。                                                                                          |
| `updateTemplateKeys(templateKeys)`                   | 替换叙事设计模板键。                                                                                           |
| `updateDynamicInfo(dynamicInfo)`                     | 发送动态上下文文本。                                                                                           |
| `updateContext(options)`                             | 追加、替换或重置运行时上下文。                                                                                      |
| `updateEmotion(stateOfMind)`                         | 设置或清除角色的心境。                                                                                          |
| `updateSceneMetadata(items, options?)`               | 发送描述性场景项。                                                                                            |
| `visionStatus(options?)`                             | 请求视觉缓冲区状态。                                                                                           |
| `visionTrigger(options?)`                            | 附加已缓冲的视觉帧，并可选择请求回复。                                                                                  |
| `respondModeUpdate(options)`                         | 更改会话的响应模式。                                                                                           |
| `toggleTts(enabled)`                                 | 开启或关闭语音输出。                                                                                           |
| `toggleStt(enabled)`                                 | 开启或关闭语音转文本。                                                                                          |
| `uploadFile(file, options?)`                         | 通过 LiveKit 传输发送文件。                                                                                   |
| `on(event, callback)`                                | 订阅客户端事件并返回取消订阅函数。                                                                                    |
| `off(event, callback)`                               | 移除监听器。                                                                                               |

### WebSocket 音频播放

当会话使用 `transport: "websocket"`时，Pipecat 传输会通过 Web Audio 自行播放角色的声音，因此无需额外代码。使用默认的 LiveKit 传输时，请渲染 `AudioRenderer` 或 `ConvaiWidget` 以听到角色的声音。参见 [在 React 中构建自定义 UI](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/react/custom-ui-and-advanced-usage.md).

### 示例

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

export function ConnectButton() {
  const client = useConvaiClient();

  const connect = () =>
    client.connect({
      apiKey: 'YOUR_API_KEY',
      characterId: 'YOUR_CHARACTER_ID',
    });

  return (
    <button onClick={connect} disabled={client.state.isConnected}>
      {client.activity}
    </button>
  );
}
```

### 相关参考

{% content-ref url="/pages/f1fc7386520b3ebeeafa719a8d9efb554e1d7024" %}
[ConvaiClient 参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/dff296725774f9173a7391e28344f5f94cf35b60" %}
[配置和类型参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md)
{% endcontent-ref %}

{% content-ref url="/pages/8c6e3631e7e7da5b3c9acf5a0019d7737dc79e19" %}
[Web SDK 事件参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/eb896fafee38ed6296228fce9cc8190b93be03b8" %}
[ConvaiWidget 组件参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/react/convaiwidget.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/react/useconvaiclient-hook.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.
