feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑

This commit is contained in:
hugo committed 2026-07-21 09:02:42 +08:00
1 parent 34d489a2d1
commit ce26d6d0c4
144 files changed
+12241 -4233

No files matched your search

@@ -35,6 +35,7 @@ MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({
'runtime_provider',
'conversation_mode',
'dify_app_type',
'exposure_mode',
'iframe_url',
'category',
'sub_category',
@@ -150,6 +151,7 @@ def validate_agent_payload(
valid_runtime_providers = get_platform_enum_set('runtime_providers')
valid_conversation_modes = get_platform_enum_set('conversation_modes')
valid_dify_app_types = get_platform_enum_set('dify_app_types')
valid_exposure_modes = get_platform_enum_set('exposure_modes')
valid_suggested_styles = get_platform_enum_set('suggested_questions_styles')
dify_required_providers = get_dify_required_providers()
@@ -175,6 +177,12 @@ def validate_agent_payload(
if dify_app_type not in valid_dify_app_types:
dify_app_type = 'chatflow'
exposure_mode = _strip(data.get('exposure_mode')) or (
getattr(agent, 'exposure_mode', None) if agent else 'workspace'
) or 'workspace'
if exposure_mode not in valid_exposure_modes:
raise ValidationError(f'无效的 exposure_mode: {exposure_mode}')
dify_app_id = _strip(data.get('dify_app_id')) or (agent.dify_app_id if agent else '')
if runtime_provider in dify_required_providers and not dify_app_id:
raise ValidationError('runtime_provider 含 dify 时 dify_app_id 必填')
@@ -260,6 +268,7 @@ def validate_agent_payload(
'runtime_provider': runtime_provider,
'conversation_mode': conversation_mode,
'dify_app_type': dify_app_type,
'exposure_mode': exposure_mode,
'iframe_url': iframe_url or None,
'category': _strip(data.get('category')) or None,
'sub_category': _strip(data.get('sub_category')) or None,
@@ -285,7 +294,7 @@ def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None:
"""
column_fields = (
'name', 'description', 'icon_url', 'is_active', 'is_aggregate', 'dify_app_id', 'api_base_url', 'type',
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url',
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'exposure_mode', 'iframe_url',
'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style',
'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id',
'handler_config',
@@ -46,6 +46,7 @@ def build_agent_registry_schema() -> dict[str, Any]:
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
'progress_contract': deepcopy_schema(entry.get('progress_contract')),
'default_intent_routes': list(entry.get('default_intent_routes') or []),
'required_runtime_capabilities': deepcopy_schema(entry.get('required_runtime_capabilities')),
})
return {
@@ -53,6 +54,7 @@ def build_agent_registry_schema() -> dict[str, Any]:
'runtime_providers': list(platform.get('runtime_providers') or []),
'conversation_modes': list(platform.get('conversation_modes') or []),
'dify_app_types': list(platform.get('dify_app_types') or []),
'exposure_modes': list(platform.get('exposure_modes') or []),
'suggested_questions_styles': list(platform.get('suggested_questions_styles') or []),
'default_capabilities': get_default_capabilities(),
'tool_run_progress_defaults': get_tool_run_progress_defaults(),
@@ -14,6 +14,9 @@ platform:
dify_app_types:
- chatflow
- workflow
exposure_modes:
- workspace
- internal
suggested_questions_styles:
- plain
- styled
@@ -83,6 +86,13 @@ agent_types:
layout: workspace
visualization: stepper
handler_config_schema: {}
required_runtime_capabilities:
shipping.order_extraction:
label: 订单抽取
required: true
allowed_runtime_providers: [dify]
allowed_dify_app_types: [workflow]
allowed_exposure_modes: [internal]
file_check:
label: 文件检核
conversation_mode_default: task_chat
@@ -1,10 +1,7 @@
"""
backend/app/services/agent_registry/handlers/shipping_notice.py
用途:货代发货通知 Hybrid Handler — 聊天流订单抽取生命周期、UI State 与上下文准备。
依赖:shipping_notice.order_extraction/query_service、chat.log_service、ui_state、agent_registry.handlers.registry。
逻辑:Dify 请求前登记并推送订单抽取状态,terminal/error 后收口、持久化结果并补发 Batch UI State;
不替代 Dify 正文生成。
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。
依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。
逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。
"""
from __future__ import annotations
@@ -39,10 +36,8 @@ class ShippingNoticeHandler(AgentHandler):
"""
货代发货通知业务 Handler。
核心逻辑:订单抽取请求进入 Dify 前登记 request/intakes 并推送 extracting;终态时先落失败、
推送并持久化抽取结果,再按 adapter_hints / task_id / batch_no 构造 shipping_ui_state。
阶段约束:`open_existing` 终态必须能为前端提供恢复锚点;最小字段是 `task_no`,若已知批次则补
`batch_no`,若已构造快照则补 `ui_state / batch_ui_state`,供实时消息与历史回放共用。
核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。
订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。
"""
@staticmethod
@@ -52,128 +47,30 @@ class ShippingNoticeHandler(AgentHandler):
shipping_hints = hints.get('shipping_notice')
return shipping_hints if isinstance(shipping_hints, dict) else {}
@classmethod
def _order_extraction_intake_nos(cls, ctx: ChatStreamContext) -> list[str]:
"""仅在订单抽取能力匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。"""
hints = cls._shipping_hints(ctx)
if (
str(hints.get('capability') or '') != 'order_extraction'
or not isinstance(hints.get('intake_nos'), list)
):
return []
return sorted({
str(item or '').strip().upper()
for item in hints.get('intake_nos') or []
if str(item or '').strip()
})
@staticmethod
def _workflow_failure_message(event_data: dict[str, Any]) -> str:
"""从 Dify terminal/error 事件提取已友好化的错误文本,缺失时返回空字符串。"""
event_name = str(event_data.get('event') or '').strip()
data = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
failed = event_name == 'error' or (
event_name == 'workflow_finished'
and str(data.get('status') or '').strip().lower() == 'failed'
)
if not failed:
return ''
for value in (
event_data.get('message'),
event_data.get('error'),
event_data.get('description'),
data.get('message'),
data.get('error'),
data.get('description'),
):
text = str(value or '').strip()
if text:
return text
return '订单识别失败,请重新发送当前邮件。'
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""
在订单抽取请求进入 Dify 前登记权威 extracting 状态。
核心逻辑:仅消费平台 adapter_hints 中的固定能力契约,并把 HXOPS request_id 绑定到完整 Intake 集合;
失败直接阻止上游调用,避免前端显示本地 extracting 而后端仍为 not_started。
"""
intake_nos = self._order_extraction_intake_nos(ctx)
if not intake_nos:
return ctx
from app.services.shipping_notice.order_extraction import start_order_extraction
start_order_extraction(
user_id=int(getattr(ctx.user, 'id', 0) or 0),
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
intake_nos=intake_nos,
request_id=ctx.request_id,
)
return ctx
def build_ui_state_event(
self,
ctx: ChatStreamContext,
*,
resolve_order_extraction: bool = False,
) -> dict[str, Any] | None:
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""
构造 shipping_ui_state SSE 事件。
用途:为聊天页当前消息与历史回放提供任务/批次恢复锚点。
核心逻辑:优先显式 task_id,其次 batch 焦点任务;订单抽取终态可按 intake 反查新建批次或
`open_existing` 命中的既有任务。`open_existing` 场景下即使没有新建批次,也必须至少返回
`task_no`;失败时记录日志并返回 None。
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
"""
if not _uses_shipping_ui_state_progress(ctx.agent):
return None
task_id = str(ctx.shipping_task_id or '').strip()
batch_no = str(ctx.shipping_batch_no or '').strip()
shipping_hints = self._shipping_hints(ctx)
if not task_id and not batch_no:
task_id = str(shipping_hints.get('task_id') or '').strip()
batch_no = str(shipping_hints.get('batch_no') or '').strip()
intake_nos = self._order_extraction_intake_nos(ctx)
if not task_id and not batch_no and not (resolve_order_extraction and intake_nos):
if not task_id and not batch_no:
return None
try:
from app.services.shipping_notice.query_service import (
get_batch_by_no,
get_task_by_ref,
resolve_order_extraction_ui_target,
)
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
task = get_task_by_ref(task_id) if task_id else None
batch = get_batch_by_no(batch_no) if batch_no else None
resolved_from_order_extraction = False
if task is None and batch is None and resolve_order_extraction and intake_nos:
batch, task = resolve_order_extraction_ui_target(
user_id=int(getattr(ctx.user, 'id', 0) or 0),
conversation_id=str(getattr(ctx.session, 'session_id', '') or ''),
intake_nos=intake_nos,
)
resolved_from_order_extraction = batch is not None or task is not None
session_id = str(getattr(ctx.session, 'session_id', '') or '')
if resolved_from_order_extraction and batch is not None:
batch_ui_state = build_batch_ui_state(batch)
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
focus_ui_state = (
batch_ui_state.get('focus_task_ui_state')
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
else None
)
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'batch_no': batch.batch_no,
'task_no': focus_task.get('task_no'),
'batch_ui_state': batch_ui_state,
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
'source': 'order_extraction',
}
if task is None and batch is not None:
focus_task_no = str(batch.current_focus_task_no or '').strip()
if focus_task_no:
@@ -187,7 +84,6 @@ class ShippingNoticeHandler(AgentHandler):
'task_no': task.task_no,
'batch_no': task.batch.batch_no if task.batch is not None else None,
'ui_state': build_task_ui_state(task),
**({'source': 'order_extraction'} if resolved_from_order_extraction else {}),
}
if batch is not None:
batch_ui_state = build_batch_ui_state(batch)
@@ -215,125 +111,6 @@ class ShippingNoticeHandler(AgentHandler):
)
return None
def build_order_extraction_state_event(
self,
ctx: ChatStreamContext,
) -> dict[str, Any] | None:
"""
构造当前请求的 shipping_order_extraction_state SSE 事件。
核心逻辑:只为固定订单抽取能力契约读取权威 Intake 状态;身份围栏失败时记录日志并跳过,
避免把旧请求或其他会话结果推送到当前消息。
Args:
ctx: 当前聊天流上下文,必须包含用户、会话、request_id 与 Intake 集合。
Returns:
可直接格式化为 SSE 的事件字典;非订单抽取回合或读取失败时返回 None。
"""
intake_nos = self._order_extraction_intake_nos(ctx)
if not intake_nos:
return None
try:
from app.services.shipping_notice.order_extraction import get_order_extraction_state
state = get_order_extraction_state(
user_id=int(getattr(ctx.user, 'id', 0) or 0),
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
intake_nos=intake_nos,
request_id=ctx.request_id,
)
return {
'event': 'shipping_order_extraction_state',
'conversation_id': str(getattr(ctx.session, 'session_id', '') or ''),
**state,
}
except Exception:
if current_app:
current_app.logger.exception(
'[shipping-handler] build order extraction state failed request_id=%s intakes=%s',
ctx.request_id,
intake_nos,
)
return None
@staticmethod
def _build_history_recovery_payload_patch(
*,
state_event: dict[str, Any] | None,
ui_event: dict[str, Any] | None,
) -> dict[str, Any]:
"""
提取历史回放所需的最小恢复载荷。
核心逻辑:抽取终态负责统计摘要,UI State 负责任务/批次锚点;两者都存在时合并为同一条
ChatLog.payload patch,保证历史消息可直接恢复工作台。
"""
payload_patch: dict[str, Any] = {}
if isinstance(state_event, dict) and state_event.get('terminal') is True:
payload_patch['shipping_order_extraction_state'] = {
key: value
for key, value in state_event.items()
if key not in {'event', 'conversation_id'}
}
if isinstance(ui_event, dict) and str(ui_event.get('event') or '') == 'shipping_ui_state':
task_no = str(ui_event.get('task_no') or '').strip()
if task_no:
payload_patch['task_no'] = task_no
if 'batch_no' in ui_event:
batch_no = str(ui_event.get('batch_no') or '').strip()
payload_patch['batch_no'] = batch_no or None
ui_state = ui_event.get('ui_state')
if isinstance(ui_state, dict):
payload_patch['shipping_ui_state'] = ui_state
batch_ui_state = ui_event.get('batch_ui_state')
if isinstance(batch_ui_state, dict):
payload_patch['shipping_batch_ui_state'] = batch_ui_state
return payload_patch
def _persist_history_recovery_payload(
self,
ctx: ChatStreamContext,
event_data: dict[str, Any],
*,
state_event: dict[str, Any] | None = None,
ui_event: dict[str, Any] | None = None,
) -> None:
"""
把订单抽取终态与 UI 锚点合并到本轮已落库 ChatLog,供历史消息恢复。
核心逻辑:使用上游终态附带的 chat_log_id 与当前身份做归属校验;缺少日志主键时保留实时 SSE,
不创建额外聊天记录。阶段 1 要求 `open_existing` 至少补齐 `task_no`,有批次或快照时继续补齐
`batch_no / shipping_ui_state / shipping_batch_ui_state`。
Args:
ctx: 当前聊天流上下文。
event_data: Dify terminal/error 原始事件。
state_event: 已构造的订单抽取状态事件。
ui_event: 已构造的 shipping_ui_state 事件。
"""
payload_patch = self._build_history_recovery_payload_patch(
state_event=state_event,
ui_event=ui_event,
)
if not payload_patch:
return
try:
chat_log_id = int(event_data.get('chat_log_id') or 0)
except (TypeError, ValueError):
chat_log_id = 0
if chat_log_id <= 0:
return
from app.services.chat.log_service import merge_chat_log_payload
merge_chat_log_payload(
chat_log_id=chat_log_id,
user_id=int(getattr(ctx.user, 'id', 0) or 0),
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
payload_patch=payload_patch,
)
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
"""仅为 shipping_ui_state 构造去重键,其他领域事件保持独立生命周期。"""
if str(event.get('event') or '') != 'shipping_ui_state':
@@ -353,15 +130,13 @@ class ShippingNoticeHandler(AgentHandler):
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
def _format_sse(self, event: dict[str, Any]) -> str:
@staticmethod
def _format_sse(event: dict[str, Any]) -> str:
"""把领域事件编码为单条 SSE data frame。"""
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
"""上游调用前先推送订单抽取进行态,再补充已有任务 UI State。"""
extraction_event = self.build_order_extraction_state_event(ctx)
if extraction_event:
yield self._format_sse(extraction_event)
"""上游调用前补充已有任务 UI State。"""
event = self.build_ui_state_event(ctx)
if event:
yield self._format_sse(event)
@@ -371,62 +146,10 @@ class ShippingNoticeHandler(AgentHandler):
ctx: ChatStreamContext,
event_data: dict[str, Any],
) -> Iterator[str]:
"""上游终态后收口抽取状态,依次推送抽取事实和任务 UI State。"""
"""上游终态后刷新显式任务或批次的 UI State。"""
event_name = str(event_data.get('event') or '').strip()
if event_name not in {'error', 'message_end', 'workflow_finished'}:
return iter(())
intake_nos = self._order_extraction_intake_nos(ctx)
if intake_nos:
from app.services.shipping_notice.order_extraction import (
ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
finalize_order_extraction_failure,
)
failure_message = self._workflow_failure_message(event_data)
try:
finalize_order_extraction_failure(
user_id=int(getattr(ctx.user, 'id', 0) or 0),
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
intake_nos=intake_nos,
request_id=ctx.request_id,
error_message=failure_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
)
except Exception:
from app import db
db.session.rollback()
if current_app:
current_app.logger.exception(
'[shipping-handler] finalize order extraction failed request_id=%s intakes=%s',
ctx.request_id,
intake_nos,
)
extraction_event = self.build_order_extraction_state_event(ctx)
event = self.build_ui_state_event(ctx, resolve_order_extraction=True)
if extraction_event or event:
self._persist_history_recovery_payload(
ctx,
event_data,
state_event=extraction_event,
ui_event=event,
)
if extraction_event:
yield self._format_sse(extraction_event)
event = self.build_ui_state_event(ctx)
if event:
yield self._format_sse(event)
def should_recover_upstream_error(self, ctx: ChatStreamContext, event_data: dict[str, Any]) -> bool:
"""
判断 Dify 流错误能否按已持久化的订单抽取结果正常收口。
核心逻辑:仅处理当前订单抽取请求;Tool 已写入 completed/partially_completed 时,
网络断流不应覆盖订单事实或向前端显示失败。仍为 extracting/failed 的请求维持原错误语义。
"""
if str(event_data.get('event') or '').strip() != 'error':
return False
state_event = self.build_order_extraction_state_event(ctx)
return bool(
state_event
and state_event.get('terminal') is True
and state_event.get('status') in {'completed', 'partially_completed'}
)
@@ -49,6 +49,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
'runtime_provider': resolve_runtime_provider(agent),
'conversation_mode': resolve_conversation_mode(agent),
'dify_app_type': getattr(agent, 'dify_app_type', None) or 'chatflow',
'exposure_mode': getattr(agent, 'exposure_mode', None) or 'workspace',
'iframe_url': getattr(agent, 'iframe_url', None),
'category': getattr(agent, 'category', None) or None,
'sub_category': getattr(agent, 'sub_category', None) or None,