# Parse Document

> Parse and extract structured data from documents using an LLM.

Source: https://docs.sommatic.ai/en/nodes/ai.parse.document/

- Slug: `ai.parse.document`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Parse and extract structured data from documents using an LLM.

Analyzes document text (OCR output, raw text, or pre-processed content) and extracts structured fields based on the document type. Includes built-in schemas for common document types and supports custom extraction schemas.

**Operations:**
- **Invoice:** Extract vendor, line items, totals, payment terms.
- **Receipt:** Extract merchant, items, totals, payment method.
- **Resume:** Extract contact info, experience, education, skills.
- **Contract:** Extract parties, dates, clauses, obligations.
- **Form:** Extract generic label-value field pairs.
- **Custom:** Use a user-defined JSON schema for extraction.

## 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. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.
- `invocation_mode` (string, optional): Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.
- `document_type` (string, required): Type of document to parse. Determines the extraction schema. Default: `form`. Allowed values: `invoice`, `receipt`, `resume`, `contract`, `form`, `custom`.
- `extraction_schema` (string, optional): JSON schema defining the fields to extract (used in custom mode). Shown when: document_type = `custom`.
- `language` (string, optional): Default: `en`.
- `knowledge_resource_id` (string, optional): Optional Knowledge Resource with additional extraction context or field definitions.

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): Document parsed with completeness >= 0.7.
- `incomplete`: Document parsed but completeness < 0.7.
- `error`: Parsing failed.

## Input contract

- `text` (string, required): Document text content to parse.
- `metadata` (object, optional): Optional metadata about the document (filename, source, etc.).

## Output contract

- `document_type` (string, optional): The document type that was parsed.
- `data` (object, optional): Extracted structured data.
- `completeness_score` (number, optional): Ratio of non-null extracted fields (0-1).
- `missing_fields` (array<string>, optional): List of expected fields that could not be extracted.

## In expressions

What a later node can read from this node's output with `$("Parse Document").item.json.<path>` (write your node's label instead of `Parse Document`). **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.

- `$("Parse Document").item.json.document_type` (string) = `"invoice"`: The document type that was parsed.
- `$("Parse Document").item.json.data` (object) = `{…}`: Extracted structured data.
- `$("Parse Document").item.json.completeness_score` (number) = `0.91`: Ratio of non-null extracted fields (0-1).
- `$("Parse Document").item.json.missing_fields` (array) = `[…] (1)`: List of expected fields that could not be extracted.
- `$("Parse Document").item.json.data.vendor` (string) = `"Example Supplies Ltd."` (Not suggested by the editor)
- `$("Parse Document").item.json.data.vendor_address` (string) = `"12 Market St, Springfield"` (Not suggested by the editor)
- `$("Parse Document").item.json.data.invoice_number` (string) = `"INV-2026-0042"` (Not suggested by the editor)
- `$("Parse Document").item.json.data.date` (string) = `"2026-11-02"` (Not suggested by the editor)
- `$("Parse Document").item.json.data.due_date` (string) = `"2026-12-02"` (Not suggested by the editor)
- `$("Parse Document").item.json.data.line_items` (array) = `[…] (1)` (Not suggested by the editor)
- `$("Parse Document").item.json.data.subtotal` (number) = `45` (Not suggested by the editor)
- `$("Parse Document").item.json.data.tax` (number) = `8.55` (Not suggested by the editor)
- `$("Parse Document").item.json.data.total` (number) = `53.55` (Not suggested by the editor)
- `$("Parse Document").item.json.data.currency` (string) = `"USD"` (Not suggested by the editor)
- `$("Parse Document").item.json.data.payment_terms` (null) = `null` (Not suggested by the editor)


## How it works

Asks the LLM to fill a fixed template for the chosen document type (invoice, receipt, resume, contract, form) or your own template, from the document `text`. It measures how many top-level fields came back filled and routes by that score.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Merges the incoming item with the resolved config (config keys win) and reads the inputs from the result.
3. Requires `text`. Picks the template for `document_type` (default `form`); for `custom` it parses `extraction_schema` as JSON.
4. If `knowledge_resource_id` is set, loads its text or structured data as extra extraction context. Input `metadata` is added to the prompt as JSON.
5. Calls the LLM through the backend with the `llm_provider_id` record. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it over SSE and joins the chunks.
6. Parses the answer as JSON (temperature 0). Counts the template’s top-level keys that are not `null`, missing or an empty array: `completeness_score` = filled / total, rounded to 2 decimals.
7. Routes to `incomplete` when the score is below 0.7, otherwise to `success`.

## In a workflow

### Node

```json
{
  "node_id": "node-parse-invoice",
  "label": "Parse invoice",
  "operator_slug": "ai.parse.document",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "invocation_mode": "sync",
    "document_type": "invoice",
    "language": "en"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "document_type": "invoice",
    "data": {
      "vendor": "Example Supplies Ltd.",
      "vendor_address": "12 Market St, Springfield",
      "invoice_number": "INV-2026-0042",
      "date": "2026-11-02",
      "due_date": "2026-12-02",
      "line_items": [
        {
          "description": "Printer paper A4",
          "quantity": 10,
          "unit_price": 4.5,
          "total": 45
        }
      ],
      "subtotal": 45,
      "tax": 8.55,
      "total": 53.55,
      "currency": "USD",
      "payment_terms": null
    },
    "completeness_score": 0.91,
    "missing_fields": [
      "payment_terms"
    ]
  }
}
```

## Output ports (behaviour in the code)

### `success`

`completeness_score` is 0.7 or higher.

```json
{
  "document_type": "invoice",
  "data": {
    "vendor": "Example Supplies Ltd.",
    "vendor_address": "12 Market St, Springfield",
    "invoice_number": "INV-2026-0042",
    "date": "2026-11-02",
    "due_date": "2026-12-02",
    "line_items": [
      {
        "description": "Printer paper A4",
        "quantity": 10,
        "unit_price": 4.5,
        "total": 45
      }
    ],
    "subtotal": 45,
    "tax": 8.55,
    "total": 53.55,
    "currency": "USD",
    "payment_terms": null
  },
  "completeness_score": 0.91,
  "missing_fields": [
    "payment_terms"
  ]
}
```

### `incomplete`

`completeness_score` is below 0.7. Same shape.

```json
{
  "document_type": "receipt",
  "data": {
    "merchant": "Corner Café",
    "date": null,
    "items": [],
    "subtotal": null,
    "tax": null,
    "total": 7.2,
    "payment_method": null
  },
  "completeness_score": 0.29,
  "missing_fields": [
    "date",
    "items",
    "subtotal",
    "tax",
    "payment_method"
  ]
}
```

### `error`

Validation, the LLM call or parsing failed. `data` is `{ error }` (plus `response` when the backend returned a body).

```json
{
  "error": "Missing input text for document parsing."
}
```

## Behaviour in the code

- `llm_provider_id`: Required at runtime although the schema does not mark it as required. It is the id of an LLM provider record; the backend resolves endpoint, deployment and credentials from it.
- `extraction_schema`: Used as a template, not as JSON Schema: write the object you want back, with `null` values, e.g. `{"po_number": null, "items": [{"sku": null}]}`. Its top-level keys are the fields counted for completeness. A JSON Schema document would make the model fill `type` and `properties`.
- `knowledge_resource_id`: If the knowledge resource cannot be loaded, the failure is only logged and the node continues without it.
- `language`: Adds a reply-language line to the prompt when it is not `en`. It does not translate field names.
- `timeout_ms`: `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input text for document parsing.` | `error` | The incoming item has no `text`. |
| `Missing extraction_schema for custom document type.` | `error` | `document_type` is `custom` but `extraction_schema` is empty. |
| `extraction_schema is not valid JSON.` | `error` | `extraction_schema` is a string that does not parse as JSON. |
| `Unknown document type: <document_type>` | `error` | `document_type` is not one of the listed values. |
| `Model did not return valid document parsing output.` | `error` | The answer did not contain a JSON object. Try a model that follows JSON instructions better. |
| `[AiParseDocument] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | The node has no `llm_provider_id`. Pick an LLM provider in the node config; the legacy `model_id` key is not accepted. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call (unknown or inactive provider record, provider error, credentials). Check the provider record. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | The backend could not be reached or returned nothing in `sync` mode. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | In `stream` mode no chunk arrived within `timeout_ms`. |

## Notes and limits

- Completeness only looks at top-level keys. A nested array with an item full of `null` values still counts as filled.
- The 0.7 threshold is fixed in code.
- The model answer is parsed as JSON after removing Markdown code fences; if that fails, the text between the first `{` and the last `}` is parsed.
- Input fields are read from the incoming item (`$json`). A key with the same name in the node config, which may be an expression, takes precedence over the input.
- The worker also returns the provider response as `raw` outside `data`; the engine does not keep it.
- On success the worker returns `port` and `data` without an `ok` field; the engine routes on `port` only.
- `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.
- In `stream` mode the temperature this node sets is not forwarded to the provider, and `raw` is `null`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (JSON Schema)

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

```json
{
  "slug": "ai.parse.document",
  "name": "Parse Document",
  "category": "ai",
  "version": "1.0.0",
  "description": "Parse and extract structured data from documents using an LLM.\n\n  Analyzes document text (OCR output, raw text, or pre-processed content) and extracts structured fields based on the document type. Includes built-in schemas for common document types and supports custom extraction schemas.\n\n  **Operations:**\n  - **Invoice:** Extract vendor, line items, totals, payment terms.\n  - **Receipt:** Extract merchant, items, totals, payment method.\n  - **Resume:** Extract contact info, experience, education, skills.\n  - **Contract:** Extract parties, dates, clauses, obligations.\n  - **Form:** Extract generic label-value field pairs.\n  - **Custom:** Use a user-defined JSON schema for extraction.",
  "capabilities": [
    "ai",
    "nlp",
    "parsing",
    "document",
    "extraction",
    "structured-output"
  ],
  "knowledge_binding": {
    "enabled": true,
    "resource_types": [
      "schema",
      "template"
    ],
    "field": "knowledge_resource_id",
    "label": "Extraction Reference"
  },
  "config_schema": {
    "type": "object",
    "properties": {
      "llm_provider_id": {
        "type": "string",
        "title": "LLM Provider",
        "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.",
        "x-ui-widget": "llm-provider-picker",
        "x-llm-provider-capabilities": [
          "chat"
        ]
      },
      "invocation_mode": {
        "type": "string",
        "title": "Invocation Mode",
        "description": "Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`.",
        "enum": [
          "sync",
          "stream"
        ],
        "default": "sync"
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "document_type": {
        "type": "string",
        "title": "Document Type",
        "enum": [
          "invoice",
          "receipt",
          "resume",
          "contract",
          "form",
          "custom"
        ],
        "default": "form",
        "description": "Type of document to parse. Determines the extraction schema."
      },
      "extraction_schema": {
        "type": "string",
        "title": "Extraction Schema",
        "format": "json",
        "description": "JSON schema defining the fields to extract (used in custom mode).",
        "ui_widget": "code_editor",
        "ui_options": {
          "language": "json"
        },
        "displayOptions": {
          "show": {
            "document_type": [
              "custom"
            ]
          }
        }
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en"
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Extraction Reference (Knowledge Resource)",
        "description": "Optional Knowledge Resource with additional extraction context or field definitions.",
        "x-ui-widget": "knowledge-resource-picker"
      },
      "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": [
      "document_type"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Document text content to parse."
      },
      "metadata": {
        "type": "object",
        "description": "Optional metadata about the document (filename, source, etc.).",
        "additionalProperties": true
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "document_type": {
        "type": "string",
        "description": "The document type that was parsed."
      },
      "data": {
        "type": "object",
        "description": "Extracted structured data."
      },
      "completeness_score": {
        "type": "number",
        "description": "Ratio of non-null extracted fields (0-1)."
      },
      "missing_fields": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "description": "List of expected fields that could not be extracted."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Parsed",
      "is_default": true,
      "description": "Document parsed with completeness >= 0.7."
    },
    {
      "port_id": "incomplete",
      "label": "Incomplete",
      "description": "Document parsed but completeness < 0.7."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Parsing failed."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "document",
    "parser",
    "extraction",
    "invoice",
    "receipt",
    "resume",
    "contract"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "llm_provider_id": {
      "type": "string",
      "title": "LLM Provider",
      "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.",
      "x-ui-widget": "llm-provider-picker",
      "x-llm-provider-capabilities": [
        "chat"
      ]
    },
    "invocation_mode": {
      "type": "string",
      "title": "Invocation Mode",
      "description": "Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`.",
      "enum": [
        "sync",
        "stream"
      ],
      "default": "sync"
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "document_type": {
      "type": "string",
      "title": "Document Type",
      "enum": [
        "invoice",
        "receipt",
        "resume",
        "contract",
        "form",
        "custom"
      ],
      "default": "form",
      "description": "Type of document to parse. Determines the extraction schema."
    },
    "extraction_schema": {
      "type": "string",
      "title": "Extraction Schema",
      "format": "json",
      "description": "JSON schema defining the fields to extract (used in custom mode).",
      "ui_widget": "code_editor",
      "ui_options": {
        "language": "json"
      },
      "displayOptions": {
        "show": {
          "document_type": [
            "custom"
          ]
        }
      }
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en"
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Extraction Reference (Knowledge Resource)",
      "description": "Optional Knowledge Resource with additional extraction context or field definitions.",
      "x-ui-widget": "knowledge-resource-picker"
    },
    "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": [
    "document_type"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Document text content to parse."
    },
    "metadata": {
      "type": "object",
      "description": "Optional metadata about the document (filename, source, etc.).",
      "additionalProperties": true
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "document_type": {
      "type": "string",
      "description": "The document type that was parsed."
    },
    "data": {
      "type": "object",
      "description": "Extracted structured data."
    },
    "completeness_score": {
      "type": "number",
      "description": "Ratio of non-null extracted fields (0-1)."
    },
    "missing_fields": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "List of expected fields that could not be extracted."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Parsed",
    "is_default": true,
    "description": "Document parsed with completeness >= 0.7."
  },
  {
    "port_id": "incomplete",
    "label": "Incomplete",
    "description": "Document parsed but completeness < 0.7."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Parsing failed."
  }
]
```
