# Compare Texts

> Comparación semántica de textos con un LLM.

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

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

Comparación semántica de textos con un LLM.

Este operador compara dos textos de entrada con un modo de comparación configurable y enruta a los puertos match/no_match según el resultado.

**Operaciones**
- **Similarity:** Calcula una puntuación de similitud semántica (0-1) entre dos textos.
- **Diff:** Identifica las diferencias semánticas relevantes (no a nivel de caracteres) entre los textos.
- **Contradiction:** Detecta contradicciones de hecho entre dos textos, con evidencia de cada uno.
- **Dedup:** Evalúa si dos textos son duplicados o casi duplicados según un umbral configurable.

**Casos de uso**
- Detectar tickets de soporte o envíos de contenido duplicados.
- Comparar documentos de políticas en busca de contradicciones o desviaciones.
- Validar la coherencia entre el material de origen y el contenido generado.
- Señalar información contradictoria entre fuentes de datos.

## 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.
- `comparison_mode` (string, opcional): El tipo de comparación que se realiza. Por defecto: `similarity`. Valores permitidos: `similarity`, `diff`, `contradiction`, `dedup`.
- `threshold` (number, opcional): Umbral de coincidencia para el modo dedup (0-1). Las puntuaciones iguales o superiores a este valor se dirigen al puerto match. Por defecto: `0.8`.
- `language` (string, opcional): Código del idioma de salida (p. ej., "en", "es"). Por defecto: `en`.

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

- `match` (por defecto): Match
- `no_match`: No Match
- `error`: Error

## Contrato de entrada

- `text_a` (string, obligatorio): Primer texto de la comparación.
- `text_b` (string, obligatorio): Segundo texto de la comparación.
- `context` (string, opcional): Contexto opcional para orientar la comparación.

## Contrato de salida

- `score` (number, opcional): Puntuación de similitud o de coincidencia (0-1).
- `assessment` (string, opcional): Valoración legible de la comparación.
- `details` (object, opcional): Resultados detallados propios de cada modo.
- `is_match` (boolean, opcional): Si los textos coinciden (dedup/similarity).
- `differences` (array<object>, opcional): Lista de diferencias semánticas (modo diff).
- `contradictions` (array<object>, opcional): Lista de contradicciones de hecho (modo contradiction).

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Compare Texts").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Compare Texts`). **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 `match`, según la salida que muestra Puertos.

- `$("Compare Texts").item.json.score` (number) = `0.91`: Puntuación de similitud o de coincidencia (0-1).
- `$("Compare Texts").item.json.assessment` (string) = `"Both texts describe the same refund policy."`: Valoración legible de la comparación.
- `$("Compare Texts").item.json.details` (object) = `{…}`: Resultados detallados propios de cada modo.
- `$("Compare Texts").item.json.is_match` (boolean) = `true`: Si los textos coinciden (dedup/similarity).
- `$("Compare Texts").item.json.differences` (array) = `[…] (0)`: Lista de diferencias semánticas (modo diff).
- `$("Compare Texts").item.json.contradictions` (array) = `[…] (0)`: Lista de contradicciones de hecho (modo contradiction).
- `$("Compare Texts").item.json.details.overlaps` (array) = `[…] (2)` (El editor no la sugiere)
- `$("Compare Texts").item.json.details.gaps` (array) = `[…] (0)` (El editor no la sugiere)
- `$("Compare Texts").item.json.raw` (null) = `null` (El editor no la sugiere)
- `$("Compare Texts").item.json.port` (string) = `"match"` (El editor no la sugiere)


## Cómo funciona

Compara `text_a` y `text_b` con el modelo en uno de cuatro modos (similarity, diff, contradiction, dedup) y enruta a `match` o `no_match`.

1. Combina el payload anterior con la configuración del nodo (gana la configuración); lanza `Missing 'text_a'` o `Missing 'text_b'` si están vacíos.
2. Construye un prompt de sistema propio del modo que pide JSON estricto, y un mensaje de usuario `Context:` (opcional) + `Text A:` + `Text B:`; llama al modelo a `temperature: 0`.
3. Interpreta la respuesta como JSON (sin bloques de código; como respaldo, del primer `{` al último `}`); una respuesta no interpretable sale por `error` con `raw_content`.
4. Elige el puerto: `similarity` y `dedup` → `match` si `score >= threshold`; `diff` → `match` si `differences` está vacío; `contradiction` → `match` si `contradictions` está vacío.
5. Devuelve `score`, `assessment`, `details`, `is_match`, `differences`, `contradictions`, `raw` y `port` en el primer nivel.

## En un workflow

### Nodo

```json
{
  "node_id": "node-compare-policy",
  "label": "Compare policy versions",
  "operator_slug": "ai.compare",
  "operator_version": "1.0.0",
  "config": {
    "text_a": "{{ $json.previous_policy }}",
    "text_b": "{{ $json.new_policy }}",
    "comparison_mode": "similarity",
    "threshold": 0.85,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "score": 0.91,
    "assessment": "Both texts describe the same refund policy.",
    "details": {
      "overlaps": [
        "30-day window",
        "original payment method"
      ],
      "gaps": []
    },
    "is_match": true,
    "differences": [],
    "contradictions": [],
    "raw": null,
    "port": "match"
  },
  "port": "match"
}
```

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

### `match`

Se cumple la regla de coincidencia del modo (ver operación). Un `comparison_mode` desconocido usa el prompt de similarity pero siempre sale por aquí.

```json
{
  "score": 0.91,
  "assessment": "Both texts describe the same refund policy.",
  "details": {
    "overlaps": [
      "30-day window",
      "original payment method"
    ],
    "gaps": []
  },
  "is_match": true,
  "differences": [],
  "contradictions": [],
  "raw": null,
  "port": "match"
}
```

### `no_match`

La puntuación es menor que `threshold` (similarity, dedup), o se encontraron diferencias o contradicciones (diff, contradiction).

```json
{
  "score": 0.4,
  "assessment": "Text B changes the refund window.",
  "details": {},
  "is_match": false,
  "differences": [
    {
      "category": "changed",
      "description": "Refund window goes from 30 to 14 days."
    }
  ],
  "contradictions": [],
  "raw": null,
  "port": "no_match"
}
```

### `error`

Falta un texto, falló la llamada al modelo o la respuesta no era JSON.

```json
{
  "error": "Failed to parse comparison result from LLM output.",
  "raw_content": "The texts are mostly similar."
}
```

## Comportamiento en el código

- `threshold`: Se aplica tanto a `similarity` como a `dedup` (por defecto 0,8) y se escribe en el prompt de dedup. `diff` y `contradiction` lo ignoran.
- `text_a, text_b, context`: No están en el esquema de configuración, pero se leen primero de la configuración y luego del payload anterior.
- `timeout_ms`: Solo en modo stream: timeout de inactividad entre fragmentos, por defecto 600000. En modo sync no se aplica a la petición.
- `execution`: Declarado pero ignorado: ni el worker ni el motor leen `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` ni `timeout_ms` de este bloque.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing 'text_a'` | `error` | `text_a` (o `text_b`) está vacío. |
| `Failed to parse comparison result from LLM output.` | `error` | La respuesta no era un objeto JSON; la respuesta recortada está en `data.raw_content`. |
| `[AiCompare] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). The legacy 'model_id' alias is no longer supported — update the node config to use 'llm_provider_id'.` | `error` | `llm_provider_id` está vacío o no es un texto. Elige un registro de proveedor LLM con capacidad de chat. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada: registro de proveedor inexistente o inactivo, error del proveedor, cuota o filtro de contenido. Revisa el registro de proveedor y los logs del backend. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Modo sync: falló la llamada HTTP al backend (error de red, estado distinto de 2xx o timeout). Los prompts largos suelen agotar el timeout de la petición; cambia a `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Modo stream: no llegó ningún fragmento dentro de `timeout_ms`. Si la petición de stream falla, el mensaje es `RemoteApiService.stream: HTTP <status> — <body>`. |

## Notas y límites

- En los modos `diff` y `contradiction` la puntuación va en el sentido 1 = idénticos / consistentes. `is_match` viene del modelo cuando lo envía (dedup); si no, refleja el puerto elegido.
- Un `score` ausente cuenta como 0 para el enrutamiento y se devuelve como `null`.
- El worker devuelve sus campos en el primer nivel en lugar de dentro de `data`, así que el motor guarda todo el valor devuelto como salida del nodo: `port` y `raw` aparecen en `$json` junto a los campos del resultado.
- La llamada al modelo pasa por el backend de Sommatic AI, que resuelve el registro de proveedor indicado en `llm_provider_id` (endpoint, credenciales, despliegue); el orquestador nunca guarda llaves del proveedor. `invocation_mode: "sync"` (por defecto) espera la respuesta completa; `"stream"` la lee como eventos SSE y une los fragmentos.
- `timeout_ms` solo tiene efecto en modo stream, como tiempo máximo de inactividad entre fragmentos (por defecto 600000). En modo sync el valor se registra en el log, pero no se aplica a la petición HTTP, así que rige el timeout por defecto de la plataforma.
- En modo stream el endpoint del backend no aplica los parámetros de muestreo, así que la `temperature: 0` fija solo tiene efecto en modo sync.
- Sin reintentos automáticos: el motor no aplica `execution.retryOnFail`, `maxTries` ni `waitBetweenTries` en este nodo; una llamada fallida sale directamente por `error`.


## Contratos (JSON Schema)

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

```json
{
  "slug": "ai.compare",
  "name": "Compare Texts",
  "category": "ai",
  "version": "1.0.0",
  "description": "Semantic text comparison powered by LLM.\n\nThis operator compares two text inputs using a configurable comparison mode and routes to match/no_match ports based on the result.\n\n**Operations**\n- **Similarity:** Computes a semantic similarity score (0-1) between two texts.\n- **Diff:** Identifies meaningful semantic differences (not character-level) between texts.\n- **Contradiction:** Detects factual contradictions between two texts with evidence from each.\n- **Dedup:** Assesses whether two texts are duplicates or near-duplicates based on a configurable threshold.\n\n**Use Cases**\n- Detecting duplicate support tickets or content submissions.\n- Comparing policy documents for contradictions or drift.\n- Validating consistency between source material and generated content.\n- Flagging conflicting information across data sources.",
  "capabilities": [
    "ai",
    "nlp",
    "comparison",
    "text"
  ],
  "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
      },
      "comparison_mode": {
        "type": "string",
        "title": "Comparison Mode",
        "description": "The type of comparison to perform.",
        "enum": [
          "similarity",
          "diff",
          "contradiction",
          "dedup"
        ],
        "default": "similarity"
      },
      "threshold": {
        "type": "number",
        "title": "Match Threshold",
        "description": "Match threshold for dedup mode (0-1). Scores at or above this value route to the match port.",
        "default": 0.8
      },
      "language": {
        "type": "string",
        "title": "Language",
        "description": "Output language code (e.g., \"en\", \"es\").",
        "default": "en"
      },
      "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
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text_a": {
        "type": "string",
        "description": "First text for comparison."
      },
      "text_b": {
        "type": "string",
        "description": "Second text for comparison."
      },
      "context": {
        "type": "string",
        "description": "Optional context to inform the comparison."
      }
    },
    "required": [
      "text_a",
      "text_b"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "score": {
        "type": "number",
        "description": "Similarity or match score (0-1)."
      },
      "assessment": {
        "type": "string",
        "description": "Human-readable assessment of the comparison."
      },
      "details": {
        "type": "object",
        "description": "Mode-specific detailed results."
      },
      "is_match": {
        "type": "boolean",
        "description": "Whether the texts match (dedup/similarity)."
      },
      "differences": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "List of semantic differences (diff mode)."
      },
      "contradictions": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "List of factual contradictions (contradiction mode)."
      }
    }
  },
  "ports": [
    {
      "port_id": "match",
      "label": "Match",
      "is_default": true
    },
    {
      "port_id": "no_match",
      "label": "No Match"
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "compare",
    "similarity",
    "dedup",
    "nlp"
  ],
  "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
    },
    "comparison_mode": {
      "type": "string",
      "title": "Comparison Mode",
      "description": "The type of comparison to perform.",
      "enum": [
        "similarity",
        "diff",
        "contradiction",
        "dedup"
      ],
      "default": "similarity"
    },
    "threshold": {
      "type": "number",
      "title": "Match Threshold",
      "description": "Match threshold for dedup mode (0-1). Scores at or above this value route to the match port.",
      "default": 0.8
    },
    "language": {
      "type": "string",
      "title": "Language",
      "description": "Output language code (e.g., \"en\", \"es\").",
      "default": "en"
    },
    "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
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text_a": {
      "type": "string",
      "description": "First text for comparison."
    },
    "text_b": {
      "type": "string",
      "description": "Second text for comparison."
    },
    "context": {
      "type": "string",
      "description": "Optional context to inform the comparison."
    }
  },
  "required": [
    "text_a",
    "text_b"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "score": {
      "type": "number",
      "description": "Similarity or match score (0-1)."
    },
    "assessment": {
      "type": "string",
      "description": "Human-readable assessment of the comparison."
    },
    "details": {
      "type": "object",
      "description": "Mode-specific detailed results."
    },
    "is_match": {
      "type": "boolean",
      "description": "Whether the texts match (dedup/similarity)."
    },
    "differences": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "List of semantic differences (diff mode)."
    },
    "contradictions": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "List of factual contradictions (contradiction mode)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "match",
    "label": "Match",
    "is_default": true
  },
  {
    "port_id": "no_match",
    "label": "No Match"
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
