> 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/features/dynamic-context/dynamic-context-usage-examples.md).

# 动态上下文使用示例

用于健康追踪、上下文事件、短暂提示、区域转换、状态移除以及训练模拟中的动态上下文重置的 Blueprint 方案。

这些示例展示了在 Blueprint 中使用动态上下文的常见方式。所有示例都假设 Actor 上有一个 `Convai Chatbot` 组件（`UConvaiChatbotComponent`），且该组件能够访问已连接的会话。

先从最简单的模式开始。每个示例都包含一个场景、Blueprint 调用，以及在对话中测试之前需要在本地验证的内容。

### 在会话连接前预置上下文

**场景：** 安全培训关卡会在 `BeginPlay` 中设置设施和场景相关信息，此时自动初始化尚未完成。

默认的防抖调用会在会话连接前安全地排队。连接后，防抖期限届满时，首次刷新会发送一条包含已组装快照的 `Replace` `context-update` 。

```
// Blueprint 伪代码 — 角色 Actor 上的 Event BeginPlay
→ Set Context State  Name="Facility"  Value="Offshore Platform Alpha"  ShouldRespond=Never
→ Set Context State  Name="Scenario"  Value="Fire Drill"               ShouldRespond=Never
→ Add Context Event  Text="Trainee briefing complete"                   ShouldRespond=Never
```

**本地验证：** 首次连接后刷新完成后， **Get Context State Value** 无需额外的 Blueprint 调用即可返回预置值。

### 跟踪玩家生命值

**场景：** 一个医疗培训模拟场景；学员询问时，教练角色会评论学员的生命体征。

绑定到一个在生命值变化时触发的自定义事件。使用 `ShouldRespond = Never` 让系统静默跟踪该值，而不在每次变化时请求语音回复。

```
// Blueprint 伪代码
Event HealthChanged (NewHealth: float)
  → ConvaiBotComponent → Set Context State
      Name:          "PlayerHealth"
      Value:         ToString(NewHealth)
      ShouldRespond: Never
```

**本地验证：** 事件触发后， **Get Context State Value** 会为 `true` 返回 `PlayerHealth` ，并且 `OutValue` 与最新值一致。将 `What is my current health?` 作为端到端运行时测试提问即可；具体回复措辞取决于角色配置。

### 发送重复事件前读取状态值

**场景：** Blueprint 条件会先检查角色是否已知晓某个正在生效的警报，再决定是否发送重复事件。

```
// Blueprint 伪代码
→ Get Context State Value
    Name:     "AlertActive"
    OutValue: → 根据 OutValue == "true" 的结果进行分支判断
如果为 false：
  → 设置上下文状态
      Name:          "AlertActive"
      Value:         "true"
      ShouldRespond: Auto
  → 添加上下文事件
      Text:          "Security alert activated"
      ShouldRespond: Auto
```

**在本地验证：** **获取上下文状态值** 会立即返回当前值，无需网络往返。执行 **设置上下文状态** 后，返回引脚的值为 `true` ，且 `OutValue` 与之匹配。

### 播报叙事事件

**场景：** 在工业安全演习中，触发火警应发送一个高优先级上下文事件。

```
// Blueprint 伪代码
事件 AlarmActivated
  → ConvaiBotComponent → 添加上下文事件
      Text:          "Fire alarm activated in Bay 3"
      ShouldRespond: Always
```

防抖窗口结束后（默认 `0.5` 秒），插件会发送 `context-update` ，并将 `run_llm` 设为 `"true"`。会话连接后，若要更快地发送更新，请在 `bFlushImmediately = true` 的 **添加上下文事件** 节点上设置该属性。

**在本地验证：** 发送更新后，该事件会包含在规范上下文中。使用一次对话轮次，测试角色配置下产生的运行时行为。

### 只提示角色一次，避免提示不断累积

**场景：** 在一个谜题房间里，提示道具会闪烁。上下文下次更新时，角色应注意到这一点；但闪烁本身并非世界永久状态的一部分。

在 `bEphemeral = true` 上设置 **添加上下文事件**。角色会在下一次更新时恰好看到该事件一次，而且该事件不会写入持久化上下文——后续更新不会再次出现，也无需调用对应的 **移除上下文状态** 来清理。

```
// Blueprint 伪代码
事件 HintPropFlickered
  → ConvaiBotComponent → 添加上下文事件
      Text:        "The wall panel flickered briefly"
      ShouldRespond: Auto
      bEphemeral:  true
```

**在本地验证：** 在不同的防抖时间窗口内触发两次事件，并确认角色每次都会做出反应——持久型 `Add Context Event` 只会将第二次事件追加到不断增长的历史记录中，而临时事件每次都会以相同方式写入并清除。

### 通过一次性提示设置对象的注意焦点

**场景：** 导览角色应转向玩家突出显示的展品，并简短地确认新的焦点，但不应在每次查询注意焦点时都重复确认。

`SetObjectInAttention` （类别 `Convai|Actions`）默认会发出仅保留一个刷新周期的注意提示—— `bAddAttentionEvent = true` ——因此角色会像响应临时上下文事件一样，对新的焦点做出一次反应。将 `bAddAttentionEvent = false` 即可静默更改焦点。

```
// Blueprint 伪代码
事件 PlayerHighlightedExhibit（Exhibit: FConvaiObjectEntry）
  → ConvaiBotComponent → SetObjectInAttention
      AttentionObject:    Exhibit
      ShouldRespond:       Auto
      bAddAttentionEvent:  true   // 默认值 — 省略此项即可保留默认值
```

**在本地验证：** 刷新后，角色的下一次回复会提及该展品一次。玩家再次突出显示另一件展品时，会为该对象生成一个新提示，而不是不断累积玩家关注过的所有对象。

### 场景切换后更新多个状态

**场景：** 在企业入职培训模拟中，学员进入新区域时，房间、可用设备和一天中的时间都会发生变化。

使用 **Set Context States** 通过一次批量调用推送所有已更改的值。

```
// Blueprint 伪代码
事件 EnteredConferenceRoom
  → ConvaiBotComponent → Set Context States
      States: {
        "CurrentZone": "会议室 B",
        "AvailableEquipment": "投影仪、白板",
        "TimeOfDay": "14:30"
      }
      ShouldRespond: Auto
```

**在本地验证：** 刷新后， **Get Context State Value** 会返回键（例如 `CurrentZone`）对应的最新本地值。询问 `我们现在在哪里？` 可作为角色配置的端到端运行时测试。

### 条件结束时移除状态

**场景：** 使用培训物品后，该物品不应再属于角色认知的一部分。

```
// Blueprint 伪代码
事件 ItemUsed（ItemName: FString）
  → ConvaiBotComponent → Remove Context State
      Name: ItemName
```

**在本地验证：** 防抖刷新后， **获取上下文状态值** 对已移除的键返回 `false` 。

### 在关键时刻组合状态和事件

**场景：** 在军事模拟中，士兵 NPC 需要知道指挥官已倒下，并对此事件作出反应。

在同一执行链中推送状态更改和事件。两者会在同一个防抖周期内暂存，并合并为一次刷新。

```
// Blueprint 伪代码
事件 CommanderDown
  → ConvaiBotComponent → Set Context State
      Name:          "CommanderStatus"
      Value:         "KIA"
      ShouldRespond: Never
  → ConvaiBotComponent → 添加上下文事件
      Text:          "Commander has been eliminated — assume command"
      ShouldRespond: Always
```

由于事件使用 `Always`，发送合并更新时会将 `run_llm` 设为 `"true"`.

**本地验证：** 刷新内容到达 Convai 后， `CommanderStatus` 状态与事件位于同一个有效负载中。

### 关卡重启时重置上下文

**场景：** 玩家重新开始模拟，之前的所有运行时状态都应被丢弃。

```
// Blueprint 伪代码
事件 OnLevelRestart
  → ConvaiBotComponent → 重置动态上下文
  → ConvaiBotComponent → 停止会话
  → ConvaiBotComponent → 启动会话
```

**重置动态上下文** 会清空暂存内容，发送一个 `Reset` `context-update`，然后清除跟踪器。 `“停止会话”` 和 `“启动会话”` 会在重置后重新连接；它们本身不会清除跟踪器。

**本地验证：** **获取上下文状态值** 在重置完成后，对上一次运行中的键返回 `false` 。

### 后续步骤

{% content-ref url="/pages/a80705d8480f2f63dc8b84ea2e437c9dac45b7c5" %}
[动态上下文 Blueprint 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/dynamic-context/dynamic-context-blueprint-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/b420c88b0fe545f2bdf932b279270d9c5974103c" %}
[排查动态上下文问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/dynamic-context/troubleshoot-dynamic-context.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/features/dynamic-context/dynamic-context-usage-examples.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.
