> 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/actions.md).

# 处理角色动作

声明角色可以使用的动作、对象和工具，接收它选择的动作，并返回你应用运行的工具结果。

在连接时声明角色可以执行的操作，并在对话过程中处理角色选择的操作，让角色在场景中行动。当角色需要移动、拾取物品或调用应用中的函数时，请使用此页面。每项操作的授权和执行仍由你的应用负责。

SDK 支持两种契约。默认使用语义操作，它会返回带有名称、目标可选的操作。客户端工具为可选功能，会返回类型化的工具调用，由你的应用通过结果进行响应。

### 前提条件

* 已安装 Convai Web SDK，并且客户端可以连接。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).
* 场景支持的操作、物体和角色名称。

### 声明语义操作

在创建客户端时传入 `actionConfig` 。此选项同样适用于 `new ConvaiClient(...)` 和 `useConvaiClient(...)`.

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

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  actionConfig: {
    actions: ['Move To', 'Pick Up', 'Drop', 'Wave'],
    objects: [
      { name: 'fire extinguisher', description: 'A red extinguisher mounted by the door' },
      { name: 'valve', description: 'The gas shut-off valve on the north wall' },
    ],
    characters: [
      { name: 'Trainee', bio: 'The person taking the safety drill' },
    ],
    current_attention_object: 'valve',
  },
});
```

`actions`, `objects`和 `characters` 必须在 `actionConfig`. `current_attention_object` 是可选项，且必须与 `objects`中的某个名称匹配。配置会在会话连接时发送，因此要更改配置，请重新连接。

### 接收语义操作

订阅 `actionResponse`。每个事件都包含一轮对话中的操作，并按顺序排列。

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

client.on('actionResponse', ({ actions }: ActionResponseEvent) => {
  for (const action of actions) {
    if (action.target) {
      // 带参数："Move To" -> "valve"
      runTargetedAction(action.name, action.target);
    } else {
      // 简单操作："Wave"
      playAnimation(action.name);
    }
  }
});
```

* `name` 是来自 `actionConfig.actions`.
* `target` 当角色对特定物体或角色执行操作时会存在；对于简单操作则不存在。应根据 `target`进行分支判断，而不要根据操作名称判断：同一操作可能带有目标，也可能不带目标。
* 空的 `actions` 数组表示有效的一轮对话，只是没有操作。
* SDK 不会运行或调度操作，也不会添加 `action` 聊天消息的入口，并使用操作名称标记。

例如，“拿起灭火器并把它带给学员”这样的请求可能会在同一事件中生成多个操作：

```json
{
  "actions": [
    { "name": "Move To", "target": "fire extinguisher" },
    { "name": "Pick Up", "target": "fire extinguisher" },
    { "name": "Move To", "target": "Trainee" },
    { "name": "Drop", "target": "Trainee" }
  ]
}
```

### 更新角色当前关注的对象

使用 `updateContext`告知角色当前关注的对象，以便它能解析“它”或“那个”等词语。该值必须与 `actionConfig.objects`中的某个名称匹配；空字符串则会清除当前关注对象。

```ts
// 静默更改关注对象
client.updateContext({ current_attention_object: 'fire extinguisher', run_llm: 'false' });

// 更改关注对象，并由 Convai 决定是否响应
client.updateContext({
  text: 'The trainee is now looking at the valve.',
  current_attention_object: 'valve',
  run_llm: 'auto',
});

// 清除关注对象
client.updateContext({ current_attention_object: '', run_llm: 'false' });
```

若要描述周围环境但不使其中的物品成为可操作对象，请使用 `updateSceneMetadata`。它不会更改 `actionConfig`，因此通过这种方式传入的物品永远不会成为操作目标。请参阅 [在运行时更新角色上下文](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/dynamic-context.md).

### 在没有输入的情况下触发响应

`sendTriggerMessage(triggerName?, triggerMessage?)` 可让角色在使用应用的人没有发送消息的情况下作出响应，例如在演练开始时。两个参数均为可选。

```ts
client.sendTriggerMessage('drill_start');
client.sendTriggerMessage(undefined, 'Ask the trainee to locate the nearest extinguisher.');
```

### 启用客户端工具

客户端工具可添加类型化参数和关联结果。在 `capabilities`中请求操作协议版本 2 和模型输出版本 2，并在 `actionConfig.tools`中声明这些工具。省略 `capabilities` 则会保留语义操作契约。

```ts
const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  capabilities: {
    actionProtocolVersion: 2,
    modelOutputVersion: 2,
  },
  actionConfig: {
    actions: [],
    objects: [],
    characters: [],
    tools: [
      {
        name: 'open_training_record',
        description: 'Open a training record after the trainee confirms.',
        inputSchema: {
          type: 'object',
          properties: { recordId: { type: 'string' } },
          required: ['recordId'],
        },
      },
    ],
  },
});
```

`capabilities` 包含三个字段：

| 字段                      | 数值                   | 省略时                          |
| ----------------------- | -------------------- | ---------------------------- |
| `actionProtocolVersion` | `1` 或 `2`            | 语义操作                         |
| `modelOutputVersion`    | `1` 或 `2`            | 旧版输出消息，没有 `modelOutput` 事件   |
| `botLlmTextMode`        | `'legacy'` 或 `'raw'` | 经过筛选的文本位于 `bot-llm-text` 消息中 |

`'raw'` 会将 `bot-llm-text` 聊天消息切换为动作解析前的完整提供方输出。这是聊天文本，而非工具调用流：切勿从中解析或执行操作。

Convai 会在连接响应中确认所选能力。 `connect()` 如果所选内容与请求不匹配，则会拒绝连接：

| 错误                                                                          | 原因                   |
| --------------------------------------------------------------------------- | -------------------- |
| `Core did not select requested action protocol version 2`                   | 请求了版本 2，但未获批准。       |
| `Core selected action protocol version 2 without an explicit client opt-in` | 未提出请求，但版本 2 获得了批准。   |
| `Core did not select requested model output version 2`                      | 请求了模型输出版本 2，但未获批准。   |
| `Core did not select requested raw bot LLM text mode`                       | `'raw'` 已提出请求，但未获批准。 |

声明会在连接时发送，因此更改工具需要重新连接。

### 处理模型输出和工具调用

使用 `modelOutputVersion: 2`时，订阅 `modelOutput`。每个事件都是一个经过验证的信封，其中的 `items` 按顺序包含消息、情绪、语义操作、工具调用和扩展。在此模式下，SDK 会抑制 `actionResponse` ，以免同一操作被处理两次；此外，如果某个信封的 `output_id` 已传递过，SDK 会将其丢弃。

```ts
import type {
  ActionResult,
  ModelOutputMessage,
  ModelOutputProtocolError,
  ModelOutputToolCallItem,
} from '@convai/web-sdk/core';

client.on('modelOutput', (output: ModelOutputMessage) => {
  for (const item of output.items) {
    if (item.type === 'message') renderMessage(item.content);
    if (item.type === 'semantic_action') runTargetedAction(item.name, item.target);
    if (item.type === 'tool_call') void runTool(item);
  }
});

client.on('modelOutputProtocolError', (error: ModelOutputProtocolError) => {
  console.error(error.code, error.message);
});

async function runTool(call: ModelOutputToolCallItem) {
  let result: ActionResult;
  try {
    // Check permissions and ask for confirmation here.
    const output = await openTrainingRecord(call.arguments);
    result = { id: call.id, status: 'completed', output };
  } catch (error) {
    result = {
      id: call.id,
      status: 'error',
      error: { message: error instanceof Error ? error.message : 'Tool failed' },
    };
  }
  client.sendActionResult(result);
}
```

仅渲染和执行经过验证的 `items`. `raw` 保存了用于诊断的提供方输出，绝不能执行。当信封格式错误或包含不受支持的项目时，SDK 会拒绝整个信封，并触发 `modelOutputProtocolError` ，错误代码为 `invalid_model_output`.

多个信封可以共用一个 `logical_turn_id`，而且 `final: true` 仅表示一个信封结束，并不表示整个轮次结束。SDK 不会跟踪待处理的调用，不会对多个信封中的工具调用 ID 去重，不会重试结果，也不保证只执行一次。请在应用程序中处理这些记录。

### 返回工具结果

`sendActionResult(result)` 会验证结果并将其发送给 Convai。它不返回任何内容；没有抛出异常只表示结果已发送，并不表示已被接受。

| 字段                   | 必填 | 备注                                       |
| -------------------- | -- | ---------------------------------------- |
| `id`                 | 是  | 工具调用的 `id` 。                             |
| `status`             | 是  | `'completed'`, `'error'`或 `'cancelled'`. |
| `output`             | 否  | 有限的 JSON 数据。                             |
| `error`              | 否  | 有限的 JSON 数据。不能与 `'completed'`.           |
| `characterSessionId` | 否  | 默认为当前会话。                                 |

如果结果无效，则会在发送前抛出错误：

| 错误                                                          | 原因                                      |
| ----------------------------------------------------------- | --------------------------------------- |
| `Cannot send an action result before the session is ready`  | 传输尚未连接。                                 |
| `Action result id is required`                              | `id` 为空。                                |
| `Unsupported action result status`                          | `status` 不是三个值之一。                       |
| `Completed action results cannot include error`             | `status` 为 `'completed'` 且 `error` 已设置。 |
| `Action result output must contain only finite JSON values` | `output` 包含非 JSON 值。                    |
| `Action result error must contain only finite JSON values`  | `error` 包含非 JSON 值。                     |

Convai 会通过一个 `serverResponse` 事件确认结果，该事件的 `event_type` 为 `'action-result'`。检查其 `status` 和 `message`.

```ts
client.on('serverResponse', (response) => {
  if (response.event_type === 'action-result' && response.status === 'error') {
    console.error('Result rejected:', response.message);
  }
});
```

要将类型化轮次与其输出关联起来，请传入 `sendUserTextMessage(text, { logicalTurnId })`。ID 必须非空，且长度不得超过 128 个 UTF-8 字节，否则该方法会抛出错误 `logicalTurnId must be non-empty and at most 128 UTF-8 bytes`.

### 后续步骤

{% content-ref url="/pages/4c37a8e73c580fc9f3ebe503a43373bd3551a22e" %}
[在运行时更新角色上下文](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/dynamic-context.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 %}

{% content-ref url="/pages/dff296725774f9173a7391e28344f5f94cf35b60" %}
[配置和类型参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/best-practices-and-type-definitions.md)
{% endcontent-ref %}

{% content-ref url="/pages/70d752d330612b0fbf1290588e718236d6a18f0e" %}
[连接 API](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/connect-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/138cedadc568671d93b18cf90042de5055cbffd5" %}
[客户端到服务器消息](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/live-apis-beta/client-to-server-messages.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/actions.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.
