> 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/client-to-server-messages.md).

# 客户端到服务器的消息

所有从客户端到服务器的消息都在成功建立后通过 WebRTC 数据通道以 JSON 发送 `/connect` 调用。有关消息格式约定、服务器返回的状态码，以及双向所有消息类型的完整索引，请参见 [消息术语表](/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/message-glossary.md).

### 消息封装

每条从客户端到服务器的消息都使用此封装：

```json
{
  "type": "<message-type>",
  "data": { ... }
}
```

| 字段     | 类型  | 必需 | 描述                           |
| ------ | --- | -- | ---------------------------- |
| `type` | 字符串 | 是  | 消息类型标识符。                     |
| `data` | 对象  | 否  | 消息负载。结构因消息类型而异。对于没有负载的消息可省略。 |

服务器会用一条 `server-response` 消息来确认每条客户端消息。参见 [服务器响应](#server-response) 如下。

### 服务器响应

服务器会发送一条 `server-response` 消息来响应其收到的每条从客户端到服务器的消息，不论类型。

```json
{
  "type": "server-response",
  "event_type": "tts-toggle",
  "status": "success",
  "message": "TTS已启用",
  "extras": {
    "enabled": true
  }
}
```

| 字段           | 类型        | 描述                                                          |
| ------------ | --------- | ----------------------------------------------------------- |
| `event_type` | 字符串       | 触发此响应的客户端消息类型。                                              |
| `status`     | 字符串       | 处理状态： `"success"`, `"error"`, `"processing"`，或 `"pending"`. |
| `message`    | 字符串或 null | 结果的可读描述。                                                    |
| `extras`     | 对象或 null  | 其他特定于事件的数据。结构因事件类型而异。                                       |

**状态值：**

| 值              | 含义                      |
| -------------- | ----------------------- |
| `"success"`    | 消息处理成功。                 |
| `"error"`      | 发生错误。检查 `message` 了解详情。 |
| `"processing"` | 消息正在异步处理中。              |
| `"pending"`    | 消息已接收，但处理被延迟。           |

***

### 交互与事件

#### trigger-message

触发叙事事件、向机器人发送上下文信息，或启动特定的机器人行为。

```json
{
  "type": "trigger-message",
  "data": {
    "trigger_name": "greeting",
    "trigger_message": "用户进入了房间"
  }
}
```

| 字段                | 类型  | 必需 | 描述            |
| ----------------- | --- | -- | ------------- |
| `trigger_name`    | 字符串 | 否  | 触发器的名称或标识符。   |
| `trigger_message` | 字符串 | 否  | 触发器的上下文或消息内容。 |

**使用场景：**

* 通知机器人场景内事件，例如玩家进入某个区域或完成任务。
* 发送上下文触发器以推动叙事流程。
* 启动与命名触发器相关的特定机器人行为。

**服务器响应附加字段：**

| 字段              | 类型  | 描述                 |
| --------------- | --- | ------------------ |
| `trigger_name`  | 字符串 | 从请求中回显的触发器名称。      |
| `has_speak_tag` | 布尔值 | 触发消息是否包含 speak 标签。 |

***

#### user\_text\_message

将文本作为用户输入发送，无需音频即可模拟语音。

```json
{
  "type": "user_text_message",
  "data": {
    "text": "你好，你怎么样？"
  }
}
```

| 字段     | 类型  | 必需 | 描述            |
| ------ | --- | -- | ------------- |
| `text` | 字符串 | 是  | 要作为用户输入发送的文本。 |

**服务器响应附加字段：**

| 字段     | 类型  | 描述         |
| ------ | --- | ---------- |
| `text` | 字符串 | 从请求中回显的文本。 |

***

### 上下文与状态

#### update-template-keys

更新机器人系统提示中使用的模板变量。

```json
{
  "type": "update-template-keys",
  "data": {
    "template_keys": {
      "player_name": "Alice",
      "current_level": "5",
      "location": "Forest"
    }
  }
}
```

| 字段              | 类型 | 必需 | 描述                   |
| --------------- | -- | -- | -------------------- |
| `template_keys` | 对象 | 是  | 模板变量名及其更新后的字符串值的键值对。 |

**使用场景：**

* 更新动态提示变量，例如玩家名称、属性或游戏状态。
* 根据当前会话状态自定义机器人的响应。

***

#### update-scene-metadata

更新机器人所知的场景描述上下文，包括场景内对象及其描述。

```json
{
  "type": "update-scene-metadata",
  "data": {
    "scene_metadata": [
      { "name": "torch", "description": "墙上的一支燃烧火炬" },
      { "name": "door", "description": "一扇锁着的木门" },
      { "name": "chest", "description": "一个旧宝箱" }
    ]
  }
}
```

| 字段                                  | 类型    | 必需 | 描述          |
| ----------------------------------- | ----- | -- | ----------- |
| `data.scene_metadata`               | 对象\[] | 是  | 要描述的场景对象数组。 |
| `data.scene_metadata[].name`        | 字符串   | 是  | 对象标识符。      |
| `data.scene_metadata[].description` | 字符串   | 是  | 对象的可读描述。    |

**使用场景：**

* 随着环境变化更新场景中的可交互对象。
* 调整机器人的环境上下文，而不修改动作可供性。

{% hint style="warning" %}
`update-scene-metadata` 仅更新描述性上下文。它不会修改权威的 `action_config.objects` 在以下时间提供的列表 `/connect` 。要更改机器人可以作用于哪些对象，请使用新的 `action_config`.
{% endhint %}

***

#### update-dynamic-info

更新注入到机器人系统提示中的动态信息。用于基本的单字段上下文更新。对于带有令牌预算跟踪的模式控制更新，请使用 [`context-update`](#context-update) ，代替它。

```json
{
  "type": "update-dynamic-info",
  "data": {
    "dynamic_info": {
      "text": "用户刚刚完成了龙之任务并获得了一把金剑。"
    }
  }
}
```

| 字段                  | 类型  | 必需 | 描述               |
| ------------------- | --- | -- | ---------------- |
| `dynamic_info.text` | 字符串 | 是  | 要注入系统提示的动态上下文文本。 |

***

#### context-update

更新机器人的运行时动态上下文，并可完全控制模式、令牌预算和 LLM 触发。这是运行时上下文管理的首选消息。

```json
{
  "type": "context-update",
  "data": {
    "text": "新的上下文信息",
    "mode": "append",
    "run_llm": "auto",
    "current_attention_object": "torch",
    "remove_static": false
  }
}
```

| 字段                         | 类型     | 必需                       | 默认值        | 描述                                      |
| -------------------------- | ------ | ------------------------ | ---------- | --------------------------------------- |
| `text`                     | 字符串    | 是的，除非 `mode` 为 `"reset"` | —          | 要应用的上下文文本。                              |
| `mode`                     | 字符串    | 否                        | `"append"` | 如何应用上下文。                                |
| `run_llm`                  | 字符串    | 否                        | `"auto"`   | 更新后是否触发 LLM 响应。                         |
| `current_attention_object` | 字符串或对象 | 否                        | —          | 更新用于动作引用锚定的当前注意对象。                      |
| `remove_static`            | 布尔值    | 否                        | `false`    | 对于 `"reset"` 仅在模式下：当 `true`时，也会清除静态上下文。 |

**模式值**

| 值           | 行为                                                            |
| ----------- | ------------------------------------------------------------- |
| `"append"`  | 添加 `text` 到现有运行时动态上下文中。                                       |
| `"replace"` | 将现有运行时动态上下文替换为 `text`.                                        |
| `"reset"`   | 清除运行时动态上下文。如果 `remove_static` 为 `true`. `text` 不需要，也会清除静态上下文。 |

**run\_llm 值**

| 值         | 行为                    |
| --------- | --------------------- |
| `"true"`  | 更新后始终触发机器人响应。         |
| `"false"` | 绝不触发机器人响应。            |
| `"auto"`  | Convai 根据上下文决定是否触发响应。 |

**令牌预算**

动态上下文使用估算的令牌预算：

| 分区                                       | 预算           |
| ---------------------------------------- | ------------ |
| `static_text` （连接时提供的会话级上下文）             | 20,000 个估算令牌 |
| 运行时 `text` （来自 `append` 和 `replace` 次更新） | 30,000 个估算令牌 |
| 合并后的动态上下文                                | 50,000 个估算令牌 |

当运行时 `text` 超过其 30,000 令牌预算时，Convai 会裁剪最旧的运行时上下文更新，并保留符合预算的最新更新。

`static_text` 是为此连接提供的会话和环境上下文。它会在 `reset` 调用之间保留，除非 `remove_static` 为 `true`.

**注意更新规则**

* `current_attention_object` 会根据已连接会话的 `action_config.objects`.
* 发送对象名称字符串或完整对象负载均可。
* 发送空字符串（`""`）以清除当前注意对象。
* 更新 `current_attention_object` 会重新生成系统提示，即使在 `run_llm` 为 `"false"`.

**成功响应**

成功时，服务器会返回一个 `server-response` ，其包含以下 `extras`:

```json
{
  "type": "server-response",
  "event_type": "context-update",
  "status": "success",
  "message": "Context updated successfully (append mode)",
  "extras": {
    "token_count": 1523,
    "static_token_count": 200,
    "runtime_token_count": 1323,
    "max_tokens": 50000,
    "static_max_tokens": 20000,
    "runtime_max_tokens": 30000,
    "remaining_tokens": 48477,
    "content": "完整上下文文本在此..."
  }
}
```

| 字段                    | 类型  | 描述                         |
| --------------------- | --- | -------------------------- |
| `token_count`         | 整数  | 动态上下文中的当前估算令牌总数。           |
| `static_token_count`  | 整数  | 来自静态动态上下文的估算令牌数。           |
| `runtime_token_count` | 整数  | 来自运行时动态上下文的估算令牌数。          |
| `max_tokens`          | 整数  | 合并后的动态上下文预算（50,000 个估算令牌）。 |
| `static_max_tokens`   | 整数  | 静态动态上下文预算（20,000 个估算令牌）。   |
| `runtime_max_tokens`  | 整数  | 运行时动态上下文预算（30,000 个估算令牌）。  |
| `remaining_tokens`    | 整数  | 在达到合并上限之前剩余的估算令牌数。         |
| `content`             | 字符串 | 保留的完整运行时动态上下文文本。           |

旧版 `word_count`, `static_word_count`, `runtime_word_count`, `max_words`，以及 `remaining_words` 字段可能会出现在旧版客户端中。令牌字段为权威字段。

**错误响应**

当超过令牌限制时，服务器会返回一个 `server-response` 与 `"status": "error"`:

```json
{
  "type": "server-response",
  "event_type": "context-update",
  "status": "error",
  "message": "处理 context-update 失败：DynamicInfo 的 1 个验证错误\n值错误，Dynamic info static_text 令牌限制已超出。static_text：20001 个估算令牌，最大值：20000 个令牌。"
}
```

* 验证检查会分别应用于静态、运行时和合并后的估算令牌限制。
* 当合并后的动态上下文超过 40,000 个估算令牌时，Convai 会记录一条服务器端警告。
* 错误消息包含两个分区的估算令牌明细。

***

### 音频控制

#### tts-toggle

启用或禁用机器人的文本转语音音频输出。

```json
{
  "type": "tts-toggle",
  "data": {
    "enabled": true
  }
}
```

| 字段        | 类型  | 必需 | 描述                               |
| --------- | --- | -- | -------------------------------- |
| `enabled` | 布尔值 | 是  | `true` 以启用 TTS 输出。 `false` 以禁用它。 |

**服务器响应附加字段：**

| 字段        | 类型  | 描述           |
| --------- | --- | ------------ |
| `enabled` | 布尔值 | 从请求中回显的启用状态。 |

**使用场景：**

* 在过场动画或旁白片段期间静音机器人音频。
* 根据无障碍需求切换音频输出。

***

#### stt-toggle

将语音转文字麦克风输入处理设为静音或取消静音。

```json
{
  "type": "stt-toggle",
  "data": {
    "muted": true
  }
}
```

| 字段      | 类型  | 必需 | 描述                           |
| ------- | --- | -- | ---------------------------- |
| `muted` | 布尔值 | 是  | `true` 以停止监听。 `false` 以恢复监听。 |

**服务器响应附加字段：**

| 字段      | 类型  | 描述           |
| ------- | --- | ------------ |
| `muted` | 布尔值 | 从请求中回显的静音状态。 |

**使用场景：**

* 通过在按钮未按住时将 STT 静音来实现按住说话输入。
* 在不应处理用户语音的时刻禁用语音输入。

***

#### interrupt-bot

立即停止机器人的当前语音。

```json
{
  "type": "interrupt-bot"
}
```

否 `data` 需要负载。

**使用场景：**

* 允许用户在机器人说话过程中打断它。
* 当场景内事件需要静音时立即停止机器人音频。

***

#### force-user-stopped-speaking

向服务器表明用户已结束说话。请在按住说话实现中使用此消息来显式结束语音片段。

```json
{
  "type": "force-user-stopped-speaking"
}
```

否 `data` 需要负载。

**使用场景：**

* 在按住说话按钮松开时发出语音结束信号。
* 在未使用 VAD 时提供手动语音结束信号。

***

### 会话管理

#### reset-idle-timer

重置用户空闲超时倒计时。发送此消息以表示用户活动并防止空闲断开。

```json
{
  "type": "reset-idle-timer",
  "data": {}
}
```

否 `data` 需要负载。服务器会忽略任何 `data` 内容。

**使用场景：**

* 当用户执行点击或按键等 UI 操作时重置计时器。
* 检测语音交互之外的用户活动（例如鼠标移动），并防止空闲超时。
* 在长时间的非语音交互期间保持会话存活。

***

### 下一步

{% content-ref url="/pages/52997086a1139479d2cbe158e37133880276b547" %}
[消息术语表](/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/message-glossary.md)
{% endcontent-ref %}

{% content-ref url="/pages/70d752d330612b0fbf1290588e718236d6a18f0e" %}
[Connect API](/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/connect-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/29ba5f52bd1ff6aac10fb390cafb074f474ab066" %}
[音频数据（通过数据通道）](/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/audio-data-via-data-channel.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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/client-to-server-messages.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
