# Compare Texts

> 由 LLM 驱动的语义文本比较。

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

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

由 LLM 驱动的语义文本比较。

该算子使用可配置的比较模式比较两段输入文本，并根据结果路由到 match/no_match 端口。

**操作**
- **Similarity：** 计算两段文本之间的语义相似度得分（0-1）。
- **Diff：** 找出文本之间有意义的语义差异（而非字符级差异）。
- **Contradiction：** 检测两段文本之间的事实矛盾，并给出各自的证据。
- **Dedup：** 根据可配置阈值判断两段文本是否重复或近似重复。

**适用场景**
- 检测重复的支持工单或内容提交。
- 比较政策文件之间的矛盾或偏移。
- 校验源材料与生成内容之间的一致性。
- 标记不同数据源之间相互冲突的信息。

## 配置

- `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。
- `comparison_mode` (string, 可选): 要执行的比较类型。 默认值: `similarity`. 可选值: `similarity`, `diff`, `contradiction`, `dedup`.
- `threshold` (number, 可选): dedup 模式的匹配阈值（0-1）。得分达到或超过该值时路由到 match 端口。 默认值: `0.8`.
- `language` (string, 可选): 输出语言代码（例如“en”“es”）。 默认值: `en`.

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

## 输出端口

- `match` (默认): Match
- `no_match`: No Match
- `error`: Error

## 输入契约

- `text_a` (string, 必填): 参与比较的第一段文本。
- `text_b` (string, 必填): 参与比较的第二段文本。
- `context` (string, 可选): 为比较提供参考的可选上下文。

## 输出契约

- `score` (number, 可选): 相似度或匹配得分（0-1）。
- `assessment` (string, 可选): 对比较结果的可读评估。
- `details` (object, 可选): 特定于模式的详细结果。
- `is_match` (boolean, 可选): 文本是否匹配（dedup/similarity）。
- `differences` (array<object>, 可选): 语义差异列表（diff 模式）。
- `contradictions` (array<object>, 可选): 事实矛盾列表（contradiction 模式）。

## 在表达式中

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

- `$("Compare Texts").item.json.score` (number) = `0.91`: 相似度或匹配得分（0-1）。
- `$("Compare Texts").item.json.assessment` (string) = `"Both texts describe the same refund policy."`: 对比较结果的可读评估。
- `$("Compare Texts").item.json.details` (object) = `{…}`: 特定于模式的详细结果。
- `$("Compare Texts").item.json.is_match` (boolean) = `true`: 文本是否匹配（dedup/similarity）。
- `$("Compare Texts").item.json.differences` (array) = `[…] (0)`: 语义差异列表（diff 模式）。
- `$("Compare Texts").item.json.contradictions` (array) = `[…] (0)`: 事实矛盾列表（contradiction 模式）。
- `$("Compare Texts").item.json.details.overlaps` (array) = `[…] (2)` (编辑器不提示)
- `$("Compare Texts").item.json.details.gaps` (array) = `[…] (0)` (编辑器不提示)
- `$("Compare Texts").item.json.raw` (null) = `null` (编辑器不提示)
- `$("Compare Texts").item.json.port` (string) = `"match"` (编辑器不提示)


## 工作原理

借助模型以四种模式之一（similarity、diff、contradiction、dedup）比较 `text_a` 与 `text_b`，并路由到 `match` 或 `no_match`。

1. 合并上游载荷与节点配置（以配置为准）；为空时抛出 `Missing 'text_a'` 或 `Missing 'text_b'`。
2. 构建按模式定制、要求严格 JSON 的系统提示词，以及由 `Context:`（可选）+ `Text A:` + `Text B:` 组成的用户消息；以 `temperature: 0` 调用模型。
3. 将回答解析为 JSON（去除代码块标记，失败时截取第一个 `{` 到最后一个 `}`）；无法解析时从 `error` 输出并附带 `raw_content`。
4. 选择端口：`similarity` 和 `dedup` 在 `score >= threshold` 时为 `match`；`diff` 在 `differences` 为空时为 `match`；`contradiction` 在 `contradictions` 为空时为 `match`。
5. 在顶层返回 `score`、`assessment`、`details`、`is_match`、`differences`、`contradictions`、`raw` 和 `port`。

## 在工作流中

### 节点

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

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

### `match`

满足该模式的匹配规则（见运行步骤）。未知的 `comparison_mode` 会使用 similarity 提示词，但总是从此端口输出。

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

得分低于 `threshold`（similarity、dedup），或发现了差异或矛盾（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`

缺少文本、模型调用失败或回答不是 JSON。

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

## 代码中的行为

- `threshold`: 同时作用于 `similarity` 和 `dedup`（默认 0.8），并写入 dedup 提示词。`diff` 和 `contradiction` 忽略此值。
- `text_a, text_b, context`: 不在配置 schema 中，但会先从配置读取，再从上游载荷读取。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'text_a'` | `error` | `text_a`（或 `text_b`）为空。 |
| `Failed to parse comparison result from LLM output.` | `error` | 回答不是 JSON 对象；去除首尾空白后的回答位于 `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` 为空或不是字符串。请选择具备 chat 能力的 LLM 提供方记录。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用：提供方记录不存在或未激活、提供方报错、配额或内容过滤。请检查提供方记录和后端日志。 |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | sync 模式：对后端的 HTTP 调用失败（网络错误、非 2xx 状态或超时）。长提示词常会触发请求超时，请改用 `invocation_mode: "stream"`。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | stream 模式：在 `timeout_ms` 内未收到任何片段。若流式请求本身失败，消息为 `RemoteApiService.stream: HTTP <status> — <body>`。 |

## 说明与限制

- 在 `diff` 和 `contradiction` 模式下，评分方向为 1 = 相同 / 一致。`is_match` 若模型给出（dedup）则采用，否则与所选端口一致。
- 缺失的 `score` 在路由时按 0 计算，返回值为 `null`。
- 该 worker 将字段直接放在返回值顶层而非 `data` 内，因此引擎把整个返回值存为节点输出：`port` 和 `raw` 会与结果字段一起出现在 `$json` 中。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- `timeout_ms` 仅在 stream 模式下生效，表示片段之间允许的最长空闲时间（默认 600000）。在 sync 模式下该值只写入日志，不会作用于 HTTP 请求，因此以平台默认请求超时为准。
- 在 stream 模式下，后端端点不应用采样参数，因此固定的 `temperature: 0` 仅在 sync 模式下生效。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（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"
  }
]
```
