refactor(agent-runtime, shipping-notice, frontend): 重构上下文体系,修复重试RPA无响应问题
- 替换原有的hxops_context模块为全新的代理运行时上下文平台协议,统一跨业务上下文注入逻辑 - 新增多语言操作繁忙提示文案(覆盖中、繁、英、泰四语),前端绑定页面繁忙状态实现操作阻断 - 调整RPA库存导出重试策略:移除可配置的最大自动重试次数,改为固定单次自动重试,手动重试需用户显式触发 - 优化任务用户态状态展示逻辑,优先展示具体的pending原因而非通用状态文案 - 重构任务焦点切换逻辑,统一事件日志与处理流程,复用switch_batch_focus工具函数 - 修复clearAllHistory函数残留UI问题,确保清空会话后完全复位发货通知相关视图 - 更新OpenAPI文档与静态快照,补充工具使用约束说明 - 新增调试打点日志与问题排查文档,完善全套单元测试与快照校验用例 - 更新RPA脚本的README文档,调整登录方式说明与浏览器 profile 路径配置 - 删除废弃的hxops_context模块,迁移所有相关调用到新的上下文体系
This commit is contained in:
1 parent
60dd0c0f58
commit
8846ce159f
102 files changed
+18289
-9072
No files matched your search
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/__init__.py
|
||||
|
||||
用途:聚合导出 HXOPS Agent Runtime Context 平台协议能力与通用构建器。
|
||||
依赖:builder、schema、generic adapter、reference。
|
||||
逻辑:业务 adapter 从本包导入平台协议与构建器;聊天分发入口单独从 `dify_inputs.py` 直接导入,避免包初始化时反向拉起业务 adapter 形成循环依赖。
|
||||
"""
|
||||
|
||||
from app.services.agent_runtime_context.adapters.generic import (
|
||||
build_generic_runtime_context,
|
||||
resolve_agent_code,
|
||||
)
|
||||
from app.services.agent_runtime_context.builder import (
|
||||
build_agent_runtime_context,
|
||||
build_dify_inputs,
|
||||
serialize_for_dify,
|
||||
)
|
||||
from app.services.agent_runtime_context.reference import (
|
||||
build_object_ref,
|
||||
build_reference_context,
|
||||
)
|
||||
from app.services.agent_runtime_context.schema import (
|
||||
AGENT_RUNTIME_CONTEXT_INPUT,
|
||||
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AGENT_RUNTIME_CONTEXT_INPUT",
|
||||
"AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION",
|
||||
"build_agent_runtime_context",
|
||||
"build_dify_inputs",
|
||||
"build_generic_runtime_context",
|
||||
"build_object_ref",
|
||||
"build_reference_context",
|
||||
"resolve_agent_code",
|
||||
"serialize_for_dify",
|
||||
]
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/adapters/generic.py
|
||||
|
||||
用途:为未接入专用业务 adapter 的 Dify Agent 构建最小可用的 agent_runtime_context。
|
||||
依赖:agent_runtime_context.builder、标准库 typing。
|
||||
逻辑:由平台级 dify_inputs 分发入口调用;当 Agent 既不是 shipping_notice 也不是 file_check 时,
|
||||
使用本模块生成通用会话快照,让 Dify Start 节点也能稳定拿到 platform/session 上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.builder import (
|
||||
build_agent_runtime_context,
|
||||
build_dify_inputs,
|
||||
)
|
||||
|
||||
|
||||
def _agent_extra_config(agent) -> dict[str, Any]:
|
||||
"""读取 Agent.extra_config;非字典时回退为空,避免通用适配器因脏配置报错。"""
|
||||
extra_config = getattr(agent, "extra_config", None)
|
||||
return extra_config if isinstance(extra_config, dict) else {}
|
||||
|
||||
|
||||
def resolve_agent_code(agent) -> str:
|
||||
"""
|
||||
解析通用 Agent 的稳定 code。
|
||||
|
||||
核心逻辑:优先读取 extra_config.agent_code;未配置或为空时回退为 generic,
|
||||
让知识库/普通问答类 Agent 也能在 Runtime 中暴露稳定标识。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent 记录或代理对象。
|
||||
|
||||
Returns:
|
||||
Agent code 字符串;缺省为 generic。
|
||||
"""
|
||||
agent_code = str(_agent_extra_config(agent).get("agent_code") or "").strip()
|
||||
return agent_code or "generic"
|
||||
|
||||
|
||||
def _resolve_domain_summary(agent) -> str:
|
||||
"""按优先级提取通用摘要,避免无业务状态 Agent 的 domain.summary 为空。"""
|
||||
extra_config = _agent_extra_config(agent)
|
||||
runtime_context_summary = str(extra_config.get("runtime_context_summary") or "").strip()
|
||||
if runtime_context_summary:
|
||||
return runtime_context_summary
|
||||
|
||||
agent_description = str(getattr(agent, "description", None) or "").strip()
|
||||
if agent_description:
|
||||
return agent_description
|
||||
return "通用对话"
|
||||
|
||||
|
||||
def build_generic_runtime_context(
|
||||
*,
|
||||
session_id: str,
|
||||
agent,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = "frontend_chat",
|
||||
locale: str | None = None,
|
||||
scope: str = "chat_turn",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为通用 Dify Agent 构建最小 Runtime Context。
|
||||
|
||||
核心逻辑:仅注入 platform/session 锚点与 generic domain 摘要,
|
||||
不附带 refs/reference_context,适用于纯 Q&A 或知识库类 Agent。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS 会话 ID;为空时返回空 dict。
|
||||
agent: 当前对话 Agent,读取 extra_config.agent_code/runtime_context_summary。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源,默认 frontend_chat。
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域,默认 chat_turn。
|
||||
|
||||
Returns:
|
||||
通用 agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
return build_agent_runtime_context(
|
||||
agent_code=resolve_agent_code(agent),
|
||||
scope=scope,
|
||||
session_id=session_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
domain={
|
||||
"type": "generic",
|
||||
"summary": _resolve_domain_summary(agent),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def build_generic_dify_inputs(
|
||||
*,
|
||||
session_id: str,
|
||||
agent,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = "frontend_chat",
|
||||
locale: str | None = None,
|
||||
scope: str = "chat_turn",
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建通用 Agent 的 Dify Start inputs。
|
||||
|
||||
核心逻辑:统一把最小 Runtime Context 序列化到 agent_runtime_context,
|
||||
让未接入专用 adapter 的 Agent 也能消费平台会话快照。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS 会话 ID。
|
||||
agent: 当前对话 Agent。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源。
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域。
|
||||
|
||||
Returns:
|
||||
仅含 agent_runtime_context 的 inputs;session_id 为空时返回空 dict。
|
||||
"""
|
||||
runtime_context = build_generic_runtime_context(
|
||||
session_id=session_id,
|
||||
agent=agent,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
scope=scope,
|
||||
)
|
||||
return build_dify_inputs(runtime_context)
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/builder.py
|
||||
|
||||
用途:构建并序列化 HXOPS 平台统一的 agent_runtime_context。
|
||||
依赖:schema 协议常量、policy 裁剪策略、json/uuid/time 标准库。
|
||||
逻辑:聊天入口或业务 adapter 调用本模块生成每次 Runtime 调用前的现场 snapshot,再作为 Dify Start 变量注入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from app.services.agent_runtime_context.policy import (
|
||||
MAX_CONTEXT_JSON_CHARS,
|
||||
normalize_domain,
|
||||
normalize_reference_context,
|
||||
normalize_refs,
|
||||
)
|
||||
from app.services.agent_runtime_context.schema import (
|
||||
AGENT_RUNTIME_CONTEXT_INPUT,
|
||||
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
AgentRuntimeContext,
|
||||
)
|
||||
|
||||
|
||||
def generate_context_id() -> str:
|
||||
"""
|
||||
生成单次 Runtime 上下文编号。
|
||||
|
||||
核心逻辑:使用毫秒时间戳与短 UUID,便于日志检索且不暴露业务编号。
|
||||
|
||||
Returns:
|
||||
形如 ctx_20260702094300000_ab12cd34 的上下文编号。
|
||||
"""
|
||||
timestamp_ms = int(time.time() * 1000)
|
||||
return f"ctx_{timestamp_ms}_{uuid4().hex[:8]}"
|
||||
|
||||
|
||||
def _normalize_platform(
|
||||
*,
|
||||
session_id: str,
|
||||
parent_session_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建平台侧上下文片段。
|
||||
|
||||
核心逻辑:session_id 为必填锚点,其余字段有值才输出,避免空字段误导 Runtime。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS ChatSession.session_id。
|
||||
parent_session_id: 后台 run 所属的用户主会话;缺省时等于 session_id。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。
|
||||
locale: 用户语言。
|
||||
|
||||
Returns:
|
||||
平台上下文字典。
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
platform = {"session_id": normalized_session_id}
|
||||
|
||||
normalized_parent = str(parent_session_id or "").strip()
|
||||
if normalized_parent:
|
||||
platform["parent_session_id"] = normalized_parent
|
||||
elif normalized_session_id:
|
||||
platform["parent_session_id"] = normalized_session_id
|
||||
|
||||
normalized_request_id = str(request_id or "").strip()
|
||||
normalized_trigger_source = str(trigger_source or "").strip()
|
||||
normalized_locale = str(locale or "").strip()
|
||||
if normalized_request_id:
|
||||
platform["request_id"] = normalized_request_id
|
||||
if normalized_trigger_source:
|
||||
platform["trigger_source"] = normalized_trigger_source
|
||||
if normalized_locale:
|
||||
platform["locale"] = normalized_locale
|
||||
return platform
|
||||
|
||||
|
||||
def build_agent_runtime_context(
|
||||
*,
|
||||
agent_code: str = "generic",
|
||||
scope: str = "chat_turn",
|
||||
session_id: str,
|
||||
parent_session_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
refs: dict[str, Any] | None = None,
|
||||
domain: dict[str, Any] | None = None,
|
||||
reference_context: dict[str, Any] | None = None,
|
||||
context_id: str | None = None,
|
||||
) -> AgentRuntimeContext:
|
||||
"""
|
||||
构建单次 Runtime 调用的上下文 snapshot。
|
||||
|
||||
核心逻辑:校验 session 锚点,填充平台字段,裁剪 refs/domain/reference_context,并生成 context_id 供审计追踪。
|
||||
|
||||
Args:
|
||||
agent_code: 稳定 Agent 标识,禁止使用展示名称。
|
||||
scope: 上下文作用域,如 chat_turn/task_run。
|
||||
session_id: HXOPS 本地会话 ID。
|
||||
parent_session_id: 后台任务所属主会话 ID。
|
||||
request_id: 本次请求 ID。
|
||||
trigger_source: 触发来源。
|
||||
locale: 用户语言。
|
||||
refs: 业务对象锚点字典。
|
||||
domain: 业务域摘要与状态提示。
|
||||
reference_context: 短期指代治理上下文。
|
||||
context_id: 外部指定的上下文编号;通常留空自动生成。
|
||||
|
||||
Returns:
|
||||
agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
context: AgentRuntimeContext = {
|
||||
"schema_version": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
"context_id": str(context_id or "").strip() or generate_context_id(),
|
||||
"agent_code": str(agent_code or "generic").strip() or "generic",
|
||||
"scope": str(scope or "chat_turn").strip() or "chat_turn",
|
||||
"platform": _normalize_platform(
|
||||
session_id=normalized_session_id,
|
||||
parent_session_id=parent_session_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
),
|
||||
"refs": normalize_refs(refs),
|
||||
}
|
||||
|
||||
normalized_domain = normalize_domain(domain)
|
||||
if normalized_domain:
|
||||
context["domain"] = normalized_domain
|
||||
normalized_reference_context = normalize_reference_context(reference_context)
|
||||
if normalized_reference_context:
|
||||
context["reference_context"] = normalized_reference_context
|
||||
return context
|
||||
|
||||
|
||||
def serialize_for_dify(context: dict[str, Any]) -> str:
|
||||
"""
|
||||
将上下文序列化为 Dify Start 节点可稳定接收的 JSON 字符串。
|
||||
|
||||
核心逻辑:使用紧凑 JSON,超过平台限制时抛 ValueError,避免悄悄截断成非法 JSON。
|
||||
|
||||
Args:
|
||||
context: agent_runtime_context 字典。
|
||||
|
||||
Returns:
|
||||
UTF-8 JSON 字符串。
|
||||
|
||||
Raises:
|
||||
ValueError: 上下文序列化后超过长度上限。
|
||||
"""
|
||||
payload = json.dumps(context or {}, ensure_ascii=False, separators=(",", ":"))
|
||||
if len(payload) > MAX_CONTEXT_JSON_CHARS:
|
||||
raise ValueError("agent_runtime_context exceeds max serialized length")
|
||||
return payload
|
||||
|
||||
|
||||
def build_dify_inputs(
|
||||
context: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建传给 Dify 的 inputs。
|
||||
|
||||
核心逻辑:统一只输出 agent_runtime_context JSON 字符串,避免 Start 协议出现多套上下文字段。
|
||||
|
||||
Args:
|
||||
context: agent_runtime_context 字典。
|
||||
|
||||
Returns:
|
||||
Dify inputs 字典。
|
||||
"""
|
||||
if not context:
|
||||
return {}
|
||||
return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(context)}
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/dify_inputs.py
|
||||
|
||||
用途:提供聊天入口构建 Dify inputs 的统一分发入口。
|
||||
依赖:generic adapter、file_check_tools.dify_inputs、shipping_notice.dify_inputs。
|
||||
逻辑:chat.py 在调用 DifyService.stream_chat 前只调用本模块;本模块按 Agent 类型分发到
|
||||
shipping_notice / file_check / generic adapter,平台层只暴露会话级公共参数,领域提示由 adapter_hints 透传。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.adapters.generic import build_generic_dify_inputs
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
|
||||
|
||||
def build_chat_dify_inputs(
|
||||
agent,
|
||||
*,
|
||||
session_id: str,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = "frontend_chat",
|
||||
locale: str | None = None,
|
||||
adapter_hints: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
统一构建聊天 Dify inputs。
|
||||
|
||||
核心逻辑:优先命中 shipping_notice 专用 adapter;其次复用 file_check 既有 task_id 注入;
|
||||
其余 Agent 一律走 generic adapter,让所有 Dify Chatflow 至少拿到 platform/session 快照。
|
||||
业务域专用提示不出现在平台签名中,而是由 adapter_hints 交给对应 adapter 自行消费。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent。
|
||||
session_id: HXOPS 会话 ID;为空时直接返回空 dict。
|
||||
request_id: 本次请求追踪 ID。
|
||||
trigger_source: 触发来源,默认 frontend_chat。
|
||||
locale: 用户语言。
|
||||
adapter_hints: 领域 adapter 可选读取的提示字典;平台层不感知其内部业务字段。
|
||||
|
||||
Returns:
|
||||
Dify inputs 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
normalized_adapter_hints = adapter_hints if isinstance(adapter_hints, dict) else {}
|
||||
|
||||
if is_shipping_notice_chat_agent(agent):
|
||||
shipping_hints = normalized_adapter_hints.get("shipping_notice")
|
||||
shipping_hints = shipping_hints if isinstance(shipping_hints, dict) else {}
|
||||
return build_shipping_notice_dify_inputs(
|
||||
normalized_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,
|
||||
)
|
||||
|
||||
if agent_declares_file_check_progress(agent) or is_file_check_chat_agent(agent):
|
||||
return build_file_check_dify_inputs(agent, required=True)
|
||||
|
||||
return build_generic_dify_inputs(
|
||||
session_id=normalized_session_id,
|
||||
agent=agent,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
)
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/openapi_spec.py
|
||||
|
||||
用途:构建 agent_runtime_context Tool API 的 OpenAPI 3.0 文档,供 Dify 导入。
|
||||
依赖:parser.ALLOWED_PARSE_PATHS。
|
||||
逻辑:api/agent_runtime_context_tools.py 调用本模块生成 JSON 文档,Dify 通过 parse 工具安全读取上下文字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.parser import ALLOWED_PARSE_PATHS, MAX_PARSE_PATHS
|
||||
|
||||
|
||||
def build_agent_runtime_context_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
构建 Dify 导入用 OpenAPI 文档。
|
||||
|
||||
核心逻辑:仅暴露 parse_agent_runtime_context 一个只读工具,不包含任何业务推进接口。
|
||||
|
||||
Args:
|
||||
base_url: HXOPS 后端公开 Base URL。
|
||||
|
||||
Returns:
|
||||
OpenAPI 3.0 字典。
|
||||
"""
|
||||
server = str(base_url or "").strip().rstrip("/")
|
||||
if not server.endswith("/api/agent-runtime-context"):
|
||||
server = f"{server}/api/agent-runtime-context" if server else "/api/agent-runtime-context"
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "HXOPS Agent Runtime Context Tools",
|
||||
"version": "1.0.0",
|
||||
"description": (
|
||||
"HXOPS 平台运行态上下文只读解析工具。"
|
||||
"Dify 应在需要读取 session、task、batch、run purpose、state_hint 或模糊指代线索时调用本工具;"
|
||||
"遇到“继续”“刚才那个”“上一个失败的”等表达时,应优先读取 reference_context。"
|
||||
"若只需要 focus id、last action 或 failure reason,可优先读取 reference_context 的细粒度字段,减少上下文判断分支。"
|
||||
"若 reference_context 返回多个 candidates(多候选),不要猜测,应追问用户或调用业务 Tool 再确认。"
|
||||
"reference_context 与 state_hint 都只是提示,不是业务事实源,也不能替代 HXOPS 状态机。"
|
||||
"推进业务状态必须调用对应业务 Tool,不能依据上下文直接宣布完成、上传成功或任务关闭。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
),
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/parse": {
|
||||
"post": {
|
||||
"operationId": "parse_agent_runtime_context",
|
||||
"summary": "解析 HXOPS agent_runtime_context 中的白名单字段",
|
||||
"description": (
|
||||
"只读解析工具;agent_runtime_context 应为 Dify Start 节点中的 JSON 字符串。"
|
||||
f"paths 最多 {MAX_PARSE_PATHS} 个,且必须属于 allowed_paths。"
|
||||
"推荐优先读取 reference_context.focus_object.id、reference_context.last_action_target.action、"
|
||||
"reference_context.last_failed_target.reason 等细粒度字段,降低提示词中的对象拆解成本。"
|
||||
"模糊指代建议优先读取 reference_context;若拿到多个 candidates(多候选),必须追问或回到业务 Tool 校验,禁止自行猜测推进。"
|
||||
"reference_context/state_hint 仅用于理解当前现场,不能替代状态机事实,更不能据此直接推进业务或宣布完成。"
|
||||
),
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": ["agent_runtime_context", "paths"],
|
||||
"properties": {
|
||||
"agent_runtime_context": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"Dify Start 变量 agent_runtime_context 的 JSON 字符串。"
|
||||
"其中 reference_context 仅用于辅助理解当前现场,不可替代 HXOPS 业务事实源。"
|
||||
),
|
||||
},
|
||||
"paths": {
|
||||
"type": "array",
|
||||
"description": "需要读取的字段路径。",
|
||||
"maxItems": MAX_PARSE_PATHS,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": sorted(ALLOWED_PARSE_PATHS),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Parse response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {"type": "string", "enum": ["ok"]},
|
||||
"data": {"type": "object", "additionalProperties": True},
|
||||
"missing": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/parser.py
|
||||
|
||||
用途:解析 Dify 传回的 agent_runtime_context JSON 字符串,并按白名单路径取值。
|
||||
依赖:json 标准库、agent_runtime_context.schema/policy、AppError 体系。
|
||||
逻辑:Tool API 调用本模块只读解析上下文;不执行表达式、不访问数据库、不推进任何业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.agent_runtime_context.policy import MAX_CONTEXT_JSON_CHARS
|
||||
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION
|
||||
|
||||
MAX_PARSE_PATHS = 20
|
||||
|
||||
ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
|
||||
{
|
||||
"schema_version",
|
||||
"context_id",
|
||||
"agent_code",
|
||||
"scope",
|
||||
"platform.session_id",
|
||||
"platform.parent_session_id",
|
||||
"platform.request_id",
|
||||
"platform.locale",
|
||||
"platform.trigger_source",
|
||||
"refs.batch_no",
|
||||
"refs.task_no",
|
||||
"refs.run_purpose",
|
||||
"refs.file_name",
|
||||
"refs.schedule_task_id",
|
||||
"domain.type",
|
||||
"domain.summary",
|
||||
"domain.state_hint.batch_no",
|
||||
"domain.state_hint.focus_task_no",
|
||||
"domain.state_hint.current_step",
|
||||
"domain.state_hint.status",
|
||||
"domain.state_hint.review_status",
|
||||
"domain.state_hint.match_status",
|
||||
"domain.state_hint.pending_human_reason",
|
||||
"domain.state_hint.upload_status",
|
||||
"reference_context.recent_activity_summary",
|
||||
"reference_context.focus_object",
|
||||
"reference_context.focus_object.type",
|
||||
"reference_context.focus_object.id",
|
||||
"reference_context.last_action_target",
|
||||
"reference_context.last_action_target.action",
|
||||
"reference_context.last_action_target.id",
|
||||
"reference_context.last_failed_target",
|
||||
"reference_context.last_failed_target.reason",
|
||||
"reference_context.last_failed_target.id",
|
||||
"reference_context.candidates",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _normalize_context(raw_context: str | dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
解析并校验 agent_runtime_context。
|
||||
|
||||
核心逻辑:优先支持 Dify Paragraph 传入的 JSON 字符串,也兼容测试/内部调用传 object。
|
||||
|
||||
Args:
|
||||
raw_context: JSON 字符串或上下文字典。
|
||||
|
||||
Returns:
|
||||
agent_runtime_context 字典。
|
||||
|
||||
Raises:
|
||||
ValidationError: 空上下文、超长、JSON 非法或协议版本不匹配。
|
||||
"""
|
||||
if isinstance(raw_context, dict):
|
||||
context = raw_context
|
||||
else:
|
||||
serialized = str(raw_context or "").strip()
|
||||
if not serialized:
|
||||
raise ValidationError("agent_runtime_context_required")
|
||||
if len(serialized) > MAX_CONTEXT_JSON_CHARS:
|
||||
raise ValidationError(
|
||||
"agent_runtime_context_too_large",
|
||||
details={"max_chars": MAX_CONTEXT_JSON_CHARS},
|
||||
)
|
||||
try:
|
||||
context = json.loads(serialized)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("agent_runtime_context_invalid_json", details={"error": str(exc)}) from exc
|
||||
|
||||
if not isinstance(context, dict):
|
||||
raise ValidationError("agent_runtime_context_must_be_object")
|
||||
schema_version = str(context.get("schema_version") or "").strip()
|
||||
if schema_version != AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION:
|
||||
raise ValidationError(
|
||||
"agent_runtime_context_schema_version_unsupported",
|
||||
details={
|
||||
"expected": AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION,
|
||||
"actual": schema_version,
|
||||
},
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
def _normalize_paths(paths: Any) -> list[str]:
|
||||
"""
|
||||
校验并规范化字段路径列表。
|
||||
|
||||
核心逻辑:限制路径数量且只允许白名单字段,避免 Dify 读取未授权内部上下文片段。
|
||||
|
||||
Args:
|
||||
paths: 请求中的 paths 字段。
|
||||
|
||||
Returns:
|
||||
去重后的路径列表。
|
||||
|
||||
Raises:
|
||||
ValidationError: paths 非列表、为空、超限或包含非白名单路径。
|
||||
"""
|
||||
if not isinstance(paths, list) or not paths:
|
||||
raise ValidationError("paths_required")
|
||||
if len(paths) > MAX_PARSE_PATHS:
|
||||
raise ValidationError("paths_too_many", details={"max_paths": MAX_PARSE_PATHS})
|
||||
|
||||
normalized: list[str] = []
|
||||
seen: set[str] = set()
|
||||
rejected: list[str] = []
|
||||
for item in paths:
|
||||
path = str(item or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
if path not in ALLOWED_PARSE_PATHS:
|
||||
rejected.append(path)
|
||||
continue
|
||||
if path not in seen:
|
||||
normalized.append(path)
|
||||
seen.add(path)
|
||||
if rejected:
|
||||
raise ValidationError("paths_not_allowed", details={"paths": rejected})
|
||||
if not normalized:
|
||||
raise ValidationError("paths_required")
|
||||
return normalized
|
||||
|
||||
|
||||
def _get_path_value(context: dict[str, Any], path: str) -> tuple[bool, Any]:
|
||||
"""
|
||||
按点路径从上下文读取值。
|
||||
|
||||
核心逻辑:只做 dict key 逐层访问,不支持数组下标、通配符或表达式。
|
||||
|
||||
Args:
|
||||
context: agent_runtime_context 字典。
|
||||
path: 白名单字段路径。
|
||||
|
||||
Returns:
|
||||
(是否存在, 值)。
|
||||
"""
|
||||
cursor: Any = context
|
||||
for part in path.split("."):
|
||||
if not isinstance(cursor, dict) or part not in cursor:
|
||||
return False, None
|
||||
cursor = cursor[part]
|
||||
return True, cursor
|
||||
|
||||
|
||||
def parse_agent_runtime_context(raw_context: str | dict[str, Any], paths: Any) -> dict[str, Any]:
|
||||
"""
|
||||
解析 agent_runtime_context 并返回指定字段。
|
||||
|
||||
【AI 触发时机】:Dify 画布需要读取当前 HXOPS 会话、任务、批次、执行目的或状态提示时调用;
|
||||
不用于推进任务状态,推进必须调用对应业务 Tool。
|
||||
|
||||
核心逻辑:校验协议版本与路径白名单,逐路径读取字段,缺失字段放入 missing。
|
||||
|
||||
Args:
|
||||
raw_context: Dify Start 变量中的 agent_runtime_context JSON 字符串。
|
||||
paths: 需要读取的白名单路径列表。
|
||||
|
||||
Returns:
|
||||
{"status": "ok", "data": {...}, "missing": [...]}。
|
||||
|
||||
Raises:
|
||||
ValidationError: 请求体、上下文或路径非法。
|
||||
"""
|
||||
context = _normalize_context(raw_context)
|
||||
normalized_paths = _normalize_paths(paths)
|
||||
|
||||
data: dict[str, Any] = {}
|
||||
missing: list[str] = []
|
||||
for path in normalized_paths:
|
||||
exists, value = _get_path_value(context, path)
|
||||
if exists:
|
||||
data[path] = value
|
||||
else:
|
||||
missing.append(path)
|
||||
return {"status": "ok", "data": data, "missing": missing}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ALLOWED_PARSE_PATHS",
|
||||
"MAX_PARSE_PATHS",
|
||||
"parse_agent_runtime_context",
|
||||
]
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/policy.py
|
||||
|
||||
用途:集中管理 agent_runtime_context 的长度、字段与安全裁剪策略。
|
||||
依赖:schema 中的平台协议常量;不访问数据库或业务服务。
|
||||
逻辑:builder 在输出给 Dify 前调用本模块,确保上下文短小、稳定且不会把大段历史塞进 Runtime。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
MAX_CONTEXT_JSON_CHARS = 8192
|
||||
MAX_DOMAIN_SUMMARY_CHARS = 500
|
||||
MAX_RECENT_ACTIVITY_SUMMARY_CHARS = 500
|
||||
MAX_REF_VALUE_CHARS = 200
|
||||
MAX_REFS = 30
|
||||
|
||||
|
||||
def truncate_text(value: Any, max_chars: int) -> str:
|
||||
"""
|
||||
将任意输入规范化为短文本。
|
||||
|
||||
核心逻辑:strip 后按字符数截断,避免上下文摘要或 ref 值撑爆 Dify Start 变量。
|
||||
|
||||
Args:
|
||||
value: 待规范化的文本或可转字符串对象。
|
||||
max_chars: 最大保留字符数。
|
||||
|
||||
Returns:
|
||||
规范化后的字符串;空值返回空字符串。
|
||||
"""
|
||||
normalized = str(value or "").strip()
|
||||
if max_chars <= 0 or len(normalized) <= max_chars:
|
||||
return normalized
|
||||
return normalized[:max_chars]
|
||||
|
||||
|
||||
def normalize_refs(refs: dict[str, Any] | None) -> dict[str, str]:
|
||||
"""
|
||||
规范化业务对象锚点。
|
||||
|
||||
核心逻辑:保留首个有效 key/value,裁剪 value 长度,并限制总数量,防止业务 adapter 注入过长对象。
|
||||
|
||||
Args:
|
||||
refs: 业务 adapter 传入的 refs 字典。
|
||||
|
||||
Returns:
|
||||
字段名和值均为非空字符串的 refs 字典。
|
||||
"""
|
||||
normalized: dict[str, str] = {}
|
||||
for raw_key, raw_value in (refs or {}).items():
|
||||
key = str(raw_key or "").strip()
|
||||
value = truncate_text(raw_value, MAX_REF_VALUE_CHARS)
|
||||
if not key or not value or key in normalized:
|
||||
continue
|
||||
normalized[key] = value
|
||||
if len(normalized) >= MAX_REFS:
|
||||
break
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_domain(domain: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
规范化领域上下文。
|
||||
|
||||
核心逻辑:只裁剪已知长文本字段,其余结构保持给业务 adapter 自主表达。
|
||||
|
||||
Args:
|
||||
domain: 业务域上下文片段。
|
||||
|
||||
Returns:
|
||||
裁剪后的领域上下文字典。
|
||||
"""
|
||||
if not domain:
|
||||
return {}
|
||||
normalized = dict(domain)
|
||||
if "summary" in normalized:
|
||||
normalized["summary"] = truncate_text(normalized.get("summary"), MAX_DOMAIN_SUMMARY_CHARS)
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_reference_context(reference_context: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
规范化短期指代上下文。
|
||||
|
||||
核心逻辑:限制 recent_activity_summary 长度,保留 focus/candidates 等结构化候选。
|
||||
|
||||
Args:
|
||||
reference_context: 指代治理上下文。
|
||||
|
||||
Returns:
|
||||
裁剪后的 reference_context 字典。
|
||||
"""
|
||||
if not reference_context:
|
||||
return {}
|
||||
normalized = dict(reference_context)
|
||||
if "recent_activity_summary" in normalized:
|
||||
normalized["recent_activity_summary"] = truncate_text(
|
||||
normalized.get("recent_activity_summary"),
|
||||
MAX_RECENT_ACTIVITY_SUMMARY_CHARS,
|
||||
)
|
||||
return normalized
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/reference.py
|
||||
|
||||
用途:构建平台级 reference_context,给外部 Runtime 提供短期指代解析线索。
|
||||
依赖:agent_runtime_context.policy、schema;不依赖具体业务模型。
|
||||
逻辑:业务 adapter 先把 focus/last_action/candidates 等抽象成对象引用,再由本模块统一裁剪、去重和限流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_runtime_context.policy import MAX_REF_VALUE_CHARS, normalize_reference_context, truncate_text
|
||||
from app.services.agent_runtime_context.schema import ReferenceContext
|
||||
|
||||
MAX_REFERENCE_OBJECT_TYPE_CHARS = 64
|
||||
MAX_REFERENCE_KEY_CHARS = 64
|
||||
MAX_REFERENCE_CANDIDATES = 5
|
||||
|
||||
|
||||
def build_object_ref(type_: str, id_: str, **extra: Any) -> dict[str, str]:
|
||||
"""
|
||||
构建 reference_context 中的对象引用。
|
||||
|
||||
核心逻辑:统一输出 type/id,并裁剪 action/reason/label 等扩展字段,避免业务 adapter 各自拼装不同口径。
|
||||
|
||||
Args:
|
||||
type_: 对象类型,如 task/batch。
|
||||
id_: 对象稳定标识,如 SN-001。
|
||||
**extra: 可选扩展字段,例如 action/reason/label。
|
||||
|
||||
Returns:
|
||||
规范化后的对象引用;type 或 id 为空时返回空 dict。
|
||||
"""
|
||||
normalized_type = truncate_text(type_, MAX_REFERENCE_OBJECT_TYPE_CHARS)
|
||||
normalized_id = truncate_text(id_, MAX_REF_VALUE_CHARS)
|
||||
if not normalized_type or not normalized_id:
|
||||
return {}
|
||||
|
||||
object_ref: dict[str, str] = {
|
||||
"type": normalized_type,
|
||||
"id": normalized_id,
|
||||
}
|
||||
for raw_key, raw_value in extra.items():
|
||||
key = truncate_text(raw_key, MAX_REFERENCE_KEY_CHARS)
|
||||
if not key or key in object_ref or raw_value is None:
|
||||
continue
|
||||
value = truncate_text(raw_value, MAX_REF_VALUE_CHARS)
|
||||
if not value:
|
||||
continue
|
||||
object_ref[key] = value
|
||||
return object_ref
|
||||
|
||||
|
||||
def _normalize_object_ref(value: dict[str, Any] | None) -> dict[str, str]:
|
||||
"""
|
||||
规范化单个对象引用。
|
||||
|
||||
核心逻辑:兼容业务 adapter 传入的普通 dict,统一转成 build_object_ref 输出结构。
|
||||
|
||||
Args:
|
||||
value: 原始对象引用。
|
||||
|
||||
Returns:
|
||||
规范化后的对象引用;非法输入返回空 dict。
|
||||
"""
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
extra = {key: item for key, item in value.items() if key not in {"type", "type_", "id"}}
|
||||
return build_object_ref(
|
||||
str(value.get("type") or value.get("type_") or ""),
|
||||
str(value.get("id") or ""),
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_candidates(candidates: list[dict[str, Any]] | None) -> list[dict[str, str]]:
|
||||
"""
|
||||
规范化候选对象列表。
|
||||
|
||||
核心逻辑:只保留前几个有效候选,按 type/id 去重,避免把整批对象全塞给 Dify。
|
||||
|
||||
Args:
|
||||
candidates: 候选对象引用列表。
|
||||
|
||||
Returns:
|
||||
去重并限量后的候选列表。
|
||||
"""
|
||||
normalized: list[dict[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for item in candidates or []:
|
||||
candidate = _normalize_object_ref(item)
|
||||
if not candidate:
|
||||
continue
|
||||
dedupe_key = (candidate["type"], candidate["id"])
|
||||
if dedupe_key in seen:
|
||||
continue
|
||||
normalized.append(candidate)
|
||||
seen.add(dedupe_key)
|
||||
if len(normalized) >= MAX_REFERENCE_CANDIDATES:
|
||||
break
|
||||
return normalized
|
||||
|
||||
|
||||
def build_reference_context(
|
||||
*,
|
||||
recent_activity_summary: str | None = None,
|
||||
focus_object: dict[str, Any] | None = None,
|
||||
last_action_target: dict[str, Any] | None = None,
|
||||
last_failed_target: dict[str, Any] | None = None,
|
||||
candidates: list[dict[str, Any]] | None = None,
|
||||
) -> ReferenceContext:
|
||||
"""
|
||||
构建平台统一的 reference_context。
|
||||
|
||||
核心逻辑:收敛业务 adapter 提供的短期指代线索,限制候选数量并裁剪摘要长度,保证输出小而稳定。
|
||||
|
||||
Args:
|
||||
recent_activity_summary: 最近活动摘要。
|
||||
focus_object: 当前焦点对象。
|
||||
last_action_target: 最近一次动作作用对象。
|
||||
last_failed_target: 最近一次失败/异常对象。
|
||||
candidates: 模糊指代候选对象列表。
|
||||
|
||||
Returns:
|
||||
规范化后的 reference_context;所有字段都为空时返回空 dict。
|
||||
"""
|
||||
reference_context: ReferenceContext = {}
|
||||
|
||||
summary = str(recent_activity_summary or "").strip()
|
||||
if summary:
|
||||
reference_context["recent_activity_summary"] = summary
|
||||
|
||||
normalized_focus = _normalize_object_ref(focus_object)
|
||||
if normalized_focus:
|
||||
reference_context["focus_object"] = normalized_focus
|
||||
|
||||
normalized_last_action = _normalize_object_ref(last_action_target)
|
||||
if normalized_last_action:
|
||||
reference_context["last_action_target"] = normalized_last_action
|
||||
|
||||
normalized_last_failed = _normalize_object_ref(last_failed_target)
|
||||
if normalized_last_failed:
|
||||
reference_context["last_failed_target"] = normalized_last_failed
|
||||
|
||||
normalized_candidates = _normalize_candidates(candidates)
|
||||
if normalized_candidates:
|
||||
reference_context["candidates"] = normalized_candidates
|
||||
|
||||
return normalize_reference_context(reference_context)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MAX_REFERENCE_CANDIDATES",
|
||||
"build_object_ref",
|
||||
"build_reference_context",
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_context/schema.py
|
||||
|
||||
用途:定义 HXOPS 传递给外部 Agent Runtime 的统一上下文协议常量与类型。
|
||||
依赖:typing 标准库;不依赖具体业务域,避免平台协议与 shipping/file-check 强耦合。
|
||||
逻辑:builder/policy/parser 等模块引用本文件的字段名和类型,业务 adapter 只填充 refs/domain 差异。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, TypedDict
|
||||
|
||||
AGENT_RUNTIME_CONTEXT_INPUT = "agent_runtime_context"
|
||||
AGENT_RUNTIME_CONTEXT_SCHEMA_VERSION = "1"
|
||||
|
||||
AgentCode = Literal["generic", "shipping_notice", "file_check"]
|
||||
ContextScope = Literal["chat_turn", "task_run", "batch_summary"]
|
||||
|
||||
|
||||
class PlatformContext(TypedDict, total=False):
|
||||
"""
|
||||
描述 HXOPS 平台侧会话与请求锚点。
|
||||
|
||||
核心逻辑:只放平台身份与请求追踪字段,业务状态放入 refs/domain。
|
||||
"""
|
||||
|
||||
session_id: str
|
||||
parent_session_id: str
|
||||
request_id: str
|
||||
locale: str
|
||||
trigger_source: str
|
||||
|
||||
|
||||
class DomainContext(TypedDict, total=False):
|
||||
"""
|
||||
描述业务域运行态摘要。
|
||||
|
||||
核心逻辑:由各业务 adapter 填充 summary/state_hint,供 Dify 理解现场但不替代 HXOPS 状态机。
|
||||
"""
|
||||
|
||||
type: str
|
||||
summary: str
|
||||
state_hint: dict[str, Any]
|
||||
available_actions_hint: list[dict[str, Any]]
|
||||
|
||||
|
||||
class ReferenceContext(TypedDict, total=False):
|
||||
"""
|
||||
描述模糊指代解析所需的短期上下文。
|
||||
|
||||
核心逻辑:承载 recent_activity_summary/focus_object 等摘要,不传全量 ChatLog。
|
||||
"""
|
||||
|
||||
recent_activity_summary: str
|
||||
focus_object: dict[str, Any]
|
||||
last_action_target: dict[str, Any]
|
||||
last_failed_target: dict[str, Any]
|
||||
candidates: list[dict[str, Any]]
|
||||
|
||||
|
||||
class AgentRuntimeContext(TypedDict, total=False):
|
||||
"""
|
||||
HXOPS Agent Runtime Context 协议对象。
|
||||
|
||||
核心逻辑:每次调用外部 Runtime 前重新生成 snapshot,Dify/其他 Runtime 只读取,不作为业务事实源。
|
||||
"""
|
||||
|
||||
schema_version: str
|
||||
context_id: str
|
||||
agent_code: str
|
||||
scope: str
|
||||
platform: PlatformContext
|
||||
refs: dict[str, str]
|
||||
domain: DomainContext
|
||||
reference_context: ReferenceContext
|
||||
@@ -1,77 +0,0 @@
|
||||
"""
|
||||
backend/app/services/chat/hxops_context.py
|
||||
|
||||
用途:构建 HXOPS -> Dify 的平台统一上下文注入协议。
|
||||
依赖:无业务域依赖,仅提供平台级上下文结构与 refs 规范化工具。
|
||||
逻辑:由聊天入口、后台编排器或各 Agent 适配层调用本模块,统一生成 hxops_context,
|
||||
避免各业务目录重复定义 Dify Start 输入协议。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
HXOPS_CONTEXT_INPUT = "hxops_context"
|
||||
HXOPS_CONTEXT_SCHEMA_VERSION = "1"
|
||||
|
||||
|
||||
def build_ref(field: str, value: str | None) -> dict[str, str] | None:
|
||||
"""构建单个业务对象引用;缺值时返回 None。"""
|
||||
normalized_field = str(field or "").strip()
|
||||
normalized_value = str(value or "").strip()
|
||||
if not normalized_field or not normalized_value:
|
||||
return None
|
||||
return {"field": normalized_field, "value": normalized_value}
|
||||
|
||||
|
||||
def build_hxops_context(
|
||||
*,
|
||||
session_id: str,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
refs: list[dict[str, str] | None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建平台统一的 hxops_context。
|
||||
|
||||
设计约束:
|
||||
- 只注入平台基础信息与当前已知对象锚点
|
||||
- 不注入 query/files 等 Dify 原生输入
|
||||
- 不注入 checkpoint/stage 等运行态状态
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
request_payload: dict[str, str] = {}
|
||||
normalized_request_id = str(request_id or "").strip()
|
||||
normalized_trigger_source = str(trigger_source or "").strip()
|
||||
normalized_locale = str(locale or "").strip()
|
||||
if normalized_request_id:
|
||||
request_payload["id"] = normalized_request_id
|
||||
if normalized_trigger_source:
|
||||
request_payload["trigger_source"] = normalized_trigger_source
|
||||
if normalized_locale:
|
||||
request_payload["locale"] = normalized_locale
|
||||
|
||||
normalized_refs: list[dict[str, str]] = []
|
||||
seen_fields: set[str] = set()
|
||||
for item in refs or []:
|
||||
if not item:
|
||||
continue
|
||||
field = str(item.get("field") or "").strip()
|
||||
value = str(item.get("value") or "").strip()
|
||||
if not field or not value or field in seen_fields:
|
||||
continue
|
||||
normalized_refs.append({"field": field, "value": value})
|
||||
seen_fields.add(field)
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
|
||||
"session": {"id": normalized_session_id},
|
||||
"request": request_payload,
|
||||
"refs": normalized_refs,
|
||||
}
|
||||
return payload
|
||||
|
||||
@@ -19,7 +19,13 @@ from app.services.shipping_notice.queue_service import enqueue_shipping_notice_j
|
||||
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.tool_common import (
|
||||
auto_progress_enabled,
|
||||
cfg_bool,
|
||||
cfg_int,
|
||||
log_task_event,
|
||||
switch_batch_focus,
|
||||
)
|
||||
from app.services.shipping_notice.tools import auto_progress, submit_decision
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
@@ -97,7 +103,13 @@ def _refresh_batch_focus(task_no: str) -> None:
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task or not task.batch:
|
||||
return
|
||||
task.batch.current_focus_task_no = task.task_no
|
||||
switch_batch_focus(
|
||||
task.batch,
|
||||
task,
|
||||
source="backend_orchestrator",
|
||||
event_type="focus_auto_switched",
|
||||
emit_when_unchanged=False,
|
||||
)
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
services/shipping_notice/chat_actions.py
|
||||
|
||||
用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
|
||||
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)。
|
||||
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py,不再暴露已删除的 /chat-actions 读模型。
|
||||
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)、ui_state。
|
||||
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py / ui_state.py,本模块仅保留兼容导出。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
@@ -26,10 +26,40 @@ from app.services.shipping_notice.state_machine import (
|
||||
upload_req_options_for_task,
|
||||
validate_registry,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
# Legacy alias
|
||||
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
|
||||
|
||||
|
||||
def build_chat_actions_payload(task) -> dict:
|
||||
"""
|
||||
构建聊天气泡侧动作按钮兼容 payload。
|
||||
|
||||
核心逻辑:复用统一 UI State 读模型,只抽取聊天侧需要的 checkpoint/action_buttons/summary,
|
||||
避免 workspace 路由继续依赖已删除的旧读模型实现。
|
||||
|
||||
Args:
|
||||
task: ShippingTask 模型实例。
|
||||
|
||||
Returns:
|
||||
包含 task_no、checkpoint、action_buttons 与摘要的字典。
|
||||
"""
|
||||
state = build_task_ui_state(task)
|
||||
return {
|
||||
"task_no": state.get("task_no"),
|
||||
"batch_no": state.get("batch_no"),
|
||||
"checkpoint": state.get("checkpoint"),
|
||||
"process_status": state.get("process_status"),
|
||||
"review_status": state.get("review_status"),
|
||||
"pending_human_reason": state.get("pending_human_reason"),
|
||||
"match_status": state.get("match_status"),
|
||||
"current_step": state.get("current_step"),
|
||||
"summary": state.get("summary"),
|
||||
"action_buttons": state.get("action_buttons") or [],
|
||||
"updated_at": state.get("updated_at"),
|
||||
}
|
||||
|
||||
__all__ = [
|
||||
"ACTION_SPECS",
|
||||
"ALL_ACTION_IDS",
|
||||
@@ -41,6 +71,7 @@ __all__ = [
|
||||
"action_buttons_for_checkpoint",
|
||||
"apply_task_transition",
|
||||
"build_action_buttons",
|
||||
"build_chat_actions_payload",
|
||||
"build_checkpoint_catalog",
|
||||
"checkpoint_for_task",
|
||||
"human_options_for_checkpoint",
|
||||
|
||||
@@ -43,6 +43,7 @@ from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
log_task_action_event,
|
||||
log_task_event,
|
||||
merge_tool_payload,
|
||||
payload_wants_auto_chain_fallback,
|
||||
@@ -79,12 +80,19 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
decision = str(payload.get("decision") or "").strip().lower()
|
||||
comment = str(payload.get("comment") or "").strip()
|
||||
lang = resolve_lang(payload)
|
||||
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
|
||||
|
||||
# [STEP 1] 先处理终止型决策。
|
||||
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
|
||||
if decision == "reject":
|
||||
apply_task_transition(task, TaskTransition.REJECTED)
|
||||
log_task_event(task, "decision_rejected", {"comment": comment})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"decision_rejected",
|
||||
action="reject",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -95,7 +103,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
if decision in {"close", "closed"}:
|
||||
apply_task_transition(task, TaskTransition.CLOSED)
|
||||
log_task_event(task, "decision_closed", {"comment": comment})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"decision_closed",
|
||||
action="close",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -128,7 +142,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
log_task_event(task, "parse_confirmed", {"comment": comment})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"parse_confirmed",
|
||||
action="confirm",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
@@ -153,7 +173,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
if match_completed(task):
|
||||
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
|
||||
log_task_event(task, "decision_confirmed", {"comment": comment})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"decision_confirmed",
|
||||
action="confirm",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -212,7 +238,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
log_task_event(task, "decision_rematch", {"comment": comment})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"decision_rematch",
|
||||
action="rematch",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
@@ -269,9 +301,19 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
**{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
**{
|
||||
"action": "confirm_inventory_mapping",
|
||||
"source": event_source,
|
||||
"target_type": "task",
|
||||
"target_id": task.task_no,
|
||||
"batch_no": task.batch.batch_no if task.batch else "",
|
||||
"conversation_id": task.conversation_id or "",
|
||||
},
|
||||
},
|
||||
)
|
||||
for link in inv_file.links or []:
|
||||
@@ -285,13 +327,29 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
linked_task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
**{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
**{
|
||||
"action": "confirm_inventory_mapping",
|
||||
"source": event_source,
|
||||
"target_type": "task",
|
||||
"target_id": linked_task.task_no,
|
||||
"batch_no": linked_task.batch.batch_no if linked_task.batch else "",
|
||||
"conversation_id": linked_task.conversation_id or "",
|
||||
},
|
||||
},
|
||||
)
|
||||
else:
|
||||
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"inventory_mapping_confirmed",
|
||||
action="confirm_inventory_mapping",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
orchestrator_started = (
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
@@ -385,7 +443,14 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
task.error_message = None
|
||||
log_task_event(task, "notice_reparse_requested", {"comment": comment, "source": "dify_required"})
|
||||
log_task_action_event(
|
||||
task,
|
||||
"notice_reparse_requested",
|
||||
action="reparse",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
extra={"reparse_mode": "dify_required"},
|
||||
)
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
|
||||
@@ -28,7 +28,8 @@ def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None)
|
||||
"""
|
||||
构造后台排程器发给 Dify 的用户意图短句。
|
||||
|
||||
后台任务号与批次号通过 hxops_context.refs 注入,不能拼入 query,避免 Dify 预处理把 SB-/流程指令误判为切换任务。
|
||||
后台任务号与批次号通过 agent_runtime_context.refs 注入,不能拼入 query,
|
||||
避免 Dify 预处理把 SB-/流程指令误判为切换任务。
|
||||
"""
|
||||
return "解析当前发货通知任务"
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/dify_inputs.py
|
||||
|
||||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||||
依赖:agent_resolver、models.ShippingBatch/ShippingTask、chat.hxops_context。
|
||||
依赖:agent_runtime_context 平台协议、agent_resolver、models.ShippingBatch/ShippingTask、shipping_notice.runtime_context。
|
||||
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
|
||||
仅补充货代发货场景可识别的 refs,再委托平台级上下文构造器生成 hxops_context。
|
||||
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,8 +12,10 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.chat.hxops_context import HXOPS_CONTEXT_INPUT, build_hxops_context, build_ref
|
||||
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:
|
||||
@@ -45,12 +47,26 @@ def _task_by_task_no(task_id: str) -> ShippingTask | None:
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
|
||||
"""构建货代发货 Agent 当前已知业务对象锚点。"""
|
||||
return [
|
||||
build_ref("task", task),
|
||||
build_ref("batch", batch),
|
||||
]
|
||||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None:
|
||||
"""
|
||||
解析当前显式焦点任务行。
|
||||
|
||||
核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询,
|
||||
但不在无焦点时回退到最近任务,避免多票批次串单。
|
||||
|
||||
Args:
|
||||
focus_task: 已解析出的焦点任务号。
|
||||
explicit_task_row: task_id 显式传入时查询到的任务。
|
||||
|
||||
Returns:
|
||||
当前焦点任务;无法明确识别时返回 None。
|
||||
"""
|
||||
normalized = str(focus_task or "").strip().upper()
|
||||
if not normalized:
|
||||
return None
|
||||
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
|
||||
return explicit_task_row
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def build_dify_chat_inputs(
|
||||
@@ -66,7 +82,7 @@ def build_dify_chat_inputs(
|
||||
构建发货通知 Dify Chatflow inputs。
|
||||
|
||||
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
|
||||
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布通过 refs 稳定定位当前 task/batch。
|
||||
无需再注入 HXOPS_TOOLS_API_BASE;这里仅注入 agent_runtime_context,避免新旧上下文字段并存导致画布协议漂移。
|
||||
"""
|
||||
conv_id = str(conversation_id or "").strip()
|
||||
if not conv_id:
|
||||
@@ -93,13 +109,18 @@ def build_dify_chat_inputs(
|
||||
):
|
||||
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
|
||||
|
||||
hxops_context = build_hxops_context(
|
||||
runtime_context = build_shipping_runtime_context(
|
||||
session_id=conv_id,
|
||||
request_id=request_id,
|
||||
task=_focus_task_row(focus_task, explicit_task_row),
|
||||
batch=batch or getattr(explicit_task_row, "batch", None),
|
||||
trigger_source=trigger_source,
|
||||
request_id=request_id,
|
||||
locale=locale,
|
||||
refs=_build_hxops_refs(task=focus_task, batch=focus_batch),
|
||||
scope="task_run" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||||
run_purpose="parse_notice" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||||
)
|
||||
if not hxops_context:
|
||||
if not runtime_context:
|
||||
return {}
|
||||
return {HXOPS_CONTEXT_INPUT: hxops_context}
|
||||
return {
|
||||
AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context),
|
||||
}
|
||||
@@ -58,6 +58,70 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent
|
||||
)
|
||||
|
||||
|
||||
def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
|
||||
"""
|
||||
生成库存 RPA 尝试轮次文案。
|
||||
【AI 触发时机】:需要把当前 RPA 处于单次自动尝试、多次自动尝试或手动重试轮次解释给用户时调用。
|
||||
|
||||
核心逻辑:手动 retry_rpa 始终强调“手动第 N 次”;自动模式在 max_attempts=1 时不再输出“1/1”,
|
||||
避免 Dify 误解为系统还会继续自动重试。
|
||||
"""
|
||||
if manual_retry_round:
|
||||
return f"手动第 {attempt_no} 次尝试"
|
||||
if max_attempts <= 1:
|
||||
return "当前配置为单次自动尝试"
|
||||
return f"第 {attempt_no}/{max_attempts} 次尝试"
|
||||
|
||||
|
||||
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} 次)。"
|
||||
|
||||
|
||||
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} 次)。"
|
||||
if max_attempts <= 1:
|
||||
return "已触发 RPA 库存导出。"
|
||||
return f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||||
|
||||
|
||||
def _inventory_rpa_exhausted_message(attempts: int) -> str:
|
||||
"""生成库存 RPA 已耗尽时的用户文案;单次模式明确提示“已尝试一次”。"""
|
||||
if max_rpa_inventory_attempts() <= 1:
|
||||
return "已尝试 1 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
|
||||
return f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
|
||||
|
||||
|
||||
def _inventory_rpa_running_message(*, attempt_no: int, max_attempts: int) -> str:
|
||||
"""
|
||||
生成库存 RPA 等待中的用户提示。
|
||||
【AI 触发时机】:任务已进入 RPA 等待窗口、前端或工具再次查询状态时调用。
|
||||
|
||||
核心逻辑:前台只展示“仍在进行中”和下一步建议,不暴露 elapsed/timeout/retry_after 等秒级内部阈值。
|
||||
"""
|
||||
prefix = _inventory_rpa_running_prefix(attempt_no=attempt_no, max_attempts=max_attempts)
|
||||
return f"{prefix}请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
|
||||
|
||||
|
||||
def _inventory_rpa_triggered_message(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
|
||||
"""
|
||||
生成库存 RPA 刚触发成功后的用户提示。
|
||||
【AI 触发时机】:成功写出 trigger、准备把 running 状态回传给前端或 Agent 时调用。
|
||||
|
||||
核心逻辑:保留“已触发/已重新触发”状态提示,但不把 timeout 秒数暴露给业务用户。
|
||||
"""
|
||||
prefix = _inventory_rpa_triggered_prefix(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
manual_retry_round=manual_retry_round,
|
||||
)
|
||||
return f"{prefix}若长时间无结果,可手动重试,或上传库存 Excel。"
|
||||
|
||||
|
||||
def inventory_rpa_wait_seconds(task: ShippingTask) -> tuple[int | None, int | None, int | None]:
|
||||
"""
|
||||
返回库存 RPA 当前等待耗时、超时时间和剩余秒数。
|
||||
@@ -231,10 +295,9 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=(
|
||||
f"RPA 库存导出进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
|
||||
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
|
||||
f"请稍后再试(建议 {remaining}s 后)。"
|
||||
message=_inventory_rpa_running_message(
|
||||
attempt_no=max(attempts, 1),
|
||||
max_attempts=max_attempts,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
@@ -249,7 +312,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
)
|
||||
last_failed = latest_task_event(task, "inventory_rpa_failed")
|
||||
if not last_failed or (last_failed.created_at < last_trigger.created_at):
|
||||
task.error_message = f"RPA 库存导出超时(>{timeout_seconds}s)"
|
||||
task.error_message = "RPA 库存导出等待超时"
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_failed",
|
||||
@@ -262,7 +325,8 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 处理重试上限与已落盘文件两种捷径。
|
||||
# 已达到最大次数时直接转人工;若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。
|
||||
# 单次模式下,只有“上一轮已经失败/超时”时才允许在这里转人工;首次成功写出 trigger 后必须进入等待窗口。
|
||||
# 若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
max_attempts = max_rpa_inventory_attempts()
|
||||
if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
|
||||
@@ -273,7 +337,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
|
||||
message=_inventory_rpa_exhausted_message(attempts),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -313,10 +377,10 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
if manual_retry_round
|
||||
else "已触发 RPA 库存导出,等待结果"
|
||||
)
|
||||
progress_detail = (
|
||||
f"手动第 {attempt_no} 次尝试"
|
||||
if manual_retry_round
|
||||
else f"第 {attempt_no}/{max_attempts} 次尝试"
|
||||
progress_detail = _inventory_rpa_attempt_label(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
manual_retry_round=manual_retry_round,
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -336,28 +400,15 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
{"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round},
|
||||
)
|
||||
|
||||
if attempt_no >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempt_no})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=f"已尝试 {attempt_no} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
response_prefix = (
|
||||
f"已手动重新触发 RPA 库存导出(手动第 {attempt_no} 次)。"
|
||||
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"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可手动重试,或上传库存 Excel。",
|
||||
message=_inventory_rpa_triggered_message(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
manual_retry_round=manual_retry_round,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
@@ -417,7 +468,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
|
||||
message=_inventory_rpa_exhausted_message(attempts),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ def _post_op(
|
||||
properties: dict[str, Any],
|
||||
*,
|
||||
required: list[str] | None = None,
|
||||
description: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
schema: dict[str, Any] = {"type": "object", "properties": properties}
|
||||
if required:
|
||||
@@ -38,7 +39,7 @@ def _post_op(
|
||||
"post": {
|
||||
"operationId": operation_id,
|
||||
"summary": summary,
|
||||
"description": summary,
|
||||
"description": str(description or summary),
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
@@ -83,8 +84,13 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
|
||||
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
|
||||
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||
"推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;"
|
||||
"模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。"
|
||||
"submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source"
|
||||
" 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。"
|
||||
"若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。"
|
||||
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
|
||||
"不要在自然语言正文里列出按钮清单或“推荐下一步”动作列表;"
|
||||
"不要在自然语言正文列出按钮清单或“推荐下一步”动作列表;"
|
||||
"可点击按钮由宿主系统根据 action_buttons 统一渲染。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
),
|
||||
@@ -201,6 +207,14 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"comment": _str_prop("备注(可选)"),
|
||||
},
|
||||
required=["decision"],
|
||||
description=(
|
||||
"人工复核决策入口。必须先定位到唯一 task_id 才能推进;若 conversation_id 对应多个任务,必须先追问或调用状态查询工具确认,"
|
||||
"禁止用模糊指代直接推进。"
|
||||
"本 Tool 的返回结果以 HXOPS 状态机为准,Dify 必须根据实际返回的 status、checkpoint、forbidden_next_tools、"
|
||||
"human_options 或 action_buttons 解释当前现场。"
|
||||
"若返回 needs_human 或 failed,不得自行宣布完成、不得改写为成功,也不要在正文列出按钮清单;"
|
||||
"按钮由 HXOPS 前端渲染。"
|
||||
),
|
||||
),
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
|
||||
@@ -391,14 +391,16 @@ 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 serialize_conversation_batch_workspace(batch: ShippingBatch) -> dict[str, Any]:
|
||||
"""
|
||||
序列化会话工作台中的单个批次。
|
||||
|
||||
核心逻辑:直接复用批次级 UI State 构建器,确保会话级工作台与批次详情页的
|
||||
`tasks[].ui_state / focus_task_ui_state / action_buttons` 完全同源,避免按钮来源漂移。
|
||||
"""
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state
|
||||
|
||||
return build_batch_ui_state(batch)
|
||||
|
||||
|
||||
def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]:
|
||||
@@ -417,7 +419,7 @@ def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict
|
||||
"conversation_id": value,
|
||||
"summary": compute_conversation_workspace_summary(ordered_batches),
|
||||
"batches": [
|
||||
serialize_conversation_batch_workspace(batch, user_id)
|
||||
serialize_conversation_batch_workspace(batch)
|
||||
for batch in ordered_batches
|
||||
],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/reference_context.py
|
||||
|
||||
用途:从发货通知批次/任务/事件构建 shipping_notice 专用 reference_context。
|
||||
依赖:models.ShippingBatch/ShippingTask/ShippingTaskEvent、agent_runtime_context.reference。
|
||||
逻辑:runtime_context 在调用 Dify 前经本模块提炼当前 focus、最近动作、最近失败和候选对象,避免把全量事件流水直接暴露给 Runtime。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent
|
||||
from app.services.agent_runtime_context.reference import build_object_ref, build_reference_context
|
||||
|
||||
MAX_REFERENCE_EVENT_SCAN = 8
|
||||
MAX_REFERENCE_SUMMARY_CANDIDATES = 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _ActionEventMeta:
|
||||
"""定义 reference builder 可识别动作事件的语义与优先级。"""
|
||||
|
||||
action: str
|
||||
summary_template: str
|
||||
priority: int
|
||||
|
||||
|
||||
_ACTION_EVENT_MAP: dict[str, _ActionEventMeta] = {
|
||||
"parse_confirmed": _ActionEventMeta("confirm_parse", "用户已确认 {task_no} 解析", 40),
|
||||
"decision_confirmed": _ActionEventMeta("confirm_matched", "用户已确认 {task_no} 当前结果", 40),
|
||||
"decision_rematch": _ActionEventMeta("rematch", "用户已要求重新匹配 {task_no}", 40),
|
||||
"notice_reparse_requested": _ActionEventMeta("reparse", "用户已要求重新解析 {task_no}", 40),
|
||||
"decision_rejected": _ActionEventMeta("reject", "用户已驳回 {task_no}", 40),
|
||||
"focus_switched": _ActionEventMeta("switch_focus", "用户已切换 focus 到 {task_no}", 35),
|
||||
"focus_auto_switched": _ActionEventMeta("auto_focus", "系统自动聚焦到 {task_no}", 10),
|
||||
"inventory_mapping_confirmed": _ActionEventMeta("confirm_inventory_mapping", "用户已确认 {task_no} 库存映射", 30),
|
||||
"inventory_source_confirmed": _ActionEventMeta("confirm_inventory_source", "用户已确认 {task_no} 库存源", 30),
|
||||
}
|
||||
|
||||
|
||||
def _clean_text(value: Any) -> str:
|
||||
"""将任意值规范化为去空白字符串。"""
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _task_no(task: ShippingTask | None) -> str:
|
||||
"""提取任务号并统一成大写。"""
|
||||
return _clean_text(getattr(task, "task_no", None)).upper()
|
||||
|
||||
|
||||
def _task_recency_key(task: ShippingTask) -> tuple[datetime, int]:
|
||||
"""
|
||||
构造任务最近性排序键。
|
||||
|
||||
核心逻辑:优先按 updated_at,其次 created_at 与主键排序,保证最近失败/最近动作关联稳定可复现。
|
||||
"""
|
||||
updated_at = getattr(task, "updated_at", None) or getattr(task, "created_at", None) or datetime.min
|
||||
return updated_at, int(getattr(task, "id", 0) or 0)
|
||||
|
||||
|
||||
def _collect_batch_tasks(batch: ShippingBatch | None, focus_task: ShippingTask | None) -> list[ShippingTask]:
|
||||
"""
|
||||
汇总当前 reference_context 可见的任务集合。
|
||||
|
||||
核心逻辑:优先读取当前批次任务;若 focus_task 尚未包含则补入,避免后台单票 run 丢失最近失败/焦点判断。
|
||||
"""
|
||||
tasks: list[ShippingTask] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for task in list(getattr(batch, "tasks", None) or []):
|
||||
task_no = _task_no(task)
|
||||
if not task_no or task_no in seen:
|
||||
continue
|
||||
tasks.append(task)
|
||||
seen.add(task_no)
|
||||
|
||||
focus_task_no = _task_no(focus_task)
|
||||
if focus_task is not None and focus_task_no and focus_task_no not in seen:
|
||||
tasks.append(focus_task)
|
||||
|
||||
return sorted(tasks, key=_task_recency_key, reverse=True)
|
||||
|
||||
|
||||
def _recent_events(tasks: list[ShippingTask]) -> list[ShippingTaskEvent]:
|
||||
"""
|
||||
查询最近关键事件。
|
||||
|
||||
核心逻辑:只取当前批次/任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。
|
||||
"""
|
||||
task_ids = [int(task.id) for task in tasks if getattr(task, "id", None) is not None]
|
||||
if not task_ids:
|
||||
return []
|
||||
return (
|
||||
ShippingTaskEvent.query.filter(ShippingTaskEvent.task_id.in_(task_ids))
|
||||
.order_by(ShippingTaskEvent.created_at.desc(), ShippingTaskEvent.id.desc())
|
||||
.limit(MAX_REFERENCE_EVENT_SCAN)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _task_failure_descriptor(task: ShippingTask | None) -> dict[str, str] | None:
|
||||
"""
|
||||
提取任务失败/异常摘要。
|
||||
|
||||
核心逻辑:把 HXOPS 内部状态机信号收敛成 Dify 可理解的 shortage/rejected/upload_failed 等短标签。
|
||||
"""
|
||||
task_no = _task_no(task)
|
||||
if not task_no:
|
||||
return None
|
||||
|
||||
process_status = _clean_text(getattr(task, "process_status", None)).lower()
|
||||
review_status = _clean_text(getattr(task, "review_status", None)).lower()
|
||||
match_status = _clean_text(getattr(task, "match_status", None)).lower()
|
||||
pending_reason = _clean_text(getattr(task, "pending_human_reason", None)).lower()
|
||||
upload_status = _clean_text(getattr(task, "upload_status", None)).lower()
|
||||
|
||||
if match_status == "shortage" or pending_reason == "shortage" or getattr(task, "shortage_json", None):
|
||||
return {
|
||||
"reason": "shortage",
|
||||
"label": "异常:库存不足",
|
||||
"summary": f"{task_no} 库存匹配失败",
|
||||
}
|
||||
if process_status == "rejected" or review_status == "rejected":
|
||||
return {
|
||||
"reason": "rejected",
|
||||
"label": "已驳回",
|
||||
"summary": f"{task_no} 已被驳回",
|
||||
}
|
||||
if process_status == "upload_failed" or upload_status == "failed" or pending_reason == "upload_rpa_failed":
|
||||
return {
|
||||
"reason": "upload_failed",
|
||||
"label": "异常:上传失败",
|
||||
"summary": f"{task_no} 上传失败",
|
||||
}
|
||||
if _clean_text(getattr(task, "error_message", None)):
|
||||
return {
|
||||
"reason": "error",
|
||||
"label": "异常:处理失败",
|
||||
"summary": f"{task_no} 处理失败",
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def _last_action_target(
|
||||
*,
|
||||
events: list[ShippingTaskEvent],
|
||||
task_by_id: dict[int, ShippingTask],
|
||||
) -> tuple[dict[str, str], str]:
|
||||
"""
|
||||
根据最近事件提取最后动作对象。
|
||||
|
||||
核心逻辑:只识别对指代解析价值高的人工动作事件,如 confirm/rematch/reparse,避免把系统内部流水误当“用户刚才那个”。
|
||||
"""
|
||||
best_match: tuple[int, dict[str, str], str] | None = None
|
||||
for event in events:
|
||||
event_type = _clean_text(getattr(event, "event_type", None))
|
||||
meta = _ACTION_EVENT_MAP.get(event_type)
|
||||
if not meta:
|
||||
continue
|
||||
detail = getattr(event, "detail_json", None)
|
||||
task_no = ""
|
||||
source = ""
|
||||
if isinstance(detail, dict):
|
||||
task_no = _clean_text(detail.get("target_id")).upper()
|
||||
source = _clean_text(detail.get("source")).lower()
|
||||
if not task_no:
|
||||
task = task_by_id.get(int(getattr(event, "task_id", 0) or 0))
|
||||
task_no = _task_no(task)
|
||||
if not task_no:
|
||||
continue
|
||||
priority = meta.priority
|
||||
if source in {"workspace_api", "tool_api"}:
|
||||
priority += 5
|
||||
candidate_ref = build_object_ref("task", task_no, action=meta.action)
|
||||
candidate_summary = meta.summary_template.format(task_no=task_no)
|
||||
if best_match is None or priority > best_match[0]:
|
||||
best_match = (priority, candidate_ref, candidate_summary)
|
||||
if best_match is None:
|
||||
return {}, ""
|
||||
return best_match[1], best_match[2]
|
||||
|
||||
|
||||
def _last_failed_target(tasks: list[ShippingTask]) -> tuple[dict[str, str], str]:
|
||||
"""
|
||||
提取最近失败或异常的目标对象。
|
||||
|
||||
核心逻辑:优先按任务最近更新时间选择一个失败任务,供“上一个失败的”之类模糊指代使用。
|
||||
"""
|
||||
for task in tasks:
|
||||
failure = _task_failure_descriptor(task)
|
||||
task_no = _task_no(task)
|
||||
if not failure or not task_no:
|
||||
continue
|
||||
return (
|
||||
build_object_ref("task", task_no, reason=failure["reason"], label=failure["label"]),
|
||||
failure["summary"],
|
||||
)
|
||||
return {}, ""
|
||||
|
||||
|
||||
def _candidate_refs(tasks: list[ShippingTask], focus_task_no: str) -> list[dict[str, str]]:
|
||||
"""
|
||||
生成模糊指代候选对象列表。
|
||||
|
||||
核心逻辑:仅暴露少量异常/失败任务,如 shortage/rejected/upload_failed,避免把整批任务全部透传给 Dify。
|
||||
"""
|
||||
candidates: list[dict[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
for task in tasks:
|
||||
task_no = _task_no(task)
|
||||
failure = _task_failure_descriptor(task)
|
||||
if not task_no or not failure:
|
||||
continue
|
||||
if focus_task_no and task_no == focus_task_no:
|
||||
continue
|
||||
if task_no in seen:
|
||||
continue
|
||||
candidates.append(build_object_ref("task", task_no, label=failure["label"]))
|
||||
seen.add(task_no)
|
||||
return candidates
|
||||
|
||||
|
||||
def _build_recent_activity_summary(
|
||||
*,
|
||||
batch: ShippingBatch | None,
|
||||
focus_task_no: str,
|
||||
last_action_summary: str,
|
||||
last_failed_summary: str,
|
||||
candidates: list[dict[str, str]],
|
||||
) -> str:
|
||||
"""
|
||||
组装 recent_activity_summary 短摘要。
|
||||
|
||||
核心逻辑:优先描述最近动作、当前 focus 和最近失败,再补少量候选摘要,帮助 Dify 理解“继续/刚才那个/上一个失败的”。
|
||||
"""
|
||||
pieces: list[str] = []
|
||||
if last_action_summary:
|
||||
pieces.append(last_action_summary)
|
||||
if focus_task_no:
|
||||
pieces.append(f"当前 focus 为 {focus_task_no}")
|
||||
elif _clean_text(getattr(batch, "batch_no", None)):
|
||||
pieces.append(f"当前批次为 {_clean_text(batch.batch_no).upper()}")
|
||||
if last_failed_summary:
|
||||
pieces.append(last_failed_summary)
|
||||
if len(candidates) > 1:
|
||||
candidate_labels = "、".join(
|
||||
f"{item['id']}({item.get('label') or '候选'})"
|
||||
for item in candidates[:MAX_REFERENCE_SUMMARY_CANDIDATES]
|
||||
if item.get("id")
|
||||
)
|
||||
if candidate_labels:
|
||||
pieces.append(f"候选对象:{candidate_labels}")
|
||||
return (";".join(pieces) + "。") if pieces else ""
|
||||
|
||||
|
||||
def build_shipping_reference_context(
|
||||
*,
|
||||
batch: ShippingBatch | None,
|
||||
focus_task: ShippingTask | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知 Agent 专用 reference_context。
|
||||
|
||||
【AI 触发时机】:当用户在 HXOPS 已做确认、重匹配、切票等动作后,又在对话里说“继续”“刚才那个”“上一个失败的”时,
|
||||
Dify 需要优先读取这份上下文理解当前现场,但不能直接据此推进业务状态。
|
||||
|
||||
核心逻辑:读取 batch.current_focus_task_no、任务状态和最近少量事件,提炼 focus_object / last_action_target /
|
||||
last_failed_target / candidates / recent_activity_summary 五类短期线索;不输出全量任务详情或完整事件日志。
|
||||
|
||||
Args:
|
||||
batch: 当前批次;可为空。
|
||||
focus_task: 当前焦点任务;可为空。
|
||||
|
||||
Returns:
|
||||
shipping_notice 领域的 reference_context;没有有效线索时返回空 dict。
|
||||
"""
|
||||
tasks = _collect_batch_tasks(batch, focus_task)
|
||||
focus_task_no = _task_no(focus_task)
|
||||
if not focus_task_no and batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
|
||||
focus_task_no = _clean_text(batch.current_focus_task_no).upper()
|
||||
|
||||
if not tasks and not focus_task_no:
|
||||
return {}
|
||||
|
||||
events = _recent_events(tasks)
|
||||
task_by_id = {int(task.id): task for task in tasks if getattr(task, "id", None) is not None}
|
||||
last_action_target, last_action_summary = _last_action_target(events=events, task_by_id=task_by_id)
|
||||
last_failed_target, last_failed_summary = _last_failed_target(tasks)
|
||||
candidates = _candidate_refs(tasks, focus_task_no)
|
||||
|
||||
focus_object = build_object_ref("task", focus_task_no) if focus_task_no else {}
|
||||
recent_activity_summary = _build_recent_activity_summary(
|
||||
batch=batch,
|
||||
focus_task_no=focus_task_no,
|
||||
last_action_summary=last_action_summary,
|
||||
last_failed_summary=last_failed_summary,
|
||||
candidates=candidates,
|
||||
)
|
||||
return build_reference_context(
|
||||
recent_activity_summary=recent_activity_summary or None,
|
||||
focus_object=focus_object or None,
|
||||
last_action_target=last_action_target or None,
|
||||
last_failed_target=last_failed_target or None,
|
||||
candidates=candidates or None,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["build_shipping_reference_context"]
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_attempts.py
|
||||
|
||||
用途:统计任务的 RPA 库存导出与货代上传重试次数,并给出默认上限。
|
||||
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
|
||||
依赖:ShippingTask、ShippingTaskEvent 模型与事件查询逻辑。
|
||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
|
||||
"""
|
||||
@@ -13,7 +13,7 @@ from datetime import datetime
|
||||
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
|
||||
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 1
|
||||
FIXED_RPA_INVENTORY_MAX_ATTEMPTS = 1
|
||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||
|
||||
_INVENTORY_SUCCESS_EVENTS = {
|
||||
@@ -87,15 +87,8 @@ def upload_rpa_attempts(task: ShippingTask | None) -> int:
|
||||
|
||||
|
||||
def max_rpa_inventory_attempts() -> int:
|
||||
"""RPA 库存导出最大重试次数(环境变量 SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS)。"""
|
||||
value = os.getenv("SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS")
|
||||
if value is None or not str(value).strip():
|
||||
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
|
||||
return max(parsed, 1)
|
||||
"""RPA 库存导出固定只允许自动尝试一次;再次尝试必须由用户显式点击 retry_rpa。"""
|
||||
return FIXED_RPA_INVENTORY_MAX_ATTEMPTS
|
||||
|
||||
|
||||
def max_rpa_upload_attempts() -> int:
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/runtime_context.py
|
||||
|
||||
用途:构建货代发货通知 Agent 的 agent_runtime_context 领域适配层。
|
||||
依赖:models.ShippingBatch/ShippingTask、agent_runtime_context.builder。
|
||||
逻辑:dify_inputs 与后台编排器在调用 Dify 前通过本模块生成最新业务现场,
|
||||
Dify 只消费 snapshot,任务推进仍以 HXOPS 状态机和 Tool API 为准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.agent_runtime_context.builder import build_agent_runtime_context
|
||||
from app.services.shipping_notice.reference_context import build_shipping_reference_context
|
||||
|
||||
SHIPPING_NOTICE_AGENT_CODE = "shipping_notice"
|
||||
|
||||
|
||||
def _clean_text(value: Any) -> str:
|
||||
"""
|
||||
将模型字段规范化为短文本。
|
||||
|
||||
核心逻辑:统一处理 None/空白字符串,避免 domain/state_hint 中混入空值。
|
||||
|
||||
Args:
|
||||
value: 待规范化字段。
|
||||
|
||||
Returns:
|
||||
去除首尾空白后的字符串。
|
||||
"""
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _batch_no(batch: ShippingBatch | None, task: ShippingTask | None) -> str:
|
||||
"""
|
||||
获取当前上下文的批次号。
|
||||
|
||||
核心逻辑:优先使用显式 batch;缺失时从 task.batch 补齐,避免后台单票 run 丢失批次锚点。
|
||||
|
||||
Args:
|
||||
batch: 当前批次。
|
||||
task: 当前任务。
|
||||
|
||||
Returns:
|
||||
批次号;无法识别时返回空字符串。
|
||||
"""
|
||||
if batch and _clean_text(getattr(batch, "batch_no", None)):
|
||||
return _clean_text(batch.batch_no).upper()
|
||||
task_batch = getattr(task, "batch", None)
|
||||
if task_batch and _clean_text(getattr(task_batch, "batch_no", None)):
|
||||
return _clean_text(task_batch.batch_no).upper()
|
||||
return ""
|
||||
|
||||
|
||||
def _task_no(task: ShippingTask | None) -> str:
|
||||
"""
|
||||
获取当前上下文的任务号。
|
||||
|
||||
核心逻辑:只使用已解析出的显式任务对象,不按会话猜测最近任务,避免多票串单。
|
||||
|
||||
Args:
|
||||
task: 当前任务。
|
||||
|
||||
Returns:
|
||||
任务号;缺失时返回空字符串。
|
||||
"""
|
||||
return _clean_text(getattr(task, "task_no", None)).upper()
|
||||
|
||||
|
||||
def _build_refs(
|
||||
*,
|
||||
task: ShippingTask | None,
|
||||
batch: ShippingBatch | None,
|
||||
run_purpose: str | None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建新版 agent_runtime_context.refs。
|
||||
|
||||
核心逻辑:使用稳定业务字段名 task_no/batch_no/run_purpose/file_name,区别于旧 hxops_context 的 task/batch。
|
||||
|
||||
Args:
|
||||
task: 当前任务。
|
||||
batch: 当前批次。
|
||||
run_purpose: 本次 Dify run 的目的。
|
||||
|
||||
Returns:
|
||||
非空业务锚点字典。
|
||||
"""
|
||||
refs: dict[str, str] = {}
|
||||
task_no = _task_no(task)
|
||||
batch_no = _batch_no(batch, task)
|
||||
file_name = _clean_text(getattr(task, "source_file_name", None))
|
||||
normalized_run_purpose = _clean_text(run_purpose)
|
||||
if task_no:
|
||||
refs["task_no"] = task_no
|
||||
if batch_no:
|
||||
refs["batch_no"] = batch_no
|
||||
if normalized_run_purpose:
|
||||
refs["run_purpose"] = normalized_run_purpose
|
||||
if file_name:
|
||||
refs["file_name"] = file_name
|
||||
return refs
|
||||
|
||||
|
||||
def _build_state_hint(task: ShippingTask | None, batch: ShippingBatch | None) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知运行态提示。
|
||||
|
||||
核心逻辑:只放 Dify 判断流程所需的状态摘要;真正能否推进仍由 HXOPS Tool/状态机校验。
|
||||
|
||||
Args:
|
||||
task: 当前任务。
|
||||
batch: 当前批次。
|
||||
|
||||
Returns:
|
||||
状态提示字典。
|
||||
"""
|
||||
state_hint: dict[str, Any] = {}
|
||||
task_no = _task_no(task)
|
||||
if task_no:
|
||||
state_hint["focus_task_no"] = task_no
|
||||
elif batch and _clean_text(getattr(batch, "current_focus_task_no", None)):
|
||||
state_hint["focus_task_no"] = _clean_text(batch.current_focus_task_no).upper()
|
||||
|
||||
if task is not None:
|
||||
for attr, key in (
|
||||
("current_step", "current_step"),
|
||||
("process_status", "status"),
|
||||
("review_status", "review_status"),
|
||||
("match_status", "match_status"),
|
||||
("pending_human_reason", "pending_human_reason"),
|
||||
("upload_status", "upload_status"),
|
||||
):
|
||||
value = _clean_text(getattr(task, attr, None))
|
||||
if value:
|
||||
state_hint[key] = value
|
||||
|
||||
batch_no = _batch_no(batch, task)
|
||||
if batch_no:
|
||||
state_hint["batch_no"] = batch_no
|
||||
return state_hint
|
||||
|
||||
|
||||
def _build_summary(
|
||||
*,
|
||||
task: ShippingTask | None,
|
||||
batch: ShippingBatch | None,
|
||||
run_purpose: str | None,
|
||||
) -> str:
|
||||
"""
|
||||
构建给 Dify 阅读的短摘要。
|
||||
|
||||
核心逻辑:用自然语言说明当前 run 的任务、批次、文件和状态,避免 Dify 依赖 conversation memory 猜现场。
|
||||
|
||||
Args:
|
||||
task: 当前任务。
|
||||
batch: 当前批次。
|
||||
run_purpose: 本次 Dify run 的目的。
|
||||
|
||||
Returns:
|
||||
200 字以内的现场摘要。
|
||||
"""
|
||||
pieces: list[str] = []
|
||||
task_no = _task_no(task)
|
||||
batch_no = _batch_no(batch, task)
|
||||
file_name = _clean_text(getattr(task, "source_file_name", None))
|
||||
status = _clean_text(getattr(task, "process_status", None))
|
||||
current_step = _clean_text(getattr(task, "current_step", None))
|
||||
normalized_run_purpose = _clean_text(run_purpose)
|
||||
if task_no:
|
||||
pieces.append(f"当前任务 {task_no}")
|
||||
if batch_no:
|
||||
pieces.append(f"属于批次 {batch_no}")
|
||||
if file_name:
|
||||
pieces.append(f"来源文件 {file_name}")
|
||||
if normalized_run_purpose:
|
||||
pieces.append(f"本次执行目的为 {normalized_run_purpose}")
|
||||
if status:
|
||||
pieces.append(f"当前状态 {status}")
|
||||
if current_step:
|
||||
pieces.append(f"当前步骤 {current_step}")
|
||||
if not pieces:
|
||||
return "当前为货代发货通知 Agent 会话,尚未解析出明确任务或批次锚点。"
|
||||
return ",".join(pieces) + "。"
|
||||
|
||||
|
||||
def build_shipping_runtime_context(
|
||||
*,
|
||||
session_id: str,
|
||||
task: ShippingTask | None = None,
|
||||
batch: ShippingBatch | None = None,
|
||||
trigger_source: str | None = None,
|
||||
request_id: str | None = None,
|
||||
locale: str | None = None,
|
||||
scope: str = "task_run",
|
||||
run_purpose: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建货代发货通知 Agent 的 agent_runtime_context。
|
||||
|
||||
核心逻辑:以 HXOPS DB 中的 task/batch 为事实源,生成 refs/domain.state_hint/reference_context snapshot,
|
||||
供 Dify 每次 run 显式识别现场。
|
||||
|
||||
Args:
|
||||
session_id: HXOPS 本地 ChatSession.session_id。
|
||||
task: 当前显式任务;禁止在本函数内按会话猜测。
|
||||
batch: 当前批次。
|
||||
trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。
|
||||
request_id: 本次请求 ID。
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域。
|
||||
run_purpose: 本次 Dify run 的目的,如 parse_notice。
|
||||
|
||||
Returns:
|
||||
agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
"""
|
||||
domain = {
|
||||
"type": SHIPPING_NOTICE_AGENT_CODE,
|
||||
"summary": _build_summary(task=task, batch=batch, run_purpose=run_purpose),
|
||||
"state_hint": _build_state_hint(task, batch),
|
||||
"available_actions_hint": [],
|
||||
}
|
||||
reference_context = build_shipping_reference_context(
|
||||
batch=batch,
|
||||
focus_task=task,
|
||||
)
|
||||
return build_agent_runtime_context(
|
||||
agent_code=SHIPPING_NOTICE_AGENT_CODE,
|
||||
scope=scope,
|
||||
session_id=session_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
refs=_build_refs(task=task, batch=batch, run_purpose=run_purpose),
|
||||
domain=domain,
|
||||
reference_context=reference_context,
|
||||
)
|
||||
@@ -15,7 +15,7 @@ import uuid
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ def auto_rpa_inventory_enabled() -> bool:
|
||||
|
||||
def rpa_inventory_timeout_seconds() -> int:
|
||||
"""RPA 库存导出等待超时秒数。"""
|
||||
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 120, min_value=5)
|
||||
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 360, min_value=5)
|
||||
|
||||
|
||||
def auto_mapping_allow_llm() -> bool:
|
||||
@@ -181,6 +181,58 @@ def generate_task_no() -> str:
|
||||
return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _clean_event_value(value: Any) -> str:
|
||||
"""把事件详情值规范化为短字符串;空值返回空字符串。"""
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _task_batch_no(task: ShippingTask | None) -> str:
|
||||
"""从任务关系中提取批次号。"""
|
||||
batch = getattr(task, "batch", None)
|
||||
return _clean_event_value(getattr(batch, "batch_no", None))
|
||||
|
||||
|
||||
def build_task_action_event_detail(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
action: str,
|
||||
source: str,
|
||||
comment: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建任务动作类事件详情。
|
||||
|
||||
核心逻辑:统一补齐 action/source/target/batch/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。
|
||||
|
||||
Args:
|
||||
task: 动作作用的目标任务。
|
||||
action: 规范化动作名,如 confirm/reject/rematch/reparse/switch_focus。
|
||||
source: 触发来源,如 workspace_api/tool_api/backend_orchestrator。
|
||||
comment: 用户附带备注。
|
||||
extra: 其他扩展字段,例如 previous_focus_task_no。
|
||||
|
||||
Returns:
|
||||
标准化的事件 detail_json。
|
||||
"""
|
||||
detail: dict[str, Any] = {
|
||||
"action": _clean_event_value(action),
|
||||
"source": _clean_event_value(source),
|
||||
"target_type": "task",
|
||||
"target_id": _clean_event_value(getattr(task, "task_no", None)),
|
||||
"batch_no": _task_batch_no(task),
|
||||
"conversation_id": _clean_event_value(getattr(task, "conversation_id", None)),
|
||||
}
|
||||
normalized_comment = _clean_event_value(comment)
|
||||
if normalized_comment:
|
||||
detail["comment"] = normalized_comment
|
||||
for key, value in (extra or {}).items():
|
||||
if value is None:
|
||||
continue
|
||||
detail[key] = value
|
||||
return detail
|
||||
|
||||
|
||||
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
|
||||
"""写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。"""
|
||||
if task.id is None:
|
||||
@@ -190,3 +242,81 @@ def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] |
|
||||
event_type=event_type,
|
||||
detail_json=detail or {},
|
||||
))
|
||||
|
||||
|
||||
def log_task_action_event(
|
||||
task: ShippingTask,
|
||||
event_type: str,
|
||||
*,
|
||||
action: str,
|
||||
source: str,
|
||||
comment: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入标准化任务动作事件。
|
||||
|
||||
核心逻辑:在原始 event_type 之外,统一补足 reference_context 所需的动作元数据,避免各入口散落拼接。
|
||||
"""
|
||||
log_task_event(
|
||||
task,
|
||||
event_type,
|
||||
build_task_action_event_detail(
|
||||
task,
|
||||
action=action,
|
||||
source=source,
|
||||
comment=comment,
|
||||
extra=extra,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def switch_batch_focus(
|
||||
batch: ShippingBatch,
|
||||
task: ShippingTask,
|
||||
*,
|
||||
source: str,
|
||||
event_type: str = "focus_switched",
|
||||
comment: str | None = None,
|
||||
emit_when_unchanged: bool = True,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
切换批次焦点任务并写入标准事件。
|
||||
|
||||
核心逻辑:统一处理 current_focus_task_no 更新与 focus 切换事件,供 workspace/tool/orchestrator 复用。
|
||||
|
||||
Args:
|
||||
batch: 所属批次。
|
||||
task: 新焦点任务。
|
||||
source: 触发来源,如 workspace_api/tool_api/backend_orchestrator。
|
||||
event_type: 事件名;用户态默认 focus_switched,系统自动切票可传 focus_auto_switched。
|
||||
comment: 用户备注。
|
||||
emit_when_unchanged: 焦点未变化时是否仍记事件。
|
||||
extra: 附加字段。
|
||||
|
||||
Returns:
|
||||
是否实际发生焦点变化。
|
||||
"""
|
||||
previous_focus_task_no = _clean_event_value(getattr(batch, "current_focus_task_no", None))
|
||||
next_focus_task_no = _clean_event_value(getattr(task, "task_no", None))
|
||||
changed = previous_focus_task_no != next_focus_task_no
|
||||
batch.current_focus_task_no = next_focus_task_no or None
|
||||
|
||||
if changed or emit_when_unchanged:
|
||||
detail_extra = {
|
||||
"previous_focus_task_no": previous_focus_task_no or None,
|
||||
"next_focus_task_no": next_focus_task_no or None,
|
||||
"changed": changed,
|
||||
}
|
||||
if extra:
|
||||
detail_extra.update(extra)
|
||||
log_task_action_event(
|
||||
task,
|
||||
event_type,
|
||||
action="switch_focus",
|
||||
source=source,
|
||||
comment=comment,
|
||||
extra=detail_extra,
|
||||
)
|
||||
return changed
|
||||
@@ -87,13 +87,18 @@ _PENDING_REASON_LABELS: dict[str, str] = {
|
||||
|
||||
|
||||
def user_facing_task_stage(task: ShippingTask) -> str:
|
||||
"""Short Chinese label for chat / get_task_status — no snake_case codes."""
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
|
||||
return _CHECKPOINT_LABELS[ui.checkpoint]
|
||||
"""
|
||||
Short Chinese label for chat / get_task_status — no snake_case codes.
|
||||
|
||||
核心逻辑:优先返回更具体的 pending_human_reason 标签,避免 `rpa_pending`
|
||||
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖。
|
||||
"""
|
||||
reason = str(task.pending_human_reason or "").strip()
|
||||
if reason in _PENDING_REASON_LABELS:
|
||||
return _PENDING_REASON_LABELS[reason]
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
|
||||
return _CHECKPOINT_LABELS[ui.checkpoint]
|
||||
process = str(task.process_status or "").strip()
|
||||
return _PROCESS_STATUS_LABELS.get(process, "处理中")
|
||||
|
||||
|
||||
Reference in new issue
Block a user