# Deep Entity Extraction

> Extract entities from large documents (100+ pages) using Hierarchical Map-Reduce with context propagation.

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

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

Extract entities from large documents (100+ pages) using Hierarchical Map-Reduce with context propagation.

Unlike basic entity extraction which processes text in a single pass, Deep Extract handles documents of unlimited length by:

**Phase 1 — Document Profile:** Analyzes the first and last pages to understand document type, parties involved, structure, and key references.

**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.

**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.

Ideal for court sentences, contracts, regulatory filings, and any document where context matters.

## 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. Use a record pointing to a high-quality reasoning model (e.g. gpt-4o, gpt-5.4) for complex legal documents.
- `invocation_mode` (string, optional): 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`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): Maximum time to wait for each of the 3 LLM phases (profile, chunk extract, consolidate) to complete. Default 30000 for sync, 600000 for stream.
- `document_type` (string, optional): Predefined extraction profiles optimized for specific document types. Default: `legal_sentence`. Allowed values: `legal_sentence`, `contract`, `invoice_set`, `report`, `custom`.
- `entity_types` (array<string>, optional): Filter standard entity types to extract. Leave empty for all.
- `custom_entities` (array<object>, optional): Define custom entity types with name, description, and examples.
- `knowledge_resource_id` (string, optional): Optional: load entity definitions from a Knowledge Resource.
- `language` (string, optional): Language of the document. Default: `es`.
- `chunk_size` (number, optional): Target chunk size. Documents are split into chunks of this size for processing. Default: `40000`.
- `max_pages` (number, optional): Safety limit for maximum pages to process. Default: `500`.

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

- `success` (default): Entities successfully extracted and consolidated.
- `none_found`: No entities detected in the document.
- `error`: Extraction failed.

## Input contract

- `text` (string, required): Full text of the document (from OCR or text extraction). No length limit.

## Output contract

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

## In expressions

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

- `$("Deep Entity Extraction").item.json.entities` (array) = `[…] (2)`: Consolidated, deduplicated entities.
- `$("Deep Entity Extraction").item.json.document_profile` (object) = `{…}`: Document analysis (type, parties, structure).
- `$("Deep Entity Extraction").item.json.entity_counts` (object) = `{…}`: Count per entity type.
- `$("Deep Entity Extraction").item.json.unique_entities` (object) = `{…}`: Entities grouped by type.
- `$("Deep Entity Extraction").item.json.confidence_summary` (object) = `{…}`: Average confidence per type and overall.
- `$("Deep Entity Extraction").item.json.phases_completed` (number) = `3`: Number of processing phases completed (1-3).
- `$("Deep Entity Extraction").item.json.document_profile.document_type` (string) = `"Judgment"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.jurisdiction` (string) = `"Labour"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.court_name` (string) = `"Labour Court No. 3"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.judge_name` (null) = `null` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.case_number` (string) = `"2025-00418"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.parties_plaintiff` (string) = `"Laura Gómez"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.parties_defendant` (string) = `"Northwind Logistics"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.parties_third_parties` (null) = `null` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.document_date` (string) = `"2026-03-14"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.key_dates` (array) = `[…] (2)` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.sentence_type` (string) = `"First instance"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.document_profile.document_structure` (string) = `"Background, considerations, ruling"` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.entity_counts.PERSON` (number) = `1` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.entity_counts.ORG` (number) = `1` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.unique_entities.PERSON` (array) = `[…] (1)` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.unique_entities.ORG` (array) = `[…] (1)` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.confidence_summary.PERSON` (number) = `0.97` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.confidence_summary.ORG` (number) = `0.95` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.relationships` (array) = `[…] (1)` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.stats` (object) = `{…}` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.stats.total_chunks` (number) = `3` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.stats.raw_entities` (number) = `64` (Not suggested by the editor)
- `$("Deep Entity Extraction").item.json.stats.consolidated_entities` (number) = `2` (Not suggested by the editor)


## How it works

Extracts named entities from long documents in three model phases: a document profile from the first and last pages, per-chunk extraction with a rolling context of entities already found, and a final consolidation with roles and relationships.

1. Merges the upstream payload with the node config (config wins) and reads `text` (falling back to `input`). Builds the entity type list: the standard types (filtered by `entity_types`), plus `custom_entities`, plus `structured_data.entity_types` of `knowledge_resource_id`.
2. Phase 1: if the text has more than 10 pages (split on `--- PAGE <n> ---` markers), keeps the first and last 5; sends at most 30000 characters to get a JSON profile with the fields of the `document_type` profile. Invalid JSON gives an empty profile.
3. Phase 2: splits the text into chunks of about `chunk_size` characters (page markers first, then near paragraph or sentence breaks) and calls the model once per chunk with the profile and up to 50 previously found entities. Entities of other types, or whose text clearly looks like another type (dates, money, emails, phones, company suffixes), are dropped; a chunk with invalid JSON yields nothing.
4. If no entity was found, routes to `none_found` with `phases_completed: 2`.
5. Phase 3: groups entities by type and normalised text. With fewer than 10 unique entities they are returned directly; otherwise the top 200 by mentions go to a consolidation call that merges duplicates, assigns roles and relationships and ranks them.
6. Counts entities per type, groups them in `unique_entities`, averages confidence per type and routes to `success`.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `success`

At least one entity was found and consolidated.

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

No chunk returned a valid entity. `relationships` and `stats` are not included.

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

Any model call failed (profile, a chunk or consolidation), or the input was not text.

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

## Behaviour in the code

- `document_type`: Selects the persona, profile fields and extraction focus: `legal_sentence` (default), `contract`, `invoice_set`, `report` or `custom`; unknown values use `custom`.
- `entity_types`: Filters only the standard types (PERSON, ORG, LOCATION, DATE, MONEY, ID, EMAIL, PHONE, CASE_NUMBER, LEGAL_REFERENCE); custom and resource types are always added.
- `max_pages`: Declared but ignored: there is no page limit in the code.
- `language`: Default `es`. Sets the response language line of every phase prompt.
- `timeout_ms`: Applies to each model call separately, and only in stream mode (idle timeout between chunks).
- `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 |
| --- | --- | --- |
| `text.split is not a function` | `error` | `text` was empty, so the worker took the upstream payload object as text. Map `text` to the document string. |
| `[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` 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

- Cost grows with document length: 1 profile call + 1 call per chunk + 1 consolidation call when there are 10 or more unique entities. Calls run one after another.
- If the consolidation answer is not valid JSON, the pre-consolidated list is returned instead, with items shaped `{ type, text, mentions, confidence, contexts }`. `confidence_summary` holds per-type averages only, with no overall value.
- Feed it text with `--- PAGE <n> ---` markers (as produced by `ai.multimodal.extract.text.cascade-pipeline`) so profiling and chunking follow page boundaries.
- 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.
- 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.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
  }
]
```
