170 lines
6.8 KiB
Python
170 lines
6.8 KiB
Python
"""
|
||
services/shipping_notice/dify_inputs.py
|
||
|
||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||
依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。
|
||
逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点,
|
||
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
|
||
发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
from app.models import ShippingNotice, ShippingTemporaryInventorySession
|
||
from app.services.agent_runtime_context.builder import serialize_for_dify
|
||
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
|
||
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
|
||
|
||
|
||
def _latest_batch_for_conversation(conversation_id: str) -> None:
|
||
"""shipping_batches 已删除;固定返回 None。"""
|
||
del conversation_id
|
||
return None
|
||
|
||
|
||
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
|
||
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
|
||
normalized = str(task_id or "").strip().upper()
|
||
if not normalized:
|
||
return None
|
||
return ShippingNotice.query.filter_by(task_no=normalized).first()
|
||
|
||
|
||
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
|
||
"""
|
||
恢复当前聊天中仍待用户处理的临时库存会话锚点。
|
||
|
||
Args:
|
||
conversation_id: HXOPS 本地聊天会话 ID。
|
||
|
||
Returns:
|
||
最新未过期待处理会话号;没有符合条件的会话时返回 None。
|
||
"""
|
||
normalized = str(conversation_id or '').strip()
|
||
if not normalized:
|
||
return None
|
||
item = ShippingTemporaryInventorySession.query.filter(
|
||
ShippingTemporaryInventorySession.conversation_id == normalized,
|
||
ShippingTemporaryInventorySession.status.in_([
|
||
'created',
|
||
'awaiting_profile_confirmation',
|
||
'awaiting_mapping_suggestion',
|
||
'awaiting_mapping_confirmation',
|
||
]),
|
||
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
|
||
).order_by(
|
||
ShippingTemporaryInventorySession.updated_at.desc(),
|
||
ShippingTemporaryInventorySession.id.desc(),
|
||
).first()
|
||
return str(item.session_no or '').strip().upper() or None if item else None
|
||
|
||
|
||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None:
|
||
"""
|
||
解析当前显式焦点任务行。
|
||
|
||
核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询,
|
||
但不在无焦点时回退到最近任务,避免多票批次串单。
|
||
|
||
Args:
|
||
focus_task: 已解析出的焦点任务号。
|
||
explicit_task_row: task_id 显式传入时查询到的任务。
|
||
|
||
Returns:
|
||
当前焦点任务;无法明确识别时返回 None。
|
||
"""
|
||
normalized = str(focus_task or "").strip().upper()
|
||
if not normalized:
|
||
return None
|
||
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
|
||
return explicit_task_row
|
||
return ShippingNotice.query.filter_by(task_no=normalized).first()
|
||
|
||
|
||
def build_dify_chat_inputs(
|
||
conversation_id: str | None = None,
|
||
*,
|
||
task_id: str | None = None,
|
||
batch_no: str | None = None,
|
||
trigger_source: str | None = None,
|
||
request_id: str | None = None,
|
||
locale: 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]:
|
||
"""
|
||
构建发货通知 Dify Chatflow inputs。
|
||
|
||
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
|
||
无需再注入 HXOPS_TOOLS_API_BASE;这里仅注入 agent_runtime_context,避免新旧上下文字段并存导致画布协议漂移。
|
||
"""
|
||
conv_id = str(conversation_id or "").strip()
|
||
if not conv_id:
|
||
return {}
|
||
|
||
explicit_task = str(task_id or "").strip().upper()
|
||
explicit_batch = str(batch_no or "").strip().upper()
|
||
explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper()
|
||
resolved_temporary_session = (
|
||
explicit_temporary_session
|
||
or (
|
||
_latest_pending_temporary_inventory_session(conv_id)
|
||
if trigger_source != 'backend_orchestrator'
|
||
else None
|
||
)
|
||
)
|
||
|
||
batch = _latest_batch_for_conversation(conv_id)
|
||
explicit_task_row = _task_by_task_no(explicit_task)
|
||
|
||
focus_task = explicit_task
|
||
if not focus_task and batch and batch.current_focus_task_no:
|
||
focus_task = str(batch.current_focus_task_no or "").strip().upper()
|
||
|
||
focus_batch = explicit_batch
|
||
if not focus_batch and batch and batch.batch_no:
|
||
focus_batch = str(batch.batch_no or "").strip().upper()
|
||
elif (
|
||
not focus_batch
|
||
and explicit_task_row
|
||
and getattr(explicit_task_row, "batch", None) is not None
|
||
and getattr(explicit_task_row.batch, "batch_no", None)
|
||
):
|
||
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
|
||
|
||
runtime_context = build_shipping_runtime_context(
|
||
session_id=conv_id,
|
||
task=_focus_task_row(focus_task, explicit_task_row),
|
||
batch=batch or getattr(explicit_task_row, "batch", None),
|
||
trigger_source=trigger_source,
|
||
request_id=request_id,
|
||
locale=locale,
|
||
scope="task_run" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||
run_purpose=(
|
||
"chat_turn" if trigger_source == "backend_orchestrator"
|
||
else ("temporary_inventory" if temporary_inventory_asset_no else "chat_turn")
|
||
),
|
||
intake_nos=intake_nos,
|
||
capability=capability or ("temporary_inventory" if temporary_inventory_asset_no else None),
|
||
temporary_inventory_asset_no=temporary_inventory_asset_no,
|
||
temporary_inventory_session_no=resolved_temporary_session,
|
||
)
|
||
if not runtime_context:
|
||
return {}
|
||
from app.models import ChatSession
|
||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability
|
||
session = ChatSession.query.filter_by(session_id=conv_id).one_or_none()
|
||
capability_token = issue_chat_capability(
|
||
user_id=session.user_id, session_id=conv_id, agent_id=session.agent_id,
|
||
task_no=focus_task, batch_no=focus_batch,
|
||
) if session is not None else None
|
||
return {
|
||
AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context),
|
||
**({'shipping_chat_capability_token': capability_token} if capability_token else {}),
|
||
}
|