> 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` 类型，供 `Apply`.

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

IConvaiDynamicContext context = character.DynamicContext;
```

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

### 方法参考

以下每个跟踪方法都会先将变更暂存到本地跟踪器中；Convai 会在下一个动态上下文批次中收到更新——该批次会在 `ConvaiCharacter.DynamicContextBatchDelaySeconds` （默认值为 0.5 秒）之后在后台发送，或者在调用 `Flush()` 时立即发送，并受内部最大延迟限制，因此暂存的变更不会被无限期搁置。如果一个批次发送前请求了多个反应，则整个批次采用其中最强的值，优先级从高到低依次为 `Silent` < `Auto` < `MustRespond`。详见 [同步行为和时序](https://docs.convai.com/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 会按首次设置的顺序将其添加到 [规范上下文](https://docs.convai.com/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` | `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 会记录警告（`Cannot set empty dynamic context states`），并直接返回，不会暂存任何内容。无效的单个条目（名称为空、值）会被跳过；同一次调用中的其余有效条目仍会暂存。 `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` | 要移除的状态名称。不能为空；如果为空或仅包含空白字符，则会记录警告（`Dynamic context state name cannot be empty`），并立即返回。 |

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

#### `Reset`

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

清除所有已跟踪的状态和事件，并暂存一条发送给 Convai 的 Reset 消息。

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

`Reset` 没有 `reaction` 参数——暂存的 Reset 消息始终携带 `ConvaiRespondMode.Silent`。有关如何设置静态初始动态上下文，请参阅 [连接时的静态上下文](https://docs.convai.com/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` | 焦点变更所请求的反应。                                                              |

有关完整的指代消解模型、静默失败条件和用法示例，请参阅 [注意力与指代消解](https://docs.convai.com/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)
```

暂存清除当前注意力对象的操作。在下一次调用 `SetCurrentAttentionObject` 之前，Convai 会将角色视为没有特定关注目标。

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

#### `Flush`

```csharp
void Flush()
```

立即发送所有已暂存的动态上下文变更（以及待处理的场景元数据变更），而无需等待批处理窗口。 `Flush` 当角色不在进行中的对话中时，此方法不执行任何操作——暂存的数据仍会保持待处理状态，并在角色准备就绪后自动随批次一并发送。

#### `TryGetStateValue`

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

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

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

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

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

#### `Apply`

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

将原始的类型化更新直接发送到传输层，绕过本地跟踪器和批处理队列。适用于高级场景，例如在外部构造上下文文本，或在一条消息中组合上下文更新与运行时动作配置补丁或注意力对象更改。请参阅 [`ConvaiActionConfigPatch`](https://docs.convai.com/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`                                                                        | 警告： `Raw dynamic context update cannot be null`。调用将直接返回，不会发送更新。                                                        |
| `update.Mode` 不为 `Reset`，并且 `Text`, `ActionConfig`，并且 `CurrentAttentionObject` 均为 `null` | 警告： `Raw dynamic context updates require text, action_config, current_attention_object, or Reset mode`。调用将直接返回，不会发送更新。 |
| 角色当前不在进行中的对话中                                                                            | 警告： `Cannot apply raw dynamic context update: not in conversation`。更新已丢弃。                                              |

{% hint style="danger" %}
**`Apply` 不会将更新加入队列或批量处理。** 如果角色当前不在进行中的对话中，Convai 会丢弃更新并记录警告；不会发送任何内容，也不会重试。通过 `Apply` 发送的值会绕过本地跟踪器： `TryGetStateValue` 返回 `false` 以这种方式发送的键。对于所有标准上下文管理，请使用受跟踪的方法（`SetState`, `SetStates`, `AddEvent`, `RemoveState`, `Reset`）。
{% 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` ；或者， `mode` 必须设置为 `Reset`.                                                                                                 |
| `mode`                   | `ConvaiContextUpdateMode` | `Append`  | Convai 如何应用文本。                                                                                                                                                                                      |
| `reaction`               | `ConvaiRespondMode`       | `Auto`    | 此更新是否会触发语音回复。                                                                                                                                                                                       |
| `removeStatic`           | `bool`                    | `false`   | 当 `mode` 为 `Reset` 且此参数为 `true`时，还会请求 Convai 移除该会话中角色的静态初始动态上下文。                                                                                                                                    |
| `currentAttentionObject` | `object`                  | `时显示为灰色。` | 与此更新一同设置的注意对象。可接受 `string` 对象名称或 `ConvaiActionObjectDefinition` 引用。                                                                                                                                 |
| `updateId`               | `string`                  | `时显示为灰色。` | 将此更新与其后端确认信息相关联。若省略，则自动生成。                                                                                                                                                                          |
| `actionConfig`           | `ConvaiActionConfigPatch` | `时显示为灰色。` | 要与此上下文更新一同应用的运行时操作配置补丁。请参阅 [角色动作脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/actions-scripting-reference.md#convaiactionconfigpatch). |

### `ConvaiContextUpdateMode`

使用方 `Apply` 和 `ConvaiDynamicContextUpdate`.

| 值         | 说明                                       |
| --------- | ---------------------------------------- |
| `Append`  | 将文本添加到现有动态上下文中，不会替换之前的内容。                |
| `Replace` | 使用提供的文本替换整个动态上下文。                        |
| `Reset`   | 清除所有动态上下文。当 `text` 参数在 `mode` 为 `Reset`. |

### `ConvaiRespondMode`

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

| 值             | 字符串值           | 说明                      |
| ------------- | -------------- | ----------------------- |
| `Silent`      | `silent`       | 融入角色的感知，不会单独触发口头回复。     |
| `Auto`        | `auto`         | Convai 会判断此次更新是否需要口头回复。 |
| `MustRespond` | `must_respond` | 更新后始终触发口头回复。            |

### 默认反应模式参考

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

### 后续步骤

{% content-ref url="/pages/bb1aef3496a2be08987c770aa7b8072e7d8c5cd6" %}
[同步行为与时序](https://docs.convai.com/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" %}
[中继组件参考](https://docs.convai.com/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" %}
[动作目标解析的工作方式](https://docs.convai.com/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" %}
[排查动态上下文问题](https://docs.convai.com/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.
