feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑
This commit is contained in:
1 parent
34d489a2d1
commit
ce26d6d0c4
144 files changed
+12241
-4233
No files matched your search
@@ -18,6 +18,7 @@ import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
|
||||
@@ -9,6 +9,7 @@ from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
@@ -106,6 +107,38 @@ def test_agent(id: int):
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/runtime-bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_runtime_bindings(id: int):
|
||||
"""列出入口 Agent 的显式运行能力绑定。"""
|
||||
from app.services.agent_runtime_binding_service import list_runtime_bindings
|
||||
|
||||
return ok(list_runtime_bindings(id), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/runtime-bindings/<path:capability_code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_agent_runtime_binding(id: int, capability_code: str):
|
||||
"""保存单个能力 Provider;API Key 仍由 Provider Agent 自身配置管理。"""
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
provider_agent_id = int(body.get('provider_agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('provider_agent_id is required') from exc
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding, serialize_runtime_binding
|
||||
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=id,
|
||||
capability_code=capability_code,
|
||||
provider_agent_id=provider_agent_id,
|
||||
enabled=body.get('enabled') is not False,
|
||||
config=body.get('config'),
|
||||
)
|
||||
return ok(serialize_runtime_binding(binding), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id: int):
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_extraction.py
|
||||
|
||||
用途:提供订单抽取异步 Run 的管理员运维健康视图。
|
||||
依赖:admin Blueprint、require_admin、order_extraction_run_service。
|
||||
逻辑:路由校验监控窗口与阈值后返回安全聚合指标,不暴露文档、Provider 配置或错误正文。
|
||||
"""
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health
|
||||
|
||||
|
||||
def _query_int(name: str, default: int) -> int:
|
||||
"""读取可选整数查询参数;非整数抛出统一参数错误。"""
|
||||
raw = request.args.get(name)
|
||||
if raw in (None, ''):
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f'{name} must be an integer') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_extraction_health():
|
||||
"""返回 Run 积压、失败率、阶段分布和分段时延的管理员安全视图。"""
|
||||
payload = get_order_extraction_run_health(
|
||||
window_hours=_query_int('window_hours', 24),
|
||||
queued_stale_seconds=_query_int('queued_stale_seconds', 300),
|
||||
running_stale_seconds=_query_int('running_stale_seconds', 1800),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
@@ -38,11 +38,11 @@ def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
return [agent for agent in user.agents if agent.is_active and agent.exposure_mode == 'workspace']
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
@@ -70,7 +70,7 @@ def list_agent_guides(agent_id):
|
||||
if agent_id == 0:
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.filter_by(agent_code='generic', is_active=True, exposure_mode='workspace')
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
+4
-17
@@ -141,7 +141,6 @@ def _build_chat_adapter_hints(
|
||||
*,
|
||||
shipping_task_id: str | None = None,
|
||||
shipping_batch_no: str | None = None,
|
||||
shipping_intake_nos: list[str] | None = None,
|
||||
shipping_temporary_inventory_asset_no: str | None = None,
|
||||
shipping_temporary_inventory_session_no: str | None = None,
|
||||
) -> dict | None:
|
||||
@@ -153,17 +152,15 @@ def _build_chat_adapter_hints(
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
|
||||
temporary_asset_no = str(shipping_temporary_inventory_asset_no or '').strip().upper()
|
||||
temporary_session_no = str(shipping_temporary_inventory_session_no or '').strip().upper()
|
||||
if not task_id and not batch_no and not intake_nos and not temporary_asset_no and not temporary_session_no:
|
||||
if not task_id and not batch_no and not temporary_asset_no and not temporary_session_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
'intake_nos': intake_nos,
|
||||
'capability': 'temporary_inventory' if temporary_asset_no else ('order_extraction' if intake_nos else None),
|
||||
'capability': 'temporary_inventory' if temporary_asset_no else None,
|
||||
'temporary_inventory_asset_no': temporary_asset_no or None,
|
||||
'temporary_inventory_session_no': temporary_session_no or None,
|
||||
}
|
||||
@@ -207,7 +204,7 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'submit_order_extraction' in value:
|
||||
if 'create_task' in value or 'get_task_status' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
@@ -1393,14 +1390,6 @@ def chat_completions():
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
shipping_temporary_inventory_asset_no = str(data.get('shipping_temporary_inventory_asset_no') or '').strip().upper()
|
||||
shipping_temporary_inventory_session_no = str(data.get('shipping_temporary_inventory_session_no') or '').strip().upper()
|
||||
raw_shipping_intakes = data.get('shipping_intake_nos')
|
||||
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
|
||||
raise ValidationError('shipping_intake_nos must be a list')
|
||||
shipping_intake_nos = sorted({
|
||||
str(item or '').strip().upper()
|
||||
for item in (raw_shipping_intakes or [])
|
||||
if str(item or '').strip()
|
||||
})
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
user_attachments = _normalize_user_attachments(data.get('user_attachments'))
|
||||
session_title = display_query or (user_attachments[0]['name'] if user_attachments else str(query or '').strip())
|
||||
@@ -1539,7 +1528,6 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
),
|
||||
@@ -1584,8 +1572,7 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -139,23 +139,6 @@ def tool_create_task():
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_order_extraction_context', methods=['POST'])
|
||||
def tool_get_order_extraction_context():
|
||||
"""
|
||||
返回当前会话待解析邮件及附件文本。
|
||||
【AI 触发时机】:仅当 agent_runtime_context.refs.capability=order_extraction 时,
|
||||
在完整订单抽取 LLM 节点之前调用一次。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_order_extraction_context(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_order_extraction', methods=['POST'])
|
||||
def tool_submit_order_extraction():
|
||||
"""
|
||||
提交 LLM 完整订单抽取结果并由 HXOPS 校验、判重和自动建单。
|
||||
【AI 触发时机】:订单抽取 LLM 与 JSON 标准化节点成功后调用;禁止绕过此 Tool 直接建单。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_order_extraction(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
|
||||
|
||||
@@ -1342,9 +1342,14 @@ def home():
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
agent_rows = Agent.query.filter(
|
||||
Agent.is_active.is_(True), Agent.exposure_mode == 'workspace',
|
||||
).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = [
|
||||
agent for agent in user.agents
|
||||
if agent.is_active and agent.exposure_mode == 'workspace'
|
||||
]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
|
||||
@@ -864,6 +864,78 @@ def workspace_list_shipping_notice_intakes():
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['POST'])
|
||||
def workspace_create_shipping_order_extraction_run():
|
||||
"""冻结当前会话的已解析 Intake 并创建异步订单抽取领域 Run。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True)
|
||||
if body is None:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
agent_id = int(body.get('agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'agent_id is required',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
) from exc
|
||||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError(
|
||||
'intake_nos must be a list',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_INTAKES_INVALID',
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=intake_nos,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{'run': serialize_order_extraction_run(run), 'reused': reused},
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
status=202,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
get_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
return _ok(serialize_order_extraction_run(get_order_extraction_run(user_id=user.id, run_no=run_no)))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 50)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
list_order_extraction_runs,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
rows = list_order_extraction_runs(user_id=user.id, conversation_id=conversation_id, limit=limit)
|
||||
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
|
||||
Reference in new issue
Block a user