# Analyze Sentiment

> 分析文本的情感和情绪基调。

Source: https://docs.sommatic.ai/zh/nodes/ai.sentiment/

- 标识: `ai.sentiment`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

分析文本的情感和情绪基调。

判断文本是正面、负面、中性还是混合情感。可选地细分为具体情绪，或按方面/话题分析情感。

**操作：**
- **Overall：** 给出单一情感分类，附带效价得分（-1 到 1）和置信度。
- **Emotions：** 检测具体情绪（喜悦、愤怒、悲伤、恐惧、惊讶、厌恶、信任）及其强度得分。
- **Aspect-Based：** 抽取文本中提到的话题/方面，并分别为每一项评估情感。

## 配置

- `llm_provider_id` (string, 可选): `LlmProviderModel` 记录的 `id`（例如 `wf-llm-provider-*`）。编排器将调用委托给后端：sync 模式调用 `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke`，stream 模式调用 `POST /chat/conversation/execute/stream-ephemeral`（SSE）。后端根据该记录解析 endpoint + api-key + deployment，并路由到相应的适配器。
- `invocation_mode` (string, 可选): LLM 调用的传输方式。`sync` 会阻塞直到收到完整响应。`stream` 通过 SSE 逐步接收 token（长文本生成必须使用）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 等待调用完成的最长时间（stream 模式下为分块之间的空闲超时）。sync 默认 30000，stream 默认 600000。
- `analysis_mode` (string, 必填): 要执行的情感分析类型。 默认值: `overall`. 可选值: `overall`, `emotions`, `aspect_based`.
- `language` (string, 可选): 默认值: `en`.
- `aspects` (array<string>, 可选): 可选：要分析的具体方面。留空则自动检测。 显示条件: analysis_mode = `aspect_based`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `positive` (默认): 情感为正面。
- `negative`: 情感为负面。
- `neutral`: 情感为中性。
- `mixed`: 情感为混合。
- `error`: 分析失败。

## 输入契约

- `text` (string, 必填): 要分析的文本。

## 输出契约

- `sentiment` (string, 可选): 整体情感标签。
- `valence` (number, 可选): 情感得分，从 -1（负面）到 1（正面）。
- `confidence` (number, 可选): 置信度得分 0-1。
- `emotions` (object, 可选): 情绪细分（emotions 模式）。
- `aspects` (array, 可选): 各方面的情感（aspect_based 模式）。
- `reasoning` (string, 可选): 简要说明。

## 在表达式中

后续节点可通过 `$("Analyze Sentiment").item.json.<路径>` 读取此节点输出中的内容（请把 `Analyze Sentiment` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `positive` 返回的路径，依据“端口”一节所示的输出。

- `$("Analyze Sentiment").item.json.sentiment` (string) = `"positive"`: 整体情感标签。
- `$("Analyze Sentiment").item.json.valence` (number) = `0.8`: 情感得分，从 -1（负面）到 1（正面）。
- `$("Analyze Sentiment").item.json.confidence` (number) = `0.9`: 置信度得分 0-1。
- `$("Analyze Sentiment").item.json.emotions` (object) = `null`: 情绪细分（emotions 模式）。
- `$("Analyze Sentiment").item.json.aspects` (array) = `null`: 各方面的情感（aspect_based 模式）。
- `$("Analyze Sentiment").item.json.reasoning` (string) = `"The customer thanks the team."`: 简要说明。
- `$("Analyze Sentiment").item.json.dominant_emotion` (null) = `null` (编辑器不提示)


## 工作原理

使用 LLM 将 `text` 的情感分类为正面、负面、中性或混合，可选输出情绪得分或分方面情感，并路由到对应标签的端口。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `text`。根据 `analysis_mode`（默认 `overall`）选择提示词：`overall`、`emotions`（八种情绪得分及主导情绪）或 `aspect_based`（分方面情感，若提供 `aspects` 则聚焦于此）。
4. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
5. 解析 JSON 响应（温度 0），`sentiment` 必须为字符串。缺失的数字设为 0，缺失的对象设为 `null`。
6. 将标签转为小写后路由到 `positive`、`negative`、`neutral` 或 `mixed`；其他标签一律路由到 `neutral`，而 `data.sentiment` 保留原值。

## 在工作流中

### 节点

```json
{
  "node_id": "node-sentiment",
  "label": "Detect sentiment",
  "operator_slug": "ai.sentiment",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "analysis_mode": "overall",
    "language": "en"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "negative",
  "data": {
    "sentiment": "negative",
    "valence": -0.7,
    "confidence": 0.9,
    "emotions": null,
    "dominant_emotion": null,
    "aspects": null,
    "reasoning": "The customer complains about a late delivery."
  }
}
```

## 输出端口 (代码中的行为)

### `positive`

标签为 `positive`。结构与示例相同。

```json
{
  "sentiment": "positive",
  "valence": 0.8,
  "confidence": 0.9,
  "emotions": null,
  "dominant_emotion": null,
  "aspects": null,
  "reasoning": "The customer thanks the team."
}
```

### `negative`

标签为 `negative`。

```json
{
  "sentiment": "negative",
  "valence": -0.7,
  "confidence": 0.9,
  "emotions": null,
  "dominant_emotion": null,
  "aspects": null,
  "reasoning": "The customer complains about a late delivery."
}
```

### `neutral`

标签为 `neutral`，或不属于四个已知标签之一。

```json
{
  "sentiment": "neutral",
  "valence": 0,
  "confidence": 0.9,
  "emotions": null,
  "dominant_emotion": null,
  "aspects": null,
  "reasoning": "A factual question about opening hours."
}
```

### `mixed`

标签为 `mixed`。`aspect_based` 模式下会填充 `aspects`。

```json
{
  "sentiment": "mixed",
  "valence": 0.1,
  "confidence": 0.85,
  "emotions": null,
  "dominant_emotion": null,
  "aspects": [
    {
      "aspect": "food",
      "sentiment": "positive",
      "valence": 0.8,
      "reasoning": "Praises the dishes."
    },
    {
      "aspect": "service",
      "sentiment": "negative",
      "valence": -0.6,
      "reasoning": "Long wait."
    }
  ],
  "reasoning": "Good food but slow service."
}
```

### `error`

校验、LLM 调用或解析失败。`data` 为 `{ error }`（若后端返回了响应体，还包含 `response`）。

```json
{
  "error": "Model did not return valid sentiment analysis output."
}
```

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `analysis_mode`: 请使用列出的三个值之一。未知值不会被拒绝：模型会收到单词“undefined”作为系统提示词。
- `language`: 当其不为 `en` 时加入回复语言说明；标签仍为英文。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing input text for sentiment analysis.` | `error` | 既没有 `text` 也没有 `input`。 |
| `Model did not return valid sentiment analysis output.` | `error` | 响应中没有含字符串 `sentiment` 的 JSON 对象。 |
| `[AiSentiment] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 缺少 `text` 时，代码会退而使用 `input`，而运行时它是整个传入条目（对象），不是字符串。请始终提供 `text`。
- 模型响应在去除 Markdown 代码块标记后按 JSON 解析；若失败，则解析第一个 `{` 与最后一个 `}` 之间的文本。
- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- Worker 还会在 `data` 之外以 `raw` 返回提供方的原始响应；引擎不会保留它。
- 成功时 worker 返回 `port` 和 `data`，不含 `ok` 字段；引擎只依据 `port` 路由。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.sentiment",
  "name": "Analyze Sentiment",
  "category": "ai",
  "version": "1.0.0",
  "description": "Analyze the sentiment and emotional tone of text.\n\n  Detect whether text is positive, negative, neutral, or mixed. Optionally break down into specific emotions or analyze sentiment per aspect/topic.\n\n  **Operations:**\n  - **Overall:** Single sentiment classification with valence score (-1 to 1) and confidence.\n  - **Emotions:** Detect specific emotions (joy, anger, sadness, fear, surprise, disgust, trust) with intensity scores.\n  - **Aspect-Based:** Extract topics/aspects mentioned in text and score sentiment for each independently.",
  "capabilities": [
    "nlp",
    "sentiment",
    "emotions",
    "analysis"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "llm_provider_id": {
        "type": "string",
        "title": "LLM Provider",
        "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.",
        "x-ui-widget": "llm-provider-picker",
        "x-llm-provider-capabilities": [
          "chat"
        ]
      },
      "invocation_mode": {
        "type": "string",
        "title": "Invocation Mode",
        "description": "Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`.",
        "enum": [
          "sync",
          "stream"
        ],
        "default": "sync"
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "analysis_mode": {
        "type": "string",
        "title": "Analysis Mode",
        "enum": [
          "overall",
          "emotions",
          "aspect_based"
        ],
        "default": "overall",
        "description": "Type of sentiment analysis to perform."
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en"
      },
      "aspects": {
        "type": "array",
        "title": "Aspects",
        "description": "Optional: specific aspects to analyze. Leave empty for auto-detection.",
        "items": {
          "type": "string"
        },
        "displayOptions": {
          "show": {
            "analysis_mode": [
              "aspect_based"
            ]
          }
        }
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "analysis_mode"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Text to analyze."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "sentiment": {
        "type": "string",
        "description": "Overall sentiment label."
      },
      "valence": {
        "type": "number",
        "description": "Sentiment score from -1 (negative) to 1 (positive)."
      },
      "confidence": {
        "type": "number",
        "description": "Confidence score 0-1."
      },
      "emotions": {
        "type": "object",
        "description": "Emotion breakdown (emotions mode)."
      },
      "aspects": {
        "type": "array",
        "description": "Per-aspect sentiment (aspect_based mode)."
      },
      "reasoning": {
        "type": "string",
        "description": "Brief explanation."
      }
    }
  },
  "ports": [
    {
      "port_id": "positive",
      "label": "Positive",
      "description": "Sentiment is positive.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "negative",
      "label": "Negative",
      "description": "Sentiment is negative.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "neutral",
      "label": "Neutral",
      "description": "Sentiment is neutral.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "mixed",
      "label": "Mixed",
      "description": "Sentiment is mixed.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Analysis failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "sentiment",
    "emotions"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "llm_provider_id": {
      "type": "string",
      "title": "LLM Provider",
      "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.",
      "x-ui-widget": "llm-provider-picker",
      "x-llm-provider-capabilities": [
        "chat"
      ]
    },
    "invocation_mode": {
      "type": "string",
      "title": "Invocation Mode",
      "description": "Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`.",
      "enum": [
        "sync",
        "stream"
      ],
      "default": "sync"
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "analysis_mode": {
      "type": "string",
      "title": "Analysis Mode",
      "enum": [
        "overall",
        "emotions",
        "aspect_based"
      ],
      "default": "overall",
      "description": "Type of sentiment analysis to perform."
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en"
    },
    "aspects": {
      "type": "array",
      "title": "Aspects",
      "description": "Optional: specific aspects to analyze. Leave empty for auto-detection.",
      "items": {
        "type": "string"
      },
      "displayOptions": {
        "show": {
          "analysis_mode": [
            "aspect_based"
          ]
        }
      }
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "analysis_mode"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Text to analyze."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "sentiment": {
      "type": "string",
      "description": "Overall sentiment label."
    },
    "valence": {
      "type": "number",
      "description": "Sentiment score from -1 (negative) to 1 (positive)."
    },
    "confidence": {
      "type": "number",
      "description": "Confidence score 0-1."
    },
    "emotions": {
      "type": "object",
      "description": "Emotion breakdown (emotions mode)."
    },
    "aspects": {
      "type": "array",
      "description": "Per-aspect sentiment (aspect_based mode)."
    },
    "reasoning": {
      "type": "string",
      "description": "Brief explanation."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "positive",
    "label": "Positive",
    "description": "Sentiment is positive.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "negative",
    "label": "Negative",
    "description": "Sentiment is negative.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "neutral",
    "label": "Neutral",
    "description": "Sentiment is neutral.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "mixed",
    "label": "Mixed",
    "description": "Sentiment is mixed.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Analysis failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
