> 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/unity-plugin-beta-overview/dynamic-context.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 动态上下文

了解动态上下文如何实现更相关、更自适应、且具上下文感知的 AI 角色交互。

## 简介

Convai 角色有两个层级的上下文：

* **角色级别** ——背景故事、个性和行为规则。在 Convai 控制面板中配置，并在所有会话中持续生效。
* **会话级别** ——仅与当前交互相关的信息：玩家是谁、刚刚发生了什么、当前游戏状态。

动态上下文是 Convai Unity SDK 的一项运行时功能，可让游戏在对话进行期间，向 Convai AI 角色推送临时的会话专属信息。与在 Convai 控制面板中配置的固定角色背景故事不同，动态上下文在运行时注入，且是临时的——仅在当前会话期间存在。

可用它来衔接游戏世界与 AI：告诉角色刚刚发生了什么、玩家是谁、玩家带着什么、玩家身处何处，或任何其他会影响角色回复、但不应硬编码到提示词中的信息。

***

## 工作原理

调用 `UpdateDynamicContext`时，SDK 会序列化一条 `context-update` 消息，并通过当前会话的数据通道将其发送到 Convai 后端。后端收到更新后，会在处理下一条用户发言之前，将新信息整合到角色当前的上下文窗口中。

流程如下：

```
游戏代码
      │
      ▼
IConvaiRoomConnectionService.UpdateDynamicContext(text, mode, runLlm)
      │
      ▼
序列化后的 context-update 消息通过会话数据通道发送
      │
      ▼
Convai 后端 → LLM 上下文窗口
```

这是一个 **仅发送、不等待响应** 的操作。上下文更新本身不会收到直接响应——其效果会体现在角色接下来给出的口头回复中。

***

## 关键概念

编写代码之前，请先了解控制每次 `UpdateDynamicContext` 调用的这三个参数。

### `text`

希望角色了解的内容。这是一个纯文本字符串——可以是句子、结构化段落，也可以是按你偏好的格式编写的键值数据。

```
“玩家名叫 Aria。她 12 级，目前正在进行任务‘迷雾中的迷失’。”
```

`text` 在 **append** 和 `replace` 模式下是 `必需的` 。使用 `reset` 模式时会忽略该参数。

***

### `mode`

控制如何将新文本应用到角色现有的临时上下文中。

| 模式                        | 行为                                                          | 使用时机                      |
| ------------------------- | ----------------------------------------------------------- | ------------------------- |
| `append`                  | 将 `text` 添加到任何现有的临时上下文中。保留之前的条目。                            | 用于逐步补充信息——随着会话推进不断添加事实。   |
| `replace`                 | 丢弃所有当前临时上下文，并用新的 `text`.                                    | 将其完全替换。                   |
| `用于干净地切换状态——进入新场景或开始新章节。` | reset 会清除所有运行时临时上下文。 `text` 会被忽略。初始动态信息不受影响——在整个会话期间都会保持固定。 | 重置累积的运行时上下文，同时保留会话级固定上下文。 |

**默认值：** `"append"`

***

### `runLlm`

上下文更新后是否触发一次 LLM 推理。

| 值       | 行为                                |
| ------- | --------------------------------- |
| `auto`  | 由服务器根据其内部流水线状态决定。适用于大多数使用场景，建议使用。 |
| `true`  | 上下文更新后立即触发 LLM 响应。                |
| `false` | 静默更新上下文——不触发 LLM 响应。              |

**默认值：** `"auto"`

如果要批量更新多项上下文，并且只希望 LLM 在最后一次更新后响应，请使用 `"false"` 。如果希望上下文更新本身触发角色做出反应，请使用 `"true"` 。

***

#### `mode`

控制如何将新文本应用到角色现有的临时上下文中。

| 模式                        | 行为                                                               | 使用时机                      |
| ------------------------- | ---------------------------------------------------------------- | ------------------------- |
| `append`                  | 将 `text` 添加到任何现有的临时上下文中。保留之前的条目。                                 | 用于逐步补充信息——随着会话推进不断添加事实。   |
| `replace`                 | 丢弃所有当前临时上下文，并用新的 `text`.                                         | 将其完全替换。                   |
| `用于干净地切换状态——进入新场景或开始新章节。` | 清除所有 **运行时** 临时上下文。 `text` 会被忽略。 **初始动态信息不受影响** ——在整个会话期间都会保持固定。 | 重置累积的运行时上下文，同时保留会话级固定上下文。 |

默认值： `"append"`

***

## Initial Dynamic Info

`UpdateDynamicContext` 并非向角色提供会话级上下文的唯一方式。 `ConvaiCharacter` 组件还提供了第二层上下文，该上下文在整个会话期间保持固定： **初始动态信息**.

此项在 Unity Inspector 中的 `ConvaiCharacter` 组件下进行配置，位于 **会话** 部分：

1. 启用 **在上下文中保留初始动态信息** ——此开关用于控制下方文本是否包含在连接请求中，并由服务器固定保留整个会话期间。
2. 启用后，会显示 **动态信息（连接请求）** 字段。在 **初始动态信息文本**.

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FfQ9amdOyUTYFnuycNsnQ%2Fimage.png?alt=media&amp;token=88c9ffa2-48e3-4a92-90ee-498f9a3d34d5" alt=""><figcaption></figcaption></figure>

中输入初始上下文文本。 `UpdateDynamicContext`不同，此值不会在运行时通过数据通道发送——它会在会话开始前嵌入连接载荷中。

**关键区别：** `reset` 模式下， `UpdateDynamicContext` 会 **不会** 清除 Initial Dynamic Info。它只会重置运行时临时层。无论你发送何种上下文更新，固定的初始文本在整个会话期间都会保持生效。

#### 分别适用于何时

|                  | Initial Dynamic Info          | 运行时动态上下文                   |
| ---------------- | ----------------------------- | -------------------------- |
| **设置方式**         | Unity 检视面板（`ConvaiCharacter`) | 代码（`UpdateDynamicContext`) |
| **发送时机**         | 房间连接时，会话开始前                   | 活动会话期间的任何时候                |
| **可变**           | 否 — 会话期间固定                    | 是 — 可随时追加、替换或重置            |
| **清除方式 `reset`** | 否                             | 是                          |
| **用途**           | 稳定的会话配置：角色定位、场景规则、固定指令        | 不断变化的游戏状态、玩家数据、事件、情绪       |

{% hint style="info" %}
对于会话期间不应发生变化的上下文（如角色指令、场景设置和固定规则），请使用 Initial Dynamic Info。对于 `UpdateDynamicContext` 会话进程中不断变化的内容，则使用此方法。
{% endhint %}

***

## 访问 API

Dynamic Context 通过 `IConvaiRoomConnectionService`公开，可通过 `ConvaiManager`获取。根据连接生命周期的管理方不同，有两种不同的模式。

### 模式 A — 自包含

当组件负责自身初始化时使用。适用于会话启动场景：连接就绪后必须立即发送上下文。

```csharp
using System.Collections;
using Convai.Runtime.Components;
using Convai.Runtime.Room;
using UnityEngine;

public class ExampleSelfContained : MonoBehaviour
{
    private IConvaiRoomConnectionService _connectionService;

    private IEnumerator Start()
    {
        // 轮询，直到 ConvaiManager 和房间服务可用。
        在正常情况下，一到两帧内即可获取。
        while (true)
        {
            ConvaiManager manager = ConvaiManager.ActiveManager;
            if (manager != null && manager.TryGetRoomConnectionService(out _connectionService))
                break;
            yield return null;
        }

        // 服务引用已可用，但房间可能尚未连接。
        // 先检查 IsConnected：如果此组件在会话
        // 已建立后才初始化，Connected 事件将永远不会触发。
        if (_connectionService.IsConnected)
            OnReady();
        else
            _connectionService.Connected += OnConnected;
    }

    private void OnConnected()
    {
        _connectionService.Connected -= OnConnected;
        OnReady();
    }

    private void OnReady()
    {
        bool sent = _connectionService.UpdateDynamicContext("...", mode: "replace", runLlm: "false");
        if (!sent)
            Debug.LogWarning("[Example] UpdateDynamicContext returned false.");
    }

    private void OnDestroy()
    {
        // 如果此对象在连接建立前被销毁，请避免留下未解除的订阅。
        if (_connectionService != null)
            _connectionService.Connected -= OnConnected;
    }
}
```

***

### 模式 B — 注入

适用于由会话协调器或父系统负责提供已连接服务的情况。该组件假定调用其公共方法时服务有效。

```csharp
using Convai.Runtime.Room;
using UnityEngine;

public class ExampleInjected : MonoBehaviour
{
    private IConvaiRoomConnectionService _connectionService;

    /// <summary>
    /// 使用处于活动状态的房间连接服务初始化此组件。
    /// Convai 会话建立后，必须由会话所有者调用。
    /// </summary>
    public void Initialize(IConvaiRoomConnectionService connectionService)
    {
        _connectionService = connectionService;
    }

    public void DoSomething()
    {
        // ?. 可防止 Initialize 尚未调用时出现问题。
        bool sent = _connectionService?.UpdateDynamicContext("...", mode: "append", runLlm: "false") ?? false;
        if (!sent)
            Debug.LogWarning("[Example] UpdateDynamicContext returned false.");
    }
}
```

{% hint style="info" %}
`UpdateDynamicContext` 会返回 `false` （如果会话尚未连接）。务必检查返回值。
{% endhint %}

***

## API 参考

```csharp
bool UpdateDynamicContext(string text, string mode = "append", string runLlm = "auto");
```

| 参数       | 类型       | 必填      | 默认值        | 说明                                           |
| -------- | -------- | ------- | ---------- | -------------------------------------------- |
| `text`   | `string` | 是（除非重置） | —          | 要注入的上下文文本。                                   |
| `mode`   | `string` | 否       | `"append"` | 如何应用文本： `"append"`, `"replace"`，或 `"reset"`. |
| `runLlm` | `string` | 否       | `"auto"`   | 是否触发 LLM 响应： `"true"`, `"false"`, `"auto"`.  |

**返回值：** `true` 表示消息已分发到传输层； `false` 表示会话尚未连接。

***

#### `mode`

控制如何将新文本应用到角色现有的临时上下文中。

| 模式                        | 行为                                                               | 使用时机                      |
| ------------------------- | ---------------------------------------------------------------- | ------------------------- |
| `append`                  | 将 `text` 添加到任何现有的临时上下文中。保留之前的条目。                                 | 用于逐步补充信息——随着会话推进不断添加事实。   |
| `replace`                 | 丢弃所有当前临时上下文，并用新的 `text`.                                         | 将其完全替换。                   |
| `用于干净地切换状态——进入新场景或开始新章节。` | 清除所有 **运行时** 临时上下文。 `text` 会被忽略。 **初始动态信息不受影响** ——在整个会话期间都会保持固定。 | 重置累积的运行时上下文，同时保留会话级固定上下文。 |

**默认值：** `"append"`

***

## 动态上下文与相关功能的区别

<table><thead><tr><th>功能</th><th width="216.407470703125">方法</th><th width="127.9259033203125">范围</th><th width="107.370361328125">是否跨会话持久化</th><th>用途</th></tr></thead><tbody><tr><td><strong>动态上下文</strong></td><td><code>UpdateDynamicContext</code></td><td>临时（运行时）</td><td>否</td><td>运行时事实：玩家状态、游戏事件、情境感知。</td></tr><tr><td><strong>Initial Dynamic Info</strong></td><td><code>ConvaiCharacter</code> 检查器</td><td>临时（会话开始时固定）</td><td>否</td><td>固定的会话指令：场景规则、角色职责、稳定的设置。不受 <code>reset</code>.</td></tr><tr><td><strong>动态信息</strong></td><td><code>SendDynamicInfo</code></td><td>每条消息</td><td>否</td><td>附加到特定用户话语中的内联上下文。</td></tr><tr><td><strong>模板键</strong></td><td><code>UpdateTemplateKeys</code></td><td>会话</td><td>否</td><td>解析叙事设计文本中的命名占位符（<code>{PlayerName}</code>）。</td></tr><tr><td><strong>场景元数据</strong></td><td><code>UpdateSceneMetadata</code></td><td>会话</td><td>否</td><td>用于后端上下文 grounding 流程的场景结构数据。</td></tr><tr><td><strong>仪表板背景故事</strong></td><td>Convai 仪表板</td><td>永久</td><td>是</td><td>角色个性、背景设定和固定行为规则。</td></tr></tbody></table>

***

## 常见陷阱

* **在会话连接前调用** `UpdateDynamicContext` 会返回 `false` ，并静默丢弃更新。请使用协程或订阅 `IConvaiRoomConnectionService.Connected` ，等会话处于活动状态后再注入上下文。
* **无限期使用 `append` 模式** 每次 `append` 都会扩展上下文窗口。在较长的会话中，这会降低回复连贯性并增加延迟。请定期使用 `replace` ，或采用 `DynamicContextManager` 模式。
* **在 `text` 为 `reset` 模式时发送** `text` 会被忽略，因为 `mode` 的值是 `"reset"`。请显式传入 `null` ，以明确表达意图。
* **预期效果会同步发生** 动态上下文从头到尾都是异步的。角色要到下一次 LLM 推理时才会获知更新。不要设计假定更新会立即生效的逻辑。
* **过度使用 `runLlm: "true"`** 每次更新都强制立即回复，会造成对话噪声。仅在确实期待角色作出反应时使用。

***

## 快速参考

```csharp
// 将新信息追加到现有的临时上下文（默认）
connectionService.UpdateDynamicContext("Player just entered the dungeon.");

// 用新内容替换所有临时上下文
connectionService.UpdateDynamicContext("Player is now in Act 2.", mode: "replace");

// 清除所有临时上下文
connectionService.UpdateDynamicContext(null, mode: "reset");

// 静默累积（不触发 LLM 响应）
connectionService.UpdateDynamicContext("Player picked up the golden key.", runLlm: "false");

// 更新并立即触发角色响应
connectionService.UpdateDynamicContext("The village is on fire!", runLlm: "true");

// 注入情绪状态
connectionService.UpdateDynamicContext("Speak with urgency. A threat is approaching.", mode: "replace", runLlm: "false");
```

***

## 总结

动态上下文是连接游戏或应用实时状态与 AI 角色对其理解的桥梁。角色的永久配置——个性、背景故事和行为规则——在 Convai 控制面板中保持稳定。属于本次会话、当前用户和此时此刻的一切信息，都会通过 `UpdateDynamicContext`.

这个 API 刻意设计得十分简单：一个方法，三个参数。真正的精妙之处在于如何使用它——无论是在会话开始时为对话添加个性化信息、在会话中途响应阈值变化、静默累积事件直到值得评论时再触发响应，还是在整个培训会话中跟踪能力差距。

请牢记以下几点：

* **默认应采用静默更新。** 使用 `runLlm: "false"` 进行状态同步。仅在确实需要角色响应时，才使用 `runLlm: "true"` 。
* **将上下文窗口视为一种资源。** 不受限制地使用 `append` 会导致质量随时间下降。在自然的节点——场景转换、模块变更、会话重置——使用 `replace` 。
* **状态由你的应用负责管理，角色负责接收状态。** 动态上下文机制能够清晰地确保这种职责分离。

{% hint style="info" %}
**需要帮助？** 如有疑问，请访问 [**Convai 开发者论坛**](https://forum.convai.com/).
{% endhint %}


---

# 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/unity-plugin-beta-overview/dynamic-context.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.
