> 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

Convai Unity SDK 动态上下文脚本接口参考，包括每个方法、respond mode 枚举和 attention 对象 API。

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

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

IConvaiDynamicContext context = character.DynamicContext;
```

`DynamicContext` 可在每个 `ConvaiCharacter` 实例上使用，无需额外设置。下面每个方法都接受一个 `ConvaiRespondMode` 值，用于控制更新是否触发语音回复。

### 方法参考

下方每个受跟踪的方法都会将其更改暂存到本地跟踪器中；Convai 会在下一次动态上下文批处理中接收该更新——这次后台刷新会在 `ConvaiCharacter.DynamicContextBatchDelaySeconds` （默认 0.5 秒）之后，或者在 `Flush()` 被调用时立即触发，并且会受到内部最大延迟限制，因此暂存的更改不会被无限期保留。当在批处理刷新之前请求了多个反应时，整个批次将采用优先级最高的值，排序为 `静默` < `自动` < `必须响应`。请参阅 [同步行为和时机](/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)
```

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

| 参数   | 类型                  | 默认值  | 说明                          |
| ---- | ------------------- | ---- | --------------------------- |
| `名称` | `string`            | —    | 状态标识符。不能为空且不能仅包含空白字符。区分大小写。 |
| `值`  | `string`            | —    | 状态值。可以为空字符串。不能为 `null`.     |
| `反应` | `ConvaiRespondMode` | `静默` | 此更改请求的反应。                   |

#### `SetStates`

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

一次调用设置或更新多个受跟踪的状态项，每个项都以相同的 `反应` 值暂存。建议使用 `SetStates` 而不是顺序的 `SetState` 调用，当多个值同时变化时进行调用。

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

如果 `状态` 是 `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`            | —    | 事件描述。不能为空且不能仅包含空白字符。                                |
| `反应`   | `ConvaiRespondMode` | `自动` | 请求的反应。注意默认值不同于 `SetState` 和 `SetStates`，其默认值为 `静默`. |

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

#### `RemoveState`

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

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

| 参数   | 类型       | 说明                                                         |
| ---- | -------- | ---------------------------------------------------------- |
| `名称` | `string` | 要移除的状态名称。不能为空；空值或仅包含空白字符的值会记录警告（`动态上下文状态名称不能为空`）并且调用会立即返回。 |

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

#### `Reset`

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

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

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

`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`，都会被拒绝。 |
| `反应`                     | `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` 调用。

| 参数   | 类型                  | 默认值  | 说明         |
| ---- | ------------------- | ---- | ---------- |
| `反应` | `ConvaiRespondMode` | `静默` | 清除操作请求的反应。 |

#### `刷新`

```csharp
void Flush()
```

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

#### `TryGetStateValue`

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

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

| 参数   | 类型           | 说明                          |
| ---- | ------------ | --------------------------- |
| `名称` | `string`     | 要查找的状态名称。                   |
| `值`  | `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) 在角色动作脚本参考中。

| 参数   | 类型                           | 说明                                                                        |
| ---- | ---------------------------- | ------------------------------------------------------------------------- |
| `更新` | `ConvaiDynamicContextUpdate` | 要发送的更新。参见 [`ConvaiDynamicContextUpdate`](#convaidynamiccontextupdate) 下文。 |

| 条件                                                                     | 结果                                                                                   |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `更新` 是 `null`                                                          | 警告： `原始动态上下文更新不能为空`。调用将返回且不会发送。                                                      |
| `update.Mode` 不是 `Reset`，以及 `文本`, `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)
```

| 参数                       | 类型                        | 默认值     | 说明                                                                                                                                                                                     |
| ------------------------ | ------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`                   | `string`                  | —       | 要发送的上下文文本。至少其中一个 `text`, `actionConfig`，或 `currentAttentionObject` 必须设置，或者 `mode` 必须为 `Reset`.                                                                                         |
| `mode`                   | `ConvaiContextUpdateMode` | `附加`    | Convai 如何应用该文本。                                                                                                                                                                        |
| `反应`                     | `ConvaiRespondMode`       | `自动`    | 此更新是否触发语音回复。                                                                                                                                                                           |
| `removeStatic`           | `bool`                    | `false` | 当 `mode` 是 `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` | 清除所有动态上下文。该 `text` 参数在……时会被忽略 `mode` 是 `Reset`. |

### `ConvaiRespondMode`

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

| 值      | 线格式字符串 | 说明                      |
| ------ | ------ | ----------------------- |
| `静默`   | `静默`   | 被吸收到角色的感知中；本身绝不会触发语音回复。 |
| `自动`   | `自动`   | Convai 决定该更新是否值得触发语音回复。 |
| `必须响应` | `必须回应` | 在更新后始终触发语音回复。           |

### 默认反应模式参考

| 方法                                  | 默认反应                  |
| ----------------------------------- | --------------------- |
| `SetState`                          | `静默`                  |
| `SetStates`                         | `静默`                  |
| `AddEvent`                          | `自动`                  |
| `RemoveState`                       | *（无 `反应` 参数；始终 `静默`)* |
| `Reset`                             | *（无 `反应` 参数；始终 `静默`)* |
| `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 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-unity-sdk/features/dynamic-context/dynamic-context-scripting-api.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.
