# Deep Entity Extraction

> 使用带上下文传递的分层 Map-Reduce，从大型文档（100 页以上）中抽取实体。

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

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

使用带上下文传递的分层 Map-Reduce，从大型文档（100 页以上）中抽取实体。

基础实体抽取只对文本做单次处理，而 Deep Extract 通过以下方式处理任意长度的文档：

**阶段 1：文档画像。** 分析首页和末页，了解文档类型、涉及各方、结构和关键引用。

**阶段 2：带滚动上下文的 Map。** 按顺序处理每个分块，并将此前已发现的实体作为上下文向后传递。这可以避免 LLM 抽取出不完整的姓名或遗漏关系。

**阶段 3：Reduce 与整合。** 最后一轮对实体去重（J. Pérez = Juan Pérez）、厘清关系（谁是原告、谁是被告）、校验一致性，并标注法律相关性。

非常适合法院判决、合同、监管申报文件以及任何依赖上下文的文档。

## 配置

- `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）。处理复杂法律文档时，请使用指向高质量推理模型（例如 gpt-4o、gpt-5.4）的记录。
- `invocation_mode` (string, 可选): LLM 调用的传输方式。`sync` 阻塞直到收到完整响应。`stream` 通过 SSE 逐步接收 token（对长文档做深度抽取时推荐使用，因为 3 个阶段中任一阶段都可能超过 30 秒）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 3 个 LLM 阶段（画像、分块抽取、整合）各自完成的最长等待时间。sync 默认 30000，stream 默认 600000。
- `document_type` (string, 可选): 针对特定文档类型优化的预定义抽取配置。 默认值: `legal_sentence`. 可选值: `legal_sentence`, `contract`, `invoice_set`, `report`, `custom`.
- `entity_types` (array<string>, 可选): 筛选要抽取的标准实体类型。留空则抽取全部类型。
- `custom_entities` (array<object>, 可选): 用名称、描述和示例定义自定义实体类型。
- `knowledge_resource_id` (string, 可选): 可选：从 Knowledge Resource 加载实体定义。
- `language` (string, 可选): 文档的语言。 默认值: `es`.
- `chunk_size` (number, 可选): 目标分块大小。文档会按此大小拆分为分块进行处理。 默认值: `40000`.
- `max_pages` (number, 可选): 最多处理页数的安全上限。 默认值: `500`.

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

## 输出端口

- `success` (默认): 实体已成功抽取并整合。
- `none_found`: 文档中未检测到实体。
- `error`: 抽取失败。

## 输入契约

- `text` (string, 必填): 文档全文（来自 OCR 或文本抽取）。无长度限制。

## 输出契约

- `entities` (array, 可选): 经整合、去重后的实体。
- `document_profile` (object, 可选): 文档分析结果（类型、各方、结构）。
- `entity_counts` (object, 可选): 每种实体类型的数量。
- `unique_entities` (object, 可选): 按类型分组的实体。
- `confidence_summary` (object, 可选): 各类型及整体的平均置信度。
- `phases_completed` (number, 可选): 已完成的处理阶段数（1-3）。

## 在表达式中

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

- `$("Deep Entity Extraction").item.json.entities` (array) = `[…] (2)`: 经整合、去重后的实体。
- `$("Deep Entity Extraction").item.json.document_profile` (object) = `{…}`: 文档分析结果（类型、各方、结构）。
- `$("Deep Entity Extraction").item.json.entity_counts` (object) = `{…}`: 每种实体类型的数量。
- `$("Deep Entity Extraction").item.json.unique_entities` (object) = `{…}`: 按类型分组的实体。
- `$("Deep Entity Extraction").item.json.confidence_summary` (object) = `{…}`: 各类型及整体的平均置信度。
- `$("Deep Entity Extraction").item.json.phases_completed` (number) = `3`: 已完成的处理阶段数（1-3）。
- `$("Deep Entity Extraction").item.json.document_profile.document_type` (string) = `"Judgment"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.jurisdiction` (string) = `"Labour"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.court_name` (string) = `"Labour Court No. 3"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.judge_name` (null) = `null` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.case_number` (string) = `"2025-00418"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.parties_plaintiff` (string) = `"Laura Gómez"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.parties_defendant` (string) = `"Northwind Logistics"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.parties_third_parties` (null) = `null` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.document_date` (string) = `"2026-03-14"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.key_dates` (array) = `[…] (2)` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.sentence_type` (string) = `"First instance"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.document_profile.document_structure` (string) = `"Background, considerations, ruling"` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.entity_counts.PERSON` (number) = `1` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.entity_counts.ORG` (number) = `1` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.unique_entities.PERSON` (array) = `[…] (1)` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.unique_entities.ORG` (array) = `[…] (1)` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.confidence_summary.PERSON` (number) = `0.97` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.confidence_summary.ORG` (number) = `0.95` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.relationships` (array) = `[…] (1)` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.stats` (object) = `{…}` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.stats.total_chunks` (number) = `3` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.stats.raw_entities` (number) = `64` (编辑器不提示)
- `$("Deep Entity Extraction").item.json.stats.consolidated_entities` (number) = `2` (编辑器不提示)


## 工作原理

分三个模型阶段从长文档中提取命名实体：依据首尾页生成文档画像；按分块提取并携带已发现实体的滚动上下文；最后合并整理并给出角色与关系。

1. 合并上游载荷与节点配置（以配置为准），读取 `text`（回退到 `input`）。构建实体类型列表：标准类型（按 `entity_types` 过滤），加上 `custom_entities`，再加上 `knowledge_resource_id` 的 `structured_data.entity_types`。
2. 阶段 1：若文本超过 10 页（按 `--- PAGE <n> ---` 标记拆分），只保留前 5 页和后 5 页；最多发送 30000 个字符，按 `document_type` 画像的字段生成 JSON 画像。JSON 无效时画像为空。
3. 阶段 2：按约 `chunk_size` 个字符分块（先按页标记，再在段落或句子边界附近切分），每块调用一次模型，并附带画像和最多 50 个已发现实体。其他类型的实体，或文本明显属于其他类型（日期、金额、邮箱、电话、公司后缀）的实体会被丢弃；JSON 无效的分块不产出结果。
4. 若未发现任何实体，以 `phases_completed: 2` 从 `none_found` 输出。
5. 阶段 3：按类型和规范化文本对实体分组。唯一实体少于 10 个时直接返回；否则取提及次数最多的 200 个进行合并调用，去重并给出角色、关系和排序。
6. 按类型统计实体数量，在 `unique_entities` 中分组，计算各类型的平均置信度，并从 `success` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-deep-entities",
  "label": "Extract parties",
  "operator_slug": "ai.deep.extract",
  "operator_version": "1.0.0",
  "config": {
    "text": "{{ $json.text }}",
    "document_type": "legal_sentence",
    "entity_types": [
      "PERSON",
      "ORG",
      "MONEY",
      "DATE"
    ],
    "language": "en",
    "chunk_size": 40000,
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "stream",
    "timeout_ms": 120000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "entities": [
      {
        "text": "Laura Gómez",
        "type": "PERSON",
        "normalized": "Laura Gómez",
        "confidence": 0.97,
        "mentions": 12,
        "role": "plaintiff",
        "relevance": "high"
      },
      {
        "text": "Northwind Logistics",
        "type": "ORG",
        "normalized": "Northwind Logistics",
        "confidence": 0.95,
        "mentions": 8,
        "role": "defendant",
        "relevance": "high"
      }
    ],
    "document_profile": {
      "document_type": "Judgment",
      "jurisdiction": "Labour",
      "court_name": "Labour Court No. 3",
      "judge_name": null,
      "case_number": "2025-00418",
      "parties_plaintiff": "Laura Gómez",
      "parties_defendant": "Northwind Logistics",
      "parties_third_parties": null,
      "document_date": "2026-03-14",
      "key_dates": [
        "2025-06-02",
        "2026-03-14"
      ],
      "sentence_type": "First instance",
      "document_structure": "Background, considerations, ruling"
    },
    "entity_counts": {
      "PERSON": 1,
      "ORG": 1
    },
    "unique_entities": {
      "PERSON": [
        {
          "text": "Laura Gómez",
          "type": "PERSON",
          "normalized": "Laura Gómez",
          "confidence": 0.97,
          "mentions": 12,
          "role": "plaintiff",
          "relevance": "high"
        }
      ],
      "ORG": [
        {
          "text": "Northwind Logistics",
          "type": "ORG",
          "normalized": "Northwind Logistics",
          "confidence": 0.95,
          "mentions": 8,
          "role": "defendant",
          "relevance": "high"
        }
      ]
    },
    "confidence_summary": {
      "PERSON": 0.97,
      "ORG": 0.95
    },
    "relationships": [
      {
        "entity_a": "Laura Gómez",
        "relation": "sues",
        "entity_b": "Northwind Logistics"
      }
    ],
    "phases_completed": 3,
    "stats": {
      "total_chunks": 3,
      "raw_entities": 64,
      "consolidated_entities": 2
    }
  },
  "port": "success"
}
```

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

### `success`

至少发现并合并了一个实体。

```json
{
  "entities": [
    {
      "text": "Laura Gómez",
      "type": "PERSON",
      "normalized": "Laura Gómez",
      "confidence": 0.97,
      "mentions": 12,
      "role": "plaintiff",
      "relevance": "high"
    },
    {
      "text": "Northwind Logistics",
      "type": "ORG",
      "normalized": "Northwind Logistics",
      "confidence": 0.95,
      "mentions": 8,
      "role": "defendant",
      "relevance": "high"
    }
  ],
  "document_profile": {
    "document_type": "Judgment",
    "jurisdiction": "Labour",
    "court_name": "Labour Court No. 3",
    "judge_name": null,
    "case_number": "2025-00418",
    "parties_plaintiff": "Laura Gómez",
    "parties_defendant": "Northwind Logistics",
    "parties_third_parties": null,
    "document_date": "2026-03-14",
    "key_dates": [
      "2025-06-02",
      "2026-03-14"
    ],
    "sentence_type": "First instance",
    "document_structure": "Background, considerations, ruling"
  },
  "entity_counts": {
    "PERSON": 1,
    "ORG": 1
  },
  "unique_entities": {
    "PERSON": [
      {
        "text": "Laura Gómez",
        "type": "PERSON",
        "normalized": "Laura Gómez",
        "confidence": 0.97,
        "mentions": 12,
        "role": "plaintiff",
        "relevance": "high"
      }
    ],
    "ORG": [
      {
        "text": "Northwind Logistics",
        "type": "ORG",
        "normalized": "Northwind Logistics",
        "confidence": 0.95,
        "mentions": 8,
        "role": "defendant",
        "relevance": "high"
      }
    ]
  },
  "confidence_summary": {
    "PERSON": 0.97,
    "ORG": 0.95
  },
  "relationships": [
    {
      "entity_a": "Laura Gómez",
      "relation": "sues",
      "entity_b": "Northwind Logistics"
    }
  ],
  "phases_completed": 3,
  "stats": {
    "total_chunks": 3,
    "raw_entities": 64,
    "consolidated_entities": 2
  }
}
```

### `none_found`

没有任何分块返回有效实体。不包含 `relationships` 和 `stats`。

```json
{
  "entities": [],
  "document_profile": {
    "document_type": "Report",
    "author": null,
    "organization": null,
    "date": null,
    "subject": "Quarterly review",
    "key_findings": null
  },
  "entity_counts": {},
  "unique_entities": {},
  "confidence_summary": {},
  "phases_completed": 2
}
```

### `error`

任一模型调用失败（画像、某个分块或合并），或输入不是文本。

```json
{
  "error": "LLM Invocation Error: empty response from backend (Request failed with status code 500)"
}
```

## 代码中的行为

- `document_type`: 选择角色设定、画像字段和提取重点：`legal_sentence`（默认）、`contract`、`invoice_set`、`report` 或 `custom`；未知值按 `custom` 处理。
- `entity_types`: 仅过滤标准类型（PERSON、ORG、LOCATION、DATE、MONEY、ID、EMAIL、PHONE、CASE_NUMBER、LEGAL_REFERENCE）；自定义类型和资源中的类型总会被加入。
- `max_pages`: 已声明但被忽略：代码中没有页数限制。
- `language`: 默认 `es`。决定各阶段提示词中的回答语言说明行。
- `timeout_ms`: 分别作用于每次模型调用，且仅在 stream 模式下生效（片段间空闲超时）。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `text.split is not a function` | `error` | `text` 为空，worker 因此把上游载荷对象当作文本。请把 `text` 映射到文档字符串。 |
| `[DeepExtract] 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>`。 |

## 说明与限制

- 成本随文档长度增长：1 次画像调用 + 每个分块 1 次调用 + 唯一实体不少于 10 个时再加 1 次合并调用。调用依次串行执行。
- 若合并阶段的回答不是有效 JSON，则返回合并前的列表，其元素形如 `{ type, text, mentions, confidence, contexts }`。`confidence_summary` 只含各类型平均值，没有总体值。
- 请输入带 `--- PAGE <n> ---` 标记的文本（例如 `ai.multimodal.extract.text.cascade-pipeline` 的输出），使画像和分块按页边界进行。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- 在 stream 模式下，后端端点不应用采样参数，因此固定的 `temperature: 0` 仅在 sync 模式下生效。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.deep.extract",
  "name": "Deep Entity Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extract entities from large documents (100+ pages) using Hierarchical Map-Reduce with context propagation.\n\n  Unlike basic entity extraction which processes text in a single pass, Deep Extract handles documents of unlimited length by:\n\n  **Phase 1 — Document Profile:** Analyzes the first and last pages to understand document type, parties involved, structure, and key references.\n\n  **Phase 2 — Map with Rolling Context:** Processes each chunk sequentially, carrying forward previously found entities as context. This prevents the LLM from extracting partial names or missing relationships.\n\n  **Phase 3 — Reduce & Consolidate:** A final pass deduplicates entities (J. Pérez = Juan Pérez), resolves relationships (who is plaintiff, defendant), validates coherence, and assigns legal relevance.\n\n  Ideal for court sentences, contracts, regulatory filings, and any document where context matters.",
  "capabilities": [
    "nlp",
    "ner",
    "extraction",
    "legal",
    "deep-analysis",
    "map-reduce"
  ],
  "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. Use a record pointing to a high-quality reasoning model (e.g. gpt-4o, gpt-5.4) for complex legal documents.",
        "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 (recommended for deep extraction over long documents where any of the 3 phases can run >30s). Default `sync`.",
        "enum": [
          "sync",
          "stream"
        ],
        "default": "sync"
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for each of the 3 LLM phases (profile, chunk extract, consolidate) to complete. Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "document_type": {
        "type": "string",
        "title": "Document Type",
        "enum": [
          "legal_sentence",
          "contract",
          "invoice_set",
          "report",
          "custom"
        ],
        "default": "legal_sentence",
        "description": "Predefined extraction profiles optimized for specific document types."
      },
      "entity_types": {
        "type": "array",
        "title": "Entity Types",
        "description": "Filter standard entity types to extract. Leave empty for all.",
        "items": {
          "type": "string"
        }
      },
      "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": {
              "type": "string"
            },
            "examples": {
              "type": "string"
            }
          }
        }
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Knowledge Resource",
        "description": "Optional: load entity definitions from a Knowledge Resource.",
        "ui_widget": "knowledge_resource_picker"
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "es",
        "description": "Language of the document."
      },
      "chunk_size": {
        "type": "number",
        "title": "Chunk Size (characters)",
        "default": 40000,
        "description": "Target chunk size. Documents are split into chunks of this size for processing."
      },
      "max_pages": {
        "type": "number",
        "title": "Max Pages",
        "default": 500,
        "description": "Safety limit for maximum pages to process."
      },
      "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": "Full text of the document (from OCR or text extraction). No length limit."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "entities": {
        "type": "array",
        "description": "Consolidated, deduplicated entities."
      },
      "document_profile": {
        "type": "object",
        "description": "Document analysis (type, parties, structure)."
      },
      "entity_counts": {
        "type": "object",
        "description": "Count per entity type."
      },
      "unique_entities": {
        "type": "object",
        "description": "Entities grouped by type."
      },
      "confidence_summary": {
        "type": "object",
        "description": "Average confidence per type and overall."
      },
      "phases_completed": {
        "type": "number",
        "description": "Number of processing phases completed (1-3)."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Entities Found",
      "description": "Entities successfully extracted and consolidated.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "none_found",
      "label": "No Entities",
      "description": "No entities detected in the document.",
      "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",
    "legal",
    "deep",
    "map-reduce"
  ],
  "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. Use a record pointing to a high-quality reasoning model (e.g. gpt-4o, gpt-5.4) for complex legal documents.",
      "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 (recommended for deep extraction over long documents where any of the 3 phases can run >30s). Default `sync`.",
      "enum": [
        "sync",
        "stream"
      ],
      "default": "sync"
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait for each of the 3 LLM phases (profile, chunk extract, consolidate) to complete. Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "document_type": {
      "type": "string",
      "title": "Document Type",
      "enum": [
        "legal_sentence",
        "contract",
        "invoice_set",
        "report",
        "custom"
      ],
      "default": "legal_sentence",
      "description": "Predefined extraction profiles optimized for specific document types."
    },
    "entity_types": {
      "type": "array",
      "title": "Entity Types",
      "description": "Filter standard entity types to extract. Leave empty for all.",
      "items": {
        "type": "string"
      }
    },
    "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": {
            "type": "string"
          },
          "examples": {
            "type": "string"
          }
        }
      }
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Knowledge Resource",
      "description": "Optional: load entity definitions from a Knowledge Resource.",
      "ui_widget": "knowledge_resource_picker"
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "es",
      "description": "Language of the document."
    },
    "chunk_size": {
      "type": "number",
      "title": "Chunk Size (characters)",
      "default": 40000,
      "description": "Target chunk size. Documents are split into chunks of this size for processing."
    },
    "max_pages": {
      "type": "number",
      "title": "Max Pages",
      "default": 500,
      "description": "Safety limit for maximum pages to process."
    },
    "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": "Full text of the document (from OCR or text extraction). No length limit."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "entities": {
      "type": "array",
      "description": "Consolidated, deduplicated entities."
    },
    "document_profile": {
      "type": "object",
      "description": "Document analysis (type, parties, structure)."
    },
    "entity_counts": {
      "type": "object",
      "description": "Count per entity type."
    },
    "unique_entities": {
      "type": "object",
      "description": "Entities grouped by type."
    },
    "confidence_summary": {
      "type": "object",
      "description": "Average confidence per type and overall."
    },
    "phases_completed": {
      "type": "number",
      "description": "Number of processing phases completed (1-3)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Entities Found",
    "description": "Entities successfully extracted and consolidated.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "none_found",
    "label": "No Entities",
    "description": "No entities detected in the document.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Extraction failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
