# Extract Data

> 使用 LLM 从非结构化文本中抽取结构化数据（JSON）。

Source: https://docs.sommatic.ai/zh/nodes/ai.extract/

- 标识: `ai.extract`
- 类别: AI
- 版本: 1.0.0
- 状态: 部分可用. 执行成功时该 worker 不返回端口，引擎会沿 `out` 继续，而该节点并未声明 `out`：从其成功端口引出的连线永远不会触发。修复前，请勿在其成功路径后串接其他节点。
- 执行方式: async

使用 LLM 从非结构化文本中抽取结构化数据（JSON）。

该算子能智能解析邮件、文档或日志，并将其转换为你定义的严格 JSON schema。它使用 LLM（Schema Mode）来保证输出格式。

**适用场景：**
- **发票：** 从 OCR 文本中抽取“Total Amount”“Due Date”“Vendor”。
- **简历：** 从个人简介中抽取“Skills”“Experience”“Contact Info”。
- **客服：** 从聊天记录中抽取“Ticket ID”“Severity”“Sentiment”。

## 配置

- `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。
- `schema` (string, 必填): 定义抽取结构的 JSON Schema 对象。

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

## 输出端口

- `success` (默认): 返回了有效结构。
- `error`: 模型未能抽取出有效 JSON。

## 输入契约

- `input` (string, 必填): 要处理的非结构化文本。

## 输出契约

- `data` (object, 可选): 抽取出的 JSON 对象。

## 在表达式中

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

- `$("Extract Data").item.json.data` (object): 抽取出的 JSON 对象。 **worker 不返回：读取结果为 undefined.**
- `$("Extract Data").item.json.customer_name` (string) = `"Ana Ruiz"` (编辑器不提示)
- `$("Extract Data").item.json.order_id` (string) = `"4521"` (编辑器不提示)
- `$("Extract Data").item.json.amount` (number) = `129.9` (编辑器不提示)
- `$("Extract Data").item.json.currency` (string) = `"USD"` (编辑器不提示)


## 工作原理

把完整的上游载荷连同你的 `schema` 发送给模型，并返回模型提取的 JSON 对象。部分可用：成功时从未声明的 `out` 端口输出。

1. 从节点配置读取 `schema`（或 `structure`）；为空时抛出 `Missing 'schema'`。
2. 把完整的上游载荷对象用 `JSON.stringify` 序列化后作为输入。
3. 发送嵌入 `schema` 且只要求 JSON 的系统提示词，以序列化后的载荷作为用户消息，`temperature: 0`。
4. 去除代码块标记后用严格的 `JSON.parse` 解析回答（不做部分恢复）。解析结果作为节点输出从 `out` 发出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-extract-order",
  "label": "Extract order",
  "operator_slug": "ai.extract",
  "operator_version": "1.0.0",
  "config": {
    "model_id": "wf-llm-provider-xxxx",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "schema": "{\"type\":\"object\",\"properties\":{\"customer_name\":{\"type\":\"string\"},\"order_id\":{\"type\":\"string\"},\"amount\":{\"type\":\"number\"},\"currency\":{\"type\":\"string\"}}}",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "customer_name": "Ana Ruiz",
    "order_id": "4521",
    "amount": 129.9,
    "currency": "USD"
  },
  "port": "out"
}
```

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

### `success`

已声明但从不发出。成功时引擎走 `out`；从 `success` 画出的连线永远不会触发。下列数据为 `out` 携带的内容。

```json
{
  "customer_name": "Ana Ruiz",
  "order_id": "4521",
  "amount": 129.9,
  "currency": "USD"
}
```

### `error`

缺少 `schema`、模型调用失败或回答不是有效 JSON。

```json
{
  "error": "LLM output was not valid JSON"
}
```

## 代码中的行为

- `model_id`: schema 把 `model_id` 列为必填，但 worker 从不读取它；提供方取自 `llm_provider_id`。示例中包含它仅为通过 schema 校验。
- `schema`: 以文本形式插入提示词。请以字符串存储（JSON Schema 或文字描述）；若为对象会被插入为 `[object Object]`。`structure` 是未声明的别名。
- `input`: 无法在节点上设置：运行时会用上游载荷替换，因此模型总是收到上一节点的完整输出。请在上游裁剪该输出（例如用 `data.transform`）以控制发送内容。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'schema'` | `error` | `schema` 和 `structure` 都未设置。 |
| `LLM output was not valid JSON` | `error` | 回答在 JSON 外还有其他文字或格式错误。请收紧 schema 描述，或改用会带纠正信息重试的 `ai.legal.extract.structured-multi-pass`。 |
| `[AiExtract] 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` 为空或不是字符串。请选择具备 chat 能力的 LLM 提供方记录。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用：提供方记录不存在或未激活、提供方报错、配额或内容过滤。请检查提供方记录和后端日志。 |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | sync 模式：对后端的 HTTP 调用失败（网络错误、非 2xx 状态或超时）。长提示词常会触发请求超时，请改用 `invocation_mode: "stream"`。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | stream 模式：在 `timeout_ms` 内未收到任何片段。若流式请求本身失败，消息为 `RemoteApiService.stream: HTTP <status> — <body>`。 |

## 说明与限制

- 已知缺陷：成功路径不返回端口，引擎因此使用节点未声明的 `out`。在修复之前，不要在其成功路径之后串接节点。
- 输出即提取出的对象本身（不包在 `data` 中），`raw` 会被丢弃。结果不会按 `schema` 校验。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- `timeout_ms` 仅在 stream 模式下生效，表示片段之间允许的最长空闲时间（默认 600000）。在 sync 模式下该值只写入日志，不会作用于 HTTP 请求，因此以平台默认请求超时为准。
- 在 stream 模式下，后端端点不应用采样参数，因此固定的 `temperature: 0` 仅在 sync 模式下生效。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.extract",
  "name": "Extract Data",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts structured data (JSON) from unstructured text using an LLM.\n\n  This operator intelligently parses emails, documents, or logs and converts them into a strict JSON schema you define. It uses an LLM (Schema Mode) to guarantee the output format.\n\n  **Use Cases:**\n  - **Invoices:** extracting 'Total Amount', 'Due Date', 'Vendor' from OCR text.\n  - **Resumes:** extracting 'Skills', 'Experience', 'Contact Info' from a bio.\n  - **Support:** extracting 'Ticket ID', 'Severity', 'Sentiment' from a chat log.",
  "capabilities": [
    "llm",
    "extraction",
    "parsing",
    "structured-output"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "model_id",
      "schema"
    ],
    "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
      },
      "schema": {
        "type": "string",
        "title": "Extraction Schema",
        "format": "json",
        "description": "JSON Schema object defining the structure to extract."
      },
      "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": {
      "input": {
        "type": "string",
        "description": "The unstructured text to process."
      }
    },
    "required": [
      "input"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "data": {
        "type": "object",
        "description": "The extracted JSON object."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Extracted",
      "is_default": true,
      "description": "Valid structure returned."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Model failed to extract valid JSON."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "extract",
    "llm",
    "parse"
  ],
  "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",
  "required": [
    "model_id",
    "schema"
  ],
  "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
    },
    "schema": {
      "type": "string",
      "title": "Extraction Schema",
      "format": "json",
      "description": "JSON Schema object defining the structure to extract."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "input": {
      "type": "string",
      "description": "The unstructured text to process."
    }
  },
  "required": [
    "input"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "description": "The extracted JSON object."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Extracted",
    "is_default": true,
    "description": "Valid structure returned."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Model failed to extract valid JSON."
  }
]
```
