> 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/api-can-kao/core-api-reference/live-apis-beta/turn-lifecycle-and-message-ordering.md).

# 轮次生命周期与消息顺序

了解 Live API 轮次传递，包括旧版文本、规范输出、动作结果续接、关联和顺序保证。

Live API 会话会通过并行的媒体载体和数据载体传递一个逻辑轮次。请将消息顺序、逻辑轮次关联和客户端工具完成状态作为彼此独立的问题处理。

| 载体              | 承载内容                      | 格式                                              |
| --------------- | ------------------------- | ----------------------------------------------- |
| **WebRTC 音频轨道** | 语音音频本身                    | 标准 WebRTC 媒体轨道（或者 `audio-data` 消息，如果选择通过数据通道路由） |
| **机器人输出流**      | 机器人的响应文本和语音状态转换           | 数据通道，事件类型位于 **顶层**                              |
| **自定义服务器消息**    | 规范模型输出、操作、情绪、转录文本、动画和生命周期 | 数据通道，事件类型嵌套在 `data.type`                        |

只有在启用 `audio_routing: "data_only"` 或 `"both"` 之后，音频才会出现在数据通道流中；该配置位于 `audio_config`。请参阅 [通过数据通道传输音频数据](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/audio-data-via-data-channel.md).

***

### 两种信封格式

数据通道承载两种不同格式的信封。消息处理程序必须同时检查这两种格式。

**格式 A — 机器人输出流。** 事件类型位于顶层的 `type`:

```json
{ "label": "rtvi-ai", "type": "bot-llm-text", "data": { "text": "Sure, on my way." } }
```

**格式 B — 自定义服务器消息。** 顶层的 `type` 始终为 `"server-message"`，实际事件类型则嵌套其中：

```json
{
  "label": "rtvi-ai",
  "type": "server-message",
  "data": { "type": "action-response", "actions": [{ "name": "Move To", "target": "cube" }] }
}
```

按如下方式解析有效事件类型：

```javascript
function eventType(message) {
  return message.type === "server-message" && message.data?.type
    ? message.data.type
    : message.type;
}
```

`server-response` 是第三种旧版格式。它的字段位于顶层，而不是嵌套在 `server-message` 信封中。请参阅 [server-response](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/server-to-client-messages.md#server-response).

***

### 机器人输出流

这些消息使用 **表单 A**。机器人回复文本只会出现在这些位置。

| 消息                | 负载         | 含义                               |
| ----------------- | ---------- | -------------------------------- |
| `bot-llm-started` | `{}`       | 模型已开始生成本轮回复                      |
| `bot-llm-text`    | `{ text }` | 所选旧版或原始文本投影的增量片段。按接收顺序拼接，即可还原该投影 |
| `bot-llm-stopped` | `{}`       | 生成已完成                            |
| `bot-tts-started` | `{}`       | 本轮语音合成已开始                        |

如果未指定能力，或使用 `bot_llm_text_mode: "legacy"`, `bot-llm-text` 会携带经过筛选的对话文本。使用 `bot_llm_text_mode: "raw"`时，它会携带结构化输出解析和对话内容筛选之前、提供方可见的文本。原始输出不应被视为可信的可渲染或可执行内容。请参阅 [响应约定与解析](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/response-contract-and-parsing.md).

#### 语音状态消息

`bot-started-speaking` 和 `bot-stopped-speaking` 标记本轮音频的起止边界。这些消息采用 **表单 B** 并且还会在 `label` 内重复出现 `data`:

```json
{
  "label": "rtvi-ai",
  "type": "server-message",
  "data": {
    "label": "rtvi-ai",
    "type": "bot-started-speaking",
    "response_id": "session-id:r4",
    "epoch": 1,
    "sequence": 3
  }
}
```

***

### 响应生命周期元数据

以下三种消息—— `bot-started-speaking`, `bot-stopped-speaking`和 `bot-turn-completed` ——可以携带可选的关联字段。每个字段仅在 **已设置时**才会包含，因此不同轮次的键集合可能不同。

| 字段                  | 类型  | 说明                        |
| ------------------- | --- | ------------------------- |
| `response_id`       | 字符串 | 此机器人回复的标识符，在整个轮次中保持不变     |
| `neurosync_turn_id` | 整数  | NeuroSync 轮次标识符，用于关联混合形变流 |
| `epoch`             | 整数  | NeuroSync 连接/会话周期         |
| `sequence`          | 整数  | 每轮消息序列号                   |

使用 `response_id` 将 blendshape 和 cancel 消息与生成它们的轮次关联起来。不要假设这些字段一定存在。

协商使用模型输出 v2 的客户端会收到一个或多个 `model-output` 信封。使用 `output_id` 对信封进行去重。使用可选的 `logical_turn_id` 将属于同一逻辑轮次的文本、语义动作和客户端工具调用信封归为一组。不同信封可以共享同一个 `logical_turn_id`.

***

### 一个完整的旧版轮次

用户说 *"去把那个立方体拿过来"*。一个典型的 v1 消息序列如下：

```json
{"label":"rtvi-ai","type":"server-message","data":{"type":"vad-stt-started",
  "timestamp":"2026-08-10T10:30:45.123Z","pre_roll_ms":1500}}

{"label":"rtvi-ai","type":"server-message","data":{"type":"final-user-transcription",
  "text":"go grab the cube","speaker_name":"Alice"}}

{"label":"rtvi-ai","type":"bot-llm-started","data":{}}
{"label":"rtvi-ai","type":"bot-llm-text","data":{"text":"Sure,"}}
{"label":"rtvi-ai","type":"bot-llm-text","data":{"text":" on my way."}}
{"label":"rtvi-ai","type":"bot-llm-stopped","data":{}}

{"label":"rtvi-ai","type":"server-message","data":{"type":"action-response",
  "actions":[{"name":"Move To","target":"cube"},{"name":"Pick Up","target":"cube"}]}}
{"label":"rtvi-ai","type":"server-message","data":{"type":"bot-emotion",
  "emotion":"happy","scale":2}}

{"label":"rtvi-ai","type":"bot-tts-started","data":{}}
{"label":"rtvi-ai","type":"server-message","data":{"type":"bot-started-speaking",
  "label":"rtvi-ai","response_id":"session-id:r4"}}
{"label":"rtvi-ai","type":"server-message","data":{"type":"visemes","visemes":{ }}}
{"label":"rtvi-ai","type":"server-message","data":{"type":"bot-stopped-speaking",
  "label":"rtvi-ai","response_id":"session-id:r4"}}
{"label":"rtvi-ai","type":"server-message","data":{"type":"bot-turn-completed",
  "was_interrupted":false}}
```

该轮次的语音音频通过 WebRTC 音频轨道播放，与上述消息并行。

对于协商使用模型输出 v2 的客户端，Convai 还可以发出多个独立的规范信封，并共享同一个逻辑轮次 ID：

```json
{"type":"model-output","version":2,"output_id":"out_text","logical_turn_id":"turn_42",
  "format":"text","raw":"Sure, on my way.","items":[{"type":"message","role":"assistant",
  "channel":"final","content":"Sure, on my way."}],"final":true}

{"type":"model-output","version":2,"output_id":"out_action","logical_turn_id":"turn_42",
  "format":"semantic-actions-json","raw":"{\"actions\":[{\"name\":\"Move To\",\"target\":\"cube\"}]}",
  "items":[{"type":"semantic_action","id":"act_42","name":"Move To","target":"cube"}],"final":true}
```

`final: true` 表示一个信封已完成，但不会结束整个逻辑轮次。

***

### 顺序保证

正确处理这一点可以避免大量集成错误。

#### 保证内容

* **`bot-llm-text` 分块会按顺序到达。** 按到达顺序拼接这些分块，即可还原所选的文本投影。
* **回合的边界事件有先后顺序。** `bot-llm-started` 先于任何 `bot-llm-text`，而后者先于 `bot-llm-stopped`. `bot-started-speaking` 先于 `bot-stopped-speaking`，而后者先于 `bot-turn-completed`.
* **数组及其中元素的顺序会得到保留。** 这并不要求客户端按顺序执行。
* **`output_id` 标识一个规范信封。** 重复的 ID 表示重复项。不同的 ID 代表不同的信封，即使它们共享 `logical_turn_id`.
* **客户端工具调用会等待其关联结果或超时。** 在该工具调用继续执行之前，Convai 会将超时前接受的结果提供给同一个模型上下文。
* **`bot-turn-completed` 表示终止** ，指的是关联的服务器响应生命周期终止，并不能证明客户端操作或播放已完成。

#### 哪些内容 *不* 受保证

{% hint style="danger" %}
**`action-response` 和 `bot-emotion` 与响应文本不存在位置关联。** 它们是独立的消息，没有索引、时间戳或偏移量将其与任何 `bot-llm-text` 块关联起来。
{% endhint %}

具体而言，这意味着：

* 你 **无法** 判断某个动作是否旨在“第二句话之后”发生。
* 你 **无法** 判断 `bot-emotion` 适用于哪些词。情绪是 **回合级**的，而不是文本片段级的。
* 旧版 v1 无法表示交错序列，例如 *先说话，再移动，然后再说话*。规范 v2 可以将多个已完成的信封分组，但不提供词级动作偏移量。
* `action-response` 通常在生成过程接近结束时到达，但它相对于 `bot-llm-stopped` 的位置 **不受协议保证**。不要以是否已看到 `bot-llm-stopped`.

**建议的处理方式：** v1 客户端可以将 `action-response` 视为建议的操作计划。V2 客户端应使用 `model-output.items` 作为权威来源，并忽略重复的映射。在两种模式下，都应在应用程序中授权和安排操作。只有在客户端操作达到终止状态后，才返回 [`action-result`](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/client-to-server-messages.md#action-result) 。

***

### 轮次完成

`bot-turn-completed` 表示服务器端的 **服务器端** 终止状态：服务器已完成该轮次所需的所有输出交接，或者该轮次已被中断或终止。

```json
{ "type": "bot-turn-completed", "was_interrupted": false }
```

| 字段                | 类型  | 是否存在           | 说明                                    |
| ----------------- | --- | -------------- | ------------------------------------- |
| `was_interrupted` | 布尔值 | 始终             | `true` 如果用户中断了机器人                     |
| `was_aborted`     | 布尔值 | 仅当 `true`      | 因无法交付所需输出而结束该轮次                       |
| `error_reason`    | 字符串 | 仅在终止时 **且** 设置 | 机器可读的终止原因；目前为 `audio_delivery_failed` |

`bot-turn-completed` 并非客户端播放确认。它不表示用户已听完音频，也不表示 avatar blendshapes 或客户端工具已完成。对于驱动本地音频播放、 `isSpeaking` 状态、唇形同步或 avatar 动画的客户端，应在清除这些状态前排空自身队列。

#### 中断

用户插话时，当前轮次会以 `was_interrupted: true`结束。选择接收提前发送的 NeuroSync 分块的客户端还会收到 [`neurosync-blendshapes-cancel`](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/server-to-client-messages.md#neurosync-blendshapes-cancel)，其中指定要保留多少已缓冲的视觉尾部内容。

中断时，已交付的操作和工具调用不会被撤回。如果你的体验需要取消正在进行的客户端工作，请在应用程序中处理这种情况：当 `was_interrupted` 为 `true`时，为受影响的 v2 工具调用返回终止状态的 `"cancelled"` 结果。

***

### 字段存在规则

字段是否存在 **并不统一** ，不同消息类型各不相同。目前有三种不同的约定；编写假定某个键必定存在的客户端前，请先查看此表。

| 约定                   | 行为                              | 适用范围                                                                                                                                                                                                                                                    |
| -------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **始终存在**             | 即使值为 `null`                     | `moderation-response.reason`；每条消息都包含所有必需字段                                                                                                                                                                                                              |
| **为空时省略**            | 键会 **从 JSON 中省略** ，而不是设为 `null` | `server-response.message`, `server-response.extras`, `final-user-transcription.speaker_id` / `speaker_name` / `participant_id` / `message_id`, `user-idle-warning.message`, `llm-no-response.reason`, `bot-turn-completed.was_aborted` / `error_reason` |
| **为 null 时省略（嵌套对象）** | 嵌套对象中的可选键会被省略                   | `action-response.actions[].target`                                                                                                                                                                                                                      |
| **仅在已设置时包含**         | 关联元数据，每轮可能不同                    | `response_id`, `neurosync_turn_id`, `epoch`, `sequence`                                                                                                                                                                                                 |

编写代码时应考虑字段缺失的情况。使用可选访问（`message.data?.target`），不要只检查值是否为 `null`。语义操作中的 `target` 缺失表示该操作没有目标。v2 工具调用会在 `arguments`中携带经过验证的输入；其可选 `target` 字段不代表授权决策。

例如， `final-user-transcription`的最简真实负载为：

```json
{ "type": "final-user-transcription", "text": "hello" }
```

***

### 相关页面

* [响应约定与解析](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/response-contract-and-parsing.md) ——如何将语音响应与操作及其他输出区分开来
* [服务器到客户端的消息](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/server-to-client-messages.md) — 所有服务器消息的完整字段参考
* [客户端到服务器的消息](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/client-to-server-messages.md) — 您发送的消息
* [消息术语表](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/message-glossary.md) — 所有消息类型的摘要
* [连接 API](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/connect-api.md) — 建立会话


---

# 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/api-can-kao/core-api-reference/live-apis-beta/turn-lifecycle-and-message-ordering.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.
