feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理

This commit is contained in:
hugo committed 2026-07-22 18:52:43 +08:00
1 parent c4095b08da
commit c35223d49d
148 files changed
+15709 -1353

No files matched your search

@@ -2,6 +2,55 @@
> 适用范围:HXOPS 货代订单抽取内部 Workflow。本文是当前唯一有效的 Dify 画布契约。
## 唯一 Manifest 配置(2026-07-22,优先执行)
> HXOPS 只发送一种 `execution_manifest`。Dify 必须只接受本手册定义的唯一结构。
1. Start 节点继续只保留一个 **String** 输入 `execution_manifest`。
2. `parse_and_prepare_input` 直接读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`;不得读取其他文档集合、确定性表格内部载荷或任何输入格式分支。
3. Code 节点不得期待或生成 HTML、bbox、token、cell_id、evidence_ref、field_code。结构化候选字段仅为 `column_index/field_id/value/quote`;表/行同时带 `status/issues`,候选顶层带 `field_policy`。
4. LLM 对 `field_policy=locked` 的字段必须原样保留稳定 `field_id/value/quote`,只能补充缺失字段;对 `suggested` 候选可结合当前文档短文本判断,但不得把自然语言表头改写为其他 field_id。
5. `unit.intake_no` 必须写入每个订单 `source_intake_no`;`unit.document_id` 必须写入 `primary_document_id` 及每条 Observation 的 `document_id`。End 仍只输出 String 类型 `orders`,内容必须是 JSON 数组,不得附加 think/XML/Markdown 标签。
6. 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。
人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。不得在 Code 节点自行把候选提升为 accepted,不得据此开启自动建单,也不得宣称达到 95% 准确率。
### 单文档证据与跨文档订单的边界(必须遵守)
一个 Unit 只代表 EML 正文或一份附件,不代表完整订单。EML 通常提供 PO、收货/账款信息、Reservation 或沟通上下文;PDF 通常提供订单行、料号和数量。Dify 必须分别返回当前 Document 能逐字证明的字段,**不得**要求 EML 或任一 PDF 单独具有 PO、所有必填 Header、完整订单行、Reservation 或完整订单才能通过校验。
`VALIDATE_AND_NORMALIZE_ORDERS` 的职责仅为 JSON 结构、Schema、当前 Unit 来源、字段类型和明显错位防护;它不做订单完整性、必填字段、跨文档关联、冲突裁决、库存门禁或自动建单判断。HXOPS 在收齐同一 Intake 的全部 Unit 后,才按 PO 或强行身份保守合并、比较所有 Observation,并将无法安全归属或缺少必填信息的结果置为 `needs_review`。因此:
- 某个字段未找到、类型不正确或语义明显错位时,Code 节点应丢弃该字段的 Observation,保留同一 Unit 的其他有效证据;不得让整份 EML/PDF 失败。
- 单文档完全没有可证明字段时,LLM 返回 `{"orders":[]}`,属于成功空结果,不是校验失败。
- 只有 JSON 无法解析、订单/字段结构损坏、Schema/Intake/Document 不一致、Observation 指向其他 Document 等协议或来源越界,才进入失败分支。
- Dify 不可把没有锚点的 EML 证据猜测性并入某份 PDF;是否能合并、是否能创建订单只能由 HXOPS 后端决定。
Reservation 的最终裁决也在 HXOPS:PDF 缺少 `reservation_id` 时,Dify 必须照常返回其可证明的 PO、料号、数量、项次等字段;EML 若有明确 Reservation 也只返回该 Document 自己的 Observation。后端仅在同 Intake、同 PO 下,且邮件/PDF 行可通过**唯一且一致**的 `part_number` 或 `line_no` 关联时,才把合法 Reservation 合并到最终行。重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点时都不得自动补入,必须保留证据并进入 `needs_review`。
自动建单策略不是 Dify 变量。它在“货代配置 → 订单字段模板”中维护:一个总开关,以及每个字段自己的关键字段标记和最低置信度;Run 会冻结开关和字段快照。Dify 不得自行创建订单或绕过 HXOPS 的证据、冲突、重复和 Reservation 门禁。
## 重新识别的 Dify 配置说明
HXOPS 的“按当前规则重新识别”不会调用新的 Dify 节点,也不需要在画布添加循环、重试或版本判断。它创建新的 HXOPS Run,并把当前已发布的 Schema 契约和单文档 manifest 重新发送到已发布 Workflow。管理员只需在修改本手册规定的 Start/Code/LLM/End 节点后发布 Workflow;然后业务用户重新识别即可使用新画布。失败 Run 的“重试”仍复用旧 Run 的冻结 Provider 执行上下文,不能用于验证新 Prompt 或新 Schema。
订单识别异步状态卡也无需 Dify 配置:HXOPS 根据既有 Workflow SSE 事件投影用户阶段、运行时长和健康状态。画布不得为状态卡新增节点、变量、错误正文或浏览器 SSE;Provider 的异常正文只保留在 HXOPS 服务端诊断边界,用户卡片仅显示通用提示。
### L6 证据门禁补充
- Dify 不返回 `evidence_ref`、`cell_id`、bbox 或 token;这些只由 HXOPS 冻结布局和后端裁决生成。
- `field_policy=locked` 仅表示后端已判定字段不可覆盖,不授权 Code/LLM 将 `suggested` 提升为 locked。
- 模型 Observation 仍必须提供逐字 `quote`;confidence 只是弱辅助,不能替代 quote 或 layout cell 证据。
- 纯文本中看似整齐的列不得由 Dify 标记为确定性表格。HXOPS 会以 `plain_text_table_has_no_cell_evidence` 转复核。
## L7 正式切换检查表
- [ ] 人工单元格真值和真实质量/性能指标全部达到 `technical.md` 阈值。
- [ ] Dify 已发布本手册定义的唯一画布,Start 仍只有 String `execution_manifest`。
- [ ] 保持 `auto_create_enabled=false` 完成至少 20 个测试环境真实 Run。
- [ ] 管理员诊断中证据追溯率、issue code 和失败单元均可解释;无错误合并、错误拆分或错误 Task。
- [ ] 业务负责人和技术负责人书面批准后才开启自动建单。
## 1. 边界与运行模型
HXOPS Worker 每次调用 Workflow 时,只传入一个冻结的抽取单元(Unit):一个 Intake 下的一份邮件正文或一份附件。Dify 只读取该 Unit、按冻结 Schema 提取字段并返回 `orders`;不负责合并附件、创建 Candidate/Task、判重、库存、RPA、Excel 或重试。
@@ -44,7 +93,6 @@ End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错
```json
{
"contract_version": "shipping_order_extraction.unit.v2",
"run": {"run_no": "SNER-..."},
"unit": {
"unit_id": 123,
@@ -55,19 +103,29 @@ End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错
"document_type": "attachment"
},
"integrity": {"input_snapshot_hash": "..."},
"extraction_contract": {"schema_version_id": 14, "checksum": "...", "fields": []},
"documents": [
"extraction_contract": {"schema_version_id": 15, "checksum": "...", "fields": []},
"document": {
"document_id": 789,
"filename": "order.pdf",
"document_type": "attachment",
"extracted_text": "..."
},
"structured_table_candidates": [
{
"intake_id": 456,
"intake_no": "SNI-...",
"document": {"document_id": 789, "extracted_text": "..."}
"candidate_id": "p1:table-1",
"page_no": 1,
"table_id": "table-1",
"status": "candidate",
"field_policy": "suggested",
"rows": [{"row_index": 2, "role": "data", "fields": [], "issues": []}],
"issues": ["layout_table_not_accepted"]
}
],
"readonly_hints": []
}
```
`documents` 必须恰好有一项,实际文档位于 `documents[0].document`。同次调用不存在其他附件或兄弟 Document。
`document` 是当前 Unit 的唯一文档;`structured_table_candidates` 是可选的紧凑字段候选。两者都不包含兄弟附件、HTML、bbox、token、cell ID、证据内部 ID 或完整布局载荷。
## 4. Code 节点:parse_and_prepare_input
@@ -84,6 +142,7 @@ End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错
| `primary_document_id` | Number |
| `schema_contract_json` | String |
| `document_json` | String |
| `table_candidates_json` | String |
| `readonly_context_json` | String |
| `header_field_ids_json` | String |
| `line_field_ids_json` | String |
@@ -127,39 +186,47 @@ def _as_int(value, name):
def main(execution_manifest: str):
manifest = _object(_parse_json(execution_manifest, "execution_manifest"), "execution_manifest")
if manifest.get("contract_version") != "shipping_order_extraction.unit.v2":
raise ValueError("unsupported execution_manifest.contract_version")
run = _object(manifest.get("run"), "execution_manifest.run")
unit = _object(manifest.get("unit"), "execution_manifest.unit")
integrity = _object(manifest.get("integrity"), "execution_manifest.integrity")
schema = _object(manifest.get("extraction_contract"), "execution_manifest.extraction_contract")
wrappers = _array(manifest.get("documents"), "execution_manifest.documents")
document = _object(manifest.get("document"), "execution_manifest.document")
table_candidates = _array(
manifest.get("structured_table_candidates", []),
"execution_manifest.structured_table_candidates",
)
readonly_hints = _array(manifest.get("readonly_hints"), "execution_manifest.readonly_hints")
if len(wrappers) != 1:
raise ValueError("unit.v2 requires exactly one document wrapper")
wrapper = _object(wrappers[0], "execution_manifest.documents[0]")
document = _object(wrapper.get("document"), "execution_manifest.documents[0].document")
run_no = str(run.get("run_no") or "").strip()
unit_id = _as_int(unit.get("unit_id"), "unit.unit_id")
intake_no = str(unit.get("intake_no") or "").strip().upper()
document_id = _as_int(unit.get("document_id"), "unit.document_id")
wrapper_intake_no = str(wrapper.get("intake_no") or "").strip().upper()
wrapped_document_id = _as_int(document.get("document_id"), "document.document_id")
manifest_document_id = _as_int(document.get("document_id"), "document.document_id")
checksum = str(schema.get("checksum") or "").strip()
fields = schema.get("fields")
if not run_no or not intake_no or not checksum or not isinstance(fields, list):
raise ValueError("manifest is missing required run, unit, or schema values")
if wrapper_intake_no != intake_no:
raise ValueError("documents[0].intake_no must equal unit.intake_no")
if wrapped_document_id != document_id:
raise ValueError("documents[0].document.document_id must equal unit.document_id")
if manifest_document_id != document_id:
raise ValueError("document.document_id must equal unit.document_id")
if not str(integrity.get("input_snapshot_hash") or "").strip():
raise ValueError("integrity.input_snapshot_hash is required")
allowed_candidate_keys = {
"candidate_id", "page_no", "table_id", "continuation_of", "status",
"field_policy", "rows", "issues",
}
forbidden_keys = {"html", "bbox", "token", "token_ids", "cell_id", "evidence_ref", "field_code"}
for index, candidate in enumerate(table_candidates):
candidate = _object(candidate, f"structured_table_candidates[{index}]")
if set(candidate) - allowed_candidate_keys:
raise ValueError(f"structured_table_candidates[{index}] has unsupported keys")
if candidate.get("field_policy") not in {"locked", "suggested"}:
raise ValueError(f"structured_table_candidates[{index}].field_policy is invalid")
serialized = json.dumps(candidate, ensure_ascii=False).lower()
if any(f'"{key}"' in serialized for key in forbidden_keys):
raise ValueError(f"structured_table_candidates[{index}] contains forbidden layout data")
header_ids = []
line_ids = []
for index, field in enumerate(fields):
@@ -190,7 +257,6 @@ def main(execution_manifest: str):
"intake_no": intake_no,
"filename": str(document.get("filename") or ""),
"document_type": str(document.get("document_type") or unit.get("document_type") or ""),
"classification": str(document.get("classification") or ""),
"extracted_text": str(document.get("extracted_text") or ""),
}
return {
@@ -201,6 +267,9 @@ def main(execution_manifest: str):
"primary_document_id": document_id,
"schema_contract_json": json.dumps(model_schema, ensure_ascii=False, separators=(",", ":")),
"document_json": json.dumps(model_document, ensure_ascii=False, separators=(",", ":")),
"table_candidates_json": json.dumps(
table_candidates, ensure_ascii=False, separators=(",", ":")
),
"readonly_context_json": json.dumps(readonly_hints, ensure_ascii=False, separators=(",", ":")),
"header_field_ids_json": json.dumps(sorted(set(header_ids)), ensure_ascii=False, separators=(",", ":")),
"line_field_ids_json": json.dumps(sorted(set(line_ids)), ensure_ascii=False, separators=(",", ":")),
@@ -211,7 +280,7 @@ def main(execution_manifest: str):
建议参数:Temperature `0`,Top P `0.1`,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。
输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。
输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`table_candidates_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。
### System Prompt
@@ -222,19 +291,57 @@ def main(execution_manifest: str):
你只能读取当前 document_json。不得假设存在邮件正文、其他附件、兄弟 Document 或外部数据;不得跨文档合并、补全、判重、建单、调用工具、查询数据库或读取外部文件。
classification 必须根据当前 document_json.extracted_text 独立判断。document_json 不提供、也不得继承任何上游文档分类;不得根据文件名或既有任务状态回填分类。
固定来源约束:每一条订单的 source_intake_no 必须逐字等于输入 source_intake_no;primary_document_id 必须逐字等于输入 primary_document_id;每个 Observation.document_id 也必须逐字等于输入 primary_document_id。违反任一约束即为无效输出。
仅可使用 schema_contract_json.fields[] 中 collection_mode=llm_extraction 的 stable field_id。Header 字段仅能使用 header_field_ids_json;明细字段仅能使用 line_field_ids_json。不要用 field_code、显示名称或自然语言字段名代替 field_id。
字段没有可信逐字证据时,直接省略该字段;不要输出空 observations、null、默认值、猜测值或模型解释。每个返回的 Observation 必须有 value、document_id、quote 和 0 到 1 的 confidence;quote 必须是当前 document_json.extracted_text 中能直接证明 value 的原文片段。
字段没有可信逐字证据时,直接省略整个字段;不要输出空 observations、null、空字符串、`0` 占位、`not found`/“未找到”占位、猜测值或模型解释。每个返回的 Observation 必须有 value、document_id、quote 和 0 到 1 的 confidence;quote 必须是当前 document_json.extracted_text 中能直接证明 value 的原文片段。不得以 `Unit Price not found`、`项次 not found`、`AWS Sku not found` 等文本充当 quote,也不得在未找到金额/单价时输出数值 `0`。
`quote` 必须包含该 value 的逐字值,或仅经过允许的格式化(大小写、千分位、日期 `MM/DD/YYYY -> YYYY-MM-DD`)后可验证为同一值;不得截断、拼写改写或概括原文。例如 `IEC Technologies` 不能输出为 `iecnologies`。表格被拆为多行、字段归属不明时,宁可省略字段,也不得把裸料号、站点文字、项次或相邻行值猜入任何字段。
必须严格匹配 schema 中每个 field_id 的 value_type:decimal/integer 必须返回 JSON 数字;boolean 必须返回 JSON 布尔值;date 的 value 必须为 `YYYY-MM-DD`。例如原文 `06/22/2026` 的 date value 必须输出 `2026-06-22`,但 quote 仍保留原文 `06/22/2026`。不符合类型或无法规范化时省略字段,不得原样输出非 ISO 日期。
高风险行字段不得按位置或猜测映射:`line_no` 只能是订单行号(如 `00010`);`part_number` 是 HXOPS 内部料号,通常来自明确的 MPN、Supplier Part Number、Vendor Part Number 等供应商/制造商语义;`customer_part_number` 通常来自客户订单中的 `Material`、`Material No`、`Material Number`;`reservation_id` 只能是原文明确标注的 Reservation ID;`inventory_source_hint` 只能是明确库存源/仓库提示,绝不能填行号;`aws_part_number` 只能来自明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。若邮件正文或任一附件已有明确 AWS 料号,必须优先使用该证据,不能用 Material 覆盖。不得以料号、行号、描述、金额或数量互相替代。已发布的精确模板 Profile 可以覆盖裸表头的通常语义;例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法契约,Dify 不得重新改写。
`Item deleted`、`Cancelled` 等删除标记可能独占一行并作用于前一条视觉明细,而非标记后的下一条明细。只有 `table_candidates_json` 已按版面行关系明确将候选行标记为 `role=deleted` 时,才忽略该行;纯文本或拆行文本中不得自行推断删除标记归属,也不得自动删除任何订单行,应保留候选并进入后续复核。若 Reservation ID 没有 `Reservation ID`、`COM ID`、`Reservation Order`、`Reservation No`、`Resv ID`、`PR Number` 或 `External reservation ID` 等明确标签和对应的 5 位或 10 位纯数字,必须省略 `reservation_id`;`EXW AWS HUB`、仓库/站点、贸易术语、项次和料号绝不能填入该字段。
【EML 正文专项规则】
当当前 `document_json.document_type` 为 `email_body`,或当前正文不是具有明确表头和行列关系的表格时,必须按“明确字段标签 + 紧邻逐字证据”提取;禁止按文本相邻位置、出现顺序、常识或空字段补位猜测字段。
`unit_price`、`amount`、`qty` 是数值字段,必须遵守以下规则:
- `unit_price` 只能从明确标注为 `Unit Price`、`Price Each`、`Unit Cost`、`单价`、`价格` 的标签或同一明确表格列提取。
- `amount` 只能从明确标注为 `Amount`、`Line Amount`、`Line Total`、`Total Amount`、`金额`、`小计`、`总价` 的标签或同一明确表格列提取。
- `qty` 只能从明确标注为 `Qty`、`Quantity`、`Order Qty`、`数量`、`需求数量` 的标签或同一明确表格列提取。
- 三者的 `value` 必须是 JSON 数字;不得输出字符串、料号、SKU、MPN、日期、站点或描述。
- 未找到明确标签和逐字证据时,直接省略整个字段;不得填 `0`、不得猜测、不得用相邻字段代替。
料号严格规则:
- 包含字母、连字符、斜杠或典型料号结构的值,例如 `D4-A08AR12000002`、`B3-AR1000270A1`,默认仅可作为料号候选,绝不能填入 `unit_price`、`amount` 或 `qty`。
- 仅当原文明确标注 `MPN`、`Vendor Part Number`、`Supplier Part Number`、`Part Number`、`Material`、`Customer PN`、`AWS SKU` 等语义时,才按当前 Schema 的字段定义填入对应料号字段。
- 料号角色无法可靠判断时直接省略;不得因为价格、金额或数量字段为空而把料号填入数值字段。
示例:正文为 `MPN: D4-A08AR12000002`,但没有 `Unit Price`、`Amount` 或 `Qty` 标签时,只能在 MPN 语义明确且满足当前 Schema 时输出对应料号字段;必须省略 `unit_price`、`amount` 和 `qty`,禁止把 `D4-A08AR12000002` 写入任何数值字段。
`[PROMPT_UPDATE]` 2026-07-22:补充 EML 正文的标签证据门禁,防止 MPN/料号因文本邻近或字段空缺被错填为单价、金额或数量。
`inventory_source_hint` 是可选字段:只有当前行或明确文档级文本含 Source Type、Hub Code、Warehouse、Site、仓库或站点语义时才输出。看到 `00010`、`00020` 等 Item/Line No 时必须输出 `line_no` 或省略,绝不能复制到 `inventory_source_hint`。Reservation ID 只允许原文明确标注的 5 位或 10 位纯数字;字母型编号和其他长度数字均不得输出。
`lines` 只能包含真实的订单货品行。不得把表头、跨页重复表头、空白占位行、版面解析产生的零值伪行输出为明细。`qty`/数量为 `0` 或负数时,默认省略整行;唯一例外是原文明确存在一条真实业务明细行且其数量确为 `0` 或负数:此时仍输出该行的原始逐字证据,让校验节点将其阻断并进入人工复核,绝不能把它伪装成正常订单行。若行号含料号字母,或数字行号被填入 `inventory_source_hint`,说明该行发生列错位;当该错位同时伴随非正数量时,必须省略整行,不得保留任何字段。
`table_candidates_json` 是 Code 节点从后端 `manifest.structured_table_candidates` 转换出的 Dify 内部变量。`field_policy=locked` 的 `field_id/value/quote` 必须原样返回,不得删除、改值或改字段;`field_policy=suggested` 只能作为列归属线索,仍须用当前文档原文判断并允许省略。`role=deleted` 的行不得恢复。不得要求或猜测 HTML、bbox、token、cell ID、evidence_ref 或内部 field_code;候选为空时按普通文档抽取。
Reservation ID、料号、数量、金额、日期等不得根据常识、计算结果、文件名或其他字段反推。readonly_context_json 仅作提示,不得写入 header_fields、lines、conflicts 或输出。
classification 只能是 shipping_request、non_shipping_request 或 uncertain,classification_confidence 必须是 0 到 1 的数字。一个单文档可以有零条、一条或多条独立订单;不得和不存在的 Document 合并。
classification 只能是 shipping_request、non_shipping_request 或 uncertain,classification_confidence 必须是 0 到 1 的数字。采购订单、订单通知、PO、shipping order、delivery request 等需要发货处理的订单文档,一律使用 shipping_request。禁止输出 order_notice、purchase_order、shipping_order、invoice、order、other 或其他自定义分类值。一个单文档可以有零条、一条或多条独立订单;不得和不存在的 Document 合并。
【跨文档补全规则】
当前 Unit 不是完整订单边界。EML 与 PDF 必须各自独立抽取当前文档能证明的片段:EML 可以只返回 PO、地址、Reservation 或联系人;PDF 可以只返回订单行、料号、数量或价格。不得因为当前 Unit 缺少 PO、缺少任何必填 Header、缺少完整 Line、缺少 Reservation,或无法独立建单而返回失败、虚构字段或丢弃已验证证据。不要尝试读取、比较或合并其他 Document;尤其不得把 EML Reservation 复制到当前 PDF 行。HXOPS 会在所有 Unit 成功返回后以唯一强锚点保守关联行、完成冲突裁决和完整性门禁。
最终只输出一个 JSON Object,首字符必须是 {,末字符必须是 }。禁止输出 think、analysis、reasoning、XML/HTML、Markdown、代码围栏、自然语言、日志、Provider 信息或内部配置。
@@ -267,6 +374,9 @@ schema_contract_json:
document_json:
{{#parse_and_prepare_input.document_json#}}
table_candidates_json:
{{#parse_and_prepare_input.table_candidates_json#}}
readonly_context_json:
{{#parse_and_prepare_input.readonly_context_json#}}
@@ -292,7 +402,7 @@ line_field_ids_json:
输出:`orders`(String)、`order_count`(Number)、`validation_ok`(Boolean)、`validation_error`(String)。
`extract_orders.text` 在不同 Dify 版本或模型连接器中可能是 JSON Object、JSON 字符串,或被额外 JSON 编码一次的字符串。验证节点最多解包两层;最终不是含 `orders` 数组的 JSON Object 时必须失败。此兼容仅处理序列化包装,不兼容 Markdown、思考文本或任意前后缀。
`extract_orders.text` 在不同 Dify 版本或模型连接器中可能是 JSON Object、JSON 字符串,或被额外 JSON 编码一次的字符串。验证节点最多解包两层;模型偶发在完整 JSON Object 后额外输出最多两个 `]`/`}` 闭合符时,仅允许移除这些冗余闭合符。最终不是含 `orders` 数组的 JSON Object 时必须失败;不得吞掉 Markdown、思考文本、第二段 JSON 或任意其他前后缀。
将节点代码整体替换为:
@@ -317,7 +427,7 @@ def _parse_json(value, name):
def _parse_llm_output(value):
"""兼容 Dify 对 LLM JSON 输出最多一次额外字符串化。"""
"""兼容 Dify 字符串包装,以及模型偶发的少量冗余 JSON 闭合符。"""
raw = value
for _ in range(2):
if isinstance(raw, dict):
@@ -327,10 +437,18 @@ def _parse_llm_output(value):
text = raw.strip()
if not text:
raise ValueError("llm_output is empty")
if text.startswith("```json") and text.endswith("```"):
text = text[7:-3].strip()
decoder = json.JSONDecoder()
try:
raw = json.loads(text)
parsed, end = decoder.raw_decode(text)
except json.JSONDecodeError as exc:
raise ValueError(f"llm_output is not valid JSON: {exc.msg}") from exc
trailing = text[end:].strip()
if trailing and (len(trailing) > 2 or any(char not in "]}" for char in trailing)):
raise ValueError("llm_output contains unexpected trailing content")
raw = parsed
if isinstance(raw, dict):
return raw
raise ValueError("llm_output must unwrap to a JSON object")
@@ -372,87 +490,182 @@ def _field_map(schema):
"scope": str(field.get("scope") or "").strip().lower(),
"value_type": str(field.get("value_type") or "string").strip().lower(),
"field_code": str(field.get("field_code") or "").strip(),
"display_name": str(field.get("display_name") or field.get("field_code") or "未知字段").strip(),
"required": bool(field.get("required")),
"validator_keys": list(field.get("validator_keys") or []),
}
return result
def _typed_value(value, config, field_id):
"""在 Dify 侧拒绝无法落入冻结 Schema 类型的模型值。"""
def _field_label(config):
"""返回校验日志使用的中文字段名称,禁止向业务用户暴露内部 field_id。"""
return config["display_name"] or config["field_code"] or "未知字段"
def _typed_value(value, config):
"""在 Dify 侧拒绝无法落入冻结 Schema 类型的模型值,并返回业务可读错误。"""
label = _field_label(config)
value_type = config["value_type"]
if value_type == "decimal":
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"{field_id} must be a JSON number")
raise ValueError(f"{label}格式错误:必须是 JSON 数字")
elif value_type == "integer":
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"{field_id} must be a JSON integer")
raise ValueError(f"{label}格式错误:必须是 JSON 整数")
elif value_type == "boolean":
if not isinstance(value, bool):
raise ValueError(f"{field_id} must be a JSON boolean")
raise ValueError(f"{label}格式错误:必须是 JSON 布尔值")
elif value_type == "date":
if not isinstance(value, str):
raise ValueError(f"{field_id} must be an ISO date string")
raise ValueError(f"{label}格式错误:必须是 YYYY-MM-DD 日期")
try:
date.fromisoformat(value)
except ValueError as exc:
raise ValueError(f"{field_id} must use YYYY-MM-DD") from exc
raise ValueError(f"{label}格式错误:必须使用 YYYY-MM-DD") from exc
elif value_type in {"string", "enum"}:
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{field_id} must be a non-empty string")
raise ValueError(f"{label}格式错误:必须是非空文本")
return value
def _validate_field_semantics(value, config, field_id):
"""拦截模型常见的列位置错配,避免错误字段作为成功 Unit 进入 HXOPS。"""
code = config["field_code"]
label = _field_label(config)
validators = set(config["validator_keys"])
if "positive_decimal" in validators or "positive_integer" in validators:
if value <= 0:
raise ValueError(f"{field_id} must be positive")
raise ValueError(f"{label}必须大于 0")
if code == "line_no" and re.search(r"[A-Za-z]", value):
raise ValueError("line_no must not contain a part number")
raise ValueError("项次不能包含料号")
if code == "inventory_source_hint" and re.fullmatch(r"\d+", value.strip()):
raise ValueError("inventory_source_hint must not be a line number")
if code == "reservation_id" and not re.fullmatch(r"\d{8,20}", value.strip()):
raise ValueError("reservation_id must be an explicit numeric reservation identifier")
raise ValueError("库存源线索不能是项次")
if code == "reservation_id" and not re.fullmatch(r"(?:\d{5}|\d{10})", value.strip()):
raise ValueError("预订单号必须恰好为 5 位或 10 位数字")
return value
def _can_drop_field_error(error):
"""字段不完整或错位只丢弃该证据;完整性由 HXOPS 在跨文档聚合后判断。"""
return isinstance(error, ValueError)
def _is_missing_evidence_observation(observation):
"""丢弃模型明确表示未找到的占位输出;其他类型、来源或语义错误继续严格失败。"""
quote = str(observation.get("quote") or "").strip()
value = observation.get("value")
if not quote:
return True
lowered_quote = quote.lower()
if "not found" in lowered_quote or "未找到" in quote:
return True
if isinstance(value, str) and not value.strip():
return True
return False
def _is_discardable_zero_quantity_pseudo_line(line, fields):
"""仅丢弃有可验证列错位证据的零值伪行;真实零数量行仍须严格失败并复核。"""
items = line.get("fields") if isinstance(line, dict) else None
if not isinstance(items, list):
return False
has_non_positive_qty = False
has_invalid_line_no = False
has_numeric_inventory_hint = False
for item in items:
if not isinstance(item, dict):
continue
config = fields.get(str(item.get("field_id") or "").strip())
observations = item.get("observations")
if not config or not isinstance(observations, list):
continue
for observation in observations:
if not isinstance(observation, dict) or _is_missing_evidence_observation(observation):
continue
value = observation.get("value")
code = config["field_code"]
if code == "qty" and isinstance(value, (int, float)) and not isinstance(value, bool) and value <= 0:
has_non_positive_qty = True
elif code == "line_no" and isinstance(value, str) and re.search(r"[A-Za-z]", value):
has_invalid_line_no = True
elif code == "inventory_source_hint" and isinstance(value, str) and re.fullmatch(r"\d+", value.strip()):
has_numeric_inventory_hint = True
return has_non_positive_qty and (has_invalid_line_no or has_numeric_inventory_hint)
def _quote_supports_value(value, quote, value_type):
"""只保留能从逐字引文验证的候选值,允许日期和数字的标准化表示。"""
if value_type == "date" and isinstance(value, str):
try:
parsed = date.fromisoformat(value)
except ValueError:
return False
return parsed.strftime("%m/%d/%Y") in quote or value in quote
if value_type in {"decimal", "integer"} and isinstance(value, (int, float)) and not isinstance(value, bool):
target = float(value)
for token in re.findall(r"[-+]?\d[\d,]*(?:\.\d+)?", quote):
try:
if float(token.replace(",", "")) == target:
return True
except ValueError:
pass
return False
normalized_value = re.sub(r"[^a-z0-9]+", "", str(value).lower())
normalized_quote = re.sub(r"[^a-z0-9]+", "", quote.lower())
return bool(normalized_value) and normalized_value in normalized_quote
def _field_group(items, scope, fields, document_id):
if items is None:
return []
if not isinstance(items, list):
raise ValueError(f"{scope} fields must be an array")
result = []
seen = set()
result_by_field_id = {}
for item in items:
if not isinstance(item, dict):
raise ValueError(f"{scope} field must be an object")
raise ValueError(f"{scope}字段必须是对象")
field_id = str(item.get("field_id") or "").strip()
config = fields.get(field_id)
if not field_id or field_id in seen or not config or config["scope"] != scope:
raise ValueError(f"invalid {scope} field_id")
seen.add(field_id)
if not field_id or not config or config["scope"] != scope:
raise ValueError(f"无效的{scope}字段")
label = _field_label(config)
observations = item.get("observations")
if not isinstance(observations, list) or not observations:
raise ValueError(f"{field_id} must have at least one observation")
raise ValueError(f"{label}至少需要一条证据")
normalized = []
for observation in observations:
if not isinstance(observation, dict) or "value" not in observation:
raise ValueError(f"invalid observation for {field_id}")
raise ValueError(f"{label}存在无效证据")
if _is_missing_evidence_observation(observation):
continue
if _as_int(observation.get("document_id"), "observation.document_id") != document_id:
raise ValueError("observation.document_id must equal unit primary_document_id")
quote = str(observation.get("quote") or "").strip()
if not quote:
raise ValueError(f"observation quote is required for {field_id}")
value = _typed_value(observation.get("value"), config, field_id)
try:
# [STEP 1] 单文档不完整是正常状态;字段错位或类型错误只丢弃该 Observation。
value = _typed_value(observation.get("value"), config)
value = _validate_field_semantics(value, config, field_id)
if not _quote_supports_value(value, quote, config["value_type"]):
raise ValueError(f"{label}的取值无法由原文证据验证")
except ValueError as exc:
if _can_drop_field_error(exc):
continue
raise
normalized.append({
"value": _validate_field_semantics(value, config, field_id),
"value": value,
"document_id": document_id,
"quote": quote,
"confidence": _confidence(observation.get("confidence"), "observation.confidence"),
})
result.append({"field_id": field_id, "observations": normalized})
if normalized:
# [STEP 2] 同字段的多次模型输出合并为多条证据,交由 HXOPS 后端统一裁决冲突。
existing = result_by_field_id.get(field_id)
if existing is None:
existing = {"field_id": field_id, "observations": []}
result_by_field_id[field_id] = existing
result.append(existing)
existing["observations"].extend(normalized)
return result
@@ -476,12 +689,28 @@ def main(llm_output, schema_contract_json: str, source_intake_no: str, primary_d
raise ValueError("source_intake_no must equal unit intake_no")
if _as_int(order.get("primary_document_id"), "primary_document_id") != expected_document:
raise ValueError("primary_document_id must equal unit document_id")
# 兼容旧 Prompt 曾输出的订单类分类,归一化后仍只保留三个业务规范值。
classification = str(order.get("classification") or "").strip().lower()
classification = {
"order_notice": "shipping_request",
"purchase_order": "shipping_request",
"shipping_order": "shipping_request",
}.get(classification, classification)
if classification not in {"shipping_request", "non_shipping_request", "uncertain"}:
raise ValueError("invalid classification")
raise ValueError("订单分类无效,仅支持发货请求、非发货请求或待确认")
lines = order.get("lines") or []
if not isinstance(lines, list):
raise ValueError("lines must be an array")
normalized_lines = []
for line in lines:
if not isinstance(line, dict):
raise ValueError("line must be an object")
# 只忽略“非正数量 + 可证明列错位”的版面伪行;其他无效字段会在字段级被省略。
if _is_discardable_zero_quantity_pseudo_line(line, fields):
continue
line_fields = _field_group(line.get("fields"), "line", fields, expected_document)
if line_fields:
normalized_lines.append({"fields": line_fields})
normalized_orders.append({
"schema_version_id": expected_schema_id,
"schema_checksum": expected_checksum,
@@ -490,7 +719,7 @@ def main(llm_output, schema_contract_json: str, source_intake_no: str, primary_d
"source_intake_no": expected_intake,
"primary_document_id": expected_document,
"header_fields": _field_group(order.get("header_fields"), "header", fields, expected_document),
"lines": [{"fields": _field_group(line.get("fields"), "line", fields, expected_document)} for line in lines if isinstance(line, dict)],
"lines": normalized_lines,
"conflicts": order.get("conflicts") if isinstance(order.get("conflicts"), list) else [],
})
return {
@@ -534,14 +763,33 @@ End 节点只配置:
- 裸 `Part Number` 存在客户模板歧义,不应作为跨客户强制语义。已确认模板使用精确 Profile 表达 `Part Number -> customer_part_number`、`Vendor Item# -> part_number`;这类映射是合法模板规则,不是异常,不应复制为 Dify Prompt 中的全局特例。
- `qty` 可增加已经确认仍为独立数量列的完整精确别名,例如 `Q TY 数量`、`Q'TY 数量`、`Q TY UNIT`、`ORDER QUANTITY EA`。不得配置 `Quantity U M Delivery`,该文本同时粘连数量、单位和交期,无法证明单一列语义。
- 不得为含首条数据的污染表头增加别名,例如 `Item No 00010`、`Order Amount 941.76`。这类结果必须由版面质量门禁转复核,不能把样本值写入 Schema。
- `reservation_id` 每条订单行最终都必须具备,但证据可能位于邮件正文或其他附件。单张 PDF 缺失 Reservation 时应保留其确定性行字段,由邮件/其他附件单元补充;补充失败时停在流程门禁,禁止进入库存匹配和发货 Excel。
- `reservation_id` 每条订单行最终都必须具备,但证据可能位于邮件正文或其他附件。单张 PDF 缺失 Reservation 时应保留其确定性行字段;只有同 Intake、同 PO 下能以唯一且一致的内部料号或项次关联到邮件/附件 Reservation 时,HXOPS 才补入最终行。重复料号、项次冲突、多个候选或无强锚点一律不得猜测,补充失败时停在流程门禁,禁止进入库存匹配和发货 Excel。
- 保存或发布前检查标准化别名碰撞;同一字段在一张表命中多个列时必须进入复核,不得通过调整 Prompt 让模型选择其中一列。
上述 Schema 修改在 HXOPS 管理端手工完成,不在 Dify Code/LLM 节点复制别名字典。
### 8.2 MinerU/Profile 接入后的 Dify 画布
本阶段不新增 Start 变量,仍只有 String 类型 `execution_manifest`。手工修改清单:
- Code 节点解析 `manifest.document` 和可选的 `manifest.structured_table_candidates`,不存在时返回空数组,不得因可选字段缺失报错。
- LLM Prompt 使用本手册 `table_candidates_json` 约束;不得要求 MinerU HTML 或坐标,也不得在 Dify 再维护 Profile 映射字典。
- End 输出保持原 `orders` String 契约,不增加 Profile/布局调试输出。
- 对候选中的 `status=deleted` 行直接忽略;`needs_review` 行只能作为补充线索,不能直接作为完整订单行。
- Dify 不调用 MinerU,不配置 MinerU URL;MinerU 只由 HXOPS 独立文档布局 Worker 调用,Intake 仅负责创建版本化布局任务。
- Profile 的样本选择、列映射、新版本、发布和退役全部在 HXOPS 管理端完成;Dify 不新增 Profile 管理 Tool,不读取 Profile 管理 API,也不维护模板映射副本。
L1 只调整 HXOPS 内部布局生命周期,不改变 `execution_manifest`、LLM Prompt、校验节点或 End 输出;如果当前画布已按本节完成配置,本阶段 **无需再次修改 Dify**。
L2 新增的 PDFium/OpenCV `layout_candidate` 只保存在 HXOPS 布局版本内部,并固定为 `needs_review`;它不会进入 `execution_manifest`。因此 L2 同样 **无需修改 Dify**。
L3 的 RapidOCR 坐标候选和清洗后 EML HTML DOM 布局也只保存在 HXOPS 内部,不会把 OCR 坐标、原始 HTML 或 `layout_candidate` 发送给 Workflow。因此 L3 **无需修改 Dify**。
L4 的 `layout_schema_candidates` 只冻结在 HXOPS Run snapshot v3 中,并在编译 Workflow Manifest 时强制删除。当前画布不会收到 cell/token/evidence_ref,因此 L4 **无需修改 Dify**。
- [ ] Start 仅有 `execution_manifest`,且为 String。
- [ ] `parse_and_prepare_input` 只接受 `shipping_order_extraction.unit.v2`。
- [ ] 代码要求 `documents` 长度恰为 1,并且只读取 `documents[0].document`。
- [ ] `parse_and_prepare_input` 只读取本手册定义的唯一 Manifest 字段。
- [ ] 代码只读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`,不再读取 `documents[0].document`。
- [ ] LLM 仅收到 `document_json`,没有 `documents_json`、附件集合或整封邮件拼接输入。
- [ ] LLM 明确固定 `source_intake_no`、`primary_document_id` 和所有 Observation 的 `document_id`。
- [ ] LLM 不输出没有证据的字段;不输出空 Observation。
@@ -552,6 +800,9 @@ End 节点只配置:
- [ ] 明确的 AWS SKU/APN 证据优先于 Material,且 Material 不覆盖已有 AWS 料号。
- [ ] Qty 只配置语义单一的完整表头;多语义粘连表头和含首条数据的污染表头未进入 Schema aliases。
- [ ] 单张 PDF 缺少 Reservation 时仍保留其确定性字段;邮件/其他附件负责补充,Dify 不伪造 Reservation,HXOPS 最终流程门禁负责阻断库存匹配。
- [ ] 同 PO 的 EML/PDF 仅在唯一且一致的 `part_number` 或 `line_no` 下跨文档补入 Reservation;重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点必须保持 `needs_review`,不得自动复制 Reservation。
- [ ] EML 或单张 PDF 缺少 PO、必填 Header、完整 Line 或 Reservation 时,Code 节点仍返回其余当前 Document 的有效证据;不得以“订单号至少需要一条证据”或任何订单完整性判断进入失败分支。
- [ ] Code 节点仅因 JSON/结构、Schema、Intake/Document 来源不一致等协议错误失败;字段缺失、字段类型不符或明显字段错位只丢弃该字段,并由 HXOPS 跨文档合并后决定 `needs_review` 或后续处理。
- [ ] 校验节点对每个订单及每个 Observation 强制当前 Unit 的 Intake/Document 归属。
- [ ] 校验失败进入失败分支,不返回成功空数组。
- [ ] End 只有 String 类型的 `orders`,API 响应顶层键为 `outputs.orders`。
@@ -561,4 +812,6 @@ End 节点只配置:
发布 Dify 后,创建一次新的订单抽取 Run。管理员诊断中,每个 Unit 应独立成功或失败;某个 Unit 的 `orders`、`primary_document_id` 和所有 Observation `document_id` 必须一致。跨文档字段合并只会在 HXOPS 后端发生。
对 PDF,Dify 的 `quote` 必须逐字引用本次输入 `document_json.extracted_text` 中的 MinerU 分页文本或 TSV 表格。HXOPS 会使用**同一个 Run 冻结且实际发送给 Dify 的文本**优先核验 quote,数据库旧 PDF 文本只作为兼容回退;这不会放宽 quote 或 value 校验。若 quote 不存在于冻结 MinerU 文本和旧文本两者,Observation 必须被拒绝并进入复核。
Workflow 成功不代表 Task 已创建。HXOPS 仍会执行动态 Schema、Reservation 证据、重复检测、客户影子识别和自动建单开关等门禁。