> 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).

# 会话生命周期

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

可以把典型场景中的两个并行会话理解为：

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

两个会话都依赖于 `UConvaiSubsystem`，它负责与 Convai 共享的 WebRTC 连接。

### 当会话启动时

默认情况下，Play 模式开始时会自动打开会话。

两者都 `UConvaiChatbotComponent` 是位于 `UConvaiPlayerComponent` 提供 **Auto Initialize Session** (`bAutoInitializeSession`）在 **Convai | 会话** 类别中 **Details** 面板。

| 组件               | 启用自动初始化时会发生什么                                        |
| ---------------- | ---------------------------------------------------- |
| **Convai 聊天机器人** | 调用 `StartSession` 来自 `BeginPlay`.                    |
| **Convai 玩家**    | 在以下时刻向子系统注册： `BeginPlay`，然后在全局连接达到以下状态后启动其会话： `已连接`. |

设置 **Auto Initialize Session** 到 `false` 当你想延迟对话时使用——例如，直到培训前测完成，或直到玩家进入对话区域。

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

调用 **开始会话** 是位于 **停止会话** 在需要显式控制时从 Blueprint 调用。

{% stepper %}
{% step %}

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

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

{% step %}

#### 启动玩家会话

在玩家的 `UConvaiPlayerComponent`，则调用 **开始会话**。这将打开玩家侧通道，使麦克风音频和文本输入可以到达 Convai。该调用返回 `true` 当初始化成功时。
{% endstep %}

{% step %}

#### 停止会话

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

对于依赖运行时状态的动态动作或对象，请覆盖 **Gather Environment Extras** 在聊天机器人组件上，于……之前 **开始会话** 运行时。该 Blueprint 事件会向连接时发送的负载中添加额外的动作、对象或角色。对以下内容的静态更改： `EnvironmentData.Actions` 在会话开始后生效于 **下一** 会话启动时。

### 连接状态

每个组件通过以下项报告连接状态： `EC_ConnectionState` 枚举：

| State   | 含义                    |
| ------- | --------------------- |
| `已断开`   | 没有活动通道。               |
| `连接中`   | 握手进行中。                |
| `已连接`   | 通道已打开；可以继续对话。         |
| `重新连接中` | 在枚举中保留；当前不由运行时连接路径驱动。 |

```mermaid
stateDiagram-v2
    [*] --> 已断开连接
    已断开连接 --> 连接中：StartSession
    连接中 --> 已连接：握手完成
    已连接 --> 已断开连接：StopSession
    连接中 --> 已断开连接：StopSession
```

从 Blueprint 检查状态：

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

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

### 重置本地对话标记

`SessionID` on `UConvaiChatbotComponent` 默认为 `"-1"`。当前的 WebRTC 连接路径不使用 `SessionID` 作为恢复令牌。调用 **重置对话** 将本地值重置为 `"-1"` ，然后再开始新的交互——例如，在用户之间共享的自助终端上。

设置 `EndUserID` 是位于 `EndUserMetadata` 在玩家或聊天机器人组件上，于以下操作之前： **开始会话** 当长期记忆需要识别特定用户时。如果 `EndUserID` 为空，SDK 会回退到生成的设备 ID。

### 连接子系统 Blueprint 接口

`UConvaiSubsystem` 提供用于监控全局连接的 Blueprint 节点。可通过以下方式在任意 Blueprint 中访问该子系统： **Get Game Instance → Get Subsystem (Convai Subsystem)**.

#### 可由 Blueprint 调用的函数

| 函数                             | 类别           | 用途                                            |
| ------------------------------ | ------------ | --------------------------------------------- |
| `GetServerConnectionState`     | `Convai\|连接` | 返回当前 `EC_ConnectionState` 用于全局 WebRTC 通道。     |
| `ResetIdleTimer`               | `Convai\|连接` | 重置空闲计时器。当玩家执行表明持续参与的动作时调用，以防止因空闲而断开连接。        |
| `InvalidateOrphanedConnection` | `Convai\|连接` | 当先前的连接被停放在管理器内部的 `孤立` 状态中时请求清理。若不存在孤立连接，则无操作。 |

#### 可在 Blueprint 中绑定的事件

| 事件                                    | 类别           | 触发时机                                                                                 |
| ------------------------------------- | ------------ | ------------------------------------------------------------------------------------ |
| `OnServerConnectionStateChangedEvent` | `Convai\|连接` | 每当全局 `EC_ConnectionState` 发生变化时触发。                                                   |
| `OnUserIdleWarning`                   | `Convai\|事件` | 当 Convai 检测到用户空闲时触发。携带 `RemainingSeconds` ，距离自动断开还有剩余秒数。调用 `ResetIdleTimer` 以阻止断开连接。 |

### 使用示例

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

一个训练模拟场景，其中 AI 教员应在关卡加载后立即就绪：

1. 设置 **Auto Initialize Session** 到 `true` 在聊天机器人和玩家组件上。
2. 进入 Play 模式。

预期结果：两个会话都达到 `已连接` 无需手动 **开始会话** 调用。

#### 将会话延迟到玩家准备好

一个安全演练场景，在学习者完成前测之前不应开始对话：

1. 设置 **Auto Initialize Session** 到 `false` 在两个组件上。
2. 当前测通过时，调用 **开始会话** 先在聊天机器人上调用，然后在玩家上调用。
3. 在以下期间可选地显示连接指示器： `GetChatbotConnectionState` 返回 `连接中`.

预期结果：关卡开始时没有连接。只有在你的门控条件通过后，对话才开始。

#### 在共享设备上于用户之间重置

一个自助终端，每位新学习者都应从干净状态开始：

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

预期结果：本地 `SessionID` 恢复为 `"-1"` 在下一次交互之前。

### 故障排查

| 症状             | 可能原因                                                     | 修复                                                                                                                                         | 验证                                    |
| -------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- |
| 关卡开始时角色没有响应    | **Auto Initialize Session** 为 `false` 是位于 **开始会话** 从未被调用 | 启用自动初始化或调用 **开始会话** 显式地。                                                                                                                   | `GetChatbotConnectionState` 返回 `已连接`. |
| 状态保持 `连接中`     | 无效的 API 密钥或网络被阻止                                         | 确认 API 密钥（参见 [配置您的 API 密钥](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/getting-started/configure-your-api-key.md)）和网络访问。 | 状态转换为 `已连接`.                          |
| 在孤立连接日志之后的陈旧连接 | 先前连接停放在 `孤立` 状态                                          | 调用 `InvalidateOrphanedConnection`，然后 **开始会话** 。                                                                                            | 下一次连接尝试成功。                            |
| 会话期间缺少动作       | 在以下之后添加的动作 **开始会话**                                      | 使用 **Gather Environment Extras** ，或在以下之前添加动作 **开始会话**.                                                                                     | 预期的动作会出现在第一条回复中。                      |

### 相关概念

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

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

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