# Compare Texts

> Semantic text comparison powered by LLM.

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

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

Semantic text comparison powered by LLM.

This operator compares two text inputs using a configurable comparison mode and routes to match/no_match ports based on the result.

**Operations**
- **Similarity:** Computes a semantic similarity score (0-1) between two texts.
- **Diff:** Identifies meaningful semantic differences (not character-level) between texts.
- **Contradiction:** Detects factual contradictions between two texts with evidence from each.
- **Dedup:** Assesses whether two texts are duplicates or near-duplicates based on a configurable threshold.

**Use Cases**
- Detecting duplicate support tickets or content submissions.
- Comparing policy documents for contradictions or drift.
- Validating consistency between source material and generated content.
- Flagging conflicting information across data sources.

## 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.
- `comparison_mode` (string, optional): The type of comparison to perform. Default: `similarity`. Allowed values: `similarity`, `diff`, `contradiction`, `dedup`.
- `threshold` (number, optional): Match threshold for dedup mode (0-1). Scores at or above this value route to the match port. Default: `0.8`.
- `language` (string, optional): Output language code (e.g., "en", "es"). Default: `en`.

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

- `match` (default): Match
- `no_match`: No Match
- `error`: Error

## Input contract

- `text_a` (string, required): First text for comparison.
- `text_b` (string, required): Second text for comparison.
- `context` (string, optional): Optional context to inform the comparison.

## Output contract

- `score` (number, optional): Similarity or match score (0-1).
- `assessment` (string, optional): Human-readable assessment of the comparison.
- `details` (object, optional): Mode-specific detailed results.
- `is_match` (boolean, optional): Whether the texts match (dedup/similarity).
- `differences` (array<object>, optional): List of semantic differences (diff mode).
- `contradictions` (array<object>, optional): List of factual contradictions (contradiction mode).

## In expressions

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

- `$("Compare Texts").item.json.score` (number) = `0.91`: Similarity or match score (0-1).
- `$("Compare Texts").item.json.assessment` (string) = `"Both texts describe the same refund policy."`: Human-readable assessment of the comparison.
- `$("Compare Texts").item.json.details` (object) = `{…}`: Mode-specific detailed results.
- `$("Compare Texts").item.json.is_match` (boolean) = `true`: Whether the texts match (dedup/similarity).
- `$("Compare Texts").item.json.differences` (array) = `[…] (0)`: List of semantic differences (diff mode).
- `$("Compare Texts").item.json.contradictions` (array) = `[…] (0)`: List of factual contradictions (contradiction mode).
- `$("Compare Texts").item.json.details.overlaps` (array) = `[…] (2)` (Not suggested by the editor)
- `$("Compare Texts").item.json.details.gaps` (array) = `[…] (0)` (Not suggested by the editor)
- `$("Compare Texts").item.json.raw` (null) = `null` (Not suggested by the editor)
- `$("Compare Texts").item.json.port` (string) = `"match"` (Not suggested by the editor)


## How it works

Compares `text_a` and `text_b` with the model in one of four modes (similarity, diff, contradiction, dedup) and routes to `match` or `no_match`.

1. Merges the upstream payload with the node config (config wins); throws `Missing 'text_a'` or `Missing 'text_b'` when empty.
2. Builds a mode-specific system prompt asking for strict JSON, and a user message `Context:` (optional) + `Text A:` + `Text B:`; calls the model at `temperature: 0`.
3. Parses the answer as JSON (code fences removed, first `{` to last `}` as fallback); an unparseable answer goes to `error` with `raw_content`.
4. Picks the port: `similarity` and `dedup` → `match` when `score >= threshold`; `diff` → `match` when `differences` is empty; `contradiction` → `match` when `contradictions` is empty.
5. Returns `score`, `assessment`, `details`, `is_match`, `differences`, `contradictions`, `raw` and `port` at the top level.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `match`

The mode's match rule holds (see operation). An unknown `comparison_mode` uses the similarity prompt but always routes here.

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

The score is below `threshold` (similarity, dedup), or differences or contradictions were found (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`

A text is missing, the model call failed, or the answer was not JSON.

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

## Behaviour in the code

- `threshold`: Applies to `similarity` as well as `dedup` (default 0.8), and is written into the dedup prompt. Ignored by `diff` and `contradiction`.
- `text_a, text_b, context`: Not in the config schema, but read from the config first and then from the upstream payload.
- `timeout_ms`: Stream mode only: idle timeout between chunks, default 600000. In sync mode it is not applied to the request.
- `execution`: Declared but ignored: neither the worker nor the engine reads `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` or `timeout_ms` from this block.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing 'text_a'` | `error` | `text_a` (or `text_b`) is empty. |
| `Failed to parse comparison result from LLM output.` | `error` | The answer was not a JSON object; the trimmed answer is in `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` is empty or not a string. Pick an LLM provider record with chat capability. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call: unknown or inactive provider record, provider error, quota or content filter. Check the provider record and the backend logs. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Sync mode: the HTTP call to the backend failed (network error, non-2xx status or timeout). Long prompts often hit the request timeout; switch to `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Stream mode: no chunk arrived within `timeout_ms`. A failed stream request shows `RemoteApiService.stream: HTTP <status> — <body>` instead. |

## Notes and limits

- In `diff` and `contradiction` modes the score direction is 1 = identical / consistent. `is_match` comes from the model when given (dedup), otherwise it mirrors the chosen port.
- A missing `score` counts as 0 for routing and is returned as `null`.
- The worker returns its fields at the top level instead of inside `data`, so the engine stores the whole return value as the node output: `port` and `raw` appear in `$json` next to the result fields.
- The model call goes through the Sommatic AI backend, which resolves the provider record named by `llm_provider_id` (endpoint, credentials, deployment); the orchestrator never holds provider keys. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it as server-sent events and joins the chunks.
- `timeout_ms` only takes effect in stream mode, as the idle time allowed between chunks (default 600000). In sync mode the value is logged but not applied to the HTTP request, so the platform's default request timeout governs.
- In stream mode the backend endpoint does not apply sampling settings, so the fixed `temperature: 0` only takes effect in sync mode.
- No automatic retries: the engine does not honour `execution.retryOnFail`, `maxTries` or `waitBetweenTries` for this node; a failed call goes straight to `error`.


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