""" backend/app/services/shipping_notice/runtime_context.py 用途:构建货代发货通知 Agent 的 agent_runtime_context 领域适配层。 依赖:models.ShippingNotice、agent_runtime_context.builder。 逻辑:dify_inputs 与后台编排器在调用 Dify 前通过本模块生成最新业务现场, Dify 只消费 snapshot,任务推进仍以 HXOPS 状态机和 Tool API 为准。 """ from __future__ import annotations import json from typing import Any from app import db from app.models import ShippingNotice, ShippingOrderIntake, ShippingOrderTask from app.services.agent_runtime_context.builder import build_agent_runtime_context from app.services.shipping_notice.reference_context import build_shipping_reference_context SHIPPING_NOTICE_AGENT_CODE = "shipping_notice" def _clean_text(value: Any) -> str: """ 将模型字段规范化为短文本。 核心逻辑:统一处理 None/空白字符串,避免 domain/state_hint 中混入空值。 Args: value: 待规范化字段。 Returns: 去除首尾空白后的字符串。 """ return str(value or "").strip() def _task_no(task: ShippingNotice | None) -> str: """ 获取当前上下文的任务号。 核心逻辑:只使用已解析出的显式任务对象,不按会话猜测最近任务,避免多票串单。 Args: task: 当前任务。 Returns: 任务号;缺失时返回空字符串。 """ return _clean_text(getattr(task, "task_no", None)).upper() def _build_refs( *, task: ShippingNotice | None, run_purpose: str | None, intake_nos: list[str] | None = None, capability: str | None = None, temporary_inventory_asset_no: str | None = None, temporary_inventory_session_no: str | None = None, ) -> dict[str, str]: """ 构建新版 agent_runtime_context.refs。 核心逻辑:使用稳定业务字段名 task_no/run_purpose/file_name。 Args: task: 当前任务。 run_purpose: 本次 Dify run 的目的。 intake_nos: 点击发送时锁定的 Intake 编号集合。 capability: 当前固定画布能力,如 order_extraction。 Returns: 非空业务锚点字典。 """ refs: dict[str, str] = {} task_no = _task_no(task) file_name = '' if getattr(task, 'source_intake_id', None): file_name = _clean_text(getattr(db.session.get(ShippingOrderIntake, int(task.source_intake_id)), 'filename', None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: refs["task_no"] = task_no if normalized_run_purpose: refs["run_purpose"] = normalized_run_purpose if file_name: refs["file_name"] = file_name normalized_intakes = sorted({str(item or '').strip().upper() for item in (intake_nos or []) if str(item or '').strip()}) if normalized_intakes: refs["intake_nos"] = json.dumps(normalized_intakes, ensure_ascii=False, separators=(",", ":")) if _clean_text(capability): refs["capability"] = _clean_text(capability) asset_no = _clean_text(temporary_inventory_asset_no).upper() if asset_no: refs["temporary_inventory_asset_no"] = asset_no session_no = _clean_text(temporary_inventory_session_no).upper() if session_no: refs["temporary_inventory_session_no"] = session_no return refs def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: """ 构建发货通知运行态提示。 核心逻辑:只放 Dify 判断流程所需的状态摘要;真正能否推进仍由 HXOPS Tool/状态机校验。 Args: task: 当前任务。 Returns: 状态提示字典。 """ state_hint: dict[str, Any] = {} task_no = _task_no(task) if task_no: state_hint["focus_task_no"] = task_no if task is not None: owner = task if isinstance(task, ShippingNotice) and task.order_task_id: owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or '' upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip() for attr, key in ( ("current_step", "current_step"), ("review_status", "review_status"), (None, "match_status"), (None, "upload_status"), ): value = match_status if key == 'match_status' else upload_status if key == 'upload_status' else _clean_text(getattr(owner, attr, None)) if value: state_hint[key] = value from app.services.shipping_notice.process_gate_projection import task_blocking_reason pending_reason = _clean_text(task_blocking_reason(task)) if pending_reason: state_hint['pending_human_reason'] = pending_reason return state_hint def _build_summary( *, task: ShippingNotice | None, run_purpose: str | None, ) -> str: """ 构建给 Dify 阅读的短摘要。 核心逻辑:用自然语言说明当前 run 的任务、文件和状态,避免 Dify 依赖 conversation memory 猜现场。 Args: task: 当前任务。 run_purpose: 本次 Dify run 的目的。 Returns: 200 字以内的现场摘要。 """ owner = task if isinstance(task, ShippingNotice) and task.order_task_id: owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task pieces: list[str] = [] task_no = _task_no(task) file_name = '' if getattr(owner, 'intake_id', None): intake = db.session.get(ShippingOrderIntake, int(owner.intake_id)) file_name = _clean_text(getattr(intake, 'filename', None)) current_step = _clean_text(getattr(owner, "current_step", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: pieces.append(f"当前任务 {task_no}") if file_name: pieces.append(f"来源文件 {file_name}") if normalized_run_purpose: pieces.append(f"本次执行目的为 {normalized_run_purpose}") if current_step: pieces.append(f"当前步骤 {current_step}") if not pieces: return "当前为货代发货通知 Agent 会话,尚未解析出明确任务锚点。" return ",".join(pieces) + "。" def build_shipping_runtime_context( *, session_id: str, task: ShippingNotice | None = None, trigger_source: str | None = None, request_id: str | None = None, locale: str | None = None, scope: str = "task_run", run_purpose: str | None = None, intake_nos: list[str] | None = None, capability: str | None = None, temporary_inventory_asset_no: str | None = None, temporary_inventory_session_no: str | None = None, ) -> dict[str, Any]: """ 构建货代发货通知 Agent 的 agent_runtime_context。 核心逻辑:以 HXOPS DB 中的 task 为事实源,生成 refs/domain.state_hint/reference_context snapshot, 供 Dify 每次 run 显式识别现场。 Args: session_id: HXOPS 本地 ChatSession.session_id。 task: 当前显式任务;禁止在本函数内按会话猜测。 trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。 request_id: 本次请求 ID。 locale: 用户语言。 scope: 上下文作用域。 run_purpose: 本次 Dify run 的目的,如 order_extraction。 intake_nos: 尚未建 Task 时的 Intake 编号集合。 capability: 当前固定画布能力。 temporary_inventory_asset_no: 本轮对话临时库存文件资产编号;仅供 Dify 调用受控 Tool。 temporary_inventory_session_no: 已创建的临时库存会话编号。 Returns: agent_runtime_context 字典;session_id 为空时返回空 dict。 """ domain = { "type": SHIPPING_NOTICE_AGENT_CODE, "summary": _build_summary(task=task, run_purpose=run_purpose), "state_hint": _build_state_hint(task), "available_actions_hint": [], } reference_context = build_shipping_reference_context(focus_task=task) return build_agent_runtime_context( agent_code=SHIPPING_NOTICE_AGENT_CODE, scope=scope, session_id=session_id, request_id=request_id, trigger_source=trigger_source, locale=locale, refs=_build_refs( task=task, run_purpose=run_purpose, intake_nos=intake_nos, capability=capability, temporary_inventory_asset_no=temporary_inventory_asset_no, temporary_inventory_session_no=temporary_inventory_session_no, ), domain=domain, reference_context=reference_context, )