> 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` ）提供相同的 `on` 和 `off`方法。事件名称是普通字符串，触发器不会为负载提供类型，因此请使用导出的类型为回调参数添加类型注解。

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

unsubscribe();
```

### 连接事件

| 事件                   | 负载                                                                            | 触发时机                                                                                                                                                                                                                   |
| -------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connect`            | 无                                                                             | `connect()` 或 `connectWithPublicationGrant()` 已建立传输连接。此时角色可能尚未就绪；发送消息前请等待 `botReady` 事件。                                                                                                                               |
| `botReady`           | 无                                                                             | 角色表示已准备好接收消息。每次连接只触发一次。                                                                                                                                                                                                |
| `disconnect`         | `DisconnectReason` (`number`)                                                 | 会话结束。代码为 `0` （传输层未提供原因时）。请参阅 [处理错误和断开连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md).                                                                       |
| `error`              | `unknown`                                                                     | `connect()` 或 `connectWithPublicationGrant()` 失败时（会重新抛出相同的错误），或者在 LiveKit 传输中，45 秒内未收到就绪信号时（`bot-ready not received within 45000ms`).                                                                                  |
| `stateChange`        | `ConvaiClientState`                                                           | 的任意字段 `client.state` 发生变化时。                                                                                                                                                                                            |
| `interactionCreated` | `InteractionCreated`: `{ interactionId: string; characterSessionId: string }` | Convai 会为会话分配一个交互 ID。                                                                                                                                                                                                  |
| `botAudioTrack`      | `MediaStreamTrack`                                                            | WebSocket 会话会公开一个角色音频轨道。当前的 Pipecat WebSocket 传输不会触发此事件，因为它会自行播放语音，并且不会公开角色轨道。请参阅 [使用 WebSocket 传输](https://docs.convai.com/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 }`    | 至少开始一轮对话后，角色停止说话。 `duration` 是自对应的 `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>` 默认为 `append` |
| `[vision-trigger:must_respond]` | `visionTrigger()` 并设置 `respondMode: "must_respond"`                                                             |
| `[scene-metadata:must_respond]` | `updateSceneMetadata()` 并设置 `respondMode: "must_respond"`                                                       |

### 语音事件

| 事件                     | 负载                                                                                                             | 触发时机                                                                                                                                                                                                                              |
| ---------------------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `speakingChange`       | `boolean`                                                                                                      | 角色开始（`true`）或停止（`false`）说话。重置或中断也会触发此事件。使用 `false`时， `audioRouting: 'data_only'` 该事件反映听到的内容；请参阅 [通过数据通道传输音频](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/audio-over-the-data-channel.md). |
| `serverSpeakingChange` | `boolean`                                                                                                      | 使用 `audioRouting: 'data_only'`时：此事件表示服务器自身的说话状态标志，反映服务器发送音频的时间，而非音频被听到的时间。                                                                                                                                                        |
| `botOutput`            | `{ text: string; spoken: boolean; aggregatedBy: string; segmentId?: number \| string; spokenStatus?: string }` | Convai 发送聚合后的输出片段。 `aggregatedBy` 在 Convai 未指定时为 `"sentence"` 。同一个 `segmentId` 可能会随着语音播放进度重复出现。                                                                                                                                   |
| `botTtsText`           | `{ text: string }`                                                                                             | Convai 会在文本被说出时发送该文本。                                                                                                                                                                                                             |
| `botTtsStarted`        | 无                                                                                                              | 响应的语音合成开始。                                                                                                                                                                                                                        |
| `botTtsStopped`        | 无                                                                                                              | 响应的语音合成停止。                                                                                                                                                                                                                        |
| `userMuteStarted`      | 无                                                                                                              | Convai 通知客户端，它已停止接收最终用户的音频。                                                                                                                                                                                                       |
| `userMuteStopped`      | 无                                                                                                              | Convai 通知客户端，它已恢复接收最终用户的音频。                                                                                                                                                                                                       |
| `emotionChange`        | `{ emotion: string; scale?: number } \| null`                                                                  | 角色的情绪发生变化。 `null` 在重置和断开连接时。需要 `enableEmotion: true`。请参阅 [使用角色情绪](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/emotions.md).                                                               |

### 口型同步事件

这些事件需要 `enableLipsync: true`。请从 `client.blendshapeQueue` 读取帧，而不要从这些负载中读取。请参阅 [使用混合形状驱动面部动画](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/lipsync-and-blendshape.md).

| 事件                        | 负载                                         | 触发时机                                  |
| ------------------------- | ------------------------------------------ | ------------------------------------- |
| `blendshapes`             | 来自 Convai 的原始分块对象，其中包含一个 `blendshapes` 帧数组 | 当前响应已接受一个混合形状分块。                      |
| `blendshapeStatsReceived` | 来自 Convai 的原始对象，回合统计信息位于 `stats`           | Convai 会发送回合结束时的混合形状统计信息，表示该响应不会再有新帧。 |
| `blendshapeCancel`        | 来自 Convai 的原始取消对象                          | Convai 会取消某个响应的混合形状流，例如在发生中断后。        |

### 动作事件

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

请参阅 [处理角色动作](https://docs.convai.com/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` 各自都有自己的 `on` 和 `off` 方法，并会发出一个事件。

| 发射器                   | 事件                       | 负载字段                                                                                                  |
| --------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------- |
| `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 ? 'Unmute' : 'Mute';
});
```

### 相关参考

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