> 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 快速入门](/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);
});

// 之后，当视图被移除时：
unsubscribe();
```

最新值也会出现在 `client.state.emotion`，它会在每次 `stateChange` 事件时更新。每次更新还会添加一个 `bot-emotion` 条目到聊天消息中，内容例如 `快乐（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 ?? '尚无情绪'}</div>
      <ConvaiWidget convaiClient={client} />
    </>
  );
}
```

### 选择检测提供方

`emotionConfig` 用于选择 Convai 如何检测情绪。仅当 `enableEmotion` 为 `true`.

```ts
// Language model（在省略 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 的八种基本情绪： `快乐`, `信任`, `恐惧`, `惊讶`, `悲伤`, `厌恶`, `愤怒`, `期待`。任何其他值（`'happy'`, `'calm'`, `'sad'`）都会被确认但应用结果为 `extras.applied: false` 并被忽略；SDK 会记录一条警告。
* 该值会保留供后续连接使用。当在会话连接之前调用时，它会被存储并在下一次 `connect()`。 `stateOfMind` 在 connect 配置中传入的值会优先于已存储的值。
* 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" %}
[在运行时更新角色上下文](/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 事件参考](/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/dff296725774f9173a7391e28344f5f94cf35b60" %}
[配置和类型参考](/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.
