On this page
Sommatic Docs
Open portal

Deep Entity Extraction

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

View as Markdown
Open in
AI Available ai.deep.extract Version 1.0.0 Execution: async

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.

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.

How it works

  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

The node as it appears in a workflow file (draft_nodes[]), and the envelope of a successful run.

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

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: syncstream

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_sentencecontractinvoice_setreportcustom

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.

Behaviour in the code

What the implementation does with these keys beyond what the schema says.

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.

Output ports

success default

At least one entity was found and consolidated.

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
  }
}
none_found

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

Data
{
  "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.

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

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.

ExpressionEditorWorker
$("Deep Entity Extraction").item.json.entitiesarray= […] (2)Consolidated, deduplicated entities.
$("Deep Entity Extraction").item.json.document_profileobject= {…}Document analysis (type, parties, structure).
$("Deep Entity Extraction").item.json.entity_countsobject= {…}Count per entity type.
$("Deep Entity Extraction").item.json.unique_entitiesobject= {…}Entities grouped by type.
$("Deep Entity Extraction").item.json.confidence_summaryobject= {…}Average confidence per type and overall.
$("Deep Entity Extraction").item.json.phases_completednumber= 3Number of processing phases completed (1-3).
$("Deep Entity Extraction").item.json.document_profile.document_typestringNot suggested by the editor= "Judgment"—
$("Deep Entity Extraction").item.json.document_profile.jurisdictionstringNot suggested by the editor= "Labour"—
$("Deep Entity Extraction").item.json.document_profile.court_namestringNot suggested by the editor= "Labour Court No. 3"—
$("Deep Entity Extraction").item.json.document_profile.judge_namenullNot suggested by the editor= null—
$("Deep Entity Extraction").item.json.document_profile.case_numberstringNot suggested by the editor= "2025-00418"—
$("Deep Entity Extraction").item.json.document_profile.parties_plaintiffstringNot suggested by the editor= "Laura Gómez"—
$("Deep Entity Extraction").item.json.document_profile.parties_defendantstringNot suggested by the editor= "Northwind Logistics"—
$("Deep Entity Extraction").item.json.document_profile.parties_third_partiesnullNot suggested by the editor= null—
$("Deep Entity Extraction").item.json.document_profile.document_datestringNot suggested by the editor= "2026-03-14"—
$("Deep Entity Extraction").item.json.document_profile.key_datesarrayNot suggested by the editor= […] (2)—
$("Deep Entity Extraction").item.json.document_profile.sentence_typestringNot suggested by the editor= "First instance"—
$("Deep Entity Extraction").item.json.document_profile.document_structurestringNot suggested by the editor= "Background, considerations, ruling"—
$("Deep Entity Extraction").item.json.entity_counts.PERSONnumberNot suggested by the editor= 1—
$("Deep Entity Extraction").item.json.entity_counts.ORGnumberNot suggested by the editor= 1—
$("Deep Entity Extraction").item.json.unique_entities.PERSONarrayNot suggested by the editor= […] (1)—
$("Deep Entity Extraction").item.json.unique_entities.ORGarrayNot suggested by the editor= […] (1)—
$("Deep Entity Extraction").item.json.confidence_summary.PERSONnumberNot suggested by the editor= 0.97—
$("Deep Entity Extraction").item.json.confidence_summary.ORGnumberNot suggested by the editor= 0.95—
$("Deep Entity Extraction").item.json.relationshipsarrayNot suggested by the editor= […] (1)—
$("Deep Entity Extraction").item.json.statsobjectNot suggested by the editor= {…}—
$("Deep Entity Extraction").item.json.stats.total_chunksnumberNot suggested by the editor= 3—
$("Deep Entity Extraction").item.json.stats.raw_entitiesnumberNot suggested by the editor= 64—
$("Deep Entity Extraction").item.json.stats.consolidated_entitiesnumberNot suggested by the editor= 2—

— Worker: The worker returns it but the editor does not suggest it: write it by hand. Keys inside objects can depend on your data or configuration (for example one key per label).

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.

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

Contracts (JSON Schema)

The definition exactly as the orchestrator declares it. All is the whole *.definition.js; compare it with the sections above to spot differences between the documentation and the schema. Use it to validate a node before you publish.

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

Execution

Execution
async
Stateful
No
Retries (retryOnFail)
No
Capabilities
nlpnerextractionlegaldeep-analysismap-reduce
Tags
ainlpnerentitieslegaldeepmap-reduce

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.

Reviewed against the orchestrator code · 31e874b · 2026-11-26

Install agent tools

Give your coding agent the official Sommatic AI docs: skills, the docs MCP server and Markdown pages, so it never has to scrape the site.

Skills only. They do not update by themselves; run it again to refresh.

npx skills add https://docs.sommatic.ai
How agents read these docs