feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持
This commit is contained in:
1 parent
ac4262cd75
commit
c8ce77199e
183 files changed
+11690
-2300
No files matched your search
@@ -2,21 +2,74 @@
|
||||
backend/app/api/admin/agents.py
|
||||
|
||||
用途:管理后台 Agent CRUD、连通性测试、权限绑定 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/agent_service。
|
||||
逻辑:/agents* 路由。
|
||||
依赖:admin.blueprint、services/admin/agent_service、core.response.ok。
|
||||
逻辑:/agents* 路由;统一 success/data/request_id envelope。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
|
||||
def _request_id() -> str | None:
|
||||
return getattr(g, 'request_id', None)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/schema', methods=['GET'])
|
||||
@require_admin
|
||||
def get_agent_registry_schema():
|
||||
"""返回 Admin Agent Registry 权威 schema(平台枚举、Catalog、handler_config schema)。"""
|
||||
from app.services.agent_registry.admin_schema import build_agent_registry_schema
|
||||
|
||||
return ok(build_agent_registry_schema(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/infer-content-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def infer_agent_content_profile():
|
||||
"""根据 intent_routes 推断 content_profile(Admin 表单建议,不参与运行时)。"""
|
||||
from app.services.agent_registry.content_profiles import infer_content_profile_from_intent_routes
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
routes = data.get('intent_routes') if isinstance(data.get('intent_routes'), list) else []
|
||||
profile = infer_content_profile_from_intent_routes(routes)
|
||||
return ok({'content_profile': profile}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/type-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_type_catalog():
|
||||
"""返回 Admin 应用类型 Catalog 下拉列表。"""
|
||||
from app.services.agent_registry.catalog import list_type_catalog
|
||||
|
||||
return ok(list_type_catalog(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/content-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_content_profiles():
|
||||
"""返回 Admin 可选 content_profile 及默认文案模板。"""
|
||||
from app.services.agent_registry.content_profiles import list_content_profiles
|
||||
|
||||
return ok(list_content_profiles(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/intent-routes', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_intent_routes():
|
||||
"""返回 Admin 可选 Intent route 注册表(前端表单动态选项)。"""
|
||||
from app.services.chat.intent_route_registry import list_chat_intent_route_definitions
|
||||
|
||||
return ok(list_chat_intent_route_definitions(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
"""返回全部 Agent 列表。"""
|
||||
return jsonify(agent_service.list_agents())
|
||||
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
@@ -25,7 +78,7 @@ def create_agent():
|
||||
"""创建 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
payload = agent_service.create_agent(data)
|
||||
return jsonify(payload), 201
|
||||
return ok(payload, request_id=_request_id(), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||||
@@ -34,7 +87,7 @@ def update_agent(id: int):
|
||||
"""更新 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
agent_service.update_agent(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||||
@@ -42,7 +95,7 @@ def update_agent(id: int):
|
||||
def delete_agent(id: int):
|
||||
"""删除 Agent。"""
|
||||
agent_service.delete_agent(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||||
@@ -50,7 +103,7 @@ def delete_agent(id: int):
|
||||
def test_agent(id: int):
|
||||
"""测试 Agent 连通性。"""
|
||||
payload = agent_service.test_agent_connectivity(id)
|
||||
return jsonify(payload), 200
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@@ -60,7 +113,7 @@ def update_agent_permissions(id: int):
|
||||
data = request.get_json() or {}
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_service.update_agent_permissions(id, user_ids)
|
||||
return jsonify({'status': 'ok'})
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||
@@ -76,4 +129,4 @@ def import_training_question_bank_from_pdf(id: int):
|
||||
agent_id=id,
|
||||
guide_id=data.get('guide_id'),
|
||||
)
|
||||
return jsonify(payload), 200
|
||||
return ok(payload, request_id=_request_id())
|
||||
+28
-36
@@ -2,8 +2,8 @@
|
||||
backend/app/api/agents.py
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;未登录 raise UnauthorizedError。
|
||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
|
||||
"""
|
||||
import os
|
||||
from flask import Blueprint, jsonify, send_from_directory
|
||||
@@ -19,45 +19,34 @@ from app.services.minio_service import minio_service
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return serialize_agent_list_item(row)
|
||||
def _serialize_agent_row(agent: Agent) -> dict:
|
||||
return serialize_agent_list_item(agent)
|
||||
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
获取当前用户可见的 Agent 列表
|
||||
用途:Workspace 页面展示应用网格
|
||||
用途:Workspace 页面展示应用网格、聊天侧栏 Agent 切换
|
||||
"""
|
||||
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||
user: User = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||
agent_rows = [
|
||||
type('AgentRow', (), {
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
'extra_config': a.extra_config,
|
||||
})()
|
||||
for a in user.agents
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# [STEP 1] 按 extra_config 分类字段排序后序列化
|
||||
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
|
||||
agents = _list_active_agents_for_user(user)
|
||||
return jsonify([_serialize_agent_row(agent) for agent in sort_agent_rows(agents)])
|
||||
|
||||
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||
def list_agent_guides(agent_id):
|
||||
@@ -68,7 +57,12 @@ def list_agent_guides(agent_id):
|
||||
get_current_user() # 确保已登录
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
if generic_agent:
|
||||
agent_id = generic_agent.id
|
||||
else:
|
||||
@@ -101,18 +95,16 @@ def list_public_agents():
|
||||
获取公开的 Agent 列表 (无需登录)
|
||||
用途:登录页面展示
|
||||
"""
|
||||
# 返回所有激活的 Agent,包含基本信息
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
|
||||
return jsonify([_serialize_agent_row(agent) for agent in sort_agent_rows(agents)])
|
||||
|
||||
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
|
||||
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||
def serve_guide_file(filename):
|
||||
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
|
||||
|
||||
|
||||
+74
-166
@@ -39,13 +39,9 @@ from app.core.errors import (
|
||||
)
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
|
||||
return agent_name in LEAVE_FEATURE_AGENT_NAMES
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
@@ -88,18 +84,18 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, agent_name: str | None = None) -> str:
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_name: 当前 Agent 名称,仅对发货通知 Agent 做工具名净化。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_name or '').strip() != SHIPPING_NOTICE_AGENT_NAME:
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
@@ -977,10 +973,10 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_name)})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
@@ -1283,6 +1279,11 @@ def chat_completions():
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
|
||||
if resolve_runtime_provider(agent) == 'iframe':
|
||||
raise ValidationError('Embedded iframe agents do not support chat completions')
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
@@ -1290,9 +1291,17 @@ def chat_completions():
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
type=getattr(agent, 'type', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
agent_code=getattr(agent, 'agent_code', None),
|
||||
runtime_provider=getattr(agent, 'runtime_provider', None),
|
||||
conversation_mode=getattr(agent, 'conversation_mode', None),
|
||||
dify_app_type=getattr(agent, 'dify_app_type', None),
|
||||
capabilities=getattr(agent, 'capabilities', None),
|
||||
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
|
||||
handler_config=getattr(agent, 'handler_config', None),
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
@@ -1302,7 +1311,6 @@ def chat_completions():
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
@@ -1369,39 +1377,44 @@ def chat_completions():
|
||||
if not normalized_files:
|
||||
normalized_files = None
|
||||
|
||||
if normalized_files and PLMOracleService.supports(query, agent_proxy):
|
||||
raise ValidationError('This route does not support attachments')
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
|
||||
relay_stream_ctx = ChatStreamContext(
|
||||
query=query,
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.chat.router import try_fast_route
|
||||
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
from app.services.maintenance_chat_service import MaintenanceChatService
|
||||
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
|
||||
|
||||
if faq_hit:
|
||||
generator = FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif not normalized_files and MaintenanceChatService.supports(query, agent_proxy):
|
||||
generator = MaintenanceChatService.stream_chat(
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
fast_route = try_fast_route(
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
)
|
||||
if fast_route is not None:
|
||||
generator = fast_route.generator
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
@@ -1422,61 +1435,10 @@ def chat_completions():
|
||||
),
|
||||
),
|
||||
)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.text2sql import Text2SQLService
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
declares_file_check = agent_declares_file_check_progress(agent_proxy)
|
||||
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
dify_inputs = build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
session_id=session.session_id,
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
)
|
||||
if declares_file_check or is_file_check_agent:
|
||||
# [STEP 1] file_check 的 task_id 校验已在统一 dify_inputs 分发入口完成;这里只保留 turn 注册
|
||||
if is_file_check_agent:
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_file_check_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
display_query=display_query,
|
||||
)
|
||||
generator = stream_chat_via_executor(relay_stream_ctx)
|
||||
|
||||
def relay_stream():
|
||||
from app.services.chat_perf import chat_perf_enabled
|
||||
@@ -1493,77 +1455,15 @@ def chat_completions():
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
is_shipping_stream = str(getattr(agent_proxy, 'name', '') or '').strip() == SHIPPING_NOTICE_AGENT_NAME
|
||||
emitted_shipping_state_keys: set[str] = set()
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
def build_shipping_ui_state_event() -> dict | None:
|
||||
"""
|
||||
构造发货通知专属 UI State SSE 事件。
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
)
|
||||
|
||||
核心逻辑:优先使用前端显式 task_id,其次按 batch 焦点任务补齐;事件只携带状态机读模型,
|
||||
不依赖 Dify 文本,供前端即时渲染按钮和步骤。
|
||||
"""
|
||||
if not is_shipping_stream:
|
||||
return None
|
||||
try:
|
||||
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(shipping_task_id)
|
||||
batch = get_batch_by_no(shipping_batch_no)
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session.session_id,
|
||||
'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),
|
||||
}
|
||||
if batch is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session.session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'batch_ui_state': build_batch_ui_state(batch),
|
||||
}
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
'[chat-api] build shipping_ui_state failed request_id=%s session_id=%s task_id=%s batch_no=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
shipping_task_id,
|
||||
shipping_batch_no,
|
||||
)
|
||||
return None
|
||||
|
||||
def maybe_emit_shipping_ui_state() -> str | None:
|
||||
event = build_shipping_ui_state_event()
|
||||
if not event:
|
||||
return None
|
||||
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
|
||||
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
|
||||
focus_state = batch_ui_state.get('focus_task_ui_state') if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) else {}
|
||||
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
|
||||
key = json.dumps({
|
||||
'task_no': event.get('task_no'),
|
||||
'batch_no': event.get('batch_no'),
|
||||
'checkpoint': checkpoint,
|
||||
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
if key in emitted_shipping_state_keys:
|
||||
return None
|
||||
emitted_shipping_state_keys.add(key)
|
||||
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
|
||||
initial_shipping_state = maybe_emit_shipping_ui_state()
|
||||
if initial_shipping_state:
|
||||
yield initial_shipping_state
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
@@ -1625,9 +1525,12 @@ def chat_completions():
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
shipping_state = maybe_emit_shipping_ui_state()
|
||||
if shipping_state:
|
||||
yield shipping_state
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
@@ -2219,3 +2122,8 @@ def preview_file_raw():
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
return resp
|
||||
|
||||
|
||||
from app.api.chat_turns import register_chat_turn_routes
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
@@ -0,0 +1,161 @@
|
||||
"""
|
||||
backend/app/api/chat_turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Response, g, request, stream_with_context
|
||||
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.chat.turn_runtime import ChatTurnRuntime
|
||||
|
||||
|
||||
def _parse_turn_body_and_files() -> tuple[dict, list]:
|
||||
"""
|
||||
解析 Chat Turn 请求体;multipart 时从 form 字段读取 JSON 与 files。
|
||||
|
||||
Returns:
|
||||
(body, uploads) — uploads 为 Werkzeug FileStorage 列表,JSON 请求时为空。
|
||||
"""
|
||||
content_type = str(request.content_type or "")
|
||||
if "multipart/form-data" in content_type:
|
||||
input_raw = request.form.get("input") or "{}"
|
||||
try:
|
||||
input_data = json.loads(input_raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("input must be valid JSON") from exc
|
||||
context_raw = request.form.get("context") or "{}"
|
||||
try:
|
||||
context_data = json.loads(context_raw) if context_raw else {}
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("context must be valid JSON") from exc
|
||||
agent_id = request.form.get("agent_id") or request.form.get("agentId")
|
||||
conversation_id = request.form.get("conversation_id") or request.form.get("conversationId")
|
||||
body: dict = {
|
||||
"agent_id": agent_id,
|
||||
"conversation_id": conversation_id,
|
||||
"input": input_data if isinstance(input_data, dict) else {},
|
||||
"context": context_data if isinstance(context_data, dict) else {},
|
||||
}
|
||||
uploads = request.files.getlist("files")
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
if single:
|
||||
uploads = [single]
|
||||
return body, uploads
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
return body if isinstance(body, dict) else {}, []
|
||||
|
||||
|
||||
def _stage_upload_files(uploads: list) -> list[dict]:
|
||||
"""将 multipart 文件读入内存 staged 结构,供 handler 构造 FileStorage。"""
|
||||
staged: list[dict] = []
|
||||
for upload in uploads:
|
||||
if upload is None:
|
||||
continue
|
||||
data = upload.read() or b""
|
||||
if not data:
|
||||
continue
|
||||
staged.append({
|
||||
"filename": str(getattr(upload, "filename", None) or "upload"),
|
||||
"content_type": str(getattr(upload, "content_type", None) or ""),
|
||||
"data": data,
|
||||
})
|
||||
return staged
|
||||
|
||||
|
||||
def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
"""
|
||||
将 multipart 附件写入 Turn input.payload。
|
||||
|
||||
- shipping.create_batch_from_notices:预检 notice_items
|
||||
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||||
"""
|
||||
if not uploads:
|
||||
return
|
||||
input_block = body.get("input") if isinstance(body.get("input"), dict) else {}
|
||||
action_type = str(input_block.get("action_type") or input_block.get("actionType") or "").strip()
|
||||
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||||
payload = dict(payload)
|
||||
|
||||
if action_type == "shipping.create_batch_from_notices":
|
||||
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
|
||||
temp_request_id = uuid.uuid4().hex
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
"all uploaded files failed extraction or contained no parseable text",
|
||||
details={"file_summary": file_summary},
|
||||
)
|
||||
payload["notice_items"] = notice_items
|
||||
payload["file_summary"] = file_summary
|
||||
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||
staged = _stage_upload_files(uploads)
|
||||
if not staged:
|
||||
raise ValidationError("file is required")
|
||||
payload["_staged_files"] = staged
|
||||
else:
|
||||
return
|
||||
|
||||
input_block["payload"] = payload
|
||||
input_block["type"] = input_block.get("type") or "upload_followup"
|
||||
body["input"] = input_block
|
||||
|
||||
|
||||
def register_chat_turn_routes(chat_bp) -> None:
|
||||
"""将 Chat Turn 路由注册到 chat Blueprint。"""
|
||||
|
||||
@chat_bp.route('/turns/stream', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_turns_stream():
|
||||
"""
|
||||
统一 Chat Turn SSE 接口。
|
||||
|
||||
核心逻辑:解析 action/form_submit/upload_followup;multipart 时预检附件并注入 payload,
|
||||
经 ChatTurnRuntime 路由至 action handler,返回 run.started / step.* / message.* / run.completed。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
body, uploads = _parse_turn_body_and_files()
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
|
||||
def relay_stream():
|
||||
if uploads:
|
||||
_inject_multipart_upload_payload(body, uploads)
|
||||
yield from ChatTurnRuntime.stream(
|
||||
user=user,
|
||||
agent=agent,
|
||||
body=body,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
return Response(
|
||||
stream_with_context(relay_stream()),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
)
|
||||
+18
-22
@@ -10,6 +10,7 @@ from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
@@ -1341,9 +1342,9 @@ def home():
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all()
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents if agent.is_active]
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
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]
|
||||
@@ -1360,7 +1361,14 @@ def home():
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': registry.get('iframe_url'),
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
@@ -1813,16 +1821,12 @@ def get_agent_details(id):
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
extra_config = agent.extra_config or {}
|
||||
if isinstance(extra_config, dict):
|
||||
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
|
||||
|
||||
extra_config = enrich_agent_extra_if_file_check(agent)
|
||||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
dify_parameters = None
|
||||
agent_type = str(getattr(agent, 'type', '') or '').strip().lower()
|
||||
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
try:
|
||||
@@ -1835,18 +1839,10 @@ def get_agent_details(id):
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'type': agent.type,
|
||||
'icon_url': agent.icon_url,
|
||||
'extra_config': extra_config if isinstance(extra_config, dict) else {},
|
||||
'dify_app_type': dify_app_type,
|
||||
'welcome_message': extra_config.get('welcome_message') if isinstance(extra_config, dict) else None,
|
||||
'suggested_questions': extra_config.get('suggested_questions', []) if isinstance(extra_config, dict) else [],
|
||||
'dify_parameters': dify_parameters,
|
||||
})
|
||||
return jsonify(serialize_agent_for_user_detail(
|
||||
agent,
|
||||
dify_parameters=dify_parameters,
|
||||
))
|
||||
|
||||
@user_bp.route('/db', methods=['GET'])
|
||||
def get_db():
|
||||
|
||||
@@ -97,58 +97,24 @@ def workspace_create_shipping_batch_from_notices():
|
||||
if not uploads:
|
||||
raise ValidationError('files is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
build_notice_file_summary,
|
||||
cleanup_temp_notice_uploads,
|
||||
intake_temp_notice_uploads,
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
intake_notice_uploads_for_batch,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
|
||||
try:
|
||||
accepted, rejected = intake_temp_notice_uploads(temp_request_id, uploads)
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
|
||||
file_summary = build_notice_file_summary(
|
||||
total_files=len(uploads),
|
||||
accepted=accepted,
|
||||
rejected=rejected,
|
||||
created = create_shipping_batch_from_notice_items(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id or None,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
)
|
||||
notice_items = [item.to_notice_item() for item in accepted]
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
'all uploaded files failed extraction or contained no parseable text',
|
||||
details={'rejected_files': file_summary['rejected_files'], 'file_summary': file_summary},
|
||||
)
|
||||
|
||||
payload = {
|
||||
'user_id': user.id,
|
||||
'conversation_id': conversation_id or None,
|
||||
'file_count': len(notice_items),
|
||||
'notice_items': notice_items,
|
||||
'defer_parse': True,
|
||||
}
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
data = created.get('data') if isinstance(created, dict) else None
|
||||
batch_data = data.get('batch') if isinstance(data, dict) else None
|
||||
tasks_data = data.get('tasks') if isinstance(data, dict) else None
|
||||
batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip()
|
||||
orchestrator_started = False
|
||||
if batch_no:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if isinstance(data, dict) and batch_no:
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if focus_task:
|
||||
data['focus_task'] = serialize_task_summary(focus_task)
|
||||
if isinstance(tasks_data, list):
|
||||
data['tasks'] = tasks_data
|
||||
data['orchestrator_started'] = orchestrator_started
|
||||
if isinstance(created, dict):
|
||||
base_message = str(created.get('message') or '').strip()
|
||||
if orchestrator_started:
|
||||
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
|
||||
created['file_summary'] = file_summary
|
||||
return _ok(created)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
|
||||
Reference in new issue
Block a user