# Analyze Sentiment

> Analiza el sentimiento y el tono emocional de un texto.

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

- Slug: `ai.sentiment`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Analiza el sentimiento y el tono emocional de un texto.

Detecta si el texto es positivo, negativo, neutral o mixto. Opcionalmente, lo desglosa en emociones concretas o analiza el sentimiento por aspecto o tema.

**Operaciones:**
- **Overall:** Una única clasificación del sentimiento con puntuación de valencia (-1 a 1) y confianza.
- **Emotions:** Detecta emociones concretas (alegría, ira, tristeza, miedo, sorpresa, asco, confianza) con puntuaciones de intensidad.
- **Aspect-Based:** Extrae los temas o aspectos mencionados en el texto y puntúa el sentimiento de cada uno de forma independiente.

## Configuración

- `llm_provider_id` (string, opcional): El `id` de un registro `LlmProviderModel` (p. ej. `wf-llm-provider-*`). El orquestador delega en el backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` en modo sync, o `POST /chat/conversation/execute/stream-ephemeral` (SSE) en modo stream. El backend resuelve endpoint + api-key + deployment a partir del registro y enruta al adaptador correspondiente.
- `invocation_mode` (string, opcional): Transporte de la llamada al LLM. `sync` se bloquea hasta recibir la respuesta completa. `stream` consume los tokens mediante SSE (necesario para generaciones largas). Predeterminado: `sync`. Por defecto: `sync`. Valores permitidos: `sync`, `stream`.
- `timeout_ms` (integer, opcional): Tiempo máximo de espera para que termine la invocación (o tiempo máximo de inactividad entre fragmentos en modo stream). Predeterminado: 30000 en sync, 600000 en stream.
- `analysis_mode` (string, obligatorio): Tipo de análisis de sentimiento que se realiza. Por defecto: `overall`. Valores permitidos: `overall`, `emotions`, `aspect_based`.
- `language` (string, opcional): Por defecto: `en`.
- `aspects` (array<string>, opcional): Opcional: aspectos concretos que se analizan. Déjalo vacío para la detección automática. Se muestra cuando: analysis_mode = `aspect_based`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `positive` (por defecto): El sentimiento es positivo.
- `negative`: El sentimiento es negativo.
- `neutral`: El sentimiento es neutral.
- `mixed`: El sentimiento es mixto.
- `error`: El análisis falló.

## Contrato de entrada

- `text` (string, obligatorio): Texto que se analiza.

## Contrato de salida

- `sentiment` (string, opcional): Etiqueta del sentimiento general.
- `valence` (number, opcional): Puntuación del sentimiento de -1 (negativo) a 1 (positivo).
- `confidence` (number, opcional): Puntuación de confianza de 0 a 1.
- `emotions` (object, opcional): Desglose por emociones (modo emotions).
- `aspects` (array, opcional): Sentimiento por aspecto (modo aspect_based).
- `reasoning` (string, opcional): Explicación breve.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Analyze Sentiment").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Analyze Sentiment`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `positive`, según la salida que muestra Puertos.

- `$("Analyze Sentiment").item.json.sentiment` (string) = `"positive"`: Etiqueta del sentimiento general.
- `$("Analyze Sentiment").item.json.valence` (number) = `0.8`: Puntuación del sentimiento de -1 (negativo) a 1 (positivo).
- `$("Analyze Sentiment").item.json.confidence` (number) = `0.9`: Puntuación de confianza de 0 a 1.
- `$("Analyze Sentiment").item.json.emotions` (object) = `null`: Desglose por emociones (modo emotions).
- `$("Analyze Sentiment").item.json.aspects` (array) = `null`: Sentimiento por aspecto (modo aspect_based).
- `$("Analyze Sentiment").item.json.reasoning` (string) = `"The customer thanks the team."`: Explicación breve.
- `$("Analyze Sentiment").item.json.dominant_emotion` (null) = `null` (El editor no la sugiere)


## Cómo funciona

Clasifica el sentimiento de `text` con el LLM como positivo, negativo, neutro o mixto, opcionalmente con puntuaciones de emociones o sentimiento por aspecto, y enruta al puerto de esa etiqueta.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Combina el ítem entrante con la configuración resuelta (las claves de configuración tienen prioridad) y lee las entradas del resultado.
3. Exige `text`. Elige el prompt de `analysis_mode` (predeterminado `overall`): `overall`, `emotions` (ocho puntuaciones de emociones y una emoción dominante) o `aspect_based` (sentimiento por aspecto, centrado en `aspects` si se indican).
4. Llama al LLM a través del backend con el registro `llm_provider_id`. `invocation_mode: "sync"` (predeterminado) espera la respuesta completa; `"stream"` la lee por SSE y une los fragmentos.
5. Interpreta la respuesta JSON (temperatura 0); `sentiment` debe ser un texto. Los números que faltan pasan a 0 y los objetos que faltan a `null`.
6. Pasa la etiqueta a minúsculas y enruta a `positive`, `negative`, `neutral` o `mixed`; cualquier otra etiqueta enruta a `neutral`, mientras que `data.sentiment` conserva el valor original.

## En un workflow

### Nodo

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

## Puertos de salida (comportamiento en el código)

### `positive`

La etiqueta es `positive`. Misma forma que el ejemplo.

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

### `negative`

La etiqueta es `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`

La etiqueta es `neutral` o no es ninguna de las cuatro conocidas.

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

### `mixed`

La etiqueta es `mixed`. En modo `aspect_based` se rellena `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`

Falló la validación, la llamada al LLM o la interpretación. `data` es `{ error }` (más `response` cuando el backend devolvió un cuerpo).

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

## Comportamiento en el código

- `llm_provider_id`: Es obligatorio en ejecución aunque el esquema no lo marque como requerido. Es el id de un registro de proveedor LLM; el backend resuelve a partir de él el endpoint, el despliegue y las credenciales.
- `analysis_mode`: Usa uno de los tres valores de la lista. Un valor desconocido no se rechaza: el modelo recibe la palabra «undefined» como prompt de sistema.
- `language`: Añade una línea de idioma de respuesta cuando no es `en`; las etiquetas siguen en inglés.
- `timeout_ms`: `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing input text for sentiment analysis.` | `error` | No llegan ni `text` ni `input`. |
| `Model did not return valid sentiment analysis output.` | `error` | La respuesta no tenía un objeto JSON con un texto en `sentiment`. |
| `[AiSentiment] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | El nodo no tiene `llm_provider_id`. Elige un proveedor LLM en la configuración del nodo; la clave antigua `model_id` no se acepta. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada (registro de proveedor desconocido o inactivo, error del proveedor, credenciales). Revisa el registro del proveedor. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | No se pudo contactar con el backend o no devolvió nada en modo `sync`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | En modo `stream` no llegó ningún fragmento dentro de `timeout_ms`. |

## Notas y límites

- Cuando falta `text`, el código recurre a `input`, que en ejecución es el ítem entrante completo (un objeto), no un texto. Proporciona siempre `text`.
- La respuesta del modelo se interpreta como JSON tras quitar los bloques de código Markdown; si falla, se interpreta el texto entre la primera `{` y la última `}`.
- Los campos de entrada se leen del ítem entrante (`$json`). Una clave con el mismo nombre en la configuración del nodo, que puede ser una expresión, tiene prioridad sobre la entrada.
- El worker también devuelve la respuesta del proveedor como `raw` fuera de `data`; el motor no la conserva.
- En caso de éxito el worker devuelve `port` y `data` sin el campo `ok`; el motor enruta solo por `port`.
- `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.
- En modo `stream` la temperatura que fija este nodo no se envía al proveedor, y `raw` es `null`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


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