> 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 | 会话** 类别中的 **Details** 面板。

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

设置 **自动初始化会话** 为 `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          | 含义                    |
| -------------- | --------------------- |
| `Disconnected` | 没有活动通道。               |
| `连接中`          | 握手进行中。                |
| `已连接`          | 通道已打开；可以继续对话。         |
| `重新连接`         | 在枚举中保留；当前未由运行时连接路径驱动。 |

```mermaid
stateDiagram-v2
    [*] --> Disconnected
    Disconnected --> Connecting : StartSession
    Connecting --> Connected : 握手完成
    Connected --> Disconnected : StopSession
    Connecting --> Disconnected : StopSession
```

从 Blueprint 检查状态：

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

订阅 `OnAttendeeConnectionStateChangedEvent` 在任一会话组件上使用，以便在连接状态变化时做出响应。

### 重置本地对话标记

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

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

### 连接子系统 Blueprint 接口

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

#### 可在 Blueprint 中调用的函数

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

#### 可分配给 Blueprint 的事件

| 事件                                    | 类别                   | 触发时机                                                                              |
| ------------------------------------- | -------------------- | --------------------------------------------------------------------------------- |
| `OnServerConnectionStateChangedEvent` | `Convai\|Connection` | 每当全局 `EC_ConnectionState` 发生变化时触发。                                                |
| `OnUserIdleWarning`                   | `Convai\|Event`      | 当 Convai 检测到用户空闲时触发。携带 `RemainingSeconds` ，在自动断开连接之前。调用 `ResetIdleTimer` 以防止断开连接。 |

### 使用示例

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

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

1. 设置 **自动初始化会话** 为 `true` 在聊天机器人和玩家组件上都执行。
2. 进入 Play 模式。

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

#### 在玩家准备就绪前延迟会话

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

1. 设置 **自动初始化会话** 为 `false` 在两个组件上都执行。
2. 当前测通过时，调用 **开始会话** 先在聊天机器人上，再在玩家上。
3. 在以下期间可选择显示连接指示器： `GetChatbotConnectionState` 返回 `连接中`.

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

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

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

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

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

### 故障排除

| 症状            | 可能原因                                   | 修复方法                                                                                                                                        | 验证                                    |
| ------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| 角色在关卡开始时没有响应  | **自动初始化会话** 是 `false` 和 **开始会话** 从未被调用 | 启用自动初始化，或调用 **开始会话** 并显式调用。                                                                                                                 | `GetChatbotConnectionState` 返回 `已连接`. |
| 状态保持为 `连接中`   | API 密钥无效或网络被阻止                         | 确认 API 密钥（参见 [配置你的 API 密钥](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/getting-started/configure-your-api-key.md)）以及网络访问。 | 状态转换为 `已连接`.                          |
| 孤立连接日志之后的陈旧连接 | 先前连接已停放在 `Orphaned` state              | 调用 `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 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.
