> 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/web-plugins/convai-web-sdk/dynamic-context.md).

# 在运行时更新角色上下文

向角色提供关于场景、会话以及它正在交谈对象的实时信息，并控制每次更新是否会促使它回应。

随着应用的变化，让角色及时了解情况：连接时传入初始上下文，然后在会话期间发送更新，无需重新连接。如果角色需要了解场景状态、进度或交谈期间发生变化的文件，请参考本页。这里介绍的每种方法都可用于 `ConvaiClient` 以及 `useConvaiClient`.

### 前提条件

* 已安装 Convai Web SDK，并且客户端可以连接。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).
* 对于模板键，需要启用 Narrative Design 的角色。请参阅 [Narrative Design 指南](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/narrative-design-guide.md).

### 连接时传入上下文

将 `dynamicInfo` 设置为对初始情境的文本描述。

```ts
import { ConvaiClient } from '@convai/web-sdk/core';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  dynamicInfo: 'Trainee: Aria. Module: chemical spill response. Progress: 2 of 5 steps.',
});
```

`keepInContext` 用于控制文本的保留方式。设为 `true`时，它会作为整个连接期间的静态提示；重新连接后必须再次发送。设为 `false`时（默认值），可在会话期间更新和重置。 `keepInContext` 仅与 `dynamicInfo`.

### 在会话期间更新上下文

`updateContext(options)` 会更改角色的临时运行时上下文。

```ts
// 添加到现有上下文，不触发回复
client.updateContext({ text: 'The trainee closed the valve.', mode: 'append', run_llm: 'false' });

// 替换上下文，并让 Convai 决定是否回复
client.updateContext({ text: 'Step 3 of 5: contain the spill.', mode: 'replace', run_llm: 'auto' });

// 清除上下文
client.updateContext({ mode: 'reset' });
```

| 选项                         | 数值                                     | 默认值        | 即可完全隐藏叠加层。                                                                                                                                                          |
| -------------------------- | -------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`                     | `string`                               | 无          | 要应用的上下文。除非 `mode` 为 `'reset'` ，或者仅 `current_attention_object` 发生变化，否则此项为必填。                                                                                         |
| `mode`                     | `'append'`, `'replace'`, `'reset'`     | `'append'` | 添加、替换或清除临时上下文。                                                                                                                                                      |
| `run_llm`                  | `'true'`, `'false'`, `'auto'`          | `'auto'`   | `'true'` 始终触发回复，并停止本地唇形同步播放。 `'false'` 则从不触发回复。 `'auto'` 让 Convai 自行决定，而不会中断播放。                                                                                     |
| `respond_mode`             | `'must_respond'`, `'auto'`, `'silent'` | 无          | 替代 `run_llm`。如果两者都已设置， `run_llm` 则以其为准。                                                                                                                             |
| `current_attention_object` | `string`                               | 无          | 角色当前关注的对象。必须与 `actionConfig.objects`中的名称匹配；空字符串会清除该对象。请参阅 [处理角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md). |

当 `text` 缺失，且不处于 `'reset'` 模式，同时未提供关注对象时，不会发送任何内容，并且控制台会记录 `[ConvaiClient] updateContext: text or current_attention_object is required unless mode is 'reset'`。除 `uploadFile`外，本页中的所有方法在会话未连接时均不会执行任何操作。

### 快速发送动态信息更新

`updateDynamicInfo(text)` 会发送一条 `update-dynamic-info` 消息，将文本作为会话的动态信息传递。它与 `updateContext`发送的是不同类型的消息，只接受字符串，且不提供模式或响应控制。空文本或仅包含空白字符的文本会被忽略。

```ts
client.updateDynamicInfo('Trainee health: 30 percent.');
```

如果需要在追加、替换和重置之间进行选择，或控制响应，请使用 `updateContext` 。

### 读取上下文令牌预算

Convai 会为每条 `context-update` 消息返回一条 `serverResponse` 事件。其 `extras` 中可能包含令牌计数。

```ts
client.on('serverResponse', (response) => {
  if (response.event_type !== 'context-update') return;
  if (response.status === 'error') {
    console.error('Context update rejected:', response.message);
    return;
  }
  const { token_count, remaining_tokens, max_tokens } = response.extras ?? {};
  console.log(`Context tokens: ${token_count} used, ${remaining_tokens} of ${max_tokens} left`);
});
```

`extras` 还可以包含 `static_token_count`, `runtime_token_count`, `static_max_tokens`, `runtime_max_tokens`，以及 `content`，即更新后保留的完整运行时上下文。

### 使用模板键个性化叙事设计

叙事设计部分目标和说话标签可以包含单花括号占位符，例如 `{player_name}`。评估部分时，模板键会替换这些占位符，因此一个叙事图即可用于多个会话。键区分大小写，没有对应键的占位符会解析为空字符串。

连接时通过 `narrativeTemplateKeys`:

```ts
const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  narrativeTemplateKeys: {
    player_name: 'Aria',
    location: 'Engineering Deck',
  },
});
```

在会话期间，可通过 `updateTemplateKeys`更改这些键，并在触发进入使用这些键的部分之前执行：

```ts
client.updateTemplateKeys({ player_name: 'Aria', location: 'Medical Bay' });
client.sendTriggerMessage('NextObjective');
```

`updateTemplateKeys` 会替换整个映射，而不是与其合并，因此请包含图中仍需使用的所有键。空映射不会发送。如果角色未启用叙事设计，Convai 会在 `update-template-keys` 消息的 `serverResponse` 中返回错误 `Narrative design service not available`.

### 控制角色何时响应

`respondModes` 用于在连接时设置每种输入是否会使角色响应。 `respondModeUpdate` 可在会话期间更改其中一种模式。

```ts
const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  respondModes: { contextUpdate: 'silent', sceneMetadata: 'auto' },
});

// 稍后：
const updateId = client.respondModeUpdate({ modality: 'context_update', mode: 'auto' });
```

| `respondModes` 字段 | `respondModeUpdate` 输入类型 | 允许的模式                                  |
| ----------------- | ------------------------ | -------------------------------------- |
| `text`            | `'text'`                 | `'must_respond'`                       |
| `audio`           | `'audio'`                | `'must_respond'`                       |
| `vision`          | `'vision'`               | `'must_respond'`, `'auto'`, `'silent'` |
| `contextUpdate`   | `'context_update'`       | `'must_respond'`, `'auto'`, `'silent'` |
| `trigger`         | `'trigger'`              | `'must_respond'`, `'auto'`, `'silent'` |
| `sceneMetadata`   | `'scene_metadata'`       | `'must_respond'`, `'auto'`, `'silent'` |

`respondModeUpdate` 返回它发送的更新 ID，或者 `null` （会话未连接时）。传入你自己的 `updateId` 来指定该 ID。

### 描述场景

`updateSceneMetadata(items, options?)` 用于告知角色可见或附近的事物。此操作仅用于描述，不会更改 `actionConfig`，因此通过这种方式发送的项目永远不会成为操作目标。

```ts
client.updateSceneMetadata(
  [
    { name: 'smoke', description: 'Light smoke is coming from the storage room.' },
    { name: 'alarm', description: 'The fire alarm is sounding.' },
  ],
  { respondMode: 'must_respond' },
);
```

`respondMode` 是可选项。 `'must_respond'` 会使角色作出回应，并停止新一轮的本地唇形同步播放。

### 向角色发送文件

`uploadFile(file, options?)` 会在会话期间向角色发送文件。此功能仅适用于默认的 LiveKit 传输方式。

```ts
const input = document.querySelector<HTMLInputElement>('#file-input');

input?.addEventListener('change', async () => {
  const file = input.files?.[0];
  if (!file) return;
  try {
    await client.uploadFile(file, {
      onProgress: (percent) => console.log(`${percent}% uploaded`),
    });
  } catch (error) {
    console.error('Upload failed:', error);
  }
});
```

| 选项           | 默认值             | 即可完全隐藏叠加层。               |
| ------------ | --------------- | ------------------------ |
| `topic`      | `'file-upload'` | 用于路由上传内容的主题。             |
| `onProgress` | 无               | 调用时会传入 0 到 100 之间的整数百分比。 |

文档列出的支持格式包括 JPEG、PNG、GIF 和 WebP，文件大小上限为 10 MB。文件以原始二进制数据的形式发送。上传完成时 Promise 会兑现；无法发送时则会拒绝，因此请将调用包在 `try`/`catch`.

### 验证更新

发送 `client.updateContext({ text: 'The alarm has stopped.', run_llm: 'false' })`，然后询问角色它对警报了解些什么。

{% hint style="success" %}
一个 `serverResponse` 事件，其 `event_type` `为` 'context-update'，并 `status` `'success'` 到达后，角色的回答会反映新的上下文。
{% endhint %}

### 后续步骤

{% content-ref url="/pages/503cd2436973022c29d385f47025d13de33f428c" %}
[处理角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md)
{% endcontent-ref %}

{% content-ref url="/pages/4f33318cc644cad5dc970e09e48c72b8b29329f6" %}
[使用长期记忆](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/long-term-memory.md)
{% endcontent-ref %}

{% content-ref url="/pages/1ef8009eea712d4c41fd7a2a07e473a277395698" %}
[处理错误和断开连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md)
{% endcontent-ref %}

{% content-ref url="/pages/8c6e3631e7e7da5b3c9acf5a0019d7737dc79e19" %}
[Web SDK 事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.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/web-plugins/convai-web-sdk/dynamic-context.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.
