> 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

`IConvaiDynamicContext` 是用于以编程方式控制动态上下文的 C# 接口。可通过 `DynamicContext` 上的属性 `ConvaiCharacter`:

```csharp
IConvaiDynamicContext context = _character.DynamicContext;
```

该属性采用延迟初始化，在组件生命周期内缓存是安全的。无需额外设置。

### 方法参考

#### `SetState`

```csharp
void SetState(string name, string value,
    ConvaiContextReactionMode reaction = ConvaiContextReactionMode.SyncOnly)
```

设置或更新一个受跟踪的状态项。如果该状态不存在，则会创建它，并按首次设置的顺序追加到规范上下文中。如果值与当前值相同，则该调用为幂等空操作——不会发送更新。

**参数**

| 参数         | 类型                          | 默认         | 描述                         |
| ---------- | --------------------------- | ---------- | -------------------------- |
| `名称`       | `string`                    | —          | 状态标识符。必须非空且不能全是空白字符。区分大小写。 |
| `值`        | `string`                    | —          | 状态值。可以是空字符串。不能为 `null`.    |
| `reaction` | `ConvaiContextReactionMode` | `SyncOnly` | 控制角色是否立即生成回复。              |

**网络行为**

| 条件        | 发送的消息                                                              |
| --------- | ------------------------------------------------------------------ |
| 新状态       | 一条 Append： `"{name} is {value}"`                                   |
| 现有状态，值已更改 | Replace（完整规范上下文）+ Append： `"{name} changed from {old} to {value}"` |
| 值相同       | 无 — 幂等空操作                                                          |

**对话前：** 会自动入队；在连接时作为单个 Replace 发送。

#### `SetStates`

```csharp
void SetStates(IReadOnlyDictionary<string, string> states,
    ConvaiContextReactionMode reaction = ConvaiContextReactionMode.SyncOnly)
```

以原子方式设置或更新多个受跟踪的状态项。优先于顺序 `SetState` 调用用于多个值同时变化时——只会生成一次规范上下文重建，而不是多次。

**参数**

| 参数         | 类型                                    | 默认         | 描述                 |
| ---------- | ------------------------------------- | ---------- | ------------------ |
| `states`   | `IReadOnlyDictionary<string, string>` | —          | 状态名称到值的映射。至少必须有一项。 |
| `reaction` | `ConvaiContextReactionMode`           | `SyncOnly` | 控制角色是否立即生成回复。      |

**网络行为**

| 条件         | 发送的消息                            |
| ---------- | -------------------------------- |
| 所有状态都是新的   | 一条 Append，列出所有新状态行               |
| 任何现有状态已更改  | Replace（完整规范上下文）+ Append（汇总所有更改） |
| 所有值都与当前值相同 | 无 — 空操作                          |

**对话前：** 会自动入队。

```csharp
_character.DynamicContext.SetStates(
    new Dictionary<string, string>
    {
        { "Station", "Bay 7" },
        { "HazardLevel", "Extreme" }
    },
    ConvaiContextReactionMode.ReactImmediately
);
```

#### `AddEvent`

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

按时间顺序追加一个事件条目。事件会在规范上下文中所有状态之后，按调用顺序累积。与状态不同，事件绝不会被替换或去重——每次调用都会添加一新行。

**参数**

| 参数         | 类型                          | 默认     | 描述                                                                            |
| ---------- | --------------------------- | ------ | ----------------------------------------------------------------------------- |
| `文本`       | `string`                    | —      | 事件描述。必须非空且不能全是空白字符。                                                           |
| `reaction` | `ConvaiContextReactionMode` | `Auto` | 控制角色是否立即生成回复。默认值为 `Auto` ——注意与 `SetState` 和 `SetStates`不同，它们的默认值为 `SyncOnly`. |

**网络行为：** 一条包含事件文本的 Append 消息。

**对话前：** 会自动入队。

#### `RemoveState`

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

按名称移除一个受跟踪的状态，并向 Convai 发送更新后的规范上下文。如果该状态不在跟踪器中，则该调用为幂等空操作——不会发送消息，也不会记录警告。

**参数**

| 参数   | 类型       | 描述             |
| ---- | -------- | -------------- |
| `名称` | `string` | 要移除的状态名称。必须非空。 |

**网络行为：** 一条 Replace 消息，包含移除该状态后的规范上下文。 `RemoveState` 没有 reaction 模式——移除操作绝不会触发立即的 LLM 回复。

**对话前：** 会自动入队。

#### `Reset`

```csharp
void Reset()
```

清除所有受跟踪的状态和事件，并向 Convai 发送 Reset 消息。无参数。

**网络行为：** 一条 Reset 模式消息。Convai 端角色的动态上下文视图将被清空。

**对话前：** 会自动入队。

{% hint style="warning" %}
`Reset()` 只清除运行时动态上下文层。它不会影响初始动态信息文本（在连接时发送一次）或 Convai 控制台中角色系统提示里的事实。角色在会话中的对话记忆也不会被清除。参见 [连接时的静态上下文](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/static-context-at-connection-time.md) 以查看 `Reset()` 会清除和不会清除的完整范围。
{% endhint %}

#### `TryGetStateValue`

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

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

**参数**

| 参数   | 类型           | 描述                           |
| ---- | ------------ | ---------------------------- |
| `名称` | `string`     | 要查找的状态名称。                    |
| `值`  | `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.");
```

#### `应用`

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

直接向传输层发送一个原始的类型化更新，绕过本地跟踪器。适用于在外部构建上下文文本的高级用例——例如，与产生自身规范文本的外部状态机集成。

**参数**

| 参数       | 类型                           | 描述      |
| -------- | ---------------------------- | ------- |
| `update` | `ConvaiDynamicContextUpdate` | 要发送的更新。 |

**`ConvaiDynamicContextUpdate` 构造函数：**

```csharp
new ConvaiDynamicContextUpdate(
    string text,
    ConvaiContextUpdateMode mode = ConvaiContextUpdateMode.Append,
    ConvaiContextReactionMode reaction = ConvaiContextReactionMode.Auto)
```

| 参数         | 类型                          | 默认       | 描述                             |
| ---------- | --------------------------- | -------- | ------------------------------ |
| `文本`       | `string`                    | —        | 要发送的上下文文本。除非 `mode` 是 `Reset`. |
| `mode`     | `ConvaiContextUpdateMode`   | `Append` | Convai 如何应用该文本。                |
| `reaction` | `ConvaiContextReactionMode` | `Auto`   | 角色是否立即回复。                      |

{% hint style="danger" %}
**`Apply()` 不会入队。** 如果角色在 `Apply()` 被调用时不处于活动对话中，则该更新会被丢弃，并通过 Convai 日志记录器发出警告。启用 Convai 调试日志即可在 Unity Console 中看到它。不会建立队列——该更新会永久丢失。

通过 `Apply()` 发送的 **不** 会记录到本地跟踪器中。 `TryGetStateValue` 返回 `false` 适用于以这种方式发送的键。

对于所有标准上下文管理，请使用受跟踪的方法（`SetState`, `SetStates`, `AddEvent`, `RemoveState`, `Reset`). `Apply()` 是供外部系统使用的后门，而不是主要 API。
{% endhint %}

### 枚举参考

#### `ConvaiContextReactionMode`

| 值                  | 描述                                   |
| ------------------ | ------------------------------------ |
| `Auto`             | Convai 决定该更新是否值得角色立即回复。              |
| `ReactImmediately` | 始终会在更新后触发一次立即的 LLM 回合。当角色必须确认该更改时使用。 |
| `SyncOnly`         | 上下文会静默更新。角色会在下一次自然回合中将其纳入。不生成立即回复。   |

#### `ConvaiContextUpdateMode`

由以下项使用 `Apply()` 和 `ConvaiDynamicContextCommand` 与 **原始更新** 命令类型。

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

### 默认 reaction 模式参考

| 方法                                       | 默认反应              |
| ---------------------------------------- | ----------------- |
| `SetState`                               | `SyncOnly`        |
| `SetStates`                              | `SyncOnly`        |
| `AddEvent`                               | `Auto`            |
| `RemoveState`                            | *（无 reaction 参数）* |
| `Reset`                                  | *（始终 `SyncOnly`)* |
| `Apply()` / `ConvaiDynamicContextUpdate` | `Auto`            |

{% hint style="warning" %}
`ConvaiDynamicContextCommand` （Inspector 组件）默认为 **反应模式** 设为 `Auto` 适用于所有命令类型——包括 `SetState` 和 `SetStates`. 这与上面的脚本 API 默认值不同。在 Inspector 和脚本之间切换时，请确认反应模式符合你的预期。
{% endhint %}

### 下一步

{% 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/fe2e3da29009b41a36bf622ae1efd7921e09aab7" %}
[命令组件参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/dynamic-context/command-component-reference.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:

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

The question should be specific, self-contained, and written in natural language.
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.
