""" backend/app/services/shipping_notice/reference_context.py 用途:从发货通知批次/任务/事件构建 shipping_notice 专用 reference_context。 依赖:models.ShippingNotice/ShippingTaskEvent、agent_runtime_context.reference。 逻辑:runtime_context 在调用 Dify 前经本模块提炼当前 focus、最近动作、最近失败和候选对象,避免把全量事件流水直接暴露给 Runtime。 """ from __future__ import annotations from dataclasses import dataclass from datetime import datetime from typing import Any from app.models import ShippingNotice, ShippingTaskEvent from app.services.agent_runtime_context.reference import build_object_ref, build_reference_context MAX_REFERENCE_EVENT_SCAN = 8 MAX_REFERENCE_SUMMARY_CANDIDATES = 2 @dataclass(frozen=True) class _ActionEventMeta: """定义 reference builder 可识别动作事件的语义与优先级。""" action: str summary_template: str priority: int _ACTION_EVENT_MAP: dict[str, _ActionEventMeta] = { "parse_confirmed": _ActionEventMeta("confirm_parse", "用户已确认 {task_no} 解析", 40), "decision_confirmed": _ActionEventMeta("confirm_matched", "用户已确认 {task_no} 当前结果", 40), "decision_rematch": _ActionEventMeta("rematch", "用户已要求重新匹配 {task_no}", 40), "notice_reparse_requested": _ActionEventMeta("reparse", "用户已要求重新解析 {task_no}", 40), "decision_rejected": _ActionEventMeta("reject", "用户已驳回 {task_no}", 40), "focus_switched": _ActionEventMeta("switch_focus", "用户已切换 focus 到 {task_no}", 35), "focus_auto_switched": _ActionEventMeta("auto_focus", "系统自动聚焦到 {task_no}", 10), "inventory_source_confirmed": _ActionEventMeta("confirm_inventory_source", "用户已确认 {task_no} 库存源", 30), } def _clean_text(value: Any) -> str: """将任意值规范化为去空白字符串。""" return str(value or "").strip() def _task_no(task: ShippingNotice | None) -> str: """提取任务号并统一成大写。""" return _clean_text(getattr(task, "task_no", None)).upper() def _task_recency_key(task: ShippingNotice) -> tuple[datetime, int]: """ 构造任务最近性排序键。 核心逻辑:优先按 updated_at,其次 created_at 与主键排序,保证最近失败/最近动作关联稳定可复现。 """ updated_at = getattr(task, "updated_at", None) or getattr(task, "created_at", None) or datetime.min return updated_at, int(getattr(task, "id", 0) or 0) def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) -> list[ShippingNotice]: """ 汇总当前 reference_context 可见的任务集合。 核心逻辑:shipping_batches 已删除;仅保留 focus_task 单票上下文。 """ if focus_task is None: return [] return [focus_task] def _recent_events(tasks: list[ShippingNotice]) -> list[ShippingTaskEvent]: """ 查询最近关键事件。 核心逻辑:只取当前批次/任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。 """ task_ids = [int(task.id) for task in tasks if getattr(task, "id", None) is not None] if not task_ids: return [] return ( ShippingTaskEvent.query.filter(ShippingTaskEvent.task_id.in_(task_ids)) .order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc()) .limit(MAX_REFERENCE_EVENT_SCAN) .all() ) def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | None: """ 提取任务失败/异常摘要。 核心逻辑:把 HXOPS 内部状态机信号收敛成 Dify 可理解的 shortage/rejected/upload_failed 等短标签。 """ task_no = _task_no(task) if not task_no: return None process_status = _clean_text(getattr(task, "process_status", None)).lower() review_status = _clean_text(getattr(task, "review_status", None)).lower() match_status = _clean_text(getattr(task, "match_status", None)).lower() pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower() upload_status = _clean_text(getattr(task, "upload_status", None)).lower() if match_status == "shortage" or pending_reason == "shortage" or getattr(task, "shortage_json", None): return { "reason": "shortage", "label": "异常:库存不足", "summary": f"{task_no} 库存匹配失败", } if process_status == "rejected" or review_status == "rejected": return { "reason": "rejected", "label": "已驳回", "summary": f"{task_no} 已被驳回", } if process_status == "upload_failed" or upload_status == "failed" or pending_reason == "upload_rpa_failed": return { "reason": "upload_failed", "label": "异常:上传失败", "summary": f"{task_no} 上传失败", } if _clean_text(getattr(task, "error_message", None)): return { "reason": "error", "label": "异常:处理失败", "summary": f"{task_no} 处理失败", } return None def _last_action_target( *, events: list[ShippingTaskEvent], task_by_id: dict[int, ShippingNotice], ) -> tuple[dict[str, str], str]: """ 根据最近事件提取最后动作对象。 核心逻辑:只识别对指代解析价值高的人工动作事件,如 confirm/rematch/reparse,避免把系统内部流水误当“用户刚才那个”。 """ best_match: tuple[int, dict[str, str], str] | None = None for event in events: event_type = _clean_text(getattr(event, "event_type", None)) meta = _ACTION_EVENT_MAP.get(event_type) if not meta: continue detail = getattr(event, "detail_json", None) task_no = "" source = "" if isinstance(detail, dict): task_no = _clean_text(detail.get("target_id")).upper() source = _clean_text(detail.get("source")).lower() if not task_no: task = task_by_id.get(int(getattr(event, "task_id", 0) or 0)) task_no = _task_no(task) if not task_no: continue priority = meta.priority if source in {"workspace_api", "tool_api"}: priority += 5 candidate_ref = build_object_ref("task", task_no, action=meta.action) candidate_summary = meta.summary_template.format(task_no=task_no) if best_match is None or priority > best_match[0]: best_match = (priority, candidate_ref, candidate_summary) if best_match is None: return {}, "" return best_match[1], best_match[2] def _last_failed_target(tasks: list[ShippingNotice]) -> tuple[dict[str, str], str]: """ 提取最近失败或异常的目标对象。 核心逻辑:优先按任务最近更新时间选择一个失败任务,供“上一个失败的”之类模糊指代使用。 """ for task in tasks: failure = _task_failure_descriptor(task) task_no = _task_no(task) if not failure or not task_no: continue return ( build_object_ref("task", task_no, reason=failure["reason"], label=failure["label"]), failure["summary"], ) return {}, "" def _candidate_refs(tasks: list[ShippingNotice], focus_task_no: str) -> list[dict[str, str]]: """ 生成模糊指代候选对象列表。 核心逻辑:仅暴露少量异常/失败任务,如 shortage/rejected/upload_failed,避免把整批任务全部透传给 Dify。 """ candidates: list[dict[str, str]] = [] seen: set[str] = set() for task in tasks: task_no = _task_no(task) failure = _task_failure_descriptor(task) if not task_no or not failure: continue if focus_task_no and task_no == focus_task_no: continue if task_no in seen: continue candidates.append(build_object_ref("task", task_no, label=failure["label"])) seen.add(task_no) return candidates def _build_recent_activity_summary( *, batch: Any | None, focus_task_no: str, last_action_summary: str, last_failed_summary: str, candidates: list[dict[str, str]], ) -> str: """ 组装 recent_activity_summary 短摘要。 核心逻辑:优先描述最近动作、当前 focus 和最近失败,再补少量候选摘要,帮助 Dify 理解“继续/刚才那个/上一个失败的”。 """ pieces: list[str] = [] if last_action_summary: pieces.append(last_action_summary) if focus_task_no: pieces.append(f"当前 focus 为 {focus_task_no}") elif _clean_text(getattr(batch, "batch_no", None)): pieces.append(f"当前批次为 {_clean_text(batch.batch_no).upper()}") if last_failed_summary: pieces.append(last_failed_summary) if len(candidates) > 1: candidate_labels = "、".join( f"{item['id']}({item.get('label') or '候选'})" for item in candidates[:MAX_REFERENCE_SUMMARY_CANDIDATES] if item.get("id") ) if candidate_labels: pieces.append(f"候选对象:{candidate_labels}") return (";".join(pieces) + "。") if pieces else "" def build_shipping_reference_context( *, batch: Any | None, focus_task: ShippingNotice | None, ) -> dict[str, Any]: """ 构建发货通知 Agent 专用 reference_context。 【AI 触发时机】:当用户在 HXOPS 已做确认、重匹配、切票等动作后,又在对话里说“继续”“刚才那个”“上一个失败的”时, Dify 需要优先读取这份上下文理解当前现场,但不能直接据此推进业务状态。 核心逻辑:读取 batch.current_focus_task_no、任务状态和最近少量事件,提炼 focus_object / last_action_target / last_failed_target / candidates / recent_activity_summary 五类短期线索;不输出全量任务详情或完整事件日志。 Args: batch: 当前批次;可为空。 focus_task: 当前焦点任务;可为空。 Returns: shipping_notice 领域的 reference_context;没有有效线索时返回空 dict。 """ tasks = _collect_batch_tasks(batch, focus_task) focus_task_no = _task_no(focus_task) if not focus_task_no and batch and _clean_text(getattr(batch, "current_focus_task_no", None)): focus_task_no = _clean_text(batch.current_focus_task_no).upper() if not tasks and not focus_task_no: return {} events = _recent_events(tasks) task_by_id = {int(task.id): task for task in tasks if getattr(task, "id", None) is not None} last_action_target, last_action_summary = _last_action_target(events=events, task_by_id=task_by_id) last_failed_target, last_failed_summary = _last_failed_target(tasks) candidates = _candidate_refs(tasks, focus_task_no) focus_object = build_object_ref("task", focus_task_no) if focus_task_no else {} recent_activity_summary = _build_recent_activity_summary( batch=batch, focus_task_no=focus_task_no, last_action_summary=last_action_summary, last_failed_summary=last_failed_summary, candidates=candidates, ) return build_reference_context( recent_activity_summary=recent_activity_summary or None, focus_object=focus_object or None, last_action_target=last_action_target or None, last_failed_target=last_failed_target or None, candidates=candidates or None, ) __all__ = ["build_shipping_reference_context"]