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

# Web SDK 事件参考

Convai Web SDK 客户端及其媒体控制发出的每个事件的参考，包括每个事件携带的负载以及触发时间。

`ConvaiClient` 通过……发出此页面上的事件 `on(event, callback)`，它返回一个取消订阅函数，并且 `off(event, callback)`。该 `useConvaiClient` 中的钩子 `@convai/web-sdk/react` 暴露相同的 `在` 并且 `移除监听`。事件名称是普通字符串，负载不由发射器进行类型标注，因此请使用导出的类型为回调参数添加注解。

```typescript
const unsubscribe = client.on('botReady', () => {
  client.sendUserTextMessage('Hello');
});

unsubscribe();
```

### 连接事件

| 事件                   | 负载                                                                            | 在以下情况下触发                                                                                                                                                                                    |
| -------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connect`            | 无                                                                             | `connect()` 或 `connectWithPublicationGrant()` 已打开传输层。角色仍可能尚未就绪；在发送前等待 `botReady` 后再发送。                                                                                                      |
| `botReady`           | 无                                                                             | 角色发出消息就绪信号。每个连接触发一次。                                                                                                                                                                        |
| `disconnect`         | `DisconnectReason` (`数值`)                                                     | 会话结束。代码为 `0` 当传输层未给出原因时。参见 [处理错误和断开连接](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md).                                                                     |
| `error`              | `未知`                                                                          | `connect()` 或 `connectWithPublicationGrant()` 失败（会重新抛出同一错误），或者在 LiveKit 传输层中，45 秒内未收到就绪信号（`未在 45000 毫秒内收到 bot-ready`).                                                                      |
| `stateChange`        | `ConvaiClientState`                                                           | 的任何字段 `client.state` 改变值。                                                                                                                                                                   |
| `interactionCreated` | `InteractionCreated`: `{ interactionId: string; characterSessionId: string }` | Convai 会为该会话分配一个交互 ID。                                                                                                                                                                      |
| `botAudioTrack`      | `MediaStreamTrack`                                                            | WebSocket 会话会暴露一个角色音轨。当前的 Pipecat WebSocket 传输不会触发此事件，因为它会自行播放语音，并且不暴露角色轨道。参见 [使用 WebSocket 传输](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/websocket-transport-layer.md). |

### 对话事件

| 事件                        | 负载                                                              | 在以下情况下触发                                                                                    |
| ------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `conversationStart`       | `{ sessionId: number; userMessage: string; timestamp: number }` | 新一轮开始。 `sessionId` 每轮递增，并匹配 `client.conversationSessionId`. `timestamp` 是一个 `Date.now()` 值。 |
| `turnEnd`                 | `{ sessionId: number; duration: number; timestamp: number }`    | 在至少开始过一轮之后，角色停止说话。 `持续时间` 是自对应的 `conversationStart`.                                        |
| `message`                 | `ChatMessage`                                                   | 消息列表发生变化。负载是列表中的最后一条消息，因此当流式消息增长时会再次触发。                                                     |
| `messagesChange`          | `ChatMessage[]`                                                 | 消息列表发生变化，包括流式更新和重置。                                                                         |
| `userTranscriptionChange` | `string`                                                        | 终端用户语音的实时转写发生变化。空字符串会清除它。                                                                   |
| `llmNoResponse`           | 无                                                               | 角色故意不回答这一轮。                                                                                 |
| `metrics`                 | `Record<string, unknown>`                                       | Convai 发送一条指标消息。原始数据也会追加到 `client.state.metrics`.                                           |

`conversationStart.userMessage` 标识了是什么触发了这一轮：

| 值                               | 由以下触发                                                                                                      |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| 截断后的消息文本                        | `sendUserTextMessage()`                                                                                    |
| `[voice]`                       | 终端用户开始说话                                                                                                   |
| `[trigger:<name>]`              | `sendTriggerMessage()`; `<name>` 当未传入触发名称时为空                                                               |
| `[context-update:<mode>]`       | `updateContext()` 与 `run_llm: "true"`，或者带有 `respond_mode: "must_respond"` 且没有 `run_llm`; `<mode>` 默认为 `追加` |
| `[vision-trigger:must_respond]` | `visionTrigger()` 与 `respondMode: "must_respond"`                                                          |
| `[scene-metadata:must_respond]` | `updateSceneMetadata()` 与 `respondMode: "must_respond"`                                                    |

### 语音事件

| 事件                | 负载                                                                                                             | 在以下情况下触发                                                                                                                                         |
| ----------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `speakingChange`  | `boolean`                                                                                                      | 角色开始（`true`）或停止（`false`）说话。重置或中断也会触发 `false`.                                                                                                    |
| `botOutput`       | `{ text: string; spoken: boolean; aggregatedBy: string; segmentId?: number \| string; spokenStatus?: string }` | Convai 发送一个聚合输出片段。 `aggregatedBy` 是 `"sentence"` 当 Convai 未指定时。相同的 `segmentId` 可在语音推进过程中重复出现。                                                    |
| `botTtsText`      | `{ text: string }`                                                                                             | Convai 会在语音播放时发送文本。                                                                                                                              |
| `botTtsStarted`   | 无                                                                                                              | 响应的语音合成开始。                                                                                                                                       |
| `botTtsStopped`   | 无                                                                                                              | 响应的语音合成停止。                                                                                                                                       |
| `userMuteStarted` | 无                                                                                                              | Convai 报告已停止接收终端用户的音频。                                                                                                                           |
| `userMuteStopped` | 无                                                                                                              | Convai 报告重新接受终端用户的音频。                                                                                                                            |
| `emotionChange`   | `{ emotion: string; scale?: number } \| null`                                                                  | 角色的情绪发生变化。 `null` 在重置和断开连接时触发。需要 `enableEmotion: true`时发送。参见 [使用角色情绪](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/emotions.md). |

### 口型同步事件

这些需要 `enableLipsync: true`。请从 `client.blendshapeQueue` 而不是这些负载。参见 [使用 blendshape 驱动面部动画](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/lipsync-and-blendshape.md).

| 事件                        | 负载                                      | 在以下情况下触发                                   |
| ------------------------- | --------------------------------------- | ------------------------------------------ |
| `blendshapes`             | 来自 Convai 的原始块对象，带有一个 `blendshapes` 帧数组 | 当前响应已接受一个 blendshape 块。                    |
| `blendshapeStatsReceived` | 来自 Convai 的原始对象，其中轮次统计位于 `stats`        | Convai 发送轮次结束的 blendshape 统计，表示该响应不会再有帧到来。 |
| `blendshapeCancel`        | 来自 Convai 的原始取消对象                       | Convai 会取消某个响应的 blendshape 流，例如在中断之后。      |

### 动作事件

| 事件                         | 负载                                                                              | 在以下情况下触发                                                                              |
| -------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `actionResponse`           | `ActionResponseEvent`: `{ actions: Array<ConvaiAction \| ConvaiToolCall> }`     | Convai 会为一轮发送动作。空数组表示没有动作。选择模型输出版本 2 时不会触发。                                           |
| `modelOutput`              | `ModelOutputMessage`                                                            | 在已选择以下项的会话中，收到一个有效的模型输出封装： `capabilities.modelOutputVersion: 2`。重复的 `output_id` 会被丢弃。 |
| `modelOutputProtocolError` | `ModelOutputProtocolError`: `{ code: "invalid_model_output"; message: string }` | 在版本 2 会话中的模型输出封装格式错误或不受支持。                                                            |

参见 [处理角色动作](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md) 了解如何使用这些事件。

### 确认和会话事件

| 事件               | 负载                                                                                                                                                                   | 在以下情况下触发                                                                         |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `serverResponse` | `ServerResponse`: `{ event_type: string; status: "success" \| "error" \| "processing" \| "pending"; message: string \| null; extras: ServerResponseExtras \| null }` | Convai 确认客户端发送的一条消息。 `event_type` 是该消息的类型，例如 `context-update` 或 `action-result`. |
| `idleWarning`    | `{ remainingSeconds: number \| null }`                                                                                                                               | Convai 警告将关闭不活跃会话。调用 `resetIdleTimer()` 以保持其开启。                                  |

### 媒体控制事件

`client.audioControls`, `client.videoControls`，以及 `client.screenShareControls` 各自都有自己的 `在` 并且 `移除监听` 方法，并发出一个事件。

| 发射器                   | 事件                       | 负载字段                                                                                                  |
| --------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------- |
| `audioControls`       | `audioStateChange`       | `isAudioMuted`, `isAudioEnabled`，并且在大多数变更时 `audioLevel`                                               |
| `videoControls`       | `videoStateChange`       | `isVideoEnabled`, `isVideoHidden`, `activeVisionSource`, `hasActiveVisionSource`, `visionSourceState` |
| `screenShareControls` | `screenShareStateChange` | `isScreenShareActive`，并且在启用、禁用和重置时 `isScreenShareEnabled`                                             |

```typescript
const off = client.audioControls.on('audioStateChange', (s: { isAudioMuted?: boolean }) => {
  micButton.textContent = s.isAudioMuted ? '取消静音' : '静音';
});
```

### 相关参考

{% 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/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/event-reference.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.
