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

# 使用角色情绪

接收 Convai 在角色回复中检测到的情绪，选择其检测方式，并设置角色的临时心境状态。

读取角色回复时表达的情绪，并设置角色开始时的心境。当你的界面或 3D 角色会根据角色的情绪状态做出反应，或场景需要让角色处于特定心境时，请使用本页。

### 前提条件

* 已安装 Convai Web SDK，并有一个可连接的客户端。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).

### 启用情绪检测

创建客户端时，将 `enableEmotion` 设为 `true` 。此选项在以下两种方式中作用相同： `new ConvaiClient(...)` 来自 `@convai/web-sdk/core` 以及 `useConvaiClient(...)` 来自 `@convai/web-sdk/react`.

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

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableEmotion: true,
});
```

`enableEmotion` 的默认值为 `false`。只有将其设为 `true` 时，SDK 才会在连接时发送情绪配置。

### 接收情绪更新

订阅 `emotionChange`事件。其载荷为 `{ emotion: string; scale?: number }`，或者在对话状态被清除时为 `null` ，例如调用 `resetSession()` 或断开连接时。

```ts
const unsubscribe = client.on('emotionChange', (emotion) => {
  if (emotion === null) {
    clearEmotionDisplay();
    return;
  }
  showEmotion(emotion.emotion, emotion.scale);
});

// Later, when the view is removed:
unsubscribe();
```

最新值也可通过 `client.state.emotion`获取；该值会随每个 `stateChange` 事件更新。每次更新还会在聊天消息中添加一条 `bot-emotion` 记录，其内容示例如 `Joy (scale: 2)`；如果聊天视图只显示文本，请过滤掉该类型。

在 React 中， `useConvaiClient` 会在状态变化时重新渲染，因此你可以在渲染期间读取该值：

```tsx
import { useConvaiClient } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    enableEmotion: true,
  });

  return (
    <>
      <div className="emotion-badge">{client.state.emotion?.emotion ?? 'No emotion yet'}</div>
      <ConvaiWidget convaiClient={client} />
    </>
  );
}
```

### 选择检测提供程序

`emotionConfig` 用于选择 Convai 检测情绪的方式。仅当 `enableEmotion` 为 `true`.

```ts
// 语言模型（省略 emotionConfig 时的默认值）
const llmClient = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableEmotion: true,
  emotionConfig: { provider: 'llm' },
});

// 基于词级词典查询和强度阈值
const lexiconClient = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  enableEmotion: true,
  emotionConfig: {
    provider: 'nrclex',
    min_word_threshold: 3,
    low_intensity_threshold: 0.33,
    high_intensity_threshold: 0.66,
  },
});
```

| 服务商        | 字段                         | SDK 发送的默认值 | 说明               |
| ---------- | -------------------------- | ---------- | ---------------- |
| `'llm'`    | 无                          | 无          | 根据响应上下文推断情绪。     |
| `'nrclex'` | `min_word_threshold`       | `3`        | 检测所需的最少词数。       |
| `'nrclex'` | `low_intensity_threshold`  | `0.33`     | 低强度阈值，范围为 0 到 1。 |
| `'nrclex'` | `high_intensity_threshold` | `0.66`     | 高强度阈值，范围为 0 到 1。 |

### 设置角色的心理状态

心理状态是角色带入后续回复中的情绪。可在连接时通过 `stateOfMind`设置，也可在会话期间通过 `updateEmotion`.

```ts
const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  stateOfMind: 'fear',
});

// 之后，角色重新感到安全时：
client.updateEmotion('trust');

// 清除状态：
client.updateEmotion(null);
```

* `updateEmotion` 不会触发任何操作。它会影响下一次回复，但不会触发回复。
* 该值会先去除首尾空白，再转换为小写。 `null`、空字符串和 `'neutral'` 都会清除心理状态。
* 服务器仅应用 Plutchik 的八种基本情绪： `joy`, `trust`, `fear`, `surprise`, `sadness`, `disgust`, `anger`, `anticipation`。任何其他值（`'happy'`, `'calm'`, `'sad'`）都会被确认并附带 `extras.applied: false` ，并被忽略；SDK 会记录一条警告。
* 该值会保留，供后续连接使用。在会话连接前调用时，该值会被存储，并在下一次 `connect()`时发送。连接配置中传入的 `stateOfMind` 优先于已存储的值。
* Convai 会通过一个 `serverResponse` 事件确认每次更新，该事件的 `event_type` 为 `'update-emotion'`.

### 验证情绪更新

连接后，发送一条能引出情绪化回复的消息，并记录 `client.state.emotion`.

{% hint style="success" %}
角色回答后， `emotionChange` 会触发并携带一个情绪名称，而 `client.state.emotion` 会保存相同的值。
{% endhint %}

如果 `emotionChange` 始终未触发，请确认客户端连接时使用的配置中 `enableEmotion` 为 `true` 。

### 后续步骤

{% 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 %}


---

# 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/emotions.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.
