53 KiB
订单抽取服务 Dify Workflow 历史退役说明
自 2026-07-27 阶段 1 起,HXOPS 订单抽取主链已完全退役 Dify Workflow、Provider 和 Runtime Binding。本文保留旧画布资料供历史 Run 与审计溯源,不是有效配置手册,禁止按本文新建、发布或修改订单抽取 Dify 画布。
当前有效边界:订单 Run 仅执行本地确定性模板解析;无法确定的文档进入人工复核。状态卡、重试、重新识别和审计均由 HXOPS 管理,Dify 无需任何订单抽取配置。
唯一 Manifest 配置(2026-07-22,优先执行)
HXOPS 只发送一种
execution_manifest。Dify 必须只接受本手册定义的唯一结构。
- Start 节点继续只保留一个 String 输入
execution_manifest。 parse_and_prepare_input直接读取manifest.document和可选的manifest.structured_table_candidates;不得读取其他文档集合、确定性表格内部载荷或任何输入格式分支。- Code 节点不得期待或生成 HTML、bbox、token、cell_id、evidence_ref、field_code。结构化候选字段仅为
column_index/field_id/value/quote;表/行同时带status/issues,候选顶层带field_policy。 - LLM 对
field_policy=locked的字段必须原样保留稳定field_id/value/quote,只能补充缺失字段;对suggested候选可结合当前文档短文本判断,但不得把自然语言表头改写为其他 field_id。 - HXOPS 的订单级字段模板在后端以页级字符坐标提取。模板已产生
confirmed的 Header 字段不会注入 Dify,Dify 省略这些字段是合法的;Dify 只补充未配置、needs_review或unavailable的 Header 字段。若 Workflow 仍输出同一已确认field_id,其值必须与后端结果一致;发生冲突时 HXOPS 会拒绝该 Unit 输出,并以自己的页级坐标 Observation 替换一致的 Provider Observation。 unit.intake_no必须写入每个订单source_intake_no;unit.document_id必须写入primary_document_id及每条 Observation 的document_id。End 输出 String 类型orders;内容可为 JSON 数组、{"orders":[...]}或{"data":{"orders":[...]}},不得附加 think/XML/Markdown 标签。- 关闭
retriever_resource;该 Workflow 不得有知识库检索、工具调用、外部 HTTP、数据库读取或其他可取得 Unit 外信息的节点。 - LLM 节点必须显式设置 Temperature
0、Top P0.1;关闭 Streaming、Memory 和 Conversation History;模型支持时启用 JSON Object 响应格式。不得依赖 Provider 默认参数。 - 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation,以及已确认订单字段原样保留与未确认订单字段补充。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。
人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。Dify 结果无论置信度多高一律为 provisional,必须由用户在 HXOPS 人工采纳后才能进入履约;不得在 Code 节点输出 _hxops_* 内部字段、自行把候选提升为 accepted、开启自动建单或宣称达到 95% 准确率。唯一已发布且盲测批准的确定性模板由 HXOPS 后端标记为自动采纳,Dify 不能模拟该标记。
模板路由审计(无需修改 Dify)
HXOPS 在每个 Unit 进入分流前追加一条不可变、脱敏的模板路由决策;该动作不新增 Start 输入、变量、节点、Tool 或 Prompt。管理员只需保持本手册的既有画布契约:当 HXOPS 因模板歧义、布局漂移、证据不足、模板未获盲测批准或行/字段门禁回退时,Workflow 照常接收原有 execution_manifest 并仅处理该 Unit。路由原因、候选 Profile、缺失锚点 ID 和执行路径由 HXOPS 管理端诊断展示;Dify 不读取、不回传或修改它们。
单文档证据与跨文档订单的边界(必须遵守)
一个 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 后端决定。
- 当前 Document 之外的任何邮件正文、附件或既有 Run 数据均不可读取、引用或作为“优先证据”。例如 AWS 料号只有在当前
document_json中存在明确标签和逐字证据时才能返回;不得因其他 Unit 的 AWS 料号覆盖或补全当前 Unit 的Material等字段。
Reservation 的最终裁决也在 HXOPS:PDF 缺少 reservation_id 时,Dify 必须照常返回其可证明的 PO、料号、数量、项次等字段;EML 若有明确 Reservation 也只返回该 Document 自己的 Observation。后端仅在同 Intake、同 PO 下,且邮件/PDF 行可通过唯一且一致的 part_number 或 line_no 关联时,才把合法 Reservation 合并到最终行。重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点时都不得自动补入,必须保留证据并进入 needs_review。
自动建单策略不是 Dify 变量。它在“货代配置 → 订单 Schema”中随 Schema 版本草稿 维护:一个总开关(写入版本 definition.auto_creation_policy,发布后生效),以及每个字段自己的关键字段标记和最低置信度;Run 会冻结开关和字段快照。直接改容器开关的旧 PUT 已废弃。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。 - 已关闭 Retriever Resource,且画布没有知识库检索、工具、HTTP 或跨文档读取节点。
- LLM 参数已显式设置为 Temperature
0、Top P0.1,并关闭 Streaming、Memory、Conversation History;支持时启用 JSON Object 输出。 - 提示词只允许使用当前
document_json;未以其他邮件正文或附件的 AWS 料号、PO、Reservation 等信息补全当前 Unit。 - 保持
auto_create_enabled=false完成至少 20 个测试环境真实 Run。 - 管理员诊断中证据追溯率、issue code 和失败单元均可解释;无错误合并、错误拆分或错误 Task。
- 业务负责人和技术负责人书面批准后才开启自动建单。
1. 边界与运行模型
HXOPS Worker 每次调用 Workflow 时,只传入一个冻结的抽取单元(Unit):一个 Intake 下的一份邮件正文或一份附件。Dify 只读取该 Unit、按冻结 Schema 提取字段并返回 orders;不负责合并附件、创建 Candidate/Task、判重、库存、RPA、Excel 或重试。
HXOPS Run / Plan
-> 一个 Unit(一个 Document)
-> Dify Workflow(无状态)
-> 当前 Unit 的 orders
-> HXOPS 校验、跨文档保守合并、Candidate/Task 门禁
不要在 Dify 中增加循环、并行、延迟重试、跨附件拼接、HTTP 建单或数据库读取。HXOPS 已负责 Unit 并发、局部重试、Provider 限流、熔断和跨文档合并。
2. 画布拓扑
Start
-> Code: parse_and_prepare_input
-> LLM: extract_orders
-> Code: validate_and_normalize_orders
-> If/Else: check_validation
true -> End: workflow_end
false -> Code: raise_validation_error -> Workflow Failed
End 只能输出 orders。HXOPS 兼容 End 将其包装为 data.orders,但不接受任意深层 JSON 搜索。失败分支必须抛出异常,不能将校验错误伪装为成功的空订单。
3. Start 节点
仅配置一个必填 String 输入:
| 变量名 | 必填 | 说明 |
|---|---|---|
execution_manifest |
是 | HXOPS Worker 发送的冻结 JSON 字符串 |
不得添加 documents、unit_id、用户 ID、Provider ID、API Key 或其他顶层输入。
输入示例(仅用于理解,实际由 HXOPS 生成):
{
"run": {"run_no": "SNER-..."},
"unit": {
"unit_id": 123,
"unit_type": "document_extraction",
"intake_id": 456,
"intake_no": "SNI-...",
"document_id": 789,
"document_type": "attachment"
},
"integrity": {"input_snapshot_hash": "..."},
"extraction_contract": {"schema_version_id": 15, "checksum": "...", "fields": []},
"document": {
"document_id": 789,
"filename": "order.pdf",
"document_type": "attachment",
"extracted_text": "..."
},
"structured_table_candidates": [
{
"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": []
}
document 是当前 Unit 的唯一文档;structured_table_candidates 是可选的紧凑字段候选。两者都不包含兄弟附件、HTML、bbox、token、cell ID、证据内部 ID 或完整布局载荷。
4. Code 节点:parse_and_prepare_input
输入:execution_manifest = Start.execution_manifest。
输出变量及类型:
| 变量名 | 类型 |
|---|---|
run_no |
String |
unit_id |
Number |
unit_type |
String |
source_intake_no |
String |
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 |
将节点代码整体替换为:
import json
def _parse_json(value, name):
if isinstance(value, (dict, list)):
return value
text = str(value or "").strip()
if not text:
raise ValueError(f"{name} is required")
try:
return json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError(f"{name} must be valid JSON: {exc.msg}") from exc
def _object(value, name):
if not isinstance(value, dict):
raise ValueError(f"{name} must be an object")
return value
def _array(value, name):
if not isinstance(value, list):
raise ValueError(f"{name} must be an array")
return value
def _as_int(value, name):
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"{name} must be an integer") from exc
def main(execution_manifest: str):
manifest = _object(_parse_json(execution_manifest, "execution_manifest"), "execution_manifest")
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")
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")
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")
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 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):
if not isinstance(field, dict):
raise ValueError(f"schema field {index} must be an object")
field_id = str(field.get("field_id") or "").strip()
if not field_id:
raise ValueError(f"schema field {index} has no field_id")
if field.get("collection_mode", "llm_extraction") != "llm_extraction":
continue
scope = str(field.get("scope") or "").strip().lower()
if scope == "header":
header_ids.append(field_id)
elif scope == "line":
line_ids.append(field_id)
else:
raise ValueError(f"schema field {field_id} has invalid scope")
model_schema = {
"schema_version_id": schema.get("schema_version_id"),
"schema_version": schema.get("schema_version"),
"checksum": checksum,
"fields": fields,
"submission_contract": schema.get("submission_contract", {}),
}
model_document = {
"document_id": document_id,
"intake_no": intake_no,
"filename": str(document.get("filename") or ""),
"document_type": str(document.get("document_type") or unit.get("document_type") or ""),
"extracted_text": str(document.get("extracted_text") or ""),
}
return {
"run_no": run_no,
"unit_id": unit_id,
"unit_type": str(unit.get("unit_type") or ""),
"source_intake_no": intake_no,
"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=(",", ":")),
}
5. LLM 节点:extract_orders
必须显式设置:Temperature 0,Top P 0.1,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。禁止保留空参数而依赖 Provider 默认值。
输入变量: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
你是 HXOPS 货运订单抽取 Workflow 的结构化识别节点。
本次调用只处理一个 Unit 和一个 Document。你的唯一任务是:读取 document_json 中的当前文档,按 schema_contract_json.fields[] 提取可被原文证明的订单字段,并只返回严格 JSON Object。
你只能读取当前 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、空字符串、`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` 只能来自**当前 `document_json`** 中明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。不得读取或用邮件正文、其他附件或其他 Unit 的 AWS 料号覆盖当前 Document 的 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 的数字。采购订单、订单通知、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 信息或内部配置。
输出格式:
{"orders":[{"schema_version_id":123,"schema_checksum":"schema checksum","classification":"shipping_request","classification_confidence":0.98,"source_intake_no":"输入原值","primary_document_id":456,"header_fields":[{"field_id":"...","observations":[{"value":"...","document_id":456,"quote":"原文","confidence":0.98}]}],"lines":[{"fields":[]}],"conflicts":[]}]}
若没有识别出订单,返回 {"orders":[]}。
User Prompt
请只识别当前 Unit 的当前文档,不要读取或推测其他文档。
run_no:
{{#parse_and_prepare_input.run_no#}}
unit_id:
{{#parse_and_prepare_input.unit_id#}}
source_intake_no(所有订单必须原样写回):
{{#parse_and_prepare_input.source_intake_no#}}
primary_document_id(所有订单和 Observation 必须原样写回):
{{#parse_and_prepare_input.primary_document_id#}}
schema_contract_json:
{{#parse_and_prepare_input.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#}}
header_field_ids_json:
{{#parse_and_prepare_input.header_field_ids_json#}}
line_field_ids_json:
{{#parse_and_prepare_input.line_field_ids_json#}}
只返回 {"orders": [...]} 或 {"orders":[]},不要输出任何其他文字。
6. Code 节点:validate_and_normalize_orders
输入:
| 变量 | 来源 |
|---|---|
llm_output |
extract_orders.text |
schema_contract_json |
parse_and_prepare_input.schema_contract_json |
source_intake_no |
parse_and_prepare_input.source_intake_no |
primary_document_id |
parse_and_prepare_input.primary_document_id |
输出:orders(String)、order_count(Number)、validation_ok(Boolean)、validation_error(String)。
extract_orders.text 在不同 Dify 版本或模型连接器中可能是 JSON Object、JSON 字符串,或被额外 JSON 编码一次的字符串。验证节点最多解包两层;模型偶发在完整 JSON Object 后额外输出最多两个 ]/} 闭合符时,仅允许移除这些冗余闭合符。最终不是含 orders 数组的 JSON Object 时必须失败;不得吞掉 Markdown、思考文本、第二段 JSON 或任意其他前后缀。
将节点代码整体替换为:
import json
import re
from datetime import date
def _parse_json(value, name):
if isinstance(value, (dict, list)):
return value
text = str(value or "").strip()
if not text:
raise ValueError(f"{name} is empty")
if text.startswith("```json") and text.endswith("```"):
text = text[7:-3].strip()
try:
return json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError(f"{name} is not valid JSON: {exc.msg}") from exc
def _parse_llm_output(value):
"""兼容 Dify 字符串包装,以及模型偶发的少量冗余 JSON 闭合符。"""
raw = value
for _ in range(2):
if isinstance(raw, dict):
return raw
if not isinstance(raw, str):
raise ValueError("llm_output must be a JSON object or JSON string")
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:
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")
def _as_int(value, name):
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"{name} must be an integer") from exc
def _confidence(value, name):
try:
result = float(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"{name} must be numeric") from exc
if not 0 <= result <= 1:
raise ValueError(f"{name} must be between 0 and 1")
return result
def _orders(raw):
if isinstance(raw, dict) and isinstance(raw.get("orders"), list):
return raw["orders"]
raise ValueError("LLM output must be an object containing orders array")
def _field_map(schema):
fields = schema.get("fields") if isinstance(schema, dict) else None
if not isinstance(fields, list):
raise ValueError("schema_contract_json.fields must be an array")
result = {}
for field in fields:
if isinstance(field, dict) and field.get("collection_mode", "llm_extraction") == "llm_extraction":
field_id = str(field.get("field_id") or "").strip()
if field_id:
result[field_id] = {
"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 _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"{label}格式错误:必须是 JSON 数字")
elif value_type == "integer":
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"{label}格式错误:必须是 JSON 整数")
elif value_type == "boolean":
if not isinstance(value, bool):
raise ValueError(f"{label}格式错误:必须是 JSON 布尔值")
elif value_type == "date":
if not isinstance(value, str):
raise ValueError(f"{label}格式错误:必须是 YYYY-MM-DD 日期")
try:
date.fromisoformat(value)
except ValueError as 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"{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"{label}必须大于 0")
if code == "line_no" and re.search(r"[A-Za-z]", value):
raise ValueError("项次不能包含料号")
if code == "inventory_source_hint" and re.fullmatch(r"\d+", value.strip()):
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 = []
result_by_field_id = {}
for item in items:
if not isinstance(item, dict):
raise ValueError(f"{scope}字段必须是对象")
field_id = str(item.get("field_id") or "").strip()
config = fields.get(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"{label}至少需要一条证据")
normalized = []
for observation in observations:
if not isinstance(observation, dict) or "value" not in observation:
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()
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": value,
"document_id": document_id,
"quote": quote,
"confidence": _confidence(observation.get("confidence"), "observation.confidence"),
})
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
def main(llm_output, schema_contract_json: str, source_intake_no: str, primary_document_id):
try:
schema = _parse_json(schema_contract_json, "schema_contract_json")
expected_intake = str(source_intake_no or "").strip().upper()
expected_document = _as_int(primary_document_id, "primary_document_id")
expected_schema_id = _as_int(schema.get("schema_version_id"), "schema.schema_version_id")
expected_checksum = str(schema.get("checksum") or "").strip()
fields = _field_map(schema)
normalized_orders = []
for order in _orders(_parse_llm_output(llm_output)):
if not isinstance(order, dict):
raise ValueError("each order must be an object")
if _as_int(order.get("schema_version_id"), "schema_version_id") != expected_schema_id:
raise ValueError("schema_version_id mismatch")
if str(order.get("schema_checksum") or "").strip() != expected_checksum:
raise ValueError("schema_checksum mismatch")
if str(order.get("source_intake_no") or "").strip().upper() != expected_intake:
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("订单分类无效,仅支持发货请求、非发货请求或待确认")
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,
"classification": classification,
"classification_confidence": _confidence(order.get("classification_confidence"), "classification_confidence"),
"source_intake_no": expected_intake,
"primary_document_id": expected_document,
"header_fields": _field_group(order.get("header_fields"), "header", fields, expected_document),
"lines": normalized_lines,
"conflicts": order.get("conflicts") if isinstance(order.get("conflicts"), list) else [],
})
return {
"orders": json.dumps(normalized_orders, ensure_ascii=False, separators=(",", ":")),
"order_count": len(normalized_orders),
"validation_ok": True,
"validation_error": "",
}
except Exception as exc:
return {"orders": "[]", "order_count": 0, "validation_ok": False, "validation_error": str(exc)[:500]}
7. If/Else、错误与 End 节点
check_validation 的条件:validate_and_normalize_orders.validation_ok is true。
失败分支的 raise_validation_error:
def main(validation_error: str):
raise ValueError(str(validation_error or "LLM order extraction output validation failed")[:500])
End 节点只配置:
| 输出变量 | 类型 | 值 |
|---|---|---|
orders |
String | validate_and_normalize_orders.orders |
不要输出 result、data、answer、日志、思考内容或错误详情。HXOPS 只读取 outputs.orders。
8. 手工配置验收
8.1 HXOPS 发布 Schema 表头别名
在重新发布订单 Schema 前,管理员必须检查确定性表格别名。表头别名是全局精确规则,不是 LLM 提示词;一旦配置,后端会在所有客户模板中按该语义执行。
- 从
aws_part_number删除裸Material、Material No、Material Number,并将这些别名配置到customer_part_number。aws_part_number只保留明确含 AWS/APN 业务限定的表头,例如AWS SKU、AWS Part Number、Allocated APN。 Item、Item No可作为line_no的全局别名,但只表示订单行序号;不得同时配置到任何料号字段。part_number保留明确的内部/供应商料号表头,例如Supplier Part Number、Vendor Part Number、MPN;不得把客户订单的裸 Material 当作内部料号。- 裸
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 时应保留其确定性行字段;只有同 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 输出保持原
ordersString 契约,不增加 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只读取本手册定义的唯一 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。
date字段的 value 为YYYY-MM-DD;原文日期只保留在 quote 中。decimal/integer/boolean分别输出 JSON 数字 / 数字 / 布尔值。line_no、part_number、reservation_id、inventory_source_hint和aws_part_number不发生位置性或互相替代的错误映射。- HXOPS published Schema 的
customer_part_number包含Material/Material No/Material Number,aws_part_number不包含这些裸别名。 - 明确的 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。 - 没有旧整包输入判断、嵌套附件遍历、跨附件合并、自动建单、Dify 侧重试或循环。
9. 运行后核验
发布 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 证据、重复检测、客户影子识别和自动建单开关等门禁。