267 lines
9.0 KiB
Python
267 lines
9.0 KiB
Python
"""
|
||
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.models import ShippingNotice
|
||
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 _batch_no(batch: Any | None, task: ShippingNotice | None) -> str:
|
||
"""
|
||
获取当前上下文的批次号。
|
||
|
||
核心逻辑:shipping_batches 已删除;仅保留显式传入 batch 对象的兼容读取。
|
||
|
||
Returns:
|
||
批次号;无法识别时返回空字符串。
|
||
"""
|
||
if batch and _clean_text(getattr(batch, "batch_no", None)):
|
||
return _clean_text(batch.batch_no).upper()
|
||
return ""
|
||
|
||
|
||
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,
|
||
batch: Any | 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/batch_no/run_purpose/file_name,区别于旧 hxops_context 的 task/batch。
|
||
|
||
Args:
|
||
task: 当前任务。
|
||
batch: 当前批次。
|
||
run_purpose: 本次 Dify run 的目的。
|
||
intake_nos: 点击发送时锁定的 Intake 编号集合。
|
||
capability: 当前固定画布能力,如 order_extraction。
|
||
|
||
Returns:
|
||
非空业务锚点字典。
|
||
"""
|
||
refs: dict[str, str] = {}
|
||
task_no = _task_no(task)
|
||
batch_no = _batch_no(batch, task)
|
||
file_name = _clean_text(getattr(task, "source_file_name", None))
|
||
normalized_run_purpose = _clean_text(run_purpose)
|
||
if task_no:
|
||
refs["task_no"] = task_no
|
||
if batch_no:
|
||
refs["batch_no"] = batch_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, batch: Any | None) -> dict[str, Any]:
|
||
"""
|
||
构建发货通知运行态提示。
|
||
|
||
核心逻辑:只放 Dify 判断流程所需的状态摘要;真正能否推进仍由 HXOPS Tool/状态机校验。
|
||
|
||
Args:
|
||
task: 当前任务。
|
||
batch: 当前批次。
|
||
|
||
Returns:
|
||
状态提示字典。
|
||
"""
|
||
state_hint: dict[str, Any] = {}
|
||
task_no = _task_no(task)
|
||
if task_no:
|
||
state_hint["focus_task_no"] = task_no
|
||
elif batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
|
||
state_hint["focus_task_no"] = _clean_text(batch.current_focus_task_no).upper()
|
||
|
||
if task is not None:
|
||
for attr, key in (
|
||
("current_step", "current_step"),
|
||
("process_status", "status"),
|
||
("review_status", "review_status"),
|
||
("match_status", "match_status"),
|
||
("pending_human_reason", "pending_human_reason"),
|
||
("upload_status", "upload_status"),
|
||
):
|
||
value = _clean_text(getattr(task, attr, None))
|
||
if value:
|
||
state_hint[key] = value
|
||
|
||
batch_no = _batch_no(batch, task)
|
||
if batch_no:
|
||
state_hint["batch_no"] = batch_no
|
||
return state_hint
|
||
|
||
|
||
def _build_summary(
|
||
*,
|
||
task: ShippingNotice | None,
|
||
batch: Any | None,
|
||
run_purpose: str | None,
|
||
) -> str:
|
||
"""
|
||
构建给 Dify 阅读的短摘要。
|
||
|
||
核心逻辑:用自然语言说明当前 run 的任务、批次、文件和状态,避免 Dify 依赖 conversation memory 猜现场。
|
||
|
||
Args:
|
||
task: 当前任务。
|
||
batch: 当前批次。
|
||
run_purpose: 本次 Dify run 的目的。
|
||
|
||
Returns:
|
||
200 字以内的现场摘要。
|
||
"""
|
||
pieces: list[str] = []
|
||
task_no = _task_no(task)
|
||
batch_no = _batch_no(batch, task)
|
||
file_name = _clean_text(getattr(task, "source_file_name", None))
|
||
status = _clean_text(getattr(task, "process_status", None))
|
||
current_step = _clean_text(getattr(task, "current_step", None))
|
||
normalized_run_purpose = _clean_text(run_purpose)
|
||
if task_no:
|
||
pieces.append(f"当前任务 {task_no}")
|
||
if batch_no:
|
||
pieces.append(f"属于批次 {batch_no}")
|
||
if file_name:
|
||
pieces.append(f"来源文件 {file_name}")
|
||
if normalized_run_purpose:
|
||
pieces.append(f"本次执行目的为 {normalized_run_purpose}")
|
||
if status:
|
||
pieces.append(f"当前状态 {status}")
|
||
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,
|
||
batch: Any | 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/batch 为事实源,生成 refs/domain.state_hint/reference_context snapshot,
|
||
供 Dify 每次 run 显式识别现场。
|
||
|
||
Args:
|
||
session_id: HXOPS 本地 ChatSession.session_id。
|
||
task: 当前显式任务;禁止在本函数内按会话猜测。
|
||
batch: 当前批次。
|
||
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, batch=batch, run_purpose=run_purpose),
|
||
"state_hint": _build_state_hint(task, batch),
|
||
"available_actions_hint": [],
|
||
}
|
||
reference_context = build_shipping_reference_context(
|
||
batch=batch,
|
||
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,
|
||
batch=batch,
|
||
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,
|
||
)
|