> 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/convai-unreal-engine-plugin/core-concepts/session-lifecycle.md).

# 会话生命周期

了解 Convai 会话如何开始和停止，连接状态意味着什么，以及哪些 Blueprint 节点监控全局连接。

一个 **会话** 是你的 Unreal 项目与 Convai 之间针对特定角色或玩家组件建立的实时连接。会话开启时，可以传输语音、发送文本，角色也可以接收回复、动作和面部数据。没有开启会话时，角色无法进行对话。

在典型场景中，可以将两个并行会话想象为：

* **聊天机器人会话** — 位于 `UConvaiChatbotComponent`上；Convai 知道正在说话的是哪个角色，并能将回复发送回该 Actor。
* **玩家会话** — 位于 `UConvaiPlayerComponent`上；玩家的麦克风和文本输入通过此通道传送到 Convai。

这两个会话都依赖于 `UConvaiSubsystem`，它负责管理与 Convai 之间共用的 WebRTC 连接。

### 会话何时启动

默认情况下，进入 Play 模式时会自动开启会话。

和 `UConvaiChatbotComponent` 以及 `UConvaiPlayerComponent` 都提供了 **自动初始化会话** (`bAutoInitializeSession`) 选项，位于 **Convai | Session** 类别下的 **Details** 面板中。

| 组件               | 启用自动初始化后会发生什么                               |
| ---------------- | ------------------------------------------- |
| **Convai 聊天机器人** | 在 `StartSession` 中调用 `BeginPlay`.           |
| **Convai 玩家**    | 在 `BeginPlay`时向子系统注册，然后在全局连接达到 `Connected`. |

如果要延迟对话，请将 **自动初始化会话** 设为 `false` ，例如，等培训前测完成后再开始，或等玩家进入对话区域后再开始。

### 手动启动和停止会话

调用 **启动会话** 和 **停止会话** 当你需要显式控制时，可从 Blueprint 调用。

{% stepper %}
{% step %}

#### 启动聊天机器人会话

在角色的 `UConvaiChatbotComponent`上调用 **启动会话**。这会打开角色端通道，使 Convai 能够向该 Actor 发送音频、动作、情绪数据和面部数据。
{% endstep %}

{% step %}

#### 启动玩家会话

在玩家的 `UConvaiPlayerComponent`上调用 **启动会话**。这会打开玩家端通道，使麦克风音频和文本输入能够传送到 Convai。初始化成功时，该调用会返回 `true` 。
{% endstep %}

{% step %}

#### 停止会话

在任一组件上调用 **停止会话** 以拆除该组件的会话。Actor 仍会保留在关卡中。再次调用 **启动会话** 即可重新连接。
{% endstep %}
{% endstepper %}

对于依赖运行时状态的动态动作或对象，请在聊天机器人组件上重写 **收集环境附加项** ，并确保在 **启动会话** 运行之前执行。此 Blueprint 事件会将额外的动作、对象或角色添加到连接时发送的负载中。会话启动后，对 `EnvironmentData.Actions` 所做的静态更改将在 **下一次** 启动会话时生效。

### 连接状态

每个组件都会通过 `EC_ConnectionState` 枚举报告连接状态：

| 状态             | 含义                    |
| -------------- | --------------------- |
| `Disconnected` | 没有活动通道。               |
| `Connecting`   | 正在进行握手。               |
| `Connected`    | 通道已打开；可以开始对话。         |
| `Reconnecting` | 此枚举值目前保留，运行时连接流程尚未使用。 |

```mermaid
stateDiagram-v2
    [*] --> Disconnected
    Disconnected --> Connecting : StartSession
    Connecting --> Connected : handshake complete
    Connected --> Disconnected : StopSession
    Connecting --> Disconnected : StopSession
```

从 Blueprint 检查状态：

| 组件    | 函数                          | 返回                                 |
| ----- | --------------------------- | ---------------------------------- |
| 聊天机器人 | `GetChatbotConnectionState` | 当前 `EC_ConnectionState` 角色会话的连接状态。 |
| 玩家    | `IsPlayerConnected`         | `true` 当玩家会话处于 `Connected`.        |
| 子系统   | `GetServerConnectionState`  | 共享 WebRTC 通道的全局连接状态。               |

订阅 `OnAttendeeConnectionStateChangedEvent` 任一对话组件上的事件，以便在连接状态改变时作出响应。

### 重置本地对话标记

`SessionID` 在 `UConvaiChatbotComponent` 默认为 `"-1"`。当前的 WebRTC 连接流程不会将其用作 `SessionID` 恢复令牌。调用 **重置对话** 可将本地值重置为 `"-1"` ，然后再开始新的交互——例如，在多人共用的自助服务终端上切换用户时。

在 `EndUserID` 和 `EndUserMetadata` 上设置玩家或聊天机器人组件，然后再调用 **开始会话** ，以便长期记忆能够识别特定用户。如果 `EndUserID` 为空，SDK 将回退到生成的设备 ID。

### 连接子系统的蓝图接口

`UConvaiSubsystem` 提供用于监控全局连接的蓝图节点。可在任意蓝图中通过以下方式访问该子系统： **获取游戏实例 → 获取子系统（Convai 子系统）**.

#### 可通过蓝图调用的函数

| 函数                             | 类别                   | 用途                                                        |
| ------------------------------ | -------------------- | --------------------------------------------------------- |
| `GetServerConnectionState`     | `Convai\|Connection` | 返回全局 WebRTC 通道当前的 `EC_ConnectionState` 。                  |
| `ResetIdleTimer`               | `Convai\|Connection` | 重置空闲计时器。当玩家执行表示仍在参与的操作时调用，以防止因空闲而断开连接。                    |
| `InvalidateOrphanedConnection` | `Convai\|Connection` | 如果先前的连接已停留在管理器内部的 `Orphaned` 状态，则请求清理。如果不存在孤立连接，则不执行任何操作。 |

#### 可通过蓝图赋值的事件

| 事件                                    | 类别                   | 触发时机                                                                                  |
| ------------------------------------- | -------------------- | ------------------------------------------------------------------------------------- |
| `OnServerConnectionStateChangedEvent` | `Convai\|Connection` | 每当全局 `EC_ConnectionState` 发生变化时触发。                                                    |
| `OnUserIdleWarning`                   | `Convai\|Event`      | 当 Convai 检测到用户空闲时触发。携带 `RemainingSeconds` （自动断开连接前的剩余秒数）。调用 `ResetIdleTimer` 可防止断开连接。 |

### 使用示例

#### 关卡加载时自动启动

在训练模拟中，AI 教练应在关卡加载后立即就绪：

1. 将 **自动初始化会话** 设置为 `true` ，并同时应用于聊天机器人组件和玩家组件。
2. 进入 Play 模式。

预期结果：两个会话都达到 `Connected` 状态，无需手动调用 **启动会话** 。

#### 等玩家准备就绪后再启动会话

在安全演练中，学员完成预考前不应开始对话：

1. 将 **自动初始化会话** 设置为 `false` ，并同时应用于两个组件。
2. 预考通过后，先在聊天机器人上调用 **启动会话** ，再在玩家上调用。
3. 当 `GetChatbotConnectionState` 返回 `Connecting`.

时，可以选择显示连接中指示器。预期结果：关卡开始时不会建立连接，只有满足你设置的门控条件后才会开始对话。

#### 在共享设备上为不同用户重置会话

在自助服务终端上，每位新学员都应从干净状态开始：

1. 在聊天机器人组件上调用 **重置对话** 。
2. 再次调用 **启动会话** （或者依赖下一次 Play 会话时的自动初始化）。

预期结果：本地 `SessionID` 会重置为 `"-1"` ，以便进行下一次交互。

### 故障排查

| 症状                   | 可能原因                                  | 解决方法                                                                                                                                                               | 验证                                          |
| -------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------- |
| 角色在关卡开始时没有响应         | **自动初始化会话** 为 `false` 且 **启动会话** 从未调用 | 启用自动初始化，或明确调用 **启动会话** 。                                                                                                                                           | `GetChatbotConnectionState` 返回 `Connected`. |
| 状态一直保持为 `Connecting` | API 密钥无效或网络访问受阻                       | 确认 API 密钥（参见 [配置 API 密钥](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/getting-started/configure-your-api-key.md)）以及网络访问权限。 | 状态转换为 `Connected`.                          |
| 记录孤立连接日志后，连接状态过期     | 先前的连接停留在 `Orphaned` 状态                | 调用 `InvalidateOrphanedConnection`，然后再次调用 **启动会话** 。                                                                                                                | 下一次连接尝试成功。                                  |
| 会话期间缺少操作             | 在 **启动会话**                            | 之后添加的操作 **Gather Environment Extras** ，或在 **启动会话**.                                                                                                                | 之前添加操作。                                     |

### 相关概念

{% content-ref url="/pages/0a71bb8fce84999367c663a06434475b944f88da" %}
[运行时架构](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/core-concepts/runtime-architecture.md)
{% endcontent-ref %}

{% content-ref url="/pages/422d78b3fb4f61a00785b876137cbfde618d7baa" %}
[对话流程](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/core-concepts/conversation-flow.md)
{% endcontent-ref %}

{% content-ref url="/pages/ddcceab71734a05a1e99c8599b42f364e146005e" %}
[事件系统](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/core-concepts/event-system.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/convai-unreal-engine-plugin/core-concepts/session-lifecycle.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.
