feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

@@ -1,18 +1,23 @@
"""
services/shipping_notice/agent_resolver.py
用途:定位发货通知聊天 Agent 的模型记录与名称常量。
依赖:app.models.Agent。
逻辑:由 dify_inputs、聊天入口或 Agent 相关编排调用本文件,确保发货通知流程绑定到正确的 Agent。
用途:定位发货通知聊天 Agent 的模型记录。
依赖:app.models.Agent、agent_registry.resolver(agent_code 列)。
逻辑:由 dify_executor、聊天入口或 Agent 相关编排调用本文件,确保发货通知流程绑定到正确的 Agent。
"""
from __future__ import annotations
from app.models import Agent
# 历史种子/展示用常量;运行时识别须使用 agent_code=shipping_notice。
CHAT_AGENT_NAME = "货代发货通知 Agent"
def resolve_chat_agent() -> Agent | None:
"""按 CHAT_AGENT_NAME 查找当前启用的发货通知聊天 Agent 记录。"""
return Agent.query.filter_by(name=CHAT_AGENT_NAME, is_active=True).first()
"""按 agent_code=shipping_notice 查找当前启用的发货通知聊天 Agent 记录。"""
return (
Agent.query.filter_by(agent_code='shipping_notice', is_active=True)
.order_by(Agent.id.asc())
.first()
)
@@ -0,0 +1,142 @@
"""
services/shipping_notice/batch_from_notices.py
用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。
依赖:shipping_tools、notice_upload、batch_orchestrator、query_service。
逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import build_notice_file_summary
from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary
def create_shipping_batch_from_notice_items(
*,
user_id: int,
conversation_id: str | None,
notice_items: list[dict[str, Any]],
file_summary: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
根据已抽取的发货通知条目创建批次并可选启动编排器。
Args:
user_id: 当前用户 ID。
conversation_id: 可选 Agent 会话 ID。
notice_items: notice_upload 产出的 notice item 列表。
file_summary: 可选文件预检摘要,写入响应供前端展示。
Returns:
与 workspace create-from-notices 一致的结果字典。
Raises:
ValidationError: notice_items 为空。
"""
if not notice_items:
from app.core.errors import ValidationError
raise ValidationError(
"all uploaded files failed extraction or contained no parseable text",
details={"file_summary": file_summary or {}},
)
payload = {
"user_id": user_id,
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
"defer_parse": True,
}
created = shipping_tools.create_batch_tasks(payload)
if not isinstance(created, dict):
return {"status": "failed", "message": "create batch failed"}
data = created.get("data") if isinstance(created.get("data"), dict) else {}
batch_data = data.get("batch") if isinstance(data.get("batch"), dict) else {}
batch_no = str(created.get("batch_no") or batch_data.get("batch_no") or "").strip()
orchestrator_started = False
if batch_no:
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
orchestrator_started = start_batch_orchestrator(batch_no)
if batch_no and isinstance(data, dict):
focus_task = get_focus_task_for_batch(batch_no, user_id)
if focus_task:
data["focus_task"] = serialize_task_summary(focus_task)
data["orchestrator_started"] = orchestrator_started
base_message = str(created.get("message") or "").strip()
if orchestrator_started:
created["message"] = f"{base_message},后台已开始逐票处理。" if base_message else "后台已开始逐票处理。"
if file_summary:
created["file_summary"] = file_summary
return created
def format_batch_created_assistant_message(
result: dict[str, Any],
*,
file_count: int = 0,
) -> str:
"""
格式化建批成功后写入 Chat Turn assistant 气泡的文案。
核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构。
"""
data = result.get("data") if isinstance(result.get("data"), dict) else {}
batch = data.get("batch") if isinstance(data.get("batch"), dict) else {}
tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else []
focus_task = tasks[0] if tasks and isinstance(tasks[0], dict) else {}
task_id = str(
(data.get("focus_task") or {}).get("task_no")
if isinstance(data.get("focus_task"), dict)
else ""
).strip() or str(result.get("task_id") or focus_task.get("task_id") or "").strip()
batch_no = str(result.get("batch_no") or batch.get("batch_no") or "").strip()
focus_progress = ""
if focus_task.get("batch_index") and focus_task.get("batch_total"):
focus_progress = f"当前第 {focus_task['batch_index']}/{focus_task['batch_total']} 票"
count = int(file_count or batch.get("file_count") or len(tasks) or 0)
hint = str(result.get("message") or "").strip()
status = str(result.get("status") or "").strip()
orchestrator_started = bool(data.get("orchestrator_started"))
tail = "请根据提示进行确认/驳回。" if status == "needs_human" else ""
lines = [
hint or f"已处理 {count} 份发货通知附件",
f"批次编号:{batch_no}" if batch_no else "",
f"当前任务:{task_id}" if task_id else "",
focus_progress,
f"后台已开始按票拆分处理,本批 {count} 票会逐步更新状态。" if orchestrator_started else "",
tail,
]
return "\n".join(line for line in lines if line)
def intake_notice_uploads_for_batch(
request_id: str,
uploads: list,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""
预检并抽取发货通知附件,返回 notice_items 与 file_summary。
Args:
request_id: 请求级临时目录 ID。
uploads: Werkzeug FileStorage 列表。
Returns:
(notice_items, file_summary)
"""
from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads
accepted, rejected = intake_temp_notice_uploads(request_id, uploads)
file_summary = build_notice_file_summary(
total_files=len(uploads),
accepted=accepted,
rejected=rejected,
)
notice_items = [item.to_notice_item() for item in accepted]
return notice_items, file_summary
@@ -0,0 +1,285 @@
"""
backend/app/services/shipping_notice/chat_action_extended_handlers.py
用途:货代 Chat Turn 扩展 Action Handler(上传/映射/切票/缺口查询)。
依赖:shipping_tools、task_workflow、tool_common、shipping_turn_helpers、action_registry。
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大。
"""
from __future__ import annotations
import io
from typing import Any, Iterator
from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
get_batch_for_user,
get_task_for_user,
serialize_task_detail,
)
from app.services.shipping_notice.shortage_details import format_shortage_details_message
from app.services.shipping_notice.shipping_turn_context import (
resolve_shipping_batch_no,
resolve_shipping_task_no,
)
from app.services.shipping_notice.shipping_turn_helpers import (
shipping_batch_ui_state_event,
shipping_task_ui_state_event,
stream_text_events,
tool_result_message,
)
from app.services.shipping_notice.task_workflow import replace_task_notice
from app.services.shipping_notice.tool_common import switch_batch_focus
def _payload_str(payload: dict[str, Any], *keys: str) -> str:
for key in keys:
value = str(payload.get(key) or "").strip()
if value:
return value
return ""
def _require_task(ctx: TurnContext):
task_no = resolve_shipping_task_no(ctx)
if not task_no:
raise ValidationError("task_no is required")
user_id = ctx.user_id
if user_id is None:
raise ValidationError("user context is required")
task = get_task_for_user(task_no, user_id)
if task is None:
raise NotFoundError(f"Task not found: {task_no}")
return task
def _filestorage_from_staged(staged: dict[str, Any]) -> FileStorage:
data = staged.get("data")
if not isinstance(data, (bytes, bytearray)):
raise ValidationError("upload file data is missing")
filename = str(staged.get("filename") or "upload").strip() or "upload"
content_type = str(staged.get("content_type") or "").strip() or None
return FileStorage(stream=io.BytesIO(bytes(data)), filename=filename, content_type=content_type)
def _first_staged_upload(ctx: TurnContext) -> FileStorage:
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
staged_files = payload.get("_staged_files")
if not isinstance(staged_files, list) or not staged_files:
raise ValidationError("upload file is required")
first = staged_files[0]
if not isinstance(first, dict):
raise ValidationError("invalid staged upload")
return _filestorage_from_staged(first)
def _format_inventory_upload_message(result: dict[str, Any], task_no: str) -> str:
base = tool_result_message(result) or "库存文件已上传。"
lines = [base, f"任务编号:{task_no}"]
checkpoint = str(result.get("checkpoint") or "").strip()
if checkpoint == "map_infer":
lines.append("下一步:请确认或调整列映射。")
elif checkpoint == "align_review":
lines.append("下一步:请核对字段对齐结果。")
return "\n".join(lines)
def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str:
data = result.get("data") if isinstance(result.get("data"), dict) else {}
orchestrator_started = bool(data.get("orchestrator_started"))
status = str(result.get("status") or "").strip()
lines = [
tool_result_message(result) or f"已重新上传发货通知并覆盖当前任务 {task_no}",
f"任务编号:{task_no}",
"后台已开始重新解析当前任务,请稍后查看进度自动刷新。" if orchestrator_started else "",
"请根据提示重新上传清晰文件,或粘贴通知正文。" if status == "needs_human" else "",
]
return "\n".join(line for line in lines if line)
def _format_mapping_applied_message(result: dict[str, Any], task_no: str, mapping: dict[str, str]) -> str:
mapping_text = ",".join(f"{key}={value}" for key, value in mapping.items())
hint = tool_result_message(result)
lines = [
f"映射已应用:{mapping_text}" if mapping_text else "映射已应用并解析库存。",
f"任务编号:{task_no}",
hint,
]
return "\n".join(line for line in lines if line)
class ShippingUploadInventoryAction:
action_type = "shipping.upload_inventory"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
upload = _first_staged_upload(ctx)
yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."})
result = shipping_tools.upload_inventory_file(task.task_no, upload)
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "upload_inventory failed")
from app.services.shipping_notice.query_service import get_task_by_ref
refreshed = get_task_by_ref(task.task_no) or task
yield shipping_task_ui_state_event(refreshed)
data = result.get("data") if isinstance(result.get("data"), dict) else {}
message_payload: dict[str, Any] = {
"task_no": task.task_no,
"tool_result": result,
"checkpoint": result.get("checkpoint"),
}
preview = data.get("schema_preview")
if isinstance(preview, dict):
message_payload["schema_preview"] = preview
content = _format_inventory_upload_message(result, task.task_no)
yield from stream_text_events(content, message_type="text", payload=message_payload)
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
class ShippingReplaceNoticeAction:
action_type = "shipping.replace_notice"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
upload = _first_staged_upload(ctx)
yield TurnEvent(event="step.started", data={"step_id": "replace_notice", "label": "重新上传发货通知..."})
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
raw = upload.read() or b""
intake = intake_notice_attachment(
filename=upload.filename or "notice",
raw=raw,
source_file_type=notice_source_file_type(upload),
storage="task",
task_no=task.task_no,
)
task.source_type = intake.source_type or task.source_type
result = replace_task_notice(
task,
raw_text=intake.text,
source_file_name=intake.filename,
source_file_type=intake.source_file_type,
warnings=list(intake.warnings),
)
if not isinstance(result, dict):
raise ValidationError("replace_notice failed")
if str(result.get("status") or "").lower() == "failed":
raise ValidationError(tool_result_message(result) or "replace_notice failed")
from app.services.shipping_notice.query_service import get_task_by_ref
refreshed = get_task_by_ref(task.task_no) or task
yield shipping_task_ui_state_event(refreshed)
batch_no = refreshed.batch.batch_no if refreshed.batch is not None else None
if batch_no and ctx.user_id is not None:
batch_event = shipping_batch_ui_state_event(batch_no, ctx.user_id)
if batch_event is not None:
yield batch_event
content = _format_replace_notice_message(result, task.task_no)
yield from stream_text_events(
content,
payload={"task_no": task.task_no, "batch_no": batch_no, "tool_result": result},
)
yield TurnEvent(event="step.completed", data={"step_id": "replace_notice"})
class ShippingApplyInventoryMappingAction:
action_type = "shipping.apply_inventory_mapping"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
mapping_raw = payload.get(MAP_JSON) or payload.get("map_json") or payload.get("mapping")
if not isinstance(mapping_raw, dict) or not mapping_raw:
raise ValidationError(f"{MAP_JSON} is required")
mapping = {str(k): str(v) for k, v in mapping_raw.items() if str(v or "").strip()}
if not mapping.get("sku") or not mapping.get("available_qty"):
raise ValidationError("sku and available_qty mapping are required")
yield TurnEvent(event="step.started", data={"step_id": "apply_inventory_mapping", "label": "应用列映射..."})
result = shipping_tools.apply_inventory_mapping({
"task_id": task.task_no,
MAP_JSON: mapping,
AUTO_CHAIN_FALLBACK: True,
"event_source": "chat_turn",
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "apply_inventory_mapping failed")
from app.services.shipping_notice.query_service import get_task_by_ref
refreshed = get_task_by_ref(task.task_no) or task
yield shipping_task_ui_state_event(refreshed)
content = _format_mapping_applied_message(result, task.task_no, mapping)
yield from stream_text_events(content, payload={"task_no": task.task_no, "mapping": mapping, "tool_result": result})
yield TurnEvent(event="step.completed", data={"step_id": "apply_inventory_mapping"})
class ShippingSwitchBatchFocusAction:
action_type = "shipping.switch_batch_focus"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
user_id = ctx.user_id
if user_id is None:
raise ValidationError("user context is required")
batch_no = resolve_shipping_batch_no(ctx)
if not batch_no:
raise ValidationError("batch_no is required")
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
task_no = _payload_str(payload, "task_no", "taskNo", "target_task_no").upper()
if not task_no:
task_no = resolve_shipping_task_no(ctx)
if not task_no:
raise ValidationError("task_no is required")
batch = get_batch_for_user(batch_no, user_id)
if batch is None:
raise NotFoundError(f"Batch not found: {batch_no}")
task = get_task_for_user(task_no, user_id)
if task is None or task.batch_id != batch.id:
raise NotFoundError("Task not found in batch")
yield TurnEvent(event="step.started", data={"step_id": "switch_batch_focus", "label": "切换焦点任务..."})
switch_batch_focus(
batch,
task,
source="chat_turn",
comment=_payload_str(payload, "comment") or None,
extra={"actor_user_id": user_id},
)
db.session.commit()
batch_event = shipping_batch_ui_state_event(batch_no, user_id)
if batch_event is not None:
yield batch_event
else:
yield shipping_task_ui_state_event(task)
content = f"已切换到任务 {task_no},请继续当前票处理。"
yield from stream_text_events(content, payload={"batch_no": batch_no, "task_no": task_no})
yield TurnEvent(event="step.completed", data={"step_id": "switch_batch_focus"})
class ShippingQueryShortageDetailsAction:
action_type = "shipping.query_shortage_details"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "query_shortage_details", "label": "查询缺口明细..."})
detail = serialize_task_detail(task)
content = format_shortage_details_message(detail if isinstance(detail, dict) else {})
yield from stream_text_events(content, payload={"task_no": task.task_no})
yield TurnEvent(event="step.completed", data={"step_id": "query_shortage_details"})
_HANDLERS = (
ShippingUploadInventoryAction(),
ShippingReplaceNoticeAction(),
ShippingApplyInventoryMappingAction(),
ShippingSwitchBatchFocusAction(),
ShippingQueryShortageDetailsAction(),
)
for _handler in _HANDLERS:
register_action_handler(_handler)
@@ -0,0 +1,315 @@
"""
backend/app/services/shipping_notice/chat_action_handlers.py
用途:货代发货通知 Chat Turn Action Handler 注册实现。
依赖:decision_workflow、fulfillment_workflow、inventory_rpa_workflow、query_service、ui_state、action_registry。
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow。
"""
from __future__ import annotations
from typing import Any, Iterator
from app.core.errors import NotFoundError, ValidationError
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
from app.services.shipping_notice.query_service import get_task_by_ref, get_task_for_user
from app.services.shipping_notice.shipping_turn_context import resolve_shipping_task_no
from app.services.shipping_notice.shipping_turn_helpers import (
shipping_batch_ui_state_event as _shipping_batch_ui_state_event,
shipping_task_ui_state_event as _shipping_ui_state_event,
stream_text_events as _stream_text_events,
tool_result_message as _tool_result_message,
)
def _payload_str(payload: dict[str, Any], *keys: str) -> str:
for key in keys:
value = str(payload.get(key) or "").strip()
if value:
return value
return ""
def _require_task(ctx: TurnContext):
task_no = resolve_shipping_task_no(ctx)
if not task_no:
raise ValidationError("task_no is required")
user_id = ctx.user_id
if user_id is None:
raise ValidationError("user context is required")
task = get_task_for_user(task_no, user_id)
if task is None:
raise NotFoundError(f"Task not found: {task_no}")
return task
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
lines = [_tool_result_message(result) or "操作已完成。"]
data = result.get("data") if isinstance(result.get("data"), dict) else {}
if decision == "correct_inventory_mapping":
preview = data.get("schema_preview") if isinstance(data.get("schema_preview"), dict) else {}
headers = [str(item) for item in (preview.get("headers") or []) if item]
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
header_row_index = preview.get("header_row_index")
if header_row_index:
lines.extend(["", f"表头在第 {header_row_index} 行:{' | '.join(headers)}"])
elif headers:
lines.extend(["", f"当前表头:{' | '.join(headers)}"])
mapping_lines = [
f"- sku → {suggested['sku']}" if suggested.get("sku") else None,
f"- reservation_id → {suggested['reservation_id']}" if suggested.get("reservation_id") else None,
f"- available_qty → {suggested['available_qty']}" if suggested.get("available_qty") else None,
]
mapping_lines = [line for line in mapping_lines if line]
if mapping_lines:
lines.extend(["", "建议列映射:", *mapping_lines])
lines.extend([
"",
"如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。",
"也可点击「选择库存文件」重新上传。",
])
elif decision == "confirm_inventory_mapping":
if str(result.get("checkpoint") or "").strip() == "map_ok":
lines.extend(["", "下一步:匹配库存与发货需求。"])
elif decision == "reparse_inventory":
lines.extend(["", "请重新上传或粘贴库存 Excel。"])
lines.extend(["", f"任务编号:{task_no}"])
return "\n".join(lines)
def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any]:
data = result.get("data") if isinstance(result.get("data"), dict) else {}
line_results = data.get("line_results") if isinstance(data.get("line_results"), list) else []
shortage = data.get("shortage") if isinstance(data.get("shortage"), dict) else {}
shortage_lines = shortage.get("lines") if isinstance(shortage.get("lines"), list) else []
action_buttons = result.get("action_buttons") if isinstance(result.get("action_buttons"), list) else []
return {
"taskId": task_no,
"match_status": data.get("match_status"),
"line_results": line_results,
"shortage_lines": shortage_lines,
"action_buttons": action_buttons,
}
class ShippingCreateBatchFromNoticesAction:
"""上传发货通知附件并创建批次。"""
action_type = "shipping.create_batch_from_notices"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
user_id = ctx.user_id
if user_id is None:
raise ValidationError("user context is required")
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
notice_items = payload.get("notice_items")
if not isinstance(notice_items, list) or not notice_items:
raise ValidationError("notice_items is required")
file_summary = payload.get("file_summary") if isinstance(payload.get("file_summary"), dict) else None
conversation_id = _payload_str(payload, "conversation_id", "conversationId") or None
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_notices", "label": "处理发货通知..."})
from app.services.shipping_notice.batch_from_notices import (
create_shipping_batch_from_notice_items,
format_batch_created_assistant_message,
)
result = create_shipping_batch_from_notice_items(
user_id=user_id,
conversation_id=conversation_id,
notice_items=notice_items,
file_summary=file_summary,
)
batch_no = str(result.get("batch_no") or "").strip()
if batch_no:
batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
if batch_event is not None:
yield batch_event
file_count = len(notice_items)
content = format_batch_created_assistant_message(result, file_count=file_count)
data = result.get("data") if isinstance(result.get("data"), dict) else {}
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
message_payload = {
"batch_no": batch_no,
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
"orchestrator_started": bool(data.get("orchestrator_started")),
}
yield from _stream_text_events(content, message_type="text", payload=message_payload)
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"})
class ShippingSubmitDecisionAction:
"""提交人工决策:confirm / reject / rematch / retry_rpa 等。"""
action_type = "shipping.submit_decision"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
decision = _payload_str(payload, "decision").lower()
if not decision:
raise ValidationError("decision is required")
yield TurnEvent(event="step.started", data={"step_id": "submit_decision", "label": "提交决策..."})
result = submit_decision({
"task_id": task.task_no,
"decision": decision,
"comment": _payload_str(payload, "comment"),
"event_source": "chat_turn",
})
if not isinstance(result, dict):
raise ValidationError("invalid submit_decision response")
if str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result) or "submit_decision failed")
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
content = _format_decision_message(decision, result, task.task_no)
yield TurnEvent(
event="message.completed",
data={
"content": content,
"message_type": "text",
"payload": {
"decision": decision,
"task_no": task.task_no,
"tool_result": result,
},
},
)
yield TurnEvent(event="step.completed", data={"step_id": "submit_decision"})
class ShippingGenerateExcelAction:
action_type = "shipping.generate_excel"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "generate_excel", "label": "生成发货 Excel..."})
result = shipping_tools.generate_excel({"task_id": task.task_no, "event_source": "chat_turn"})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "generate_excel failed")
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
content = "\n".join(filter(None, [_tool_result_message(result), f"任务编号:{task.task_no}"]))
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
yield TurnEvent(event="step.completed", data={"step_id": "generate_excel"})
class ShippingRetryUploadAction:
action_type = "shipping.retry_upload"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "retry_upload", "label": "重试上传货代..."})
result = shipping_tools.upload_to_freight({
"task_id": task.task_no,
"mode": "retry_upload",
"event_source": "chat_turn",
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "retry_upload failed")
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
content = _tool_result_message(result) or "已触发重试上传。"
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
yield TurnEvent(event="step.completed", data={"step_id": "retry_upload"})
class ShippingMatchInventoryAction:
action_type = "shipping.match_inventory"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "match_inventory", "label": "匹配库存..."})
result = shipping_tools.match_inventory({
"task_id": task.task_no,
AUTO_CHAIN_FALLBACK: True,
"event_source": "chat_turn",
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "match_inventory failed")
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
payload = _match_result_payload(task.task_no, result)
content = _tool_result_message(result) or "库存匹配已完成。"
yield TurnEvent(
event="message.completed",
data={
"content": content,
"message_type": "shipping-match-result",
"payload": payload,
},
)
yield TurnEvent(event="step.completed", data={"step_id": "match_inventory"})
class ShippingConfirmInventorySourceAction:
action_type = "shipping.confirm_inventory_source"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
source_code = _payload_str(payload, "source_code", "sourceCode").upper()
if not source_code:
raise ValidationError("source_code is required")
yield TurnEvent(event="step.started", data={"step_id": "confirm_inventory_source", "label": "确认库存源..."})
result = shipping_tools.confirm_inventory_source({
"task_id": task.task_no,
"source_code": source_code,
"event_source": "chat_turn",
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed")
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
content = _tool_result_message(result) or f"已确认库存源 {source_code}。"
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
yield TurnEvent(event="step.completed", data={"step_id": "confirm_inventory_source"})
class ShippingMarkManualUploadedAction:
action_type = "shipping.mark_manual_uploaded"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "mark_manual_uploaded", "label": "确认手工上传..."})
result = shipping_tools.upload_to_freight({
"task_id": task.task_no,
"mode": "manual_confirm",
"event_source": "chat_turn",
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "mark_manual_uploaded failed")
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
content = _tool_result_message(result) or f"好的,任务 {task.task_no} 已确认完成,无需再处理。"
yield TurnEvent(
event="message.completed",
data={
"content": content,
"message_type": "text",
"payload": {"shipping_actions_used": True},
},
)
yield TurnEvent(event="step.completed", data={"step_id": "mark_manual_uploaded"})
_HANDLERS = (
ShippingCreateBatchFromNoticesAction(),
ShippingSubmitDecisionAction(),
ShippingGenerateExcelAction(),
ShippingRetryUploadAction(),
ShippingMatchInventoryAction(),
ShippingConfirmInventorySourceAction(),
ShippingMarkManualUploadedAction(),
)
for _handler in _HANDLERS:
register_action_handler(_handler)
@@ -0,0 +1,53 @@
"""
backend/app/services/shipping_notice/context_adapter.py
用途:发货通知 Agent 的 Context Adapter,构建 agent_runtime_context Dify inputs。
依赖:shipping_notice.dify_inputs.build_dify_chat_inputs、agent_runtime_context.registry。
逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传 task/batch。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_runtime_context.registry import register_context_adapter
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs
@register_context_adapter('shipping_notice')
def build_shipping_notice_context_adapter(
*,
agent,
session_id: str,
adapter_hints: dict[str, Any] | None = None,
request_id: str | None = None,
trigger_source: str | None = 'frontend_chat',
locale: str | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
构建发货通知 Dify Start inputs。
核心逻辑:从 adapter_hints.shipping_notice 读取 task_id/batch_no,委托 dify_inputs 组装 runtime_context。
Args:
agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。
session_id: HXOPS 会话 ID。
adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id、batch_no。
request_id: 请求追踪 ID。
trigger_source: 触发来源。
locale: 用户语言。
Returns:
含 agent_runtime_context 的 Dify inputs;session_id 为空时返回空 dict。
"""
shipping_hints = adapter_hints.get('shipping_notice') if isinstance(adapter_hints, dict) else {}
shipping_hints = shipping_hints if isinstance(shipping_hints, dict) else {}
return build_dify_chat_inputs(
session_id,
task_id=shipping_hints.get('task_id'),
batch_no=shipping_hints.get('batch_no'),
trigger_source=trigger_source,
request_id=request_id,
locale=locale,
)
@@ -47,6 +47,7 @@ from app.services.shipping_notice.tool_common import (
log_task_event,
merge_tool_payload,
payload_wants_auto_chain_fallback,
prepend_tool_message,
)
from app.services.shipping_notice.tool_response import tool_response
@@ -58,12 +59,33 @@ def start_task_orchestrator(task_no: str | None) -> bool:
return _start(task_no)
def _reset_inventory_state_for_forced_rpa(task) -> None:
"""
清理旧库存派生结果,让 retry_rpa 成为真正的“重新获取库存”。
【AI 触发时机】:用户明确要求重新获取库存时由 submit_decision 内部调用。
"""
task.inventory_lines_json = None
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“更正映射”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、映射确认、重匹配或重解析等分支。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、映射确认、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。
Args:
payload: 必须包含任务定位信息与 decision,可选 comment、lang 等上下文。
@@ -223,8 +245,12 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
# retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "retry_rpa":
log_task_event(task, "decision_retry_rpa", {"comment": comment})
task.error_message = None
_reset_inventory_state_for_forced_rpa(task)
log_task_event(
task,
"decision_retry_rpa",
{"comment": comment, "force_refresh": True},
)
db.session.flush()
retry_payload = merge_tool_payload(
task,
@@ -245,14 +271,16 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
source=event_source,
comment=comment,
)
db.session.commit()
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.rematch_running", lang=lang),
data=serialize_task_for_tool(task),
)
# flush 即可:清状态与 match_inventory 的最终 commit 同属一次连续写入,避免中间态落库。
db.session.flush()
# [STEP 3.1] 重新匹配须同步完成库存计算,避免退回 ready_to_match 后再让用户点 match_inventory。
match_result = match_inventory(merge_tool_payload(task, payload))
if match_result.get("status") != "failed":
match_result = prepend_tool_message(
match_result,
t("workflow.decision.rematch_done", lang=lang),
)
return match_result
if decision == "confirm_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
@@ -2,9 +2,10 @@
services/shipping_notice/dify_inputs.py
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
依赖:agent_runtime_context 平台协议、agent_resolver、models.ShippingBatch/ShippingTask、shipping_notice.runtime_context。
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
依赖:agent_runtime_context 平台协议、models.ShippingBatch/ShippingTask、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
@@ -14,19 +15,9 @@ from typing import Any
from app.models import ShippingBatch, ShippingTask
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.agent_resolver import CHAT_AGENT_NAME
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
def is_shipping_notice_chat_agent(agent) -> bool:
"""判断 Agent 记录是否为发货通知聊天 Agent。"""
agent_name = str(getattr(agent, "name", None) or "").strip()
if agent_name == CHAT_AGENT_NAME:
return True
normalized_name = agent_name.replace(" ", "")
return "发货通知" in normalized_name and "Agent" in normalized_name
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
"""按会话号获取最近一个发货批次,用于恢复当前批次焦点。"""
conv_id = str(conversation_id or "").strip()
+4 -4
View File
@@ -72,7 +72,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.parse_confirmed_running": "发货通知已确认,后台已开始继续处理库存与后续步骤。",
"workflow.decision.inventory_preparing": "已确认,后台继续处理库存准备步骤。",
"workflow.decision.fulfillment_running": "发货通知已确认,后台继续处理库存与后续步骤。",
"workflow.decision.rematch_running": "已提交重新匹配请求,后台继续处理。",
"workflow.decision.rematch_done": "已重新完成库存匹配。",
"workflow.decision.mapping_confirmed_running": "库存字段对齐已确认,后台继续处理匹配与后续步骤。",
"workflow.decision.task_not_found": "未找到明确任务。用户说「确认/重新解析/驳回」时禁止 create_task;多票会话必须带任务编号。",
"workflow.decision.rejected": "已驳回该发货任务。",
@@ -115,7 +115,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
"workflow.inventory.ready_for_match": "已有库存快照且字段对齐已确认,可调用 match_inventory。",
"workflow.inventory.unavailable": "暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
"workflow.inventory.unavailable": "暂无可用库存数据。请重新获取库存,或手动上传货代库存 Excel。",
"workflow.fulfillment.task_not_found": "未找到任务编号",
"workflow.fulfillment.match_running": "正在执行库存匹配",
"workflow.fulfillment.match_running_detail": "按 SKU + Reservation ID 逐行比对需求与库存",
@@ -207,7 +207,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.parse_confirmed_running": "The shipping notice is confirmed. The backend has started inventory handling and the remaining steps.",
"workflow.decision.inventory_preparing": "Confirmed. The backend is continuing the inventory preparation steps.",
"workflow.decision.fulfillment_running": "The shipping notice is confirmed. The backend is continuing inventory handling and the remaining steps.",
"workflow.decision.rematch_running": "The rematch request has been submitted. The backend is continuing processing.",
"workflow.decision.rematch_done": "Inventory rematch has been completed.",
"workflow.decision.mapping_confirmed_running": "The inventory mapping is confirmed. The backend is continuing matching and the remaining steps.",
"workflow.decision.task_not_found": "No unambiguous task was found. When the user says confirm / re-parse / reject, do not call create_task; multi-task conversations must include the task ID.",
"workflow.decision.rejected": "The shipping task has been rejected.",
@@ -342,7 +342,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.decision.parse_confirmed_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านได้เริ่มจัดการสต็อกและขั้นตอนถัดไปต่อแล้ว",
"workflow.decision.inventory_preparing": "ยืนยันแล้ว ระบบหลังบ้านกำลังดำเนินขั้นตอนเตรียมสต็อกต่อ",
"workflow.decision.fulfillment_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านกำลังดำเนินการสต็อกและขั้นตอนถัดไปต่อ",
"workflow.decision.rematch_running": "ส่งคำขอจับคู่ใหม่แล้ว ระบบหลังบ้านกำลังดำเนินการต่อ",
"workflow.decision.rematch_done": "จับคู่สต็อกใหม่เสร็จแล้ว",
"workflow.decision.mapping_confirmed_running": "ยืนยันการจับคู่คอลัมน์สต็อกแล้ว ระบบหลังบ้านกำลังดำเนินการจับคู่และขั้นตอนถัดไปต่อ",
"workflow.decision.task_not_found": "ไม่พบงานที่ระบุได้ชัดเจน เมื่อผู้ใช้พูดว่ายืนยัน / แยกใหม่ / ปฏิเสธ ห้ามเรียก create_task และหากมีหลายงานต้องส่ง task ID มาด้วย",
"workflow.decision.rejected": "ปฏิเสธงานจัดส่งนี้แล้ว",
@@ -76,17 +76,17 @@ def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_r
def _inventory_rpa_running_prefix(*, attempt_no: int, max_attempts: int) -> str:
"""生成库存 RPA 运行中的简短前缀,单次模式不暴露 1/1 计数。"""
if max_attempts <= 1:
return "RPA 库存导出进行中。"
return f"RPA 库存导出进行中(第 {attempt_no}/{max_attempts} 次)。"
return "库存获取进行中。"
return f"库存获取进行中(第 {attempt_no}/{max_attempts} 次)。"
def _inventory_rpa_triggered_prefix(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
"""生成库存 RPA 触发成功后的摘要文案,区分自动单次、自动多次与人工重试。"""
if manual_retry_round:
return f"已手动重新触发 RPA 库存导出(手动第 {attempt_no} 次)。"
return f"已重新触发库存获取(第 {attempt_no} 次)。"
if max_attempts <= 1:
return "已触发 RPA 库存导出。"
return f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
return "已触发库存获取。"
return f"已触发库存获取(第 {attempt_no}/{max_attempts} 次)。"
def _inventory_rpa_exhausted_message(attempts: int) -> str:
@@ -96,6 +96,24 @@ def _inventory_rpa_exhausted_message(attempts: int) -> str:
return f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
def _save_last_inventory_rpa_runtime(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any]:
"""保存 worker 回调上报的实际执行模式,供前端显示本次真实来源。"""
raw_mode = str(payload.get("rpa_mode") or payload.get("mode") or "").strip().lower()
mode = raw_mode if raw_mode in {"browser", "mock"} else None
runtime = {
"mode": mode or "browser",
"source": "worker_callback" if mode else "callback_default",
"reported_at": datetime.utcnow().isoformat(),
}
source_code = str(payload.get("source_code") or "").strip()
if source_code:
runtime["source_code"] = source_code
step_payload = dict(task.step_payload_json or {})
step_payload["last_inventory_rpa_runtime"] = runtime
task.step_payload_json = step_payload
return runtime
def _inventory_rpa_running_message(*, attempt_no: int, max_attempts: int) -> str:
"""
生成库存 RPA 等待中的用户提示。
@@ -373,9 +391,9 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
progress_message = (
"已手动重新触发 RPA 库存导出,等待结果"
"已重新触发库存获取,等待结果"
if manual_retry_round
else "已触发 RPA 库存导出,等待结果"
else "已触发库存获取,等待结果"
)
progress_detail = _inventory_rpa_attempt_label(
attempt_no=attempt_no,
@@ -430,7 +448,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
progress_percent=100,
current=0,
total=max_attempts,
detail="请重试 RPA 自动导出,或手动上传货代库存 Excel。",
detail="请重新获取库存,或手动上传货代库存 Excel。",
)
log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"})
db.session.commit()
@@ -454,10 +472,11 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 1] 先处理 RPA 回调失败分支。
# 失败时要累计尝试次数,并在耗尽后明确切换到人工上传兜底。
success = bool(payload.get("success", True))
runtime = _save_last_inventory_rpa_runtime(task, payload)
if not success:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
log_task_event(task, "inventory_rpa_failed", {"error": task.error_message})
log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime})
db.session.flush()
attempts = inventory_rpa_attempts(task)
if attempts >= max_rpa_inventory_attempts():
@@ -506,10 +525,11 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
log_task_event(
task,
"inventory_uploaded",
{
"source": "rpa_callback",
"upload_filename": managed_path.name,
"inventory_uploaded",
{
"source": "rpa_callback",
"rpa_runtime": runtime,
"upload_filename": managed_path.name,
"upload_path": str(managed_path),
"origin_file_path": str(path),
"inventory_file_no": inv_file.inventory_file_no,
@@ -190,7 +190,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
"decision": _str_prop(
"confirm=确认继续;reject=驳回;retry_rpa=重试 RPA 库存导出;rematch=重新匹配;reparse=重新解析;"
"confirm=确认继续;reject=驳回;retry_rpa=重新获取库存(清理旧库存解析状态并重新触发 RPA);rematch=重新匹配;reparse=重新解析;"
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
enum=[
"confirm",
@@ -247,7 +247,9 @@ def resolve_task_from_payload(
def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"""Tool data 基础字段(裁剪前)。"""
from app.services.shipping_notice.notice_upload import max_notice_chars
from app.services.shipping_notice.rpa import rpa_runtime_mode
step_payload = task.step_payload_json or {}
payload: dict[str, Any] = {
"task_no": task.task_no,
"process_status": task.process_status,
@@ -267,7 +269,8 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"freight_ref_no": task.freight_ref_no,
"error_message": task.error_message,
"conversation_id": task.conversation_id,
"step_payload": task.step_payload_json or {},
"step_payload": step_payload,
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
}
raw_content = str(task.raw_content or "").strip()
lines = task.lines_json or []
@@ -282,6 +285,8 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
from app.services.shipping_notice.rpa import rpa_runtime_mode
if projection == TaskProjection.TOOL:
from app.services.shipping_notice.user_facing_status import strip_internal_task_fields
@@ -289,6 +294,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
if projection == TaskProjection.TOOL_INTERNAL:
return _task_tool_payload(task)
if projection == TaskProjection.SUMMARY:
step_payload = task.step_payload_json or {}
return {
"id": task.id,
"task_no": task.task_no,
@@ -311,9 +317,10 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
"conversation_id": task.conversation_id,
"export_file_name": task.export_file_name,
"freight_ref_no": task.freight_ref_no,
"step_payload": task.step_payload_json or {},
"rpa_inventory_source": (task.step_payload_json or {}).get("rpa_inventory_source") if isinstance(task.step_payload_json, dict) else None,
"inventory_source_resolution": (task.step_payload_json or {}).get("inventory_source_resolution") if isinstance(task.step_payload_json, dict) else None,
"step_payload": step_payload,
"rpa_runtime": rpa_runtime_mode(step_payload.get("last_inventory_rpa_runtime") if isinstance(step_payload, dict) else None),
"rpa_inventory_source": step_payload.get("rpa_inventory_source") if isinstance(step_payload, dict) else None,
"inventory_source_resolution": step_payload.get("inventory_source_resolution") if isinstance(step_payload, dict) else None,
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"created_at": task.created_at.isoformat() if task.created_at else None,
@@ -9,6 +9,7 @@ services/shipping_notice/rpa.py
from __future__ import annotations
import json
import os
import shutil
from datetime import datetime
from pathlib import Path
@@ -17,6 +18,27 @@ from typing import Any
from flask import current_app
def _runtime_summary(mode: str) -> dict[str, str | bool]:
"""将 browser/mock 规范化为前端安全展示摘要。"""
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
mock_enabled = normalized == "mock"
return {
"mode": normalized,
"label": "Mock RPA" if mock_enabled else "真实 RPA",
"mock": mock_enabled,
}
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
if isinstance(runtime, dict):
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}:
return _runtime_summary(mode)
raw = str(os.getenv("FREIGHT_RPA_MOCK", current_app.config.get("FREIGHT_RPA_MOCK", "false")) or "false").strip().lower()
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
@@ -0,0 +1,75 @@
"""
services/shipping_notice/shipping_turn_context.py
用途:货代 Chat Turn 领域上下文解析(task_no / batch_no 等 refs 键名约定)。
依赖:turn_context.TurnContext。
逻辑:chat_action_handlers 通过本模块解析货代专属锚点;平台 turn_context 不感知这些键名。
"""
from __future__ import annotations
from typing import Any
from app.services.chat.turn_context import TurnContext
# 与 agent_runtime_context.refs 及前端 shipping 上下文对齐的键名约定。
SHIPPING_REF_TASK_NO = "task_no"
SHIPPING_REF_BATCH_NO = "batch_no"
_TASK_PAYLOAD_KEYS = ("task_no", "taskNo", "task_id", "taskId")
_TASK_REF_KEYS = (SHIPPING_REF_TASK_NO, "taskNo", "task_id", "taskId")
_BATCH_PAYLOAD_KEYS = ("batch_no", "batchNo")
_BATCH_REF_KEYS = (SHIPPING_REF_BATCH_NO, "batchNo")
def _first_non_empty(values: tuple[str, ...]) -> str:
for value in values:
text = str(value or "").strip()
if text:
return text
return ""
def _read_payload_str(payload: dict[str, Any], *keys: str) -> str:
for key in keys:
value = str(payload.get(key) or "").strip()
if value:
return value
return ""
def resolve_shipping_task_no(ctx: TurnContext) -> str:
"""
从 action payload 或 session refs 解析货代任务编号。
优先级:payload.task_no/taskNo/task_id > refs.task_no/taskNo。
Args:
ctx: 当前 Chat Turn 上下文。
Returns:
归一化大写 task_no;无法解析时返回空串。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
from_payload = _read_payload_str(payload, *_TASK_PAYLOAD_KEYS).upper()
if from_payload:
return from_payload
from_refs = _first_non_empty(tuple(ctx.refs.get(key, "") for key in _TASK_REF_KEYS)).upper()
return from_refs
def resolve_shipping_batch_no(ctx: TurnContext) -> str:
"""
从 action payload 或 session refs 解析货代批次编号。
Args:
ctx: 当前 Chat Turn 上下文。
Returns:
batch_no 文本;无法解析时返回空串。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
from_payload = _read_payload_str(payload, *_BATCH_PAYLOAD_KEYS)
if from_payload:
return from_payload
return _first_non_empty(tuple(ctx.refs.get(key, "") for key in _BATCH_REF_KEYS))
@@ -0,0 +1,88 @@
"""
services/shipping_notice/shipping_turn_helpers.py
用途:货代 Chat Turn handler 共用的 SSE 事件构造与 UI State 回写。
依赖:action_schema.TurnEvent、ui_state、query_service。
逻辑:chat_action_handlers 与 chat_action_extended_handlers 复用本模块,避免重复 yield 逻辑。
"""
from __future__ import annotations
from typing import Any, Iterator
from app.services.chat.action_schema import TurnEvent
from app.services.shipping_notice.query_service import get_batch_for_user
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
def stream_text_events(
content: str,
*,
message_type: str = "text",
payload: dict[str, Any] | None = None,
chunk_size: int = 24,
) -> Iterator[TurnEvent]:
"""
分片 yield message.delta,最后 message.completed,供前端呈现 SSE 流式效果。
Args:
content: 完整 assistant 文案。
message_type: ChatLog / 前端消息类型。
payload: 可选结构化 payload。
chunk_size: 每个 delta 块字符数。
"""
text = str(content or "").strip()
if not text:
yield TurnEvent(event="message.completed", data={"content": "", "message_type": message_type})
return
for index in range(0, len(text), chunk_size):
yield TurnEvent(event="message.delta", data={"content": text[index:index + chunk_size]})
completed: dict[str, Any] = {"content": text, "message_type": message_type}
if payload:
completed["payload"] = payload
yield TurnEvent(event="message.completed", data=completed)
def shipping_task_ui_state_event(task) -> TurnEvent:
"""单票任务 ui_state.updated 事件。"""
ui_state = build_task_ui_state(task)
batch_no = task.batch.batch_no if task.batch is not None else None
return TurnEvent(
event="ui_state.updated",
data={
"domain": "shipping",
"task_no": task.task_no,
"batch_no": batch_no,
"payload": {
"task_no": task.task_no,
"batch_no": batch_no,
"ui_state": ui_state,
},
},
)
def shipping_batch_ui_state_event(batch_no: str, user_id: int) -> TurnEvent | None:
"""批次级 ui_state.updated 事件。"""
batch = get_batch_for_user(batch_no, user_id)
if batch is None:
return None
batch_state = build_batch_ui_state(batch)
focus_task_no = str(batch_state.get("current_focus_task_no") or "").strip()
return TurnEvent(
event="ui_state.updated",
data={
"domain": "shipping",
"batch_no": batch_no,
"task_no": focus_task_no or None,
"payload": {
"batch_no": batch_no,
"batch_ui_state": batch_state,
"task_no": focus_task_no or None,
},
},
)
def tool_result_message(result: dict[str, Any]) -> str:
return str(result.get("message") or "").strip()
@@ -0,0 +1,64 @@
"""
services/shipping_notice/shortage_details.py
用途:发货缺口明细确定性格式化(Chat Turn / 工作台共用)。
依赖:query_service 序列化结构。
逻辑:shipping.query_shortage_details handler 调用;禁止把缺口数量交给 LLM 推理。
"""
from __future__ import annotations
from typing import Any
def _format_qty(value: Any) -> str:
try:
num = float(value or 0)
except (TypeError, ValueError):
return "-"
if num == int(num):
return f"{int(num):,}"
return f"{num:,.3f}"
def shortage_lines_for_task(task_data: dict[str, Any]) -> list[dict[str, Any]]:
shortage = task_data.get("shortage") if isinstance(task_data.get("shortage"), dict) else {}
lines = shortage.get("lines") if isinstance(shortage.get("lines"), list) else []
if lines:
return [line for line in lines if isinstance(line, dict)]
line_results = task_data.get("line_results") if isinstance(task_data.get("line_results"), list) else []
return [
line for line in line_results
if isinstance(line, dict) and float(line.get("shortage_qty") or 0) > 0
]
def format_shortage_details_message(task_data: dict[str, Any]) -> str:
"""
格式化缺口明细 assistant 消息。
Args:
task_data: serialize_task_detail / serialize_task_summary 风格字典。
Returns:
多行文本,供 Chat Turn 流式输出。
"""
task_no = str(task_data.get("task_no") or "").strip()
lines = shortage_lines_for_task(task_data)
if not lines:
return f"任务 {task_no or '-'} 当前没有可展示的缺口明细。"
file_label = str(
task_data.get("source_file_name")
or task_data.get("customer_name")
or "-"
).strip()
parts = [f"任务 {task_no}({file_label})缺口明细:"]
for index, line in enumerate(lines, start=1):
parts.append(
f"{index}. SKU={line.get('sku') or '-'} "
f"Reservation={line.get('reservation_id') or '-'} "
f"需求={_format_qty(line.get('required_qty'))} "
f"可用={_format_qty(line.get('available_qty'))} "
f"缺口={_format_qty(line.get('shortage_qty'))}"
)
return "\n".join(parts)
@@ -73,7 +73,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
"retry_rpa": {"label": "重新获取库存", "message": "重新获取库存", "variant": "secondary"},
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
@@ -114,6 +114,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
"retry_rpa",
"reject",
),
CP_MAP_INFER: (
@@ -130,7 +131,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
"upload_inventory_file",
),
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
RS_SHORTAGE_REVIEW: ("reparse_inventory", "correct_inventory_mapping", "rematch", "reject"),
RS_SHORTAGE_REVIEW: ("reparse_inventory", "rematch", "reject"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),