# Extract Relations

> 以主语-谓语-宾语三元组的形式，从文本中抽取实体之间的语义关系。

Source: https://docs.sommatic.ai/zh/nodes/ai.relation.extract/

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

以主语-谓语-宾语三元组的形式，从文本中抽取实体之间的语义关系。

生成可直接用于知识图谱的输出，识别谁在何时、何地对谁做了什么。可选择只保留特定关系类型，并附带证据文本片段。

**适用场景：**
- **知识图谱：** 从文档构建结构化图谱。
- **合规：** 抽取合同义务及相关当事方。
- **情报分析：** 梳理人物、组织和事件之间的关系。

## 配置

- `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。
- `relation_types` (array<string>, 可选): 只保留特定的关系类型（例如 works_for、located_in）。留空则保留全部。
- `include_evidence` (boolean, 可选): 附带支撑每条抽取关系的源文本片段。 默认值: `true`.
- `language` (string, 可选): 输入文本的语言。 默认值: `en`.

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

## 输出端口

- `success` (默认): 至少抽取到一条关系。
- `error`: 抽取失败。

## 输入契约

- `text` (string, 必填): 要从中抽取关系的文本。

## 输出契约

- `relations` (array, 可选): 以主语-谓语-宾语三元组表示的抽取关系，附带置信度。
- `entities` (array, 可选): 关系中涉及的唯一实体。
- `relation_count` (number, 可选): 抽取出的关系总数。

## 在表达式中

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

- `$("Extract Relations").item.json.relations` (array) = `[…] (2)`: 以主语-谓语-宾语三元组表示的抽取关系，附带置信度。
- `$("Extract Relations").item.json.entities` (array) = `[…] (3)`: 关系中涉及的唯一实体。
- `$("Extract Relations").item.json.relation_count` (number) = `2`: 抽取出的关系总数。


## 工作原理

使用 LLM 从 `text` 中提取“主语–谓语–宾语”关系，返回其置信度、可选的证据片段以及涉及的实体列表。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `text`。使用 `relation_types`（为空表示全部类型）、`include_evidence`（默认 `true`）和 `language`（默认 `en`）构建提示词。
4. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
5. 解析 JSON 响应（温度 0），其中必须包含 `relations` 数组。`relation_count` 会根据该数组重新计算。
6. 始终路由到 `success`，即使关系数为零。

## 在工作流中

### 节点

```json
{
  "node_id": "node-relations",
  "label": "Extract relations",
  "operator_slug": "ai.relation.extract",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "relation_types": [
      "works_for",
      "located_in"
    ],
    "include_evidence": true,
    "language": "en"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "relations": [
      {
        "subject": "Ana Ruiz",
        "predicate": "works_for",
        "object": "Example Corp",
        "confidence": 0.94,
        "evidence": "Ana Ruiz, who works for Example Corp"
      },
      {
        "subject": "Example Corp",
        "predicate": "located_in",
        "object": "Lisbon",
        "confidence": 0.88,
        "evidence": "Example Corp’s Lisbon office"
      }
    ],
    "entities": [
      "Ana Ruiz",
      "Example Corp",
      "Lisbon"
    ],
    "relation_count": 2
  }
}
```

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

### `success`

响应是含 `relations` 数组的有效 JSON，即使数组为空。描述中写的是“至少一个关系”，但代码并不检查。

```json
{
  "relations": [
    {
      "subject": "Ana Ruiz",
      "predicate": "works_for",
      "object": "Example Corp",
      "confidence": 0.94,
      "evidence": "Ana Ruiz, who works for Example Corp"
    },
    {
      "subject": "Example Corp",
      "predicate": "located_in",
      "object": "Lisbon",
      "confidence": 0.88,
      "evidence": "Example Corp’s Lisbon office"
    }
  ],
  "entities": [
    "Ana Ruiz",
    "Example Corp",
    "Lisbon"
  ],
  "relation_count": 2
}
```

### `error`

校验、LLM 调用或解析失败。`data` 为 `{ error }`（若后端返回了响应体，还包含 `response`）。

```json
{
  "error": "Model did not return valid relation extraction output."
}
```

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `relation_types`: 仅作为提示词中的提示（“重点关注这些类型”）；模型返回的其他类型关系不会被过滤。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing input text for relation extraction.` | `error` | 既没有 `text` 也没有 `input`。 |
| `Model did not return valid relation extraction output.` | `error` | 响应中没有包含 `relations` 数组的 JSON 对象。 |
| `[AiRelationExtract] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 缺少 `text` 时，代码会退而使用 `input`，而运行时它是整个传入条目（对象），不是字符串。请始终提供 `text`。
- 模型响应在去除 Markdown 代码块标记后按 JSON 解析；若失败，则解析第一个 `{` 与最后一个 `}` 之间的文本。
- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- Worker 还会在 `data` 之外以 `raw` 返回提供方的原始响应；引擎不会保留它。
- 成功时 worker 返回 `port` 和 `data`，不含 `ok` 字段；引擎只依据 `port` 路由。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.relation.extract",
  "name": "Extract Relations",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts semantic relationships between entities from text as subject-predicate-object triples.\n\n  Produces knowledge-graph-ready output that identifies who did what to whom, when, and where. Optionally filter to specific relation types and include evidence text spans.\n\n  **Use Cases:**\n  - **Knowledge Graphs:** Build structured graphs from documents.\n  - **Compliance:** Extract contractual obligations and parties.\n  - **Intelligence:** Map relationships between people, organizations, and events.",
  "capabilities": [
    "ai",
    "nlp",
    "relation-extraction",
    "knowledge-graph"
  ],
  "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
      },
      "relation_types": {
        "type": "array",
        "title": "Relation Types",
        "items": {
          "type": "string"
        },
        "description": "Filter to specific relation types (e.g., works_for, located_in). Leave empty for all."
      },
      "include_evidence": {
        "type": "boolean",
        "title": "Include Evidence",
        "default": true,
        "description": "Include the source text span that supports each extracted relation."
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en",
        "description": "Language of the input text."
      },
      "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": {
        "type": "string",
        "description": "Text to extract relations from."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "relations": {
        "type": "array",
        "description": "Extracted relations as subject-predicate-object triples with confidence."
      },
      "entities": {
        "type": "array",
        "description": "Unique entities referenced in the relations."
      },
      "relation_count": {
        "type": "number",
        "description": "Total number of relations extracted."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Relations Found",
      "description": "At least one relation was extracted.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Extraction failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "relation-extraction",
    "knowledge-graph",
    "triples"
  ],
  "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
    },
    "relation_types": {
      "type": "array",
      "title": "Relation Types",
      "items": {
        "type": "string"
      },
      "description": "Filter to specific relation types (e.g., works_for, located_in). Leave empty for all."
    },
    "include_evidence": {
      "type": "boolean",
      "title": "Include Evidence",
      "default": true,
      "description": "Include the source text span that supports each extracted relation."
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en",
      "description": "Language of the input text."
    },
    "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": {
      "type": "string",
      "description": "Text to extract relations from."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "relations": {
      "type": "array",
      "description": "Extracted relations as subject-predicate-object triples with confidence."
    },
    "entities": {
      "type": "array",
      "description": "Unique entities referenced in the relations."
    },
    "relation_count": {
      "type": "number",
      "description": "Total number of relations extracted."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Relations Found",
    "description": "At least one relation was extracted.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Extraction failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
