# 订单抽取服务 Dify Workflow 配置手册 > 适用范围:HXOPS 货运领航订单抽取服务。 > > 本 Workflow 由 HXOPS 后台 `ShippingOrderExtractionRun` Worker 调用,不由普通货代 Chatflow 调用。 > > 本 Workflow 只负责:冻结输入文档和订单 Schema,识别结构化订单并返回 `orders`。Batch、Task、Candidate、判重、库存源、RPA、Excel 和货代上传均由 HXOPS 后端负责。 ## 1. 应用管理配置 在 HXOPS「应用管理」创建一个内部 Provider: | 配置项 | 值 | | --- | --- | | 运行时 Provider | `Dify` | | Dify 应用类型 | `Workflow` | | 应用可见性 | `内部业务 Provider` | | 对话形态 | 内部服务不参与对话,建议隐藏或显示为只读“后台服务” | | 能力绑定 | 入口货代 Agent 的 `shipping.order_extraction` | | 超时时间 | `30-3600` 秒,建议按附件规模设置 | | 最大尝试次数 | `1-10`,建议 `3` | 不要将此 Workflow 配置为普通用户工作台入口,也不要让普通用户直接授权或打开此应用。 ## 2. Workflow 总体拓扑 ```text 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 ``` 节点清单: 1. `start`:接收 HXOPS Worker 的五个 String 输入。 2. `parse_and_prepare_input`:解析 JSON、生成白名单和模型输入。 3. `extract_orders`:按冻结 Schema 从正文和附件提取订单与证据。 4. `validate_and_normalize_orders`:校验字段、来源、证据和 Schema 版本,并输出规范化 `orders`。 5. `check_validation`:判断校验是否通过。 6. `raise_validation_error`:校验失败时让 Workflow 进入失败终态。 7. `workflow_end`:只输出 `orders`。 ## 3. Start 节点 节点类型:`Start`。 所有输入变量必须为 `String` 类型: | 变量名 | 必填 | 来源 | 说明 | | --- | ---: | --- | --- | | `run_no` | 是 | HXOPS Worker | 当前订单抽取 Run 编号 | | `input_snapshot_hash` | 是 | HXOPS Worker | 输入快照 SHA-256 | | `schema_contract` | 是 | HXOPS Worker | 冻结的订单 Schema JSON 字符串 | | `documents` | 是 | HXOPS Worker | 冻结的正文和附件 Document JSON 字符串 | | `readonly_context` | 是 | HXOPS Worker | 受控只读上下文 JSON 字符串 | 约束: - `schema_contract`、`documents`、`readonly_context` 必须按 JSON 字符串解析。 - 不允许回读 HXOPS 数据库、当前可变 Document 或外部文件。 - 不允许接收或输出用户 ID、Provider ID、API Key、数据库凭据。 - `readonly_context` 不得写入长期变量、知识库或自定义日志。 ## 4. Code 节点:parse_and_prepare_input ### 4.1 输入 | 变量 | 来源 | | --- | --- | | `run_no` | `Start.run_no` | | `input_snapshot_hash` | `Start.input_snapshot_hash` | | `schema_contract` | `Start.schema_contract` | | `documents` | `Start.documents` | | `readonly_context` | `Start.readonly_context` | ### 4.2 输出 | 变量名 | 类型 | 说明 | | --- | --- | --- | | `run_no` | String | Run 编号 | | `input_snapshot_hash` | String | 输入快照哈希 | | `schema_contract_json` | String | 供 LLM 使用的 Schema JSON | | `documents_json` | String | 供 LLM 使用的 Document JSON | | `readonly_context_json` | String | 只读上下文 JSON | | `allowed_field_ids_json` | String | 允许返回的稳定 `field_id` 列表 | | `document_ids_json` | String | 允许引用的 Document ID 列表 | | `intake_nos_json` | String | 允许引用的 Intake 编号列表 | ### 4.3 完整代码 ```python 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 _require_object(value, name): if not isinstance(value, dict): raise ValueError(f"{name} must be a JSON object") return value def _require_array(value, name): if not isinstance(value, list): raise ValueError(f"{name} must be a JSON array") return value def _normalize_document(document, index): if not isinstance(document, dict): raise ValueError(f"documents[{index}] must be an object") document_id = document.get("id", document.get("document_id")) intake_no = ( document.get("intake_no") or document.get("source_intake_no") or document.get("intake") ) if document_id is None: raise ValueError(f"documents[{index}] is missing id") if intake_no is None or not str(intake_no).strip(): raise ValueError(f"documents[{index}] is missing intake_no") try: document_id = int(document_id) except (TypeError, ValueError) as exc: raise ValueError(f"documents[{index}].id must be an integer") from exc return { "id": document_id, "document_id": document_id, "intake_no": str(intake_no).strip().upper(), "filename": str(document.get("filename") or ""), "document_type": str(document.get("document_type") or ""), "classification": str(document.get("classification") or ""), "extracted_text": str(document.get("extracted_text") or ""), } def main(args): run_no = str(args.get("run_no") or "").strip() input_snapshot_hash = str(args.get("input_snapshot_hash") or "").strip() if not run_no: raise ValueError("run_no is required") if not input_snapshot_hash: raise ValueError("input_snapshot_hash is required") schema = _require_object( _parse_json(args.get("schema_contract"), "schema_contract"), "schema_contract", ) documents_raw = _require_array( _parse_json(args.get("documents"), "documents"), "documents", ) readonly_context = _require_object( _parse_json(args.get("readonly_context"), "readonly_context"), "readonly_context", ) schema_version_id = schema.get("schema_version_id") checksum = str(schema.get("checksum") or "").strip() fields = schema.get("fields") if schema_version_id is None: raise ValueError("schema_contract.schema_version_id is required") if not checksum: raise ValueError("schema_contract.checksum is required") if not isinstance(fields, list): raise ValueError("schema_contract.fields must be an array") allowed_field_ids = [] for index, field in enumerate(fields): if not isinstance(field, dict): raise ValueError(f"schema_contract.fields[{index}] must be an object") field_id = str(field.get("field_id") or "").strip() if not field_id: raise ValueError(f"schema_contract.fields[{index}].field_id is required") if field.get("collection_mode", "llm_extraction") != "llm_extraction": raise ValueError( f"schema_contract.fields[{index}] is not an llm_extraction field" ) allowed_field_ids.append(field_id) documents = [ _normalize_document(document, index) for index, document in enumerate(documents_raw) ] if not documents: raise ValueError("documents must not be empty") document_ids = sorted({item["document_id"] for item in documents}) intake_nos = sorted({item["intake_no"] for item in documents}) model_schema = { "schema_version_id": schema_version_id, "schema_version": schema.get("schema_version"), "checksum": checksum, "fields": fields, "submission_contract": schema.get("submission_contract", {}), } model_documents = [ { "document_id": item["document_id"], "intake_no": item["intake_no"], "filename": item["filename"], "document_type": item["document_type"], "classification": item["classification"], "extracted_text": item["extracted_text"], } for item in documents ] return { "run_no": run_no, "input_snapshot_hash": input_snapshot_hash, "schema_contract_json": json.dumps( model_schema, ensure_ascii=False, separators=(",", ":") ), "documents_json": json.dumps( model_documents, ensure_ascii=False, separators=(",", ":") ), "readonly_context_json": json.dumps( readonly_context, ensure_ascii=False, separators=(",", ":") ), "allowed_field_ids_json": json.dumps( sorted(set(allowed_field_ids)), ensure_ascii=False, separators=(",", ":"), ), "document_ids_json": json.dumps( document_ids, ensure_ascii=False, separators=(",", ":") ), "intake_nos_json": json.dumps( intake_nos, ensure_ascii=False, separators=(",", ":") ), } ``` ## 5. LLM 节点:extract_orders ### 5.1 模型参数 | 参数 | 建议值 | | --- | ---: | | Temperature | `0` | | Top P | `0.1` | | Streaming | 关闭 | | Memory | 关闭 | | Conversation History | 不使用 | | Response Format | JSON Object(Dify 版本支持时启用) | ### 5.2 输入变量 | 变量 | 来源 | | --- | --- | | `run_no` | `parse_and_prepare_input.run_no` | | `input_snapshot_hash` | `parse_and_prepare_input.input_snapshot_hash` | | `schema_contract_json` | `parse_and_prepare_input.schema_contract_json` | | `documents_json` | `parse_and_prepare_input.documents_json` | | `readonly_context_json` | `parse_and_prepare_input.readonly_context_json` | ### 5.3 System Prompt ```text 你是 HXOPS 货运订单抽取 Workflow 的结构化识别节点。 你的唯一任务是: 1. 阅读输入的 documents; 2. 根据 schema_contract.fields[] 中定义的字段识别订单; 3. 为每个识别出的字段提供原文 Observation; 4. 返回严格 JSON; 5. 不输出任何思考过程、分析过程、解释文字、Markdown 或代码围栏。 你不是业务系统,不负责: - 创建 Batch; - 创建 Task; - 判重; - 判断库存源; - 执行库存匹配; - 生成 Excel; - 上传货代系统; - 调用 HXOPS Tool; - 选择 Provider; - 读取数据库; - 读取外部文件; - 修改 Schema; - 修改用户输入; - 回传 API Key、用户 ID、Provider 配置或内部凭据。 ==================== 一、输入数据 ==================== 你会收到以下 JSON 字符串: - schema_contract_json:当前 Run 冻结的订单 Schema; - documents_json:当前 Run 冻结的正文和附件; - readonly_context_json:只读提示上下文; - run_no:当前 Run 编号; - input_snapshot_hash:输入快照哈希。 只能使用本次输入中的内容。 禁止: - 根据文件名猜测不存在的字段; - 根据常识补造没有证据的订单; - 根据 Reply-To、抄送、签名、转发文本重建被排除的确定性字段; - 将 readonly_context_json 中的字段写入 header_fields 或 lines.fields; - 将 schema_contract.fields[] 之外的字段写入结果; - 使用 field_code、display_name 或自然语言字段名替代 field_id; - 将任意系统字段、客户主数据 ID、库存源编码写入订单字段; - 将内部邮箱、域名等 deterministic context 字段写入订单字段。 ==================== 二、Schema 约束 ==================== 只有 schema_contract_json.fields[] 中出现的稳定 field_id 可以返回。 每个字段定义可能包含: - field_id - display_name - scope:header 或 line - value_type - required - aliases - extraction_instruction - evidence_policy - validator_keys - enum_options - business_purpose 必须遵守字段的 scope、value_type、required、extraction_instruction、evidence_policy 和 enum_options。 如果字段没有可信原文证据: - 不要猜测; - 不要生成默认值; - 不要使用业务常识补全; - 对该字段返回空 observations 数组,或不返回该字段; - 如果该字段 required,后端会进入 needs_review。 ==================== 三、订单分类 ==================== 每个业务订单必须返回 classification: - shipping_request:明确的发货/出货/交付需求; - non_shipping_request:明确不是发货订单; - uncertain:无法确定。 classification_confidence 必须是 0 到 1 之间的数字。 分类依据包括邮件正文、附件内容、订单表格以及发货、出货、Ship、Delivery、Reservation、Quantity 等业务信号。 不要因为附件是 PDF、Excel 或 Word 就直接认定为发货订单。 ==================== 四、来源关联 ==================== 每个订单必须尽量返回: - source_intake_no:必须来自 documents[].intake_no; - primary_document_id:必须来自 documents[].document_id。 primary_document_id 必须是该订单主要证据所在 Document。 如果无法确定主 Document,不要伪造 ID;优先使用直接包含订单表格的 Document。 ==================== 五、Header 字段 ==================== Header 字段格式: { "field_id": "schema_contract.fields[] 中的稳定 ID", "observations": [ { "value": "字段候选值", "document_id": 123, "quote": "来自原文的逐字引用", "confidence": 0.98 } ] } 要求: - field_id 必须来自 Schema; - Header 字段只能使用 scope=header 的 field_id; - document_id 必须来自 documents; - quote 必须是原文逐字片段; - quote 不得改写、翻译或拼接不存在的文字; - value 的类型必须符合字段 value_type; - confidence 必须是 0 到 1 之间; - 同一字段存在多个来源时,可以返回多个 observations; - 不同来源冲突时,不要自行选择,全部保留供 HXOPS 裁决。 ==================== 六、Line 字段 ==================== 明细行格式: { "fields": [ { "field_id": "schema_contract.fields[] 中的稳定 ID", "observations": [ { "value": "字段候选值", "document_id": 123, "quote": "来自原文的逐字引用", "confidence": 0.95 } ] } ] } 要求: - 每一行对应一个真实订单明细; - 不要把表头、合计行、备注行当成订单明细; - 不要合并不同 Reservation、料号或数量的明细; - 不要根据数量计算结果反推不存在的字段; - Qty/quantity 必须来自原文证据; - 料号必须来自原文证据; - Reservation ID 必须来自原文证据; - Allocation ID、UUID、内部数据库主键不能冒充 Reservation ID; - 如果明细数量不确定,返回空 observations,不要猜测。 ==================== 七、证据要求 ==================== 每个非空字段值至少提供一个 Observation。 Observation 必须包含 value、document_id 和 quote。 quote 必须来自对应 Document,保留原文中的数字、字母、标点和大小写,尽量短且能直接证明 value。 不得写“根据上下文可知”,不得写模型解释,不得写不存在于文档中的规范化值。 ==================== 八、readonly_context 规则 ==================== readonly_context_json 只能作为当次提示信息使用。 禁止: - 把 readonly_context_json 中的字段放入 header_fields; - 把 readonly_context_json 中的字段放入 lines.fields; - 把 readonly_context_json 中的字段写入 conflicts; - 把 readonly_context_json 中的字段复制到长期记忆; - 把 readonly_context_json 中的字段写入自定义日志; - 通过正文、签名、转发文本恢复被排除的 deterministic context; - 输出发件人邮箱、邮箱域名或客户主数据 ID,除非它们明确存在于 schema_contract.fields[] 且允许 LLM 抽取。 ==================== 九、多个订单规则 ==================== 同一封邮件或多个附件可能包含多个业务订单。 必须: - 每个订单独立输出; - 每个订单独立指定 source_intake_no; - 每个订单独立指定 primary_document_id; - 每个订单独立输出 header_fields; - 每个订单独立输出 lines; - 不要把不同附件的订单字段无依据地合并; - 如果无法确定是否属于同一订单,分别输出,并在 conflicts 中说明。 ==================== 十、非发货内容 ==================== 如果输入明确不是发货需求,返回一个 classification=non_shipping_request 的订单,header_fields 和 lines 均为空,不得虚构订单字段。 ==================== 十一、严格输出要求 ==================== 只能输出一个 JSON Object: { "orders": [ { "schema_version_id": 123, "schema_checksum": "来自 schema_contract_json.checksum", "classification": "shipping_request", "classification_confidence": 0.98, "source_intake_no": "SNI-...", "primary_document_id": 456, "candidate_key_hint": "可选的稳定订单号", "header_fields": [], "lines": [ { "fields": [] } ], "conflicts": [] } ] } 如果没有识别出任何订单,返回 {"orders":[]}。 不得输出 thought、reasoning、analysis、answer、message、markdown、代码围栏、自然语言、Provider 信息、用户身份信息、HXOPS 内部配置或运行日志。 最终只返回 JSON。 ``` ### 5.4 User Prompt ```text 请根据以下冻结输入,识别全部发货订单。 run_no: {{run_no}} input_snapshot_hash: {{input_snapshot_hash}} schema_contract_json: {{schema_contract_json}} documents_json: {{documents_json}} readonly_context_json: {{readonly_context_json}} 请严格按照 System Prompt 中的 JSON 契约输出。 只能输出一个 JSON Object,格式为: { "orders": [] } 或包含一个或多个订单的同结构 JSON Object。 不要输出任何解释、思考、Markdown 或自然语言。 ``` ## 6. Code 节点:validate_and_normalize_orders ### 6.1 输入 | 变量 | 来源 | | --- | --- | | `llm_output` | `extract_orders` 的文本输出 | | `schema_contract_json` | `parse_and_prepare_input.schema_contract_json` | | `document_ids_json` | `parse_and_prepare_input.document_ids_json` | | `intake_nos_json` | `parse_and_prepare_input.intake_nos_json` | ### 6.2 输出 | 变量名 | 类型 | 说明 | | --- | --- | --- | | `orders` | String | JSON 字符串形式的订单数组 | | `order_count` | Number | 订单数量 | | `validation_ok` | Boolean | 是否通过校验 | | `validation_error` | String | 校验失败原因 | ### 6.3 完整代码 ```python 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 empty") try: return json.loads(text) except json.JSONDecodeError as exc: raise ValueError(f"{name} is not valid JSON: {exc.msg}") from exc def _as_float(value, name): try: result = float(value) except (TypeError, ValueError) as exc: raise ValueError(f"{name} must be a number") from exc if result < 0 or result > 1: raise ValueError(f"{name} must be between 0 and 1") return result def _normalize_document_ids(value): raw = _parse_json(value, "document_ids_json") if not isinstance(raw, list): raise ValueError("document_ids_json must be an array") result = set() for item in raw: try: result.add(int(item)) except (TypeError, ValueError) as exc: raise ValueError( "document_ids_json contains an invalid document id" ) from exc return result def _normalize_intake_nos(value): raw = _parse_json(value, "intake_nos_json") if not isinstance(raw, list): raise ValueError("intake_nos_json must be an array") return { str(item or "").strip().upper() for item in raw if str(item or "").strip() } def _extract_orders(raw): if isinstance(raw, dict): if isinstance(raw.get("orders"), list): return raw["orders"] for key in ("data", "result", "output"): nested = raw.get(key) if isinstance(nested, dict) and isinstance(nested.get("orders"), list): return nested["orders"] raise ValueError("LLM JSON object must contain orders array") if isinstance(raw, list): return raw raise ValueError("LLM output must be an object containing orders array") def _field_scope_map(schema): result = {} for item in schema.get("fields") or []: if not isinstance(item, dict): continue field_id = str(item.get("field_id") or "").strip() if field_id: result[field_id] = item return result def _validate_observation(observation, *, field_id, document_ids): if not isinstance(observation, dict): raise ValueError(f"observation for {field_id} must be an object") if "value" not in observation: raise ValueError(f"observation for {field_id} is missing value") try: document_id = int(observation.get("document_id")) except (TypeError, ValueError) as exc: raise ValueError( f"observation for {field_id} has invalid document_id" ) from exc if document_id not in document_ids: raise ValueError( f"observation for {field_id} references unknown document_id {document_id}" ) quote = str(observation.get("quote") or "").strip() if not quote: raise ValueError(f"observation for {field_id} is missing quote") normalized = { "value": observation.get("value"), "document_id": document_id, "quote": quote, } if observation.get("confidence") is not None: normalized["confidence"] = _as_float( observation.get("confidence"), f"observation confidence for {field_id}", ) return normalized def _validate_field_group(fields, *, scope, field_map, document_ids): if fields is None: return [] if not isinstance(fields, list): raise ValueError(f"{scope}_fields must be an array") normalized_fields = [] seen = set() for index, item in enumerate(fields): if not isinstance(item, dict): raise ValueError(f"{scope}_fields[{index}] must be an object") field_id = str(item.get("field_id") or "").strip() if not field_id: raise ValueError(f"{scope}_fields[{index}] is missing field_id") if field_id in seen: raise ValueError(f"duplicate {scope} field_id: {field_id}") seen.add(field_id) config = field_map.get(field_id) if config is None: raise ValueError(f"field_id is not allowed by schema: {field_id}") configured_scope = str(config.get("scope") or "").strip().lower() if configured_scope != scope: raise ValueError( f"field_id {field_id} has scope {configured_scope}, but was returned under {scope}" ) observations = item.get("observations") if not isinstance(observations, list): raise ValueError( f"observations for field_id {field_id} must be an array" ) normalized_fields.append({ "field_id": field_id, "observations": [ _validate_observation( observation, field_id=field_id, document_ids=document_ids, ) for observation in observations ], }) return normalized_fields def _validate_conflicts(conflicts): if conflicts is None: return [] if not isinstance(conflicts, list): raise ValueError("conflicts must be an array") result = [] for index, item in enumerate(conflicts): if not isinstance(item, dict): raise ValueError(f"conflicts[{index}] must be an object") normalized = dict(item) if "severity" in normalized: severity = str(normalized["severity"] or "").strip().lower() if severity not in {"blocking", "warning", "info"}: raise ValueError(f"conflicts[{index}].severity is invalid") normalized["severity"] = severity result.append(normalized) return result def _validate_order(order, *, schema, field_map, document_ids, intake_nos): if not isinstance(order, dict): raise ValueError("each order must be an object") try: schema_version_id = int(order.get("schema_version_id")) except (TypeError, ValueError) as exc: raise ValueError("schema_version_id must be an integer") from exc expected_version_id = int(schema.get("schema_version_id")) if schema_version_id != expected_version_id: raise ValueError( f"schema_version_id mismatch: expected {expected_version_id}" ) schema_checksum = str(order.get("schema_checksum") or "").strip() expected_checksum = str(schema.get("checksum") or "").strip() if schema_checksum != expected_checksum: raise ValueError("schema_checksum mismatch") classification = str(order.get("classification") or "").strip().lower() if classification not in { "shipping_request", "non_shipping_request", "uncertain", }: raise ValueError(f"invalid classification: {classification}") classification_confidence = _as_float( order.get("classification_confidence"), "classification_confidence", ) source_intake_no = str(order.get("source_intake_no") or "").strip().upper() if source_intake_no and source_intake_no not in intake_nos: raise ValueError( f"source_intake_no does not belong to input documents: {source_intake_no}" ) primary_document_id = order.get("primary_document_id") if primary_document_id is not None: try: primary_document_id = int(primary_document_id) except (TypeError, ValueError) as exc: raise ValueError("primary_document_id must be an integer") from exc if primary_document_id not in document_ids: raise ValueError( f"primary_document_id is not in documents: {primary_document_id}" ) header_fields = _validate_field_group( order.get("header_fields"), scope="header", field_map=field_map, document_ids=document_ids, ) lines = order.get("lines") or [] if not isinstance(lines, list): raise ValueError("lines must be an array") normalized_lines = [] for index, line in enumerate(lines): if not isinstance(line, dict): raise ValueError(f"lines[{index}] must be an object") normalized_lines.append({ "fields": _validate_field_group( line.get("fields"), scope="line", field_map=field_map, document_ids=document_ids, ) }) normalized = { "schema_version_id": schema_version_id, "schema_checksum": schema_checksum, "classification": classification, "classification_confidence": classification_confidence, "source_intake_no": source_intake_no or None, "primary_document_id": primary_document_id, "header_fields": header_fields, "lines": normalized_lines, "conflicts": _validate_conflicts(order.get("conflicts")), } if order.get("candidate_key_hint") is not None: normalized["candidate_key_hint"] = str( order.get("candidate_key_hint") ).strip() or None return normalized def main(args): try: raw_output = args.get("llm_output") if isinstance(raw_output, str): text = raw_output.strip() if text.startswith("```"): text = text.replace("```json", "", 1) text = text.replace("```", "", 1).strip() raw_output = _parse_json(text, "llm_output") else: raw_output = _parse_json(raw_output, "llm_output") schema = _parse_json( args.get("schema_contract_json"), "schema_contract_json", ) document_ids = _normalize_document_ids(args.get("document_ids_json")) intake_nos = _normalize_intake_nos(args.get("intake_nos_json")) field_map = _field_scope_map(schema) orders = _extract_orders(raw_output) if len(orders) > 50: raise ValueError("orders exceeds maximum limit of 50") normalized_orders = [ _validate_order( order, schema=schema, field_map=field_map, document_ids=document_ids, intake_nos=intake_nos, ) for order in orders ] 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 节点:check_validation 条件: ```text validation_ok == true ``` 分支: | 分支 | 下一个节点 | | --- | --- | | true | `workflow_end` | | false | `raise_validation_error` | ## 8. Code 节点:raise_validation_error ### 输入 | 变量 | 来源 | | --- | --- | | `validation_error` | `validate_and_normalize_orders.validation_error` | ### 完整代码 ```python def main(args): error_message = str( args.get("validation_error") or "LLM order extraction output validation failed" ).strip() raise ValueError(error_message[:500]) ``` 校验失败必须让 Workflow 进入失败状态,HXOPS Worker 才能按 `max_attempts` 重试。不要把校验错误包装成成功订单。 ## 9. End 节点:workflow_end End 节点只输出一个变量: | 输出变量 | 类型 | 来源 | | --- | --- | --- | | `orders` | String | `validate_and_normalize_orders.orders` | 输出表达式: ```text {{validate_and_normalize_orders.orders}} ``` 推荐让 `orders` 作为 JSON 字符串输出: ```json { "orders": "[{\"schema_version_id\":123,\"schema_checksum\":\"abc...\",\"classification\":\"shipping_request\",\"classification_confidence\":0.98,\"source_intake_no\":\"SNI-20260721-ABC123\",\"primary_document_id\":456,\"header_fields\":[],\"lines\":[{\"fields\":[]}],\"conflicts\":[]}]" } ``` HXOPS Worker 同时兼容 `orders` 为数组或 JSON 字符串数组,但推荐 JSON 字符串,以避免不同 Dify 版本对动态数组的序列化差异。 ## 10. 标准输出示例 ### 10.1 发货订单 ```json { "orders": [ { "schema_version_id": 123, "schema_checksum": "sha256-checksum", "classification": "shipping_request", "classification_confidence": 0.98, "source_intake_no": "SNI-20260721-ABC123", "primary_document_id": 456, "candidate_key_hint": "PO-20260721-001", "header_fields": [ { "field_id": "field-customer-name", "observations": [ { "value": "Example Customer", "document_id": 456, "quote": "Customer: Example Customer", "confidence": 0.98 } ] } ], "lines": [ { "fields": [ { "field_id": "field-part-number", "observations": [ { "value": "ABC-001", "document_id": 456, "quote": "ABC-001", "confidence": 0.99 } ] }, { "field_id": "field-quantity", "observations": [ { "value": 10, "document_id": 456, "quote": "Qty: 10", "confidence": 0.99 } ] }, { "field_id": "field-reservation-id", "observations": [ { "value": "1234567890", "document_id": 456, "quote": "Reservation: 1234567890", "confidence": 0.97 } ] } ] } ], "conflicts": [] } ] } ``` ### 10.2 非发货内容 ```json { "orders": [ { "schema_version_id": 123, "schema_checksum": "sha256-checksum", "classification": "non_shipping_request", "classification_confidence": 0.99, "source_intake_no": "SNI-20260721-ABC123", "primary_document_id": 456, "header_fields": [], "lines": [], "conflicts": [] } ] } ``` ### 10.3 无法判断 ```json { "orders": [ { "schema_version_id": 123, "schema_checksum": "sha256-checksum", "classification": "uncertain", "classification_confidence": 0.51, "source_intake_no": "SNI-20260721-ABC123", "primary_document_id": 456, "header_fields": [], "lines": [], "conflicts": [ { "severity": "warning", "reason": "document does not contain enough shipping evidence" } ] } ] } ``` ## 11. 禁止配置 订单抽取 Workflow 不得配置以下节点或行为: - HXOPS Tool 节点; - `submit_order_extraction`; - `get_order_extraction_context`; - 创建 Batch 的 HTTP 请求; - 创建 Task 的 HTTP 请求; - 库存源判断、RPA、Excel 生成或货代上传; - 数据库查询或外部文件下载; - 会话记忆、长期变量写入或知识库写入; - 自然语言 End 节点; - 输出 ``、`analysis`、`reasoning`、Markdown 或自然语言; - 根据邮箱、域名、签名或客户名称直接确认客户; - 根据常识补齐数量、料号或 Reservation ID。 ## 12. Dify 画布验收清单 ### Start - [ ] 五个输入均为 String。 - [ ] 变量名与本文完全一致。 - [ ] 没有用户 ID、Provider ID、API Key 输入。 - [ ] 没有会话历史。 ### parse_and_prepare_input - [ ] JSON 解析失败会阻断 Workflow。 - [ ] Schema 只保留 `collection_mode=llm_extraction` 字段。 - [ ] 生成字段 ID、Document ID、Intake 白名单。 - [ ] 不把确定性上下文加入 LLM 可回传字段。 ### extract_orders - [ ] Temperature 为 `0`。 - [ ] 关闭 Memory 和 Conversation History。 - [ ] 使用本文完整 System Prompt 和 User Prompt。 - [ ] 输出只允许 JSON。 - [ ] 不输出思考过程。 ### validate_and_normalize_orders - [ ] 校验 `schema_version_id`。 - [ ] 校验 `schema_checksum`。 - [ ] 校验 `source_intake_no`。 - [ ] 校验 `primary_document_id`。 - [ ] 校验 `field_id` 和 Header/Line scope。 - [ ] 校验 Observation 的 `document_id` 和 `quote`。 - [ ] 校验分类和置信度。 - [ ] 非法结果进入失败分支。 ### End - [ ] 只输出 `orders`。 - [ ] `orders` 是 JSON 数组或 JSON 字符串数组。 - [ ] 不输出 `answer`、`thought`、Provider 信息或用户身份信息。 ## 13. 与 HXOPS 的边界 ```text Intake -> ShippingOrderExtractionRun -> shipping_order_extraction Job -> 本 Workflow -> HXOPS 校验 orders -> ShippingNoticeCandidate -> Batch / Task ``` Workflow 成功不等于订单已经落库,也不等于 Task 已创建。只有 HXOPS Worker 成功持久化并通过业务门禁后,订单才会进入后续流程。