> 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-unity-sdk/features/dynamic-context/dynamic-context-scripting-api.md).

# 动态上下文脚本 API

`ConvaiCharacter.DynamicContext` 返回 `IConvaiDynamicContext` 接口——用于跟踪状态、按时间顺序的事件、注意对象更新和原始上下文发送的脚本层。本页记录了每个接口成员、 `ConvaiRespondMode` 用于控制更新是否触发语音回复的枚举，以及 `ConvaiDynamicContextUpdate` 由……使用的类型 `应用`.

```csharp
using Convai.Runtime.Components;
using Convai.Runtime.DynamicContext;

IConvaiDynamicContext context = character.DynamicContext;
```

`DynamicContext` 可在每个……上使用 `ConvaiCharacter` 实例，无需额外设置。

{% hint style="warning" %}
`ConvaiContextReactionMode` 自 SDK 4.4.0 起已移除。下面的每个方法都接受一个 `ConvaiRespondMode` 值。参见 [从 ConvaiContextReactionMode 迁移](#migration-from-convaicontextreactionmode) 以查看完整迁移表。
{% endhint %}

### 方法参考

下面的每个跟踪方法都会在本地跟踪器中暂存更改；Convai 会在下一批动态上下文中接收更新——这是一个在以下条件后触发的后台刷新： `ConvaiCharacter.DynamicContextBatchDelaySeconds` （默认 0.5 秒），或者在以下情况时立即触发： `Flush()` 被调用；其延迟上限受内部最大值限制，因此暂存的更改不会无限期保留。当在批次刷新前请求了多个回复时，整个批次中最强的值将获胜，排序为 `静默` < `自动` < `MustRespond`。另请参见 [同步行为和时序](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/sync-behavior-and-timing.md) ，关于精确的批次窗口和消息内容。

#### `SetState`

```csharp
void SetState(string name, string value,
    ConvaiRespondMode reaction = ConvaiRespondMode.Silent)
```

设置或更新一个跟踪状态条目。如果 `name` 之前未设置过，Convai 会将其添加到 [规范上下文](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/how-dynamic-context-works.md#canonical-context-format) 中，并按首次设置的顺序排列。如果 `value` 与当前值相同，则该调用无操作——不会暂存任何内容。

| 参数         | 类型                  | 默认值  | 描述                          |
| ---------- | ------------------- | ---- | --------------------------- |
| `name`     | `string`            | —    | 状态标识符。必须非空且不能只包含空白字符。区分大小写。 |
| `value`    | `string`            | —    | 状态值。可以为空字符串。不能为 `null`.     |
| `reaction` | `ConvaiRespondMode` | `静默` | 对此更改请求的回复模式。                |

#### `SetStates`

```csharp
void SetStates(IReadOnlyDictionary<string, string> states,
    ConvaiRespondMode reaction = ConvaiRespondMode.Silent)
```

在一次调用中设置或更新多个跟踪状态条目，每个条目都以相同的 `reaction` 值进行暂存。优先使用 `SetStates` 而不是按顺序逐个进行的 `SetState` 调用，当多个值同时变化时。

| 参数         | 类型                                    | 默认值  | 描述                     |
| ---------- | ------------------------------------- | ---- | ---------------------- |
| `states`   | `IReadOnlyDictionary<string, string>` | —    | 状态名称到值的映射。必须至少有一个条目。   |
| `reaction` | `ConvaiRespondMode`                   | `静默` | 本次调用中的每个条目都应用所请求的回复模式。 |

如果 `states` 为 `null` 或为空，Convai 会记录一条警告（`无法设置空的动态上下文状态`），并且调用将直接返回，不会暂存任何内容。单个无效条目（空名称、 `null` 值）会被跳过；同一次调用中其余有效条目仍会被暂存。

```csharp
character.DynamicContext.SetStates(
    new Dictionary<string, string>
    {
        { "Station", "Bay 7" },
        { "HazardLevel", "Extreme" }
    },
    ConvaiRespondMode.MustRespond
);
```

#### `AddEvent`

```csharp
void AddEvent(string text, ConvaiRespondMode reaction = ConvaiRespondMode.Auto)
```

追加一条按时间顺序的事件记录。事件会在规范上下文中排在所有状态之后累积，并且不会被后续调用替换。

| 参数         | 类型                  | 默认值  | 描述                                                      |
| ---------- | ------------------- | ---- | ------------------------------------------------------- |
| `文本`       | `string`            | —    | 事件描述。必须非空且不能只包含空白字符。                                    |
| `reaction` | `ConvaiRespondMode` | `自动` | 请求的回复模式。注意默认值不同于 `SetState` 和 `SetStates`，它们的默认值为 `静默`. |

调用 `AddEvent` 时，如果传入相同的 `文本` 在待处理批次刷新前多次调用，只会暂存一个条目。去重窗口会在每次刷新后重置——在后续批次中暂存的相同文本会再次添加。

#### `RemoveState`

```csharp
void RemoveState(string name)
```

按名称移除一个跟踪状态，并为下一批次暂存更新后的规范上下文。如果 `name` 当前未被跟踪，则该调用无操作——不会暂存任何内容，也不会记录警告。

| 参数     | 类型       | 描述                                                         |
| ------ | -------- | ---------------------------------------------------------- |
| `name` | `string` | 要移除的状态名称。必须非空；空值或只含空白字符的值会记录警告（`动态上下文状态名称不能为空`），并且调用会立即返回。 |

`RemoveState` 没有 `reaction` 参数。暂存的更改始终携带 `ConvaiRespondMode.Silent` ——移除状态本身绝不会触发即时回复。

#### `Reset`

```csharp
void Reset(bool removeStatic = false)
```

清除所有跟踪状态和事件，并为 Convai 暂存一条 Reset 消息。

| 参数             | 类型     | 默认值     | 描述                                                                    |
| -------------- | ------ | ------- | --------------------------------------------------------------------- |
| `removeStatic` | `bool` | `false` | 当 `true`时，重置还会请求 Convai 移除该角色在当前会话中的静态初始动态上下文。当 `false`时，则只会清除运行时跟踪器。 |

`Reset` 没有 `reaction` 参数——暂存的 Reset 消息始终携带 `ConvaiRespondMode.Silent`。另请参见 [连接时的静态上下文](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/static-context-at-connection-time.md) 用于设置静态初始动态上下文的方式。

#### `SetCurrentAttentionObject`

```csharp
void SetCurrentAttentionObject(object currentAttentionObject,
    ConvaiRespondMode reaction = ConvaiRespondMode.Silent)
```

暂存 Convai 应视为角色当前关注焦点的对象，用于指代消解——将诸如“把那个捡起来”之类的模糊玩家语言解析为某个已注册的具体目标。

| 参数                       | 类型                  | 默认值  | 描述                                                                           |
| ------------------------ | ------------------- | ---- | ---------------------------------------------------------------------------- |
| `currentAttentionObject` | `对象`                | —    | 接受 `string` 对象名称或一个 `ConvaiActionObjectDefinition` 引用。其他任何类型，或 `null`，都会被拒绝。 |
| `reaction`               | `ConvaiRespondMode` | `静默` | 焦点更改所请求的回复模式。                                                                |

参见 [注意力和指代消解](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/attention-and-reference-grounding.md) 以查看完整的消解模型、静默失败条件和使用示例。

#### `ClearCurrentAttentionObject`

```csharp
void ClearCurrentAttentionObject(ConvaiRespondMode reaction = ConvaiRespondMode.Silent)
```

为当前注意对象暂存清除操作。Convai 会将角色视为没有特定焦点，直到下一次 `SetCurrentAttentionObject` 调用。

| 参数         | 类型                  | 默认值  | 描述            |
| ---------- | ------------------- | ---- | ------------- |
| `reaction` | `ConvaiRespondMode` | `静默` | 清除操作所请求的回复模式。 |

#### `刷新`

```csharp
void Flush()
```

立即发送任何已暂存的动态上下文（以及待处理的场景元数据）更改，而无需等待批次窗口。 `刷新` 当角色未处于活跃对话中时，该操作无效——暂存数据仍保持待处理状态，并会在角色就绪后自动发送的批次中包含。

#### `TryGetStateValue`

```csharp
bool TryGetStateValue(string name, out string value)
```

从本地跟踪器中读取某个跟踪状态的当前值。不发起网络调用。

| 参数      | 类型           | 描述                    |
| ------- | ------------ | --------------------- |
| `name`  | `string`     | 要查找的状态名称。             |
| `value` | `out string` | 如果找到，则设为当前值； `null` 。 |

**返回：** `true` 如果该状态存在于本地跟踪器中； `false` 如果它从未设置过、已被移除，或是通过 `应用` 发送的（会绕过跟踪器）。

```csharp
if (character.DynamicContext.TryGetStateValue("HazardLevel", out string level))
    Debug.Log($"Current hazard level: {level}");
else
    Debug.Log("HazardLevel state not set.");
```

#### `应用`

```csharp
void Apply(ConvaiDynamicContextUpdate update)
```

直接向传输层发送原始的强类型更新，绕过本地跟踪器和批处理队列。用于外部构造上下文文本的高级情况，或在一条消息中将上下文更新与运行时 action-config 补丁或注意对象更改结合起来的情况——参见 [`ConvaiActionConfigPatch`](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/actions-scripting-reference.md#convaiactionconfigpatch) 角色动作脚本参考中的说明。

| 参数       | 类型                           | 描述                                                                        |
| -------- | ---------------------------- | ------------------------------------------------------------------------- |
| `update` | `ConvaiDynamicContextUpdate` | 要发送的更新。参见 [`ConvaiDynamicContextUpdate`](#convaidynamiccontextupdate) 下方。 |

| 条件                                                                      | 结果                                                                                   |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `update` 为 `null`                                                       | 警告： `原始动态上下文更新不能为空`。调用将返回且不会发送。                                                      |
| `update.Mode` 不是 `Reset`，以及 `Text`, `ActionConfig`，以及 `当前注意对象` 都 `null` | 警告： `原始动态上下文更新需要 text、action_config、current_attention_object 或 Reset 模式`。调用将返回且不会发送。 |
| 角色未处于活跃对话中                                                              | 警告： `无法应用原始动态上下文更新：未处于对话中`。更新已丢弃。                                                    |

{% hint style="danger" %}
**`应用` 不会排队或批处理。** 如果角色未处于活跃对话中，Convai 会丢弃该更新并记录警告——不会发送任何内容，也不会重试。通过 `应用` 发送的值会绕过本地跟踪器： `TryGetStateValue` 返回 `false` 针对以这种方式发送的键。对所有标准上下文管理，请使用跟踪方法（`SetState`, `SetStates`, `AddEvent`, `RemoveState`, `Reset`）。
{% endhint %}

### `ConvaiDynamicContextUpdate`

`Convai.Runtime.DynamicContext` ——密封类

由……使用的高级强类型请求 `应用` 用于发送原始动态上下文更新，而不暴露传输字符串。

```csharp
new ConvaiDynamicContextUpdate(
    string text,
    ConvaiContextUpdateMode mode = ConvaiContextUpdateMode.Append,
    ConvaiRespondMode reaction = ConvaiRespondMode.Auto,
    bool removeStatic = false,
    object currentAttentionObject = null,
    string updateId = null,
    ConvaiActionConfigPatch actionConfig = null)
```

| 参数                       | 类型                        | 默认值     | 描述                                                                                                                                                                                     |
| ------------------------ | ------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `文本`                     | `string`                  | —       | 要发送的上下文文本。至少有一个 `文本`, `actionConfig`，或 `currentAttentionObject` 必须设置，或者 `模式` 必须是 `Reset`.                                                                                              |
| `模式`                     | `ConvaiContextUpdateMode` | `追加`    | Convai 如何应用该文本。                                                                                                                                                                        |
| `reaction`               | `ConvaiRespondMode`       | `自动`    | 该更新是否触发语音回复。                                                                                                                                                                           |
| `removeStatic`           | `bool`                    | `false` | 当 `模式` 为 `Reset` 而此时为 `true`，还会请求 Convai 移除该角色在本次会话中的静态初始动态上下文。                                                                                                                        |
| `currentAttentionObject` | `对象`                      | `null`  | 要与此更新一起设置的注意对象。接受 `string` 对象名称或一个 `ConvaiActionObjectDefinition` 参考资料。                                                                                                                |
| `updateId`               | `string`                  | `null`  | 将此更新与其后端确认关联。省略时会自动生成。                                                                                                                                                                 |
| `actionConfig`           | `ConvaiActionConfigPatch` | `null`  | 要与此上下文更新一起应用的运行时 action-config 补丁。参见 [角色动作脚本参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/actions-scripting-reference.md#convaiactionconfigpatch). |

### `ConvaiContextUpdateMode`

由 `应用` 和 `ConvaiDynamicContextUpdate`.

| 值       | 描述                                          |
| ------- | ------------------------------------------- |
| `追加`    | 将文本添加到现有动态上下文中，而不替换之前的内容。                   |
| `替换`    | 用提供的文本替换整个动态上下文。                            |
| `Reset` | 清除所有动态上下文。 `文本` 参数在以下情况会被忽略 `模式` 为 `Reset`. |

### `ConvaiRespondMode`

`Convai.Runtime` ——动态上下文和动态视觉共享的统一回复模式词汇。

| 值             | 传输字符串          | 描述                       |
| ------------- | -------------- | ------------------------ |
| `静默`          | `silent`       | 被吸收到角色的感知中；其本身绝不会触发语音回复。 |
| `自动`          | `auto`         | 由 Convai 决定该更新是否需要语音回复。  |
| `MustRespond` | `must_respond` | 在更新后始终触发语音回复。            |

#### 从……迁移 `ConvaiContextReactionMode`

`ConvaiContextReactionMode` 在 SDK 4.4.0 中已移除。每个动态上下文方法都使用 `ConvaiRespondMode` 替代。

| 旧值（`ConvaiContextReactionMode`) | 新值（`ConvaiRespondMode`) |
| ------------------------------- | ----------------------- |
| `SyncOnly`                      | `静默`                    |
| `ReactImmediately`              | `MustRespond`           |
| `自动`                            | `自动` （不变）               |

该枚举在重命名时重新编号—— `ConvaiRespondMode` 声明 `Silent = 0, Auto = 1, MustRespond = 2`，而已移除的 `ConvaiContextReactionMode` 声明为 `Auto = 0, ReactImmediately = 1, SyncOnly = 2`。使用针对未发布测试版构建的序列化回复覆盖保存的场景或预制体，在升级后其含义会发生变化：旧的 `自动` (`0`）反序列化为 `静默`，旧的 `ReactImmediately` (`1`）为 `自动`，以及旧的 `SyncOnly` (`2`）为 `MustRespond`。正式发布的 SDK 资源不包含此类序列化值——这只会影响使用预发布测试版构建保存的场景。如果这适用于你的项目，请在升级后重新检查任何序列化的回复字段。

### 默认回复模式参考

| 方法                                  | 默认回复                        |
| ----------------------------------- | --------------------------- |
| `SetState`                          | `静默`                        |
| `SetStates`                         | `静默`                        |
| `AddEvent`                          | `自动`                        |
| `RemoveState`                       | *（无 `reaction` 参数；始终 `静默`)* |
| `Reset`                             | *（无 `reaction` 参数；始终 `静默`)* |
| `SetCurrentAttentionObject`         | `静默`                        |
| `ClearCurrentAttentionObject`       | `静默`                        |
| `应用` / `ConvaiDynamicContextUpdate` | `自动`                        |

### 下一步

{% content-ref url="/pages/bb1aef3496a2be08987c770aa7b8072e7d8c5cd6" %}
[同步行为和时序](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/sync-behavior-and-timing.md)
{% endcontent-ref %}

{% content-ref url="/pages/743bcc7de155496cbbf02a52a5577aee99f28aab" %}
[中继组件参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/relay-component-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/5b02ee57da9de48585f7ea92aa9e94714547d80a" %}
[动作目标解析的工作方式](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/attention-and-reference-grounding.md)
{% endcontent-ref %}

{% content-ref url="/pages/531d80b1af7cb4aba63c4979e0a4c0f8e029bc95" %}
[排查动态上下文问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/dynamic-context-scripting-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
