# Extract Entities

> 使用 LLM 驱动的识别能力从文本中抽取命名实体。

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

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

使用 LLM 驱动的识别能力从文本中抽取命名实体。

从任意非结构化文本中识别人物、组织、地点、日期、金额以及自定义实体类型。可配置实体类型，或通过 Knowledge Resource 提供你自己的定义。

**操作：**
- **Standard：** 抽取常见实体类型（PERSON、ORG、LOCATION、DATE、MONEY、EMAIL、PHONE、URL）。
- **Custom：** 用描述和示例定义你自己的实体类型。
- **All：** 同时进行标准和自定义实体抽取。

## 配置

- `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。
- `extraction_mode` (string, 必填): Standard 抽取常见类型。Custom 使用你的定义。All 两者兼用。 默认值: `standard`. 可选值: `standard`, `custom`, `all`.
- `entity_types` (array<string>, 可选): 筛选要抽取的标准类型。留空则抽取全部类型。 显示条件: extraction_mode = `standard` | `all`.
- `custom_entities` (array<object>, 可选): 用名称、描述和示例定义自定义实体类型。 显示条件: extraction_mode = `custom` | `all`.
- `knowledge_resource_id` (string, 可选): 可选：从 Knowledge Resource 加载自定义实体定义。
- `language` (string, 可选): 输入文本的语言。 默认值: `en`.
- `deduplicate` (boolean, 可选): 将重复的实体提及合并为唯一条目。 默认值: `true`.

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

## 输出端口

- `success` (默认): 至少抽取到一个实体。
- `none_found`: 文本中未检测到实体。
- `error`: 抽取失败。

## 输入契约

- `text` (string, 必填): 要从中抽取实体的文本。
- `context` (string, 可选): 用于提高抽取准确度的可选上下文。

## 输出契约

- `entities` (array, 可选): 抽取出的实体，包含类型、文本和置信度。
- `entity_counts` (object, 可选): 每种实体类型的数量。
- `unique_entities` (object, 可选): 按类型分组的去重实体。

## 在表达式中

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

- `$("Extract Entities").item.json.entities` (array) = `[…] (3)`: 抽取出的实体，包含类型、文本和置信度。
- `$("Extract Entities").item.json.entity_counts` (object) = `{…}`: 每种实体类型的数量。
- `$("Extract Entities").item.json.unique_entities` (object) = `{…}`: 按类型分组的去重实体。
- `$("Extract Entities").item.json.entity_counts.PERSON` (number) = `2` (编辑器不提示)
- `$("Extract Entities").item.json.entity_counts.EMAIL` (number) = `1` (编辑器不提示)
- `$("Extract Entities").item.json.unique_entities.PERSON` (array) = `[…] (1)` (编辑器不提示)
- `$("Extract Entities").item.json.unique_entities.EMAIL` (array) = `[…] (1)` (编辑器不提示)
- `$("Extract Entities").item.json.total` (number) = `3` (编辑器不提示)
- `$("Extract Entities").item.json.unique_total` (number) = `2` (编辑器不提示)


## 工作原理

通过一次模型调用从 `text` 中提取标准和/或自定义类型的命名实体，过滤未知类型并合并重复提及。

1. 合并上游载荷与节点配置（以配置为准），读取 `text`（回退到 `input`）和 `context`；未设置 `invocation_mode` 时默认使用 `stream`。
2. 按 `extraction_mode` 构建类型列表：`standard` 使用 PERSON、ORG、LOCATION、DATE、MONEY、EMAIL、PHONE、URL、ID（按 `entity_types` 过滤）；`custom` 使用 `custom_entities` 加 `knowledge_resource_id` 的 `structured_data.entity_types`；`all` 两者兼用。列表为空时失败。
3. 发送列出类型并要求严格 JSON 的系统提示词；用户消息为 `text`，有 `context` 时前置 `Context:`；`temperature: 0`。
4. 将回答解析为 JSON，`entities` 必须是数组。丢弃类型不在列表中的实体（不区分大小写）。
5. 启用 `deduplicate`（默认 true）时，按类型和规范化文本合并提及，统计 `mentions` 并保留最高置信度。至少剩一个实体时走 `success`，否则走 `none_found`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-extract-contacts",
  "label": "Extract contacts",
  "operator_slug": "ai.entity.extract",
  "operator_version": "1.0.0",
  "config": {
    "text": "{{ $json.body }}",
    "extraction_mode": "standard",
    "entity_types": [
      "PERSON",
      "EMAIL",
      "PHONE"
    ],
    "deduplicate": true,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "stream",
    "timeout_ms": 120000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "entities": [
      {
        "text": "Ana Ruiz",
        "type": "PERSON",
        "normalized": "Ana Ruiz",
        "confidence": 0.98
      },
      {
        "text": "ana.ruiz@example.com",
        "type": "EMAIL",
        "normalized": "ana.ruiz@example.com",
        "confidence": 0.99
      },
      {
        "text": "Ms. Ruiz",
        "type": "PERSON",
        "normalized": "Ana Ruiz",
        "confidence": 0.9
      }
    ],
    "entity_counts": {
      "PERSON": 2,
      "EMAIL": 1
    },
    "unique_entities": {
      "PERSON": [
        {
          "text": "Ana Ruiz",
          "type": "PERSON",
          "normalized": "Ana Ruiz",
          "confidence": 0.98,
          "mentions": 2
        }
      ],
      "EMAIL": [
        {
          "text": "ana.ruiz@example.com",
          "type": "EMAIL",
          "normalized": "ana.ruiz@example.com",
          "confidence": 0.99,
          "mentions": 1
        }
      ]
    },
    "total": 3,
    "unique_total": 2
  },
  "port": "success"
}
```

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

### `success`

至少找到一个已配置类型的实体。

```json
{
  "entities": [
    {
      "text": "Ana Ruiz",
      "type": "PERSON",
      "normalized": "Ana Ruiz",
      "confidence": 0.98
    },
    {
      "text": "ana.ruiz@example.com",
      "type": "EMAIL",
      "normalized": "ana.ruiz@example.com",
      "confidence": 0.99
    },
    {
      "text": "Ms. Ruiz",
      "type": "PERSON",
      "normalized": "Ana Ruiz",
      "confidence": 0.9
    }
  ],
  "entity_counts": {
    "PERSON": 2,
    "EMAIL": 1
  },
  "unique_entities": {
    "PERSON": [
      {
        "text": "Ana Ruiz",
        "type": "PERSON",
        "normalized": "Ana Ruiz",
        "confidence": 0.98,
        "mentions": 2
      }
    ],
    "EMAIL": [
      {
        "text": "ana.ruiz@example.com",
        "type": "EMAIL",
        "normalized": "ana.ruiz@example.com",
        "confidence": 0.99,
        "mentions": 1
      }
    ]
  },
  "total": 3,
  "unique_total": 2
}
```

### `none_found`

模型未找到任何已配置类型的实体。

```json
{
  "entities": [],
  "entity_counts": {},
  "unique_entities": {},
  "total": 0,
  "unique_total": 0
}
```

### `error`

未配置实体类型、模型调用失败或回答缺少 `entities` 数组。

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

## 代码中的行为

- `invocation_mode`: 代码中默认值为 `stream`，而不是 schema 所写的 `sync`，以免长文本触发同步请求超时。如不需要，请显式设置为 `sync`。
- `knowledge_resource_id`: 仅在 `extraction_mode` 为 `custom` 或 `all` 时读取；获取失败只记录日志。
- `deduplicate`: 设为 `false` 时 `unique_entities` 为 `null`，`unique_total` 为 0；`entities` 始终保留全部提及。
- `text, context`: 不在配置 schema 中（位于输入契约中），但会先从配置读取，再从上游载荷读取。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `No entity types defined. Configure standard types, custom entities, or a Knowledge Resource.` | `error` | 例如 `extraction_mode: "custom"` 却没有 `custom_entities` 和资源，或 `entity_types` 过滤后没有匹配任何标准类型。 |
| `Model did not return valid entity extraction output.` | `error` | 回答不是 JSON 或 `entities` 不是数组。 |
| `[AiEntityExtract] 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>`。 |

## 说明与限制

- 当 `text` 为空时，worker 会退而使用 `input`，而运行时 `input` 始终是上游传入的完整对象。因此“缺少文本”的校验永远不会触发，该对象会被当作消息发送给模型。请始终显式映射 `text`。
- 由于默认使用 stream 模式，`temperature: 0` 通常不会生效，也无法获得 `raw`。
- 该 worker 在 `data` 旁返回 `raw`；引擎只把 `data` 存为节点输出，因此下游无法读取 `raw`。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- `timeout_ms` 仅在 stream 模式下生效，表示片段之间允许的最长空闲时间（默认 600000）。在 sync 模式下该值只写入日志，不会作用于 HTTP 请求，因此以平台默认请求超时为准。
- 每次运行都会从后端读取知识资源（超时 10 秒）。状态不是 `active` 的资源仍会被使用，并在日志中记录警告。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.entity.extract",
  "name": "Extract Entities",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extract named entities from text using LLM-powered recognition.\n\n  Identify people, organizations, locations, dates, monetary amounts, and custom entity types from any unstructured text. Configure entity types or provide your own definitions via Knowledge Resources.\n\n  **Operations:**\n  - **Standard:** Extract common entity types (PERSON, ORG, LOCATION, DATE, MONEY, EMAIL, PHONE, URL).\n  - **Custom:** Define your own entity types with descriptions and examples.\n  - **All:** Combine standard and custom entity extraction.",
  "capabilities": [
    "nlp",
    "ner",
    "extraction",
    "entities"
  ],
  "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
      },
      "extraction_mode": {
        "type": "string",
        "title": "Extraction Mode",
        "enum": [
          "standard",
          "custom",
          "all"
        ],
        "default": "standard",
        "description": "Standard extracts common types. Custom uses your definitions. All combines both."
      },
      "entity_types": {
        "type": "array",
        "title": "Entity Types (Standard)",
        "description": "Filter which standard types to extract. Leave empty for all.",
        "items": {
          "type": "string"
        },
        "displayOptions": {
          "show": {
            "extraction_mode": [
              "standard",
              "all"
            ]
          }
        }
      },
      "custom_entities": {
        "type": "array",
        "title": "Custom Entity Definitions",
        "description": "Define custom entity types with name, description, and examples.",
        "items": {
          "type": "object",
          "properties": {
            "type": {
              "type": "string",
              "description": "Entity type name (e.g., PRODUCT, DISEASE)"
            },
            "description": {
              "type": "string",
              "description": "What this entity type represents"
            },
            "examples": {
              "type": "string",
              "description": "Comma-separated examples"
            }
          }
        },
        "displayOptions": {
          "show": {
            "extraction_mode": [
              "custom",
              "all"
            ]
          }
        }
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Knowledge Resource",
        "description": "Optional: load custom entity definitions from a Knowledge Resource.",
        "ui_widget": "knowledge_resource_picker"
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en",
        "description": "Language of the input text."
      },
      "deduplicate": {
        "type": "boolean",
        "title": "Deduplicate",
        "default": true,
        "description": "Merge duplicate entity mentions into unique entries."
      },
      "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": [
      "extraction_mode"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Text to extract entities from."
      },
      "context": {
        "type": "string",
        "description": "Optional context to improve extraction accuracy."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "entities": {
        "type": "array",
        "description": "Extracted entities with type, text, and confidence."
      },
      "entity_counts": {
        "type": "object",
        "description": "Count per entity type."
      },
      "unique_entities": {
        "type": "object",
        "description": "Deduplicated entities grouped by type."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Entities Found",
      "description": "At least one entity was extracted.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "none_found",
      "label": "No Entities",
      "description": "No entities detected in the text.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Extraction failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "ner",
    "entities",
    "extraction"
  ],
  "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
    },
    "extraction_mode": {
      "type": "string",
      "title": "Extraction Mode",
      "enum": [
        "standard",
        "custom",
        "all"
      ],
      "default": "standard",
      "description": "Standard extracts common types. Custom uses your definitions. All combines both."
    },
    "entity_types": {
      "type": "array",
      "title": "Entity Types (Standard)",
      "description": "Filter which standard types to extract. Leave empty for all.",
      "items": {
        "type": "string"
      },
      "displayOptions": {
        "show": {
          "extraction_mode": [
            "standard",
            "all"
          ]
        }
      }
    },
    "custom_entities": {
      "type": "array",
      "title": "Custom Entity Definitions",
      "description": "Define custom entity types with name, description, and examples.",
      "items": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string",
            "description": "Entity type name (e.g., PRODUCT, DISEASE)"
          },
          "description": {
            "type": "string",
            "description": "What this entity type represents"
          },
          "examples": {
            "type": "string",
            "description": "Comma-separated examples"
          }
        }
      },
      "displayOptions": {
        "show": {
          "extraction_mode": [
            "custom",
            "all"
          ]
        }
      }
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Knowledge Resource",
      "description": "Optional: load custom entity definitions from a Knowledge Resource.",
      "ui_widget": "knowledge_resource_picker"
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en",
      "description": "Language of the input text."
    },
    "deduplicate": {
      "type": "boolean",
      "title": "Deduplicate",
      "default": true,
      "description": "Merge duplicate entity mentions into unique entries."
    },
    "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": [
    "extraction_mode"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Text to extract entities from."
    },
    "context": {
      "type": "string",
      "description": "Optional context to improve extraction accuracy."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "entities": {
      "type": "array",
      "description": "Extracted entities with type, text, and confidence."
    },
    "entity_counts": {
      "type": "object",
      "description": "Count per entity type."
    },
    "unique_entities": {
      "type": "object",
      "description": "Deduplicated entities grouped by type."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Entities Found",
    "description": "At least one entity was extracted.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "none_found",
    "label": "No Entities",
    "description": "No entities detected in the text.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Extraction failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
