> 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` 由 `Apply`.

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

IConvaiDynamicContext context = character.DynamicContext;
```

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

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

### 方法参考

下面每个受跟踪的方法都会在本地跟踪器中暂存其更改；Convai 会在下一个动态上下文批次中接收更新——这是一个后台刷新，会在 `ConvaiCharacter.DynamicContextBatchDelaySeconds` （默认 0.5 秒）或在 `Flush()` 被调用时立即触发，并受内部最大延迟限制，因此暂存的更改不会被无限期保留。在一个批次刷新前如果请求了多种反应，则整个批次采用最强的值，排名为 `Silent` < `Auto` < `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) 中，并按首次设置的顺序排列。如果 `值` 与当前值相同，则该调用无操作——不会暂存任何内容。

| 参数         | 类型                  | 默认值      | 描述                      |
| ---------- | ------------------- | -------- | ----------------------- |
| `name`     | `string`            | —        | 状态标识符。不能为空或全为空白。区分大小写。  |
| `值`        | `string`            | —        | 状态值。可以是空字符串。不能是 `null`. |
| `reaction` | `ConvaiRespondMode` | `Silent` | 此次更改请求的反应。              |

#### `SetStates`

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

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

| 参数         | 类型                                    | 默认值      | 描述                  |
| ---------- | ------------------------------------- | -------- | ------------------- |
| `states`   | `IReadOnlyDictionary<string, string>` | —        | 状态名称到值的映射。必须至少包含一项。 |
| `reaction` | `ConvaiRespondMode`                   | `Silent` | 此次调用中应用于每个条目的请求反应。  |

如果 `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)
```

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

| 参数         | 类型                  | 默认值    | 描述                                                      |
| ---------- | ------------------- | ------ | ------------------------------------------------------- |
| `text`     | `string`            | —      | 事件描述。不能为空或全为空白。                                         |
| `reaction` | `ConvaiRespondMode` | `Auto` | 请求的反应。注意默认值不同于 `SetState` 和 `SetStates`，其默认值为 `Silent`. |

调用 `AddEvent` 具有相同的 `text` 在待处理批次刷新前即使多次调用，也只暂存一条条目。去重窗口会在每次刷新后重置——在后续批次中暂存的相同文本会再次添加。

#### `RemoveState`

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

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

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

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

#### `重置`

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

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

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

`重置` 没有 `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` | `object`            | —        | 接受一个 `string` 对象名称或 `ConvaiActionObjectDefinition` 引用。任何其他类型，或 `null`，都会被拒绝。 |
| `reaction`               | `ConvaiRespondMode` | `Silent` | 焦点变更请求的反应。                                                                   |

参见 [注意力与引用锚定](/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` | `Silent` | 清除请求的反应。 |

#### `刷新`

```csharp
void Flush()
```

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

#### `TryGetStateValue`

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

从本地跟踪器读取某个受跟踪状态的当前值。不会进行网络调用。

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

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

```csharp
if (character.DynamicContext.TryGetStateValue("HazardLevel", out string level))
    Debug.Log($"当前危险等级：{level}");
else
    Debug.Log("未设置 HazardLevel 状态。");
```

#### `Apply`

```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` 不是 `重置`，以及 `文本`, `动作配置`，以及 `当前注意对象` 都 `null` | 警告： `原始动态上下文更新需要 text、action_config、current_attention_object 或 Reset 模式`。调用会返回而不发送。 |
| 角色不在活动对话中                                                  | 警告： `无法应用原始动态上下文更新：不在对话中`。更新已丢弃。                                                    |

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

### `ConvaiDynamicContextUpdate`

`Convai.Runtime.DynamicContext` — 密封类

由以下内容使用的高级类型化请求： `Apply` 用于在不暴露传输字符串的情况下发送原始动态上下文更新。

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

| 参数                       | 类型                        | 默认值      | 描述                                                                                                                                                                                    |
| ------------------------ | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`                   | `string`                  | —        | 要发送的上下文文本。至少需要设置其中一个 `text`, `actionConfig`，或 `currentAttentionObject` 必须设置，或者 `模式` 必须为 `重置`.                                                                                         |
| `模式`                     | `ConvaiContextUpdateMode` | `Append` | Convai 如何应用文本。                                                                                                                                                                        |
| `reaction`               | `ConvaiRespondMode`       | `Auto`   | 该更新是否触发语音回复。                                                                                                                                                                          |
| `removeStatic`           | `bool`                    | `false`  | 当 `模式` 是 `重置` 并且这是 `true`，还会请求 Convai 移除该角色该会话的静态初始动态上下文。                                                                                                                             |
| `currentAttentionObject` | `object`                  | `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`

由……使用 `Apply` 和 `ConvaiDynamicContextUpdate`.

| 值        | 描述                                 |
| -------- | ---------------------------------- |
| `Append` | 将文本添加到现有动态上下文中，而不会替换之前的内容。         |
| `替换`     | 用提供的文本替换整个动态上下文。                   |
| `重置`     | 清除所有动态上下文。 `text` 参数在 `模式` 是 `重置`. |

### `ConvaiRespondMode`

`Convai.Runtime` ——动态上下文和动态视觉共享的单一响应模式词汇。

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

#### 从 `ConvaiContextReactionMode`

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

| 旧值（`ConvaiContextReactionMode`) | 新值（`ConvaiRespondMode`) |
| ------------------------------- | ----------------------- |
| `SyncOnly`                      | `Silent`                |
| `ReactImmediately`              | `MustRespond`           |
| `Auto`                          | `Auto` （未更改）            |

该枚举在重命名过程中重新编号—— `ConvaiRespondMode` 声明了 `Silent = 0, Auto = 1, MustRespond = 2`，而已移除的 `ConvaiContextReactionMode` 声明的 `Auto = 0, ReactImmediately = 1, SyncOnly = 2`。使用针对未发布 beta 版本的序列化反应覆盖保存的场景或预制件，在升级后其含义会改变：旧的 `Auto` (`0`）反序列化为 `Silent`，旧的 `ReactImmediately` (`1`）为 `Auto`，旧的 `SyncOnly` (`2`）为 `MustRespond`。正式发布的 SDK 资源不携带此类序列化值——这只会影响针对预发布 beta 构建保存的场景。如果这适用于你的项目，升级后请重新检查任何序列化的反应字段。

### 默认反应模式参考

| 方法                                     | 默认反应                            |
| -------------------------------------- | ------------------------------- |
| `SetState`                             | `Silent`                        |
| `SetStates`                            | `Silent`                        |
| `AddEvent`                             | `Auto`                          |
| `RemoveState`                          | *（无 `reaction` 参数；始终 `Silent`)* |
| `重置`                                   | *（无 `reaction` 参数；始终 `Silent`)* |
| `SetCurrentAttentionObject`            | `Silent`                        |
| `ClearCurrentAttentionObject`          | `Silent`                        |
| `Apply` / `ConvaiDynamicContextUpdate` | `Auto`                          |

### 下一步

{% 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" %}
[Relay 组件参考](/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.
