# Analyze Sentiment

> Analyze the sentiment and emotional tone of text.

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

- Slug: `ai.sentiment`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Analyze the sentiment and emotional tone of text.

Detect whether text is positive, negative, neutral, or mixed. Optionally break down into specific emotions or analyze sentiment per aspect/topic.

**Operations:**
- **Overall:** Single sentiment classification with valence score (-1 to 1) and confidence.
- **Emotions:** Detect specific emotions (joy, anger, sadness, fear, surprise, disgust, trust) with intensity scores.
- **Aspect-Based:** Extract topics/aspects mentioned in text and score sentiment for each independently.

## Configuration

- `llm_provider_id` (string, optional): 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.
- `invocation_mode` (string, optional): Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.
- `analysis_mode` (string, required): Type of sentiment analysis to perform. Default: `overall`. Allowed values: `overall`, `emotions`, `aspect_based`.
- `language` (string, optional): Default: `en`.
- `aspects` (array<string>, optional): Optional: specific aspects to analyze. Leave empty for auto-detection. Shown when: analysis_mode = `aspect_based`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `positive` (default): Sentiment is positive.
- `negative`: Sentiment is negative.
- `neutral`: Sentiment is neutral.
- `mixed`: Sentiment is mixed.
- `error`: Analysis failed.

## Input contract

- `text` (string, required): Text to analyze.

## Output contract

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

## In expressions

What a later node can read from this node's output with `$("Analyze Sentiment").item.json.<path>` (write your node's label instead of `Analyze Sentiment`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `positive`, from the output shown in Ports.

- `$("Analyze Sentiment").item.json.sentiment` (string) = `"positive"`: Overall sentiment label.
- `$("Analyze Sentiment").item.json.valence` (number) = `0.8`: Sentiment score from -1 (negative) to 1 (positive).
- `$("Analyze Sentiment").item.json.confidence` (number) = `0.9`: Confidence score 0-1.
- `$("Analyze Sentiment").item.json.emotions` (object) = `null`: Emotion breakdown (emotions mode).
- `$("Analyze Sentiment").item.json.aspects` (array) = `null`: Per-aspect sentiment (aspect_based mode).
- `$("Analyze Sentiment").item.json.reasoning` (string) = `"The customer thanks the team."`: Brief explanation.
- `$("Analyze Sentiment").item.json.dominant_emotion` (null) = `null` (Not suggested by the editor)


## How it works

Classifies the sentiment of `text` with the LLM as positive, negative, neutral or mixed, optionally with emotion scores or per-aspect sentiment, and routes to the port of that label.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Merges the incoming item with the resolved config (config keys win) and reads the inputs from the result.
3. Requires `text`. Picks the prompt for `analysis_mode` (default `overall`): `overall`, `emotions` (eight emotion scores and a dominant emotion) or `aspect_based` (per-aspect sentiment, focused on `aspects` when given).
4. Calls the LLM through the backend with the `llm_provider_id` record. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it over SSE and joins the chunks.
5. Parses the JSON answer (temperature 0); `sentiment` must be a string. Missing numbers become 0 and missing objects `null`.
6. Lower-cases the label and routes to `positive`, `negative`, `neutral` or `mixed`; any other label routes to `neutral` while `data.sentiment` keeps the original value.

## In a workflow

### Node

```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."
  }
}
```

## Output ports (behaviour in the code)

### `positive`

The label is `positive`. Same shape as the example.

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

### `negative`

The label is `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`

The label is `neutral` or not one of the four known labels.

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

### `mixed`

The label is `mixed`. In `aspect_based` mode `aspects` is filled.

```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`

Validation, the LLM call or parsing failed. `data` is `{ error }` (plus `response` when the backend returned a body).

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

## Behaviour in the code

- `llm_provider_id`: Required at runtime although the schema does not mark it as required. It is the id of an LLM provider record; the backend resolves endpoint, deployment and credentials from it.
- `analysis_mode`: Use one of the three listed values. An unknown value is not rejected: the model receives the word “undefined” as its system prompt.
- `language`: Adds a reply-language line when it is not `en`; labels stay in English.
- `timeout_ms`: `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input text for sentiment analysis.` | `error` | Neither `text` nor `input` is present. |
| `Model did not return valid sentiment analysis output.` | `error` | The answer had no JSON object with a `sentiment` string. |
| `[AiSentiment] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | The node has no `llm_provider_id`. Pick an LLM provider in the node config; the legacy `model_id` key is not accepted. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call (unknown or inactive provider record, provider error, credentials). Check the provider record. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | The backend could not be reached or returned nothing in `sync` mode. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | In `stream` mode no chunk arrived within `timeout_ms`. |

## Notes and limits

- When `text` is missing, the code falls back to `input`, which at runtime is the whole incoming item (an object), not a string. Always provide `text`.
- The model answer is parsed as JSON after removing Markdown code fences; if that fails, the text between the first `{` and the last `}` is parsed.
- Input fields are read from the incoming item (`$json`). A key with the same name in the node config, which may be an expression, takes precedence over the input.
- The worker also returns the provider response as `raw` outside `data`; the engine does not keep it.
- On success the worker returns `port` and `data` without an `ok` field; the engine routes on `port` only.
- `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.
- In `stream` mode the temperature this node sets is not forwarded to the provider, and `raw` is `null`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (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
  }
]
```
