# Parse Document

> 使用 LLM 解析文档并抽取结构化数据。

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

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

使用 LLM 解析文档并抽取结构化数据。

分析文档文本（OCR 输出、原始文本或预处理后的内容），并根据文档类型抽取结构化字段。内置常见文档类型的 schema，也支持自定义抽取 schema。

**操作：**
- **Invoice：** 抽取供应商、明细行、合计和付款条件。
- **Receipt：** 抽取商户、商品、合计和支付方式。
- **Resume：** 抽取联系方式、工作经历、教育背景和技能。
- **Contract：** 抽取签约各方、日期、条款和义务。
- **Form：** 抽取通用的标签-值字段对。
- **Custom：** 使用用户定义的 JSON schema 进行抽取。

## 配置

- `llm_provider_id` (string, 可选): `LlmProviderModel` 记录的 `id`（例如 `wf-llm-provider-*`）。编排器将调用委托给后端：sync 模式调用 `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke`，stream 模式调用 `POST /chat/conversation/execute/stream-ephemeral`（SSE）。后端根据该记录解析 endpoint + api-key + deployment，并路由到相应的适配器。
- `invocation_mode` (string, 可选): LLM 调用的传输方式。`sync` 会阻塞直到收到完整响应。`stream` 通过 SSE 逐步接收 token（长文本生成必须使用）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 等待调用完成的最长时间（stream 模式下为分块之间的空闲超时）。sync 默认 30000，stream 默认 600000。
- `document_type` (string, 必填): 要解析的文档类型。决定所用的抽取 schema。 默认值: `form`. 可选值: `invoice`, `receipt`, `resume`, `contract`, `form`, `custom`.
- `extraction_schema` (string, 可选): 定义要抽取字段的 JSON schema（用于 custom 模式）。 显示条件: document_type = `custom`.
- `language` (string, 可选): 默认值: `en`.
- `knowledge_resource_id` (string, 可选): 可选的 Knowledge Resource，提供额外的抽取上下文或字段定义。

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

## 输出端口

- `success` (默认): 文档已解析，完整度 >= 0.7。
- `incomplete`: 文档已解析，但完整度 < 0.7。
- `error`: 解析失败。

## 输入契约

- `text` (string, 必填): 要解析的文档文本内容。
- `metadata` (object, 可选): 关于文档的可选元数据（文件名、来源等）。

## 输出契约

- `document_type` (string, 可选): 所解析的文档类型。
- `data` (object, 可选): 抽取出的结构化数据。
- `completeness_score` (number, 可选): 非空抽取字段的占比（0-1）。
- `missing_fields` (array<string>, 可选): 未能抽取到的预期字段列表。

## 在表达式中

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

- `$("Parse Document").item.json.document_type` (string) = `"invoice"`: 所解析的文档类型。
- `$("Parse Document").item.json.data` (object) = `{…}`: 抽取出的结构化数据。
- `$("Parse Document").item.json.completeness_score` (number) = `0.91`: 非空抽取字段的占比（0-1）。
- `$("Parse Document").item.json.missing_fields` (array) = `[…] (1)`: 未能抽取到的预期字段列表。
- `$("Parse Document").item.json.data.vendor` (string) = `"Example Supplies Ltd."` (编辑器不提示)
- `$("Parse Document").item.json.data.vendor_address` (string) = `"12 Market St, Springfield"` (编辑器不提示)
- `$("Parse Document").item.json.data.invoice_number` (string) = `"INV-2026-0042"` (编辑器不提示)
- `$("Parse Document").item.json.data.date` (string) = `"2026-11-02"` (编辑器不提示)
- `$("Parse Document").item.json.data.due_date` (string) = `"2026-12-02"` (编辑器不提示)
- `$("Parse Document").item.json.data.line_items` (array) = `[…] (1)` (编辑器不提示)
- `$("Parse Document").item.json.data.subtotal` (number) = `45` (编辑器不提示)
- `$("Parse Document").item.json.data.tax` (number) = `8.55` (编辑器不提示)
- `$("Parse Document").item.json.data.total` (number) = `53.55` (编辑器不提示)
- `$("Parse Document").item.json.data.currency` (string) = `"USD"` (编辑器不提示)
- `$("Parse Document").item.json.data.payment_terms` (null) = `null` (编辑器不提示)


## 工作原理

根据文档 `text`，让 LLM 填写所选文档类型（发票、收据、简历、合同、表单）的固定模板或你的自定义模板。统计返回的顶层字段中已填写的比例，并据此路由。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `text`。根据 `document_type`（默认 `form`）选择模板；为 `custom` 时将 `extraction_schema` 解析为 JSON。
4. 若设置了 `knowledge_resource_id`，则加载其文本或结构化数据作为额外的提取上下文。输入中的 `metadata` 会以 JSON 形式加入提示词。
5. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
6. 将响应解析为 JSON（温度 0）。统计模板顶层键中非 `null`、未缺失且不是空数组的数量：`completeness_score` = 已填写 / 总数，保留 2 位小数。
7. 分数低于 0.7 时路由到 `incomplete`，否则路由到 `success`。

## 在工作流中

### 节点

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

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

### `success`

`completeness_score` 大于或等于 0.7。

```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` 低于 0.7。结构相同。

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

校验、LLM 调用或解析失败。`data` 为 `{ error }`（若后端返回了响应体，还包含 `response`）。

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

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `extraction_schema`: 作为模板使用，而非 JSON Schema：写出你希望返回的对象，值为 `null`，例如 `{"po_number": null, "items": [{"sku": null}]}`。其顶层键就是参与完整度计算的字段。若提供 JSON Schema 文档，模型会去填写 `type` 和 `properties`。
- `knowledge_resource_id`: 如果无法加载知识资源，只会记录失败，节点会在没有它的情况下继续执行。
- `language`: 当其不为 `en` 时，会在提示词中加入一行回复语言说明。不会翻译字段名。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing input text for document parsing.` | `error` | 传入条目中没有 `text`。 |
| `Missing extraction_schema for custom document type.` | `error` | `document_type` 为 `custom`，但 `extraction_schema` 为空。 |
| `extraction_schema is not valid JSON.` | `error` | `extraction_schema` 是无法解析为 JSON 的字符串。 |
| `Unknown document type: <document_type>` | `error` | `document_type` 不是列出的取值之一。 |
| `Model did not return valid document parsing output.` | `error` | 响应中没有 JSON 对象。请尝试更能遵循 JSON 指令的模型。 |
| `[AiParseDocument] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 完整度只检查顶层键。即使嵌套数组中的元素全为 `null`，也会被计为已填写。
- 0.7 的阈值在代码中是固定的。
- 模型响应在去除 Markdown 代码块标记后按 JSON 解析；若失败，则解析第一个 `{` 与最后一个 `}` 之间的文本。
- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- Worker 还会在 `data` 之外以 `raw` 返回提供方的原始响应；引擎不会保留它。
- 成功时 worker 返回 `port` 和 `data`，不含 `ok` 字段；引擎只依据 `port` 路由。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（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."
  }
]
```
