On this page
Sommatic Docs
Open portal

Structured Multi-Pass Extraction

Extract a declared set of fields from a document and, for EVERY field, return value + self-assessed confidence + textual provenance, with schema validation and retry.

View as Markdown
Open in
AI Available ai.legal.extract.structured-multi-pass Version 1.0.0 Execution: async

Extracts a declared set of fields from a document with the model, returning value, self-assessed confidence and a provenance quote per field; validates types, required fields and allowed values, and retries with a correction message.

Designed for multi-pass extraction pipelines where a long document is split into focused passes (e.g. identification, procedural framework, timeline, actors, beneficiaries, dates). Each node runs ONE pass with its own field_schema and domain system_instructions (the doctrine/strong-signal rules live in the prompt, not in a RAG node).

Unlike basic entity extraction, this worker produces per-FIELD telemetry suitable for human review and confidence gating:

value — the extracted value (null when not stated in the document). confidence — the model's self-assessed certainty in [0, 1]. provenance — { pass, source }: which pass produced it and a short verbatim snippet/section reference where it was found.

After extraction the worker validates the result against the declared field schema (required fields present, basic types, enum membership). If validation fails and retries remain, it re-invokes the model with a correction message. It also scores overall confidence and lists fields below the configured threshold, routing to the low_confidence port so a downstream gate (e.g. hitl.approval.gate) can request human review.

Domain-neutral: drive it entirely from field_schema + system_instructions, or seed those from a reusable PromptTemplate via prompt_template_id.

How it works

  1. Merges the upstream payload with the node config (config wins). text (or input) must be a non-empty string and field_schema must hold at least one item with a name; otherwise it returns error.
  2. Builds the instructions from system_instructions; with prompt_template_id, the template's system_instructions (or template_body) is put before them. A missing template is only logged.
  3. Sends a system prompt listing every field with type, required flag, strong_signals, do_not_confuse_with and allowed values, and asks for { fields: { <name>: { value, confidence, provenance } } }. The user message is # DOCUMENT + text, preceded by up to 8000 characters of the JSON context from prior passes; temperature: 0.
  4. Normalises each declared field: confidence clamped to 0–1, provenance cut to 200 characters as { pass, source }. A bare value gets confidence 0.5 (0 when null); a missing field becomes null with confidence 0. Undeclared keys are dropped.
  5. Validates required fields, types (number, boolean, array, object; string and date always pass) and enum. On invalid JSON or validation errors it calls the model again with the errors as a correction message, up to max_retries extra times (default 1).
  6. Averages field confidence into overall_confidence, lists fields below confidence_threshold, and routes to low_confidence when validation failed or any field is below the threshold, else to extracted.

In a workflow

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

{
  "node_id": "node-extract-ruling",
  "label": "Extract ruling data",
  "operator_slug": "ai.legal.extract.structured-multi-pass",
  "operator_version": "1.0.0",
  "config": {
    "text": "{{ $json.text }}",
    "pass_label": "identification",
    "field_schema": [
      {
        "name": "case_number",
        "type": "string",
        "required": true,
        "description": "Case reference number.",
        "strong_signals": "Case No., file number"
      },
      {
        "name": "ruling_date",
        "type": "date",
        "required": true,
        "description": "Date the ruling was issued."
      },
      {
        "name": "awarded_amount",
        "type": "number",
        "description": "Total amount ordered to be paid.",
        "do_not_confuse_with": "amounts claimed by the parties"
      }
    ],
    "system_instructions": "Read amounts as plain numbers without thousands separators.",
    "confidence_threshold": 0.7,
    "max_retries": 1,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "stream",
    "timeout_ms": 120000
  }
}

Configuration

llm_provider_id string Required

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 the SSE stream endpoint for stream mode. Use a high-quality reasoning model 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 long documents where a pass may run >30s). Default `sync`.

Default: sync

Allowed values: syncstream

timeout_ms integer Optional

Maximum time to wait for each LLM call (including retries). Default 30000 for sync, 600000 for stream.

pass_label string Optional

Human-readable identifier for this extraction pass (e.g. `identification`, `procedural-timeline`). Stamped into each field's provenance so downstream merge/scoring nodes can tell which pass produced each value.

Default: pass-1

field_schema array<object> Required

The fields this pass must extract. Each item declares one field. This is the contract the LLM is instructed to fill and the result is validated against.

system_instructions string Optional

Domain doctrine and rules for this pass (taxonomies, regime rules, detection guidance). Embedded verbatim into the system prompt. This is where extraction knowledge lives instead of a RAG node.

prompt_template_id string Optional

Optional `CognitiveInfrastructurePromptTemplateModel.id`. When set, its `system_instructions` are prepended to the inline `system_instructions`. Non-fatal: if the template cannot be resolved, the inline instructions are used.

confidence_threshold number Optional

Fields with self-assessed confidence below this value are flagged and route output to `low_confidence`.

Default: 0.7

max_retries number Optional

How many times to re-invoke the model with a correction message when schema validation fails or JSON is unparseable.

Default: 1

language string Optional

Language of the document and the response.

Default: es

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.

field_schema
Each item: name (required), type (default string), description, required (only true counts), strong_signals, do_not_confuse_with, enum. enum is compared with strict equality.
max_retries
Extra attempts after the first (default 1, so up to 2 model calls). Each retry resends the document with only the latest correction, not the previous answer.
prompt_template_id
Fetched from the backend with a 10 s timeout; if it is missing or the fetch fails, only system_instructions is used.
text, context
Not in the config schema, but read from the config first and then from the upstream payload. context must be an object; it is sent as JSON, cut to 8000 characters.
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

extracted default

Validation passed and every field is at or above confidence_threshold.

Data
{
  "fields": {
    "case_number": {
      "value": "2025-00418",
      "confidence": 0.96,
      "provenance": {
        "pass": "identification",
        "source": "Case No. 2025-00418"
      }
    },
    "ruling_date": {
      "value": "2026-03-14",
      "confidence": 0.9,
      "provenance": {
        "pass": "identification",
        "source": "Issued on 14 March 2026"
      }
    },
    "awarded_amount": {
      "value": 18500,
      "confidence": 0.82,
      "provenance": {
        "pass": "identification",
        "source": "orders payment of 18,500"
      }
    }
  },
  "pass_label": "identification",
  "overall_confidence": 0.8933333333333332,
  "low_confidence_fields": [],
  "validation": {
    "valid": true,
    "errors": []
  },
  "field_count": 3
}
low_confidence

Some field is below the threshold, or validation still failed after the retries. The last parsed fields are returned so a reviewer can complete them.

Data
{
  "fields": {
    "case_number": {
      "value": "2025-00418",
      "confidence": 0.96,
      "provenance": {
        "pass": "identification",
        "source": "Case No. 2025-00418"
      }
    },
    "ruling_date": {
      "value": null,
      "confidence": 0,
      "provenance": {
        "pass": "identification",
        "source": null
      }
    }
  },
  "pass_label": "identification",
  "overall_confidence": 0.48,
  "low_confidence_fields": [
    "ruling_date"
  ],
  "validation": {
    "valid": false,
    "errors": [
      "Missing required field: ruling_date"
    ]
  },
  "field_count": 2
}
error

No text, no field schema, every attempt returned unparseable JSON, or a model call failed.

Data
{
  "error": "Extraction produced no usable fields.",
  "validation": {
    "valid": false,
    "errors": [
      "LLM did not return parseable JSON"
    ]
  }
}

In expressions

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

ExpressionEditorWorker
$("Structured Multi-Pass Extraction").item.json.fieldsobject= {…}Per-field result: { value, confidence, provenance: { pass, source } } keyed by field name.
$("Structured Multi-Pass Extraction").item.json.pass_labelstring= "identification"The pass that produced these fields.
$("Structured Multi-Pass Extraction").item.json.overall_confidencenumber= 0.8933333333333332Mean self-assessed confidence across declared fields.
$("Structured Multi-Pass Extraction").item.json.low_confidence_fieldsarray= […] (0)Field names with confidence below the threshold.
$("Structured Multi-Pass Extraction").item.json.validationobject= {…}Schema validation result { valid, errors[] }.
$("Structured Multi-Pass Extraction").item.json.field_countnumber= 3Number of declared fields in this pass.
$("Structured Multi-Pass Extraction").item.json.fields.case_numberobjectNot suggested by the editor= {…}—
$("Structured Multi-Pass Extraction").item.json.fields.ruling_dateobjectNot suggested by the editor= {…}—
$("Structured Multi-Pass Extraction").item.json.fields.awarded_amountobjectNot suggested by the editor= {…}—
$("Structured Multi-Pass Extraction").item.json.validation.validbooleanNot suggested by the editor= true—
$("Structured Multi-Pass Extraction").item.json.validation.errorsarrayNot suggested by the editor= […] (0)—

— 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
Missing 'text' to extract from. error text is empty or not a string (the upstream payload object is not accepted as text here).
No field schema provided. Set 'field_schema' (array of field definitions). error field_schema is not an array or has no item with a name.
Extraction produced no usable fields. error Every attempt returned text that could not be parsed as JSON; data.validation holds the last error.
[LegalExtractStructuredMultipass] 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 (e.g. from ai.multimodal.extract.text.cascade-pipeline).

context object Optional

Optional results from prior passes, carried forward as context to improve coherence.

Output contract

fields object Optional

Per-field result: `{ value, confidence, provenance: { pass, source } }` keyed by field name.

pass_label string Optional

The pass that produced these fields.

overall_confidence number Optional

Mean self-assessed confidence across declared fields.

low_confidence_fields array<string> Optional

Field names with confidence below the threshold.

validation object Optional

Schema validation result `{ valid, errors[] }`.

field_count number Optional

Number of declared fields in this pass.

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.legal.extract.structured-multi-pass",
  "name": "Structured Multi-Pass Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extract a declared set of fields from a document and, for EVERY field, return value + self-assessed confidence + textual provenance, with schema validation and retry.\n\n  Designed for multi-pass extraction pipelines where a long document is split into focused passes (e.g. identification, procedural framework, timeline, actors, beneficiaries, dates). Each node runs ONE pass with its own `field_schema` and domain `system_instructions` (the doctrine/strong-signal rules live in the prompt, not in a RAG node).\n\n  Unlike basic entity extraction, this worker produces per-FIELD telemetry suitable for human review and confidence gating:\n\n  **value** — the extracted value (null when not stated in the document).\n  **confidence** — the model's self-assessed certainty in [0, 1].\n  **provenance** — `{ pass, source }`: which pass produced it and a short verbatim snippet/section reference where it was found.\n\n  After extraction the worker validates the result against the declared field schema (required fields present, basic types, enum membership). If validation fails and retries remain, it re-invokes the model with a correction message. It also scores overall confidence and lists fields below the configured threshold, routing to the `low_confidence` port so a downstream gate (e.g. `hitl.approval.gate`) can request human review.\n\n  Domain-neutral: drive it entirely from `field_schema` + `system_instructions`, or seed those from a reusable PromptTemplate via `prompt_template_id`.",
  "capabilities": [
    "nlp",
    "extraction",
    "legal",
    "structured",
    "confidence",
    "provenance",
    "multi-pass"
  ],
  "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 the SSE stream endpoint for stream mode. Use a high-quality reasoning model 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 long documents where a pass may run >30s). Default `sync`.",
        "enum": [
          "sync",
          "stream"
        ],
        "default": "sync"
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for each LLM call (including retries). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "pass_label": {
        "type": "string",
        "title": "Pass Label",
        "default": "pass-1",
        "description": "Human-readable identifier for this extraction pass (e.g. `identification`, `procedural-timeline`). Stamped into each field's provenance so downstream merge/scoring nodes can tell which pass produced each value."
      },
      "field_schema": {
        "type": "array",
        "title": "Field Schema",
        "description": "The fields this pass must extract. Each item declares one field. This is the contract the LLM is instructed to fill and the result is validated against.",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "title": "Field Name",
              "description": "Output key for the field."
            },
            "type": {
              "type": "string",
              "title": "Type",
              "enum": [
                "string",
                "number",
                "boolean",
                "array",
                "object",
                "date"
              ],
              "default": "string",
              "description": "Expected value type, used for validation."
            },
            "description": {
              "type": "string",
              "title": "Description",
              "description": "What this field represents."
            },
            "required": {
              "type": "boolean",
              "title": "Required",
              "default": false,
              "description": "Fail validation if missing."
            },
            "strong_signals": {
              "type": "string",
              "title": "Strong Signals",
              "description": "Textual cues that indicate where to find this field (embedded in the prompt)."
            },
            "do_not_confuse_with": {
              "type": "string",
              "title": "Do Not Confuse With",
              "description": "Disambiguation guidance to avoid common extraction mistakes."
            },
            "enum": {
              "type": "array",
              "title": "Allowed Values",
              "description": "Optional closed set of allowed values, enforced during validation.",
              "items": {
                "type": "string"
              }
            }
          },
          "required": [
            "name"
          ]
        }
      },
      "system_instructions": {
        "type": "string",
        "title": "System Instructions",
        "description": "Domain doctrine and rules for this pass (taxonomies, regime rules, detection guidance). Embedded verbatim into the system prompt. This is where extraction knowledge lives instead of a RAG node.",
        "x-ui-widget": "textarea"
      },
      "prompt_template_id": {
        "type": "string",
        "title": "Prompt Template",
        "description": "Optional `CognitiveInfrastructurePromptTemplateModel.id`. When set, its `system_instructions` are prepended to the inline `system_instructions`. Non-fatal: if the template cannot be resolved, the inline instructions are used.",
        "ui_widget": "prompt_template_picker"
      },
      "confidence_threshold": {
        "type": "number",
        "title": "Confidence Threshold",
        "default": 0.7,
        "minimum": 0,
        "maximum": 1,
        "description": "Fields with self-assessed confidence below this value are flagged and route output to `low_confidence`."
      },
      "max_retries": {
        "type": "number",
        "title": "Max Retries",
        "default": 1,
        "minimum": 0,
        "description": "How many times to re-invoke the model with a correction message when schema validation fails or JSON is unparseable."
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "es",
        "description": "Language of the document and the response."
      },
      "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": [
      "llm_provider_id",
      "field_schema"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Full text of the document (e.g. from ai.multimodal.extract.text.cascade-pipeline)."
      },
      "context": {
        "type": "object",
        "description": "Optional results from prior passes, carried forward as context to improve coherence."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "fields": {
        "type": "object",
        "description": "Per-field result: `{ value, confidence, provenance: { pass, source } }` keyed by field name."
      },
      "pass_label": {
        "type": "string",
        "description": "The pass that produced these fields."
      },
      "overall_confidence": {
        "type": "number",
        "description": "Mean self-assessed confidence across declared fields."
      },
      "low_confidence_fields": {
        "type": "array",
        "description": "Field names with confidence below the threshold.",
        "items": {
          "type": "string"
        }
      },
      "validation": {
        "type": "object",
        "description": "Schema validation result `{ valid, errors[] }`."
      },
      "field_count": {
        "type": "number",
        "description": "Number of declared fields in this pass."
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "description": "All fields valid and at/above the confidence threshold.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "low_confidence",
      "label": "Low Confidence",
      "description": "Extraction succeeded but some fields are below threshold or failed validation — route to a review gate.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Extraction failed (no text, no schema, or no parseable output).",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "extraction",
    "legal",
    "structured",
    "confidence",
    "provenance",
    "xai"
  ],
  "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
nlpextractionlegalstructuredconfidenceprovenancemulti-pass
Tags
ainlpextractionlegalstructuredconfidenceprovenancexai

Notes and limits

  • Chain several passes by giving each its own pass_label and field_schema, and pass earlier results as context; provenance.pass records which pass produced each value.
  • Confidence and provenance are the model's own claims; the code does not check that the quote exists in the document.
  • language defaults to es and only sets the response language line.
  • 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.
  • Validation retries are the only retries: a failed model call (network, provider) is not retried and goes 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