> 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` 是从 `@convai/web-sdk/react`导出的 React Hook。它会在组件的整个生命周期内创建一个 `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()` 且未提供参数时会使用此配置。之后对该参数的更改将被忽略。所有字段均列于 [配置和类型参考](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). |

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

### React 状态

这些字段属于 React 状态。在渲染期间读取它们，可使组件与对话保持同步。

| 字段                    | 类型                  | 更新时机                                                                           |
| --------------------- | ------------------- | ------------------------------------------------------------------------------ |
| `state`               | `ConvaiClientState` | 客户端触发 `stateChange`, `connect`或 `disconnect`.                                  |
| `activity`            | `string`            | 客户端触发 `stateChange`, `botReady`或 `disconnect`。请参阅 [活动值](#activity-values).     |
| `chatMessages`        | `ChatMessage[]`     | 客户端触发 `messagesChange`。清空为 `[]` 当 `disconnect`.                                |
| `userTranscription`   | `string`            | 客户端会发出 `userTranscriptionChange`。保存语音的实时非最终转录文本。                               |
| `isBotReady`          | `boolean`           | 设为 `true` 当 `botReady` 并设为 `false` 当 `disconnect`.                             |
| `isAudioMuted`        | `boolean`           | `audioControls` 会发出 `audioStateChange`。在 `true` 时设为 `disconnect`.              |
| `isVideoEnabled`      | `boolean`           | `videoControls` 会发出 `videoStateChange`。在 `false` 时设为 `disconnect`.             |
| `isScreenShareActive` | `boolean`           | `screenShareControls` 会发出 `screenShareStateChange`。在 `false` 时设为 `disconnect`. |

`activity`, `isAudioMuted`, `isVideoEnabled`和 `isScreenShareActive` 仅存在于钩子的返回值中。直接创建的 `ConvaiClient` 不包含这些属性。

### 活动状态值

`activity` 初始值为 `"Idle"`。之后，钩子会按以下优先级顺序，根据客户端状态设置该值：

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

### 客户端值

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

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

### 方法

每个方法都绑定到此 Hook 的客户端，因此可以直接将其作为事件处理程序传入。行为、参数和错误的说明请参阅 [ConvaiClient 参考文档](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md).

| 方法                                                   | 备注                                                                                                                             |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `connect(config?)`                                   | 使用 `config`连接；如果未提供，则使用传给 Hook 的配置。若两者都不存在，则抛出 `No configuration provided. Pass config to useConvaiClient() or to connect()` 。 |
| `connectWithPublicationGrant(launchToken, options?)` | 使用一次性启动令牌连接到已发布的文本聊天。                                                                                                          |
| `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](https://docs.convai.com/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 参考](https://docs.convai.com/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" %}
[配置和类型参考](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)
{% endcontent-ref %}

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

{% content-ref url="/pages/eb896fafee38ed6296228fce9cc8190b93be03b8" %}
[ConvaiWidget 组件参考](https://docs.convai.com/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.
