feat(chat): 更新发货任务处理逻辑和界面文本
- 移除不必要的状态引用 - 更新上传处理提示文本,使用国际化支持 - 扩展发货任务摘要接口,增加错误信息和短缺信息 - 更新多语言支持的文本,改善用户体验 - 增加批次工作区的汇总信息和操作提示
This commit is contained in:
1 parent
0b083cfdbd
commit
1fc9976ca3
60 files changed
+3876
-639
No files matched your search
@@ -514,6 +514,7 @@ class DifyService:
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
inputs: dict[str, Any] | None = None,
|
||||
persist_chat_log: bool = True,
|
||||
display_query: str | None = None,
|
||||
):
|
||||
"""
|
||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||
@@ -538,6 +539,7 @@ class DifyService:
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
url = DifyService._build_chat_messages_url(base_url)
|
||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||
visible_query = str(display_query or query or '').strip()
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
@@ -648,7 +650,7 @@ class DifyService:
|
||||
session_id=session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
query=visible_query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
|
||||
@@ -14,12 +14,13 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.task_workflow import recompute_batch_summary
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, cfg_bool, cfg_int, log_task_event
|
||||
from app.services.shipping_notice.tools import auto_progress
|
||||
from app.services.shipping_notice.tools import auto_progress, submit_decision
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
_RUNNING_TASKS: set[str] = set()
|
||||
@@ -59,10 +60,17 @@ def _unmark_running(bucket: set[str], key: str) -> None:
|
||||
|
||||
def _should_orchestrate_task(task: Any) -> bool:
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
||||
@@ -73,10 +81,13 @@ def _should_orchestrate_task(task: Any) -> bool:
|
||||
def _is_retryable_task(task: Any) -> bool:
|
||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if process_status == "waiting_inventory" and pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
return True
|
||||
@@ -111,7 +122,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
if not _should_orchestrate_task(task):
|
||||
return {
|
||||
"status": "skipped",
|
||||
"message": f"skip process_status={task.process_status or ''}",
|
||||
"message": (
|
||||
f"skip process_status={task.process_status or ''}"
|
||||
f" pending_human_reason={task.pending_human_reason or ''}"
|
||||
f" review_status={task.review_status or ''}"
|
||||
),
|
||||
}
|
||||
|
||||
_refresh_batch_focus(task.task_no)
|
||||
@@ -125,8 +140,27 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
db.session.commit()
|
||||
|
||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
||||
if str(task.process_status or "").strip().lower() == "created":
|
||||
process_status = str(task.process_status or "").strip().lower()
|
||||
pending_reason = str(task.pending_human_reason or "").strip().lower()
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
result = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif process_status == "created":
|
||||
result = run_shipping_parse_via_dify(task.task_no)
|
||||
# Dify 会通过 Tool API 在独立请求中提交 parse_notice;当前 worker session
|
||||
# 可能仍缓存 created 旧对象,必须重新读库后才能决定是否继续 auto_progress。
|
||||
db.session.expire_all()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
||||
@@ -307,7 +341,7 @@ def start_batch_orchestrator(batch_no: str | None) -> bool:
|
||||
|
||||
|
||||
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
"""重试批次中仍可自动推进的任务,跳过已终态和人工阻断任务。"""
|
||||
"""重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no:
|
||||
return {"status": "failed", "message": "batch_no is required"}
|
||||
@@ -321,6 +355,24 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
if not _is_retryable_task(task):
|
||||
skipped += 1
|
||||
continue
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
|
||||
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_EXHAUSTED:
|
||||
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if start_task_orchestrator(task.task_no):
|
||||
started += 1
|
||||
else:
|
||||
|
||||
@@ -198,11 +198,20 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
|
||||
if decision == "retry_rpa":
|
||||
log_task_event(task, "decision_retry_rpa", {"comment": comment})
|
||||
task.error_message = None
|
||||
db.session.flush()
|
||||
retry_payload = merge_tool_payload(task, payload, extra={"mode": "retry_rpa"})
|
||||
retry_payload = merge_tool_payload(
|
||||
task,
|
||||
payload,
|
||||
extra={"mode": "retry_rpa", "manual_retry_round": True},
|
||||
)
|
||||
return ensure_inventory(retry_payload)
|
||||
|
||||
if decision == "rematch":
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
log_task_event(task, "decision_rematch", {"comment": comment})
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
|
||||
@@ -126,10 +126,14 @@ def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | Non
|
||||
.first()
|
||||
)
|
||||
def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
|
||||
"""是否应在 match 成功后自动串联 generate_excel / upload_to_freight(Hxops fallback 链)。"""
|
||||
"""是否应在 match 成功后自动串联低风险履约步骤。
|
||||
|
||||
fulfillable 后生成 Excel 是幂等、可审计的低风险步骤,应由后端默认推进;
|
||||
auto_chain_fallback 仅保留为兼容旧聊天 fallback 链的显式触发信号。
|
||||
"""
|
||||
from app.services.shipping_notice.tool_common import payload_wants_auto_chain_fallback
|
||||
|
||||
return payload_wants_auto_chain_fallback(payload)
|
||||
return _auto_generate_excel_enabled() or payload_wants_auto_chain_fallback(payload)
|
||||
|
||||
|
||||
def try_auto_chain_after_match(
|
||||
@@ -139,10 +143,10 @@ def try_auto_chain_after_match(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
匹配成功后按配置自动串联 Excel 导出与 RPA 上传(Hxops chat fallback 链)。
|
||||
匹配成功后自动串联 Excel 导出与货代上传(Hxops chat fallback 链)。
|
||||
|
||||
核心逻辑:仅在 payload 含 auto_chain_fallback 且 match_result 为 ok 时触发;
|
||||
依次调用 generate_excel、upload_to_freight,并将消息 prepend 合并返回。
|
||||
核心逻辑:match_result 为 ok 后默认自动生成 Excel;若自动上传开关开启,
|
||||
继续触发 RPA 上传。失败、超时或缺少 RPA 配置时转人工接管。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingTask。
|
||||
|
||||
@@ -20,7 +20,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
|
||||
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
|
||||
"parse.confirm": "请确认以上信息是否正确?",
|
||||
"parse.hint": "回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。",
|
||||
"parse.hint": "请核对信息后使用下方按钮继续。",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
|
||||
"align.match_rule": "匹配规则:{rule}{note}",
|
||||
@@ -35,7 +35,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"align.source.fallback": "(后端动态兜底)",
|
||||
"align.source.other": "({source})",
|
||||
"align.confirm": "请确认以上字段对齐是否正确。",
|
||||
"align.hint": "回复「确认」进入匹配;「更正映射」重选列;「重新上传」换库存文件;「驳回」终止本任务。",
|
||||
"align.hint": "请核对字段对齐后使用下方按钮继续。",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "提示:",
|
||||
"table.field": "字段",
|
||||
@@ -109,6 +109,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.uploading": "正在上传并解析库存文件",
|
||||
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
|
||||
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
|
||||
"workflow.inventory.completed_task_locked": "该任务已完成,不能再重新上传库存。请切换到仍待处理的任务后再上传库存文件。",
|
||||
"workflow.inventory.uploaded": "库存文件已上传。",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
|
||||
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
|
||||
@@ -133,7 +134,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.fulfillment.manual_already_done": "任务 {task_no} 已标记为完成,无需重复操作。",
|
||||
"workflow.fulfillment.manual_confirmed": "已确认手工上传货代完成",
|
||||
"workflow.fulfillment.task_completed": "任务已完成",
|
||||
"workflow.fulfillment.manual_done_message": "已标记为手工上传货代系统完成。任务 {task_no} 已全部处理完毕,无需再进行任何操作。",
|
||||
"workflow.fulfillment.manual_done_message": "好的,任务 {task_no} 已确认完成,无需再处理。",
|
||||
"workflow.fulfillment.upload_running": "RPA 上传进行中(第 {attempt}/{max_attempts} 次)。已等待 {elapsed}s / 超时 {timeout}s。请稍后再试(建议 {remaining}s 后)。",
|
||||
"workflow.fulfillment.upload_timeout_error": "RPA 上传超时(>{timeout}s)",
|
||||
"workflow.fulfillment.upload_exhausted": "已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。",
|
||||
@@ -154,7 +155,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"parse.no_lines": "No order lines found. Please re-upload or re-parse.",
|
||||
"parse.low_conf": "Low confidence. Please double-check SKU, Qty, Reservation ID, Unit Price and Amount.",
|
||||
"parse.confirm": "Please confirm the above information.",
|
||||
"parse.hint": 'Reply "Confirm" to proceed; "Re-parse" to retry; "Reject" to stop this task.',
|
||||
"parse.hint": "Review the information, then use the buttons below to continue.",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
|
||||
"align.match_rule": "Match rule: {rule}{note}",
|
||||
@@ -169,7 +170,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"align.source.fallback": " (backend fallback)",
|
||||
"align.source.other": " ({source})",
|
||||
"align.confirm": "Please confirm the field alignment above.",
|
||||
"align.hint": 'Reply "Confirm" to match; "Fix mapping" to reselect columns; "Re-upload" to change the inventory file; "Reject" to stop.',
|
||||
"align.hint": "Review the field alignment, then use the buttons below to continue.",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "Notes:",
|
||||
"table.field": "Field",
|
||||
@@ -243,6 +244,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
|
||||
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
|
||||
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
|
||||
"workflow.inventory.completed_task_locked": "This task is already completed, so inventory cannot be uploaded again. Please switch to a task that still needs processing.",
|
||||
"workflow.inventory.uploaded": "The inventory file has been uploaded.",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping is complete, so the canvas can call apply_inventory_mapping directly without using the LLM.",
|
||||
"workflow.inventory.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.",
|
||||
@@ -267,7 +269,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.fulfillment.manual_already_done": "Task {task_no} is already marked complete. No further action is needed.",
|
||||
"workflow.fulfillment.manual_confirmed": "Manual freight upload has been confirmed.",
|
||||
"workflow.fulfillment.task_completed": "Task completed.",
|
||||
"workflow.fulfillment.manual_done_message": "The task has been marked as manually uploaded to the freight system. Task {task_no} is fully completed and no further action is needed.",
|
||||
"workflow.fulfillment.manual_done_message": "Done. Task {task_no} is confirmed complete. No further action is needed.",
|
||||
"workflow.fulfillment.upload_running": "RPA upload is in progress (attempt {attempt}/{max_attempts}). Waited {elapsed}s / timeout {timeout}s. Please try again later (recommended after {remaining}s).",
|
||||
"workflow.fulfillment.upload_timeout_error": "RPA upload timed out (>{timeout}s)",
|
||||
"workflow.fulfillment.upload_exhausted": "RPA upload failed after {attempts} attempts. Please download the Excel and upload it manually.",
|
||||
@@ -288,7 +290,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
|
||||
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
|
||||
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
|
||||
"parse.hint": 'พิมพ์ "ยืนยัน" เพื่อไปต่อ; "แยกใหม่" เพื่อลองใหม่; "ปฏิเสธ" เพื่อยุติงานนี้',
|
||||
"parse.hint": "ตรวจสอบข้อมูลแล้วใช้ปุ่มด้านล่างเพื่อดำเนินการต่อ",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
|
||||
"align.match_rule": "กฎการจับคู่: {rule}{note}",
|
||||
@@ -303,7 +305,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"align.source.fallback": " (สำรองโดยระบบ)",
|
||||
"align.source.other": " ({source})",
|
||||
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
|
||||
"align.hint": 'พิมพ์ "ยืนยัน" เพื่อจับคู่; "แก้ไขการจับคู่" เพื่อเลือกคอลัมน์ใหม่; "อัปโหลดใหม่" เพื่อเปลี่ยนไฟล์สต็อก; "ปฏิเสธ" เพื่อยุติ',
|
||||
"align.hint": "ตรวจสอบการจับคู่ฟิลด์แล้วใช้ปุ่มด้านล่างเพื่อดำเนินการต่อ",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "หมายเหตุ:",
|
||||
"table.field": "ฟิลด์",
|
||||
@@ -377,6 +379,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
|
||||
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
|
||||
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.inventory.completed_task_locked": "งานนี้เสร็จสิ้นแล้ว จึงไม่สามารถอัปโหลดสต็อกซ้ำได้ โปรดสลับไปยังงานที่ยังต้องดำเนินการ",
|
||||
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
|
||||
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
|
||||
@@ -401,7 +404,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.fulfillment.manual_already_done": "งาน {task_no} ถูกทำเครื่องหมายว่าเสร็จแล้ว จึงไม่ต้องดำเนินการซ้ำ",
|
||||
"workflow.fulfillment.manual_confirmed": "ยืนยันการอัปโหลดเข้าระบบขนส่งด้วยตนเองแล้ว",
|
||||
"workflow.fulfillment.task_completed": "งานเสร็จสิ้นแล้ว",
|
||||
"workflow.fulfillment.manual_done_message": "ทำเครื่องหมายว่าอัปโหลดเข้าระบบขนส่งด้วยตนเองเสร็จแล้ว งาน {task_no} เสร็จสมบูรณ์และไม่ต้องดำเนินการต่อ",
|
||||
"workflow.fulfillment.manual_done_message": "เรียบร้อย งาน {task_no} ยืนยันว่าเสร็จแล้ว ไม่ต้องดำเนินการต่อ",
|
||||
"workflow.fulfillment.upload_running": "RPA กำลังอัปโหลดอยู่ (ครั้งที่ {attempt}/{max_attempts}) รอแล้ว {elapsed}s / หมดเวลา {timeout}s โปรดลองอีกครั้งภายหลัง (แนะนำหลัง {remaining}s)",
|
||||
"workflow.fulfillment.upload_timeout_error": "RPA อัปโหลดหมดเวลา (>{timeout}s)",
|
||||
"workflow.fulfillment.upload_exhausted": "พยายามอัปโหลดผ่าน RPA มาแล้ว {attempts} ครั้งแต่ยังไม่สำเร็จ โปรดดาวน์โหลด Excel แล้วอัปโหลดด้วยตนเอง",
|
||||
|
||||
@@ -24,6 +24,13 @@ from app.services.shipping_notice.inventory_snapshot import (
|
||||
)
|
||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def _can_relink_inventory(task: ShippingTask) -> bool:
|
||||
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
|
||||
return str(task.process_status or "").strip().lower() not in _TERMINAL_PROCESS_STATUSES
|
||||
|
||||
|
||||
def _safe_ref(value: str) -> str:
|
||||
return re.sub(r"[^\w\-]+", "_", str(value or "").strip()) or "unknown"
|
||||
@@ -95,7 +102,8 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
|
||||
linked_tasks = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
|
||||
candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
|
||||
linked_tasks = [item for item in candidates if _can_relink_inventory(item)]
|
||||
for item in linked_tasks:
|
||||
replace_task_inventory_link(item, inv_file, role="owner" if item.id == task.id else "member")
|
||||
return inv_file
|
||||
@@ -199,6 +207,8 @@ def apply_inventory_parse_result_to_linked_tasks(
|
||||
for link in inv_file.links or []:
|
||||
if not link.is_active or not link.task:
|
||||
continue
|
||||
if not _can_relink_inventory(link.task):
|
||||
continue
|
||||
link.task.inventory_snapshot_id = inv_file.id
|
||||
link.task.inventory_lines_json = inventory_lines
|
||||
linked_tasks.append(link.task)
|
||||
@@ -222,7 +232,18 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
|
||||
|
||||
【AI 触发时机】:库存快照完成解析或字段映射确认后由内部调用;不暴露给 Agent。
|
||||
"""
|
||||
task_nos = linked_task_nos_for_inventory_file(inv_file)
|
||||
task_nos = [
|
||||
task_no
|
||||
for task_no in linked_task_nos_for_inventory_file(inv_file)
|
||||
if inv_file
|
||||
and any(
|
||||
link.is_active
|
||||
and link.task
|
||||
and link.task.task_no == task_no
|
||||
and _can_relink_inventory(link.task)
|
||||
for link in inv_file.links or []
|
||||
)
|
||||
]
|
||||
if not task_nos:
|
||||
return False
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
|
||||
@@ -52,6 +52,7 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent
|
||||
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
|
||||
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
|
||||
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
|
||||
@@ -140,18 +141,34 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
|
||||
if trigger:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
progress_message = (
|
||||
"已手动重新触发 RPA 库存导出,等待结果"
|
||||
if manual_retry_round
|
||||
else "已触发 RPA 库存导出,等待结果"
|
||||
)
|
||||
progress_detail = (
|
||||
f"新一轮第 {attempt_no}/{max_attempts} 次尝试"
|
||||
if manual_retry_round
|
||||
else f"第 {attempt_no}/{max_attempts} 次尝试"
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="running",
|
||||
message="已触发 RPA 库存导出,等待结果",
|
||||
message=progress_message,
|
||||
progress_percent=60,
|
||||
current=attempt_no,
|
||||
total=max_attempts,
|
||||
detail=f"第 {attempt_no}/{max_attempts} 次尝试",
|
||||
detail=progress_detail,
|
||||
extra={"manual_retry_round": manual_retry_round} if manual_retry_round else None,
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_triggered",
|
||||
{"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round},
|
||||
)
|
||||
log_task_event(task, "inventory_rpa_triggered", {"trigger": trigger, "attempt": attempt_no})
|
||||
|
||||
if attempt_no >= max_attempts and not task.inventory_lines_json:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
@@ -165,14 +182,16 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
response_prefix = (
|
||||
f"已手动重新触发 RPA 库存导出(新一轮第 {attempt_no}/{max_attempts} 次)。"
|
||||
if manual_retry_round
|
||||
else f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||||
f"若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。"
|
||||
),
|
||||
message=f"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
|
||||
@@ -61,6 +61,8 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
|
||||
"""从 payload 解析 inventory_lines / inventory_lines_json。"""
|
||||
@@ -413,6 +415,15 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
||||
lang = resolve_lang({"lang": None})
|
||||
if str(task.process_status or "").strip().lower() in _TERMINAL_PROCESS_STATUSES:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.completed_task_locked", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if upload is None or not getattr(upload, "filename", None):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
|
||||
@@ -77,12 +77,15 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Hxops Shipping Notice Tools",
|
||||
"title": "Shipping Notice Tools",
|
||||
"version": "1.0.0",
|
||||
"description": (
|
||||
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
|
||||
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
|
||||
"不包含由 hxops worker 统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
|
||||
"不要在自然语言正文里列出按钮清单或“推荐下一步”动作列表;"
|
||||
"可点击按钮由宿主系统根据 action_buttons 统一渲染。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
),
|
||||
},
|
||||
@@ -164,7 +167,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
),
|
||||
"/tools/apply_inventory_mapping": _post_op(
|
||||
"apply_inventory_mapping",
|
||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由 hxops worker 续跑",
|
||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑",
|
||||
{
|
||||
"task_id": task_id,
|
||||
MAP_JSON: _str_prop(
|
||||
@@ -175,7 +178,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
),
|
||||
"/tools/submit_decision": _post_op(
|
||||
"submit_decision",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由 hxops worker 统一续跑。",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
||||
|
||||
@@ -14,7 +14,7 @@ from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc
|
||||
from sqlalchemy import asc, desc
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
@@ -146,6 +146,55 @@ def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
|
||||
}
|
||||
|
||||
|
||||
def _is_task_completed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否已进入完成态,用于会话级聚合统计。"""
|
||||
return str(task.process_status or "").strip().lower() in {"uploaded", "completed", "closed"}
|
||||
|
||||
|
||||
def _is_task_failed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否失败或上传失败,用于会话级异常优先展示。"""
|
||||
return (
|
||||
str(task.process_status or "").strip().lower() in {"rejected"}
|
||||
or str(task.upload_status or "").strip().lower() == "failed"
|
||||
)
|
||||
|
||||
|
||||
def _is_task_needs_human(task: ShippingTask) -> bool:
|
||||
"""判断任务是否停在人工门;失败态不重复计入人工门。"""
|
||||
if _is_task_failed(task) or _is_task_completed(task):
|
||||
return False
|
||||
return bool(getattr(task, "review_status", None) or getattr(task, "pending_human_reason", None))
|
||||
|
||||
|
||||
def _is_task_active(task: ShippingTask) -> bool:
|
||||
"""判断任务是否仍处于自动执行或等待外部系统返回的状态。"""
|
||||
if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task):
|
||||
return False
|
||||
status = str(task.process_status or "").strip().lower()
|
||||
return status not in {"created", "pending_review"} and bool(status)
|
||||
|
||||
|
||||
def compute_conversation_workspace_summary(batches: list[ShippingBatch]) -> dict[str, int]:
|
||||
"""按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。"""
|
||||
tasks: list[ShippingTask] = []
|
||||
for batch in batches:
|
||||
tasks.extend(list(batch.tasks or []))
|
||||
completed = sum(1 for task in tasks if _is_task_completed(task))
|
||||
failed = sum(1 for task in tasks if _is_task_failed(task))
|
||||
needs_human = sum(1 for task in tasks if _is_task_needs_human(task))
|
||||
running = sum(1 for task in tasks if _is_task_active(task))
|
||||
pending = max(0, len(tasks) - completed - failed - needs_human - running)
|
||||
return {
|
||||
"batch_count": len(batches),
|
||||
"total": len(tasks),
|
||||
"completed": completed,
|
||||
"running": running,
|
||||
"failed": failed,
|
||||
"needs_human": needs_human,
|
||||
"pending": pending,
|
||||
}
|
||||
|
||||
|
||||
def extract_task_no_from_text(text: str) -> str | None:
|
||||
"""从自然语言文本中提取 SN- 任务编号。"""
|
||||
match = _TASK_NO_RE.search(str(text or ""))
|
||||
@@ -243,9 +292,13 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"upload_mode": task.upload_mode,
|
||||
"upload_attempt": task.upload_attempt,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"error_message": task.error_message or task.upload_error_message,
|
||||
"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 {},
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
@@ -321,6 +374,38 @@ def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def serialize_conversation_batch_workspace(batch: ShippingBatch, user_id: int) -> dict[str, Any]:
|
||||
"""序列化会话工作台中的单个批次,包含批次摘要、任务列表与焦点任务。"""
|
||||
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
|
||||
return {
|
||||
**serialize_batch_summary(batch),
|
||||
"tasks": list_batch_task_summaries(batch),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
}
|
||||
|
||||
|
||||
def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]:
|
||||
"""返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要。"""
|
||||
value = str(conversation_id or "").strip()
|
||||
batches: list[ShippingBatch] = []
|
||||
if value:
|
||||
batches = (
|
||||
ShippingBatch.query.filter(ShippingBatch.conversation_id == value)
|
||||
.filter((ShippingBatch.user_id == user_id) | (ShippingBatch.user_id.is_(None)))
|
||||
.order_by(asc(ShippingBatch.created_at), asc(ShippingBatch.id))
|
||||
.all()
|
||||
)
|
||||
ordered_batches = batches
|
||||
return {
|
||||
"conversation_id": value,
|
||||
"summary": compute_conversation_workspace_summary(ordered_batches),
|
||||
"batches": [
|
||||
serialize_conversation_batch_workspace(batch, user_id)
|
||||
for batch in ordered_batches
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||
"""工作台任务列表用的 SUMMARY 投影。"""
|
||||
return serialize_task(task, TaskProjection.SUMMARY)
|
||||
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
|
||||
@@ -16,6 +17,7 @@ from app import db
|
||||
from app.jobs.queue import enqueue, fail_job, finish_job, process_next_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING, PH_UPLOAD_RPA_PENDING
|
||||
|
||||
logger = logging.getLogger('shipping-worker')
|
||||
|
||||
@@ -54,6 +56,49 @@ def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = Non
|
||||
return True, 'queued_manual'
|
||||
|
||||
|
||||
def _should_requeue_waiting_external_result(task_no: str) -> bool:
|
||||
"""RPA 等外部回传中的任务需要持续复查,直到成功、超时重试或转人工。"""
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return False
|
||||
process_status = str(task.process_status or '').strip()
|
||||
pending_reason = str(task.pending_human_reason or '').strip()
|
||||
return (
|
||||
process_status == 'waiting_inventory'
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
and not task.inventory_lines_json
|
||||
) or (
|
||||
process_status == 'waiting_upload'
|
||||
and pending_reason == PH_UPLOAD_RPA_PENDING
|
||||
)
|
||||
|
||||
|
||||
def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None:
|
||||
"""把等待 RPA 回调的任务重新放回队列,供 worker 下一轮做超时/重试判断。"""
|
||||
if not _should_requeue_waiting_external_result(task_no):
|
||||
return
|
||||
recheck_seconds = max(
|
||||
float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10),
|
||||
1,
|
||||
)
|
||||
enqueue(
|
||||
JobType.SHIPPING_NOTICE_RUN,
|
||||
{
|
||||
'task_no': task_no,
|
||||
'batch_no': (job.payload_json or {}).get('batch_no') if job and job.payload_json else None,
|
||||
},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=task_no,
|
||||
created_by_id=job.created_by_id if job else None,
|
||||
message='等待 RPA 回传,稍后自动复查',
|
||||
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3),
|
||||
dedupe_active=False,
|
||||
scheduled_at=datetime.utcnow() + timedelta(seconds=recheck_seconds),
|
||||
)
|
||||
|
||||
|
||||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
"""兼容旧调用:回收通用 jobs 表里超时的发货任务。"""
|
||||
from app.jobs.queue import recover_stale_jobs
|
||||
@@ -103,6 +148,8 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
|
||||
result=dict(result),
|
||||
message=str(result.get('message') or '')[:500] or '发货任务处理完成',
|
||||
)
|
||||
if status == 'running':
|
||||
_requeue_external_wait_job(task_no, job=job)
|
||||
else:
|
||||
fail_job(
|
||||
job,
|
||||
|
||||
@@ -24,6 +24,10 @@ _INVENTORY_SUCCESS_EVENTS = {
|
||||
"inventory_template_mapping_used",
|
||||
}
|
||||
|
||||
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
||||
"decision_retry_rpa",
|
||||
}
|
||||
|
||||
_UPLOAD_SUCCESS_EVENTS = {
|
||||
"upload_rpa_success",
|
||||
"upload_manual_confirmed",
|
||||
@@ -35,13 +39,13 @@ def inventory_rpa_attempts(task: ShippingTask | None) -> int:
|
||||
if not task or task.id is None:
|
||||
return 0
|
||||
|
||||
last_success = (
|
||||
last_reset = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_SUCCESS_EVENTS))
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_ATTEMPT_RESET_EVENTS))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
since: datetime | None = last_success.created_at if last_success else None
|
||||
since: datetime | None = last_reset.created_at if last_reset else None
|
||||
|
||||
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
|
||||
|
||||
@@ -429,6 +429,7 @@ class TaskTransition(StrEnum):
|
||||
CORRECT_MAPPING = "correct_mapping"
|
||||
REPARSE_INVENTORY = "reparse_inventory"
|
||||
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
|
||||
REMATCH_REQUESTED = "rematch_requested"
|
||||
WAITING_UPLOAD = "waiting_upload"
|
||||
UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
UPLOAD_FAILED = "upload_failed"
|
||||
@@ -535,6 +536,12 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.REMATCH_REQUESTED: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
|
||||
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
||||
process_status="waiting_upload",
|
||||
|
||||
@@ -391,9 +391,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
batch_no=batch.batch_no,
|
||||
message=f"已创建发货批次 {batch.batch_no},任务 {task.task_no}",
|
||||
data={**serialize_task_for_tool(task), "batch": serialize_batch_for_tool(batch)},
|
||||
extra={"batch_no": batch.batch_no},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,36 @@ if TYPE_CHECKING:
|
||||
from app.models import ShippingTask
|
||||
|
||||
|
||||
def _sanitize_user_facing_text(value: str) -> str:
|
||||
"""
|
||||
清理会被 Agent 复述给业务用户的内部项目名。
|
||||
|
||||
核心逻辑:Tool response 会进入 Dify 上下文,先在后端把项目代号替换为业务表达,
|
||||
避免模型把内部系统名称带到对话气泡中。
|
||||
"""
|
||||
text = str(value or "")
|
||||
replacements = (
|
||||
("通过 Hxops 聊天区上传", "在当前对话中上传"),
|
||||
("通过 HXOPS 聊天区上传", "在当前对话中上传"),
|
||||
("通过 hxops 聊天区上传", "在当前对话中上传"),
|
||||
("在 Hxops 聊天区上传", "在当前对话中上传"),
|
||||
("在 HXOPS 聊天区上传", "在当前对话中上传"),
|
||||
("在 hxops 聊天区上传", "在当前对话中上传"),
|
||||
("Hxops 聊天区", "当前对话"),
|
||||
("HXOPS 聊天区", "当前对话"),
|
||||
("hxops 聊天区", "当前对话"),
|
||||
("Hxops Chat", "当前对话"),
|
||||
("HXOPS Chat", "当前对话"),
|
||||
("hxops chat", "当前对话"),
|
||||
("Hxops", "当前系统"),
|
||||
("HXOPS", "当前系统"),
|
||||
("hxops", "当前系统"),
|
||||
)
|
||||
for old, new in replacements:
|
||||
text = text.replace(old, new)
|
||||
return text
|
||||
|
||||
|
||||
def tool_response(
|
||||
*,
|
||||
status: str,
|
||||
@@ -27,6 +57,7 @@ def tool_response(
|
||||
next_required_action: str | None = None,
|
||||
forbidden_next_tools: list[str] | None = None,
|
||||
stop_agent_turn: bool = False,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知 Tool 标准 JSON 响应。
|
||||
@@ -37,6 +68,7 @@ def tool_response(
|
||||
Args:
|
||||
stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。
|
||||
forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。
|
||||
extra: 需要保留在顶层的兼容字段,例如 batch_no。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
@@ -61,7 +93,7 @@ def tool_response(
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"status": status,
|
||||
"message": message,
|
||||
"message": _sanitize_user_facing_text(message),
|
||||
"data": data or {},
|
||||
}
|
||||
if task_id:
|
||||
@@ -79,9 +111,11 @@ def tool_response(
|
||||
if resolved_checkpoint:
|
||||
payload["checkpoint"] = resolved_checkpoint
|
||||
if next_required_action:
|
||||
payload["next_required_action"] = next_required_action
|
||||
payload["next_required_action"] = _sanitize_user_facing_text(next_required_action)
|
||||
if forbidden_next_tools:
|
||||
payload["forbidden_next_tools"] = forbidden_next_tools
|
||||
if stop_agent_turn:
|
||||
payload["stop_agent_turn"] = True
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
Reference in new issue
Block a user