bea288e414
== 已部署上线 (9项) == - 代办事项真实数据源集成 (企微审批API 8bug修复链) - H5/坐席端 Logo样式统一+绿色背景 - 视频引导页修复 (localStorage key v2) - 坐席端 v9 Vue版本修复 (ElMessage._context) - 截图按钮 v10 修复 (getDisplayMedia user gesture) - 扫码样式恢复+H5扫码登录跳转修复 - H5截图快捷键提示 == 代码完成待部署 (3项) == - 知识迭代3Bug修复 (#8 POST端点/#7 MERGE幂等/#6 过期检查) - 会议室预定-小鱼易联终端 (40文件, 40/40测试通过) - IT资产升级审批推送 (asset_service.py) == 需求文档 (2项) == - 坐席端AI辅助消息框-PRD (4项新功能确认) - 坐席端布局优化建议 v2.0 (7天计划) == 新增文档 == - 日报-2026-07-11.md - 知识迭代Bug修复报告-20260711.md - 会议室预定-部署指南.md - CHANGELOG.md 更新 == 测试 == - test_todo_integration.py: 40/40 - test_meetingroom.py: 40/40 - test_bugfix_ki_suggestions.py: 21/21
474 lines
19 KiB
Python
474 lines
19 KiB
Python
# =============================================================================
|
||
# 企微IT智能服务台 — H5 员工端 AI 回复后台任务
|
||
# =============================================================================
|
||
# 背景:原 h5_send_message 在同步 HTTP 请求内 await AI 推理(Dify 3~15s),
|
||
# 整条请求被阻塞,前端表现为"发送中"长时间卡顿。
|
||
# 本模块将 AI 推理移出请求,改为 asyncio 后台任务,结果经 WebSocket
|
||
# 流式推回(ai_reply_chunk / ai_reply),发送瞬时完成。
|
||
#
|
||
# 关键约束(详见 docs/02-需求分析/技术架构演进/员工端消息发送延时改造方案.md):
|
||
# 1. 必须单 worker 运行(docker-compose --workers 1):
|
||
# ws_manager 是进程内单例,多 worker 时后台任务与员工 WS 连接可能不在
|
||
# 同进程,broadcast 会静默丢失(约 50%)。
|
||
# 2. 使用独立 DB session(_get_session_factory),不可复用请求的 db
|
||
# (请求返回后该 session 会被关闭)。
|
||
# =============================================================================
|
||
|
||
import logging
|
||
from datetime import datetime
|
||
|
||
from app.api.byod import _byod_keyword_prefilter
|
||
from app.database import _get_session_factory
|
||
from app.dependencies import get_shared_ai_handler
|
||
from app.models.conversation import Conversation
|
||
from app.models.message import Message
|
||
from app.services.routing_service import (
|
||
routing_keyword_prefilter,
|
||
detect_routing_intent,
|
||
get_contact_by_category,
|
||
send_contact_card,
|
||
record_routing_event,
|
||
_keyword_fallback_category,
|
||
)
|
||
from app.services.ws_manager import manager as ws_manager
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
async def _persist_and_push(
|
||
db,
|
||
conversation: Conversation,
|
||
employee_id: str,
|
||
content: str,
|
||
is_guidance: bool,
|
||
should_count: bool,
|
||
should_transfer: bool,
|
||
dify_conversation_id,
|
||
):
|
||
"""持久化 AI 回复并推送给员工端 + 广播坐席端。
|
||
|
||
做什么:
|
||
1. 存 AI 消息到 DB
|
||
2. 更新会话状态(dify 上下文 / 计数 / 转人工)
|
||
3. 经 WS 向员工推 ai_reply 终态(前端据此替换打字机气泡)
|
||
4. 经 WS 向坐席端广播 new_message + conversation_updated
|
||
为什么:把"落库 + 推送"封装为单点,供同步路径与流式路径复用。
|
||
"""
|
||
# 1. 存 AI 消息
|
||
ai_message = Message(
|
||
conversation_id=conversation.id,
|
||
sender_type="ai",
|
||
sender_id="ai_bot",
|
||
sender_name="Duckula(达寇拉)",
|
||
content=content,
|
||
msg_type="text",
|
||
is_read=True,
|
||
)
|
||
db.add(ai_message)
|
||
await db.flush()
|
||
|
||
# 2. 更新会话状态
|
||
if dify_conversation_id:
|
||
conversation.dify_conversation_id = dify_conversation_id
|
||
if should_count:
|
||
conversation.ai_substantive_reply_count += 1
|
||
if should_transfer:
|
||
conversation.status = "queued"
|
||
conversation.updated_at = datetime.now()
|
||
db.add(conversation)
|
||
await db.flush()
|
||
await db.commit()
|
||
|
||
# 3. 推 ai_reply 终态给员工(前端替换打字机气泡)
|
||
await ws_manager.broadcast_to_employees([employee_id], {
|
||
"type": "ai_reply",
|
||
"data": {
|
||
"message_id": str(ai_message.id),
|
||
"conversation_id": str(conversation.id),
|
||
"sender_type": "ai",
|
||
"sender_id": "ai_bot",
|
||
"sender_name": "Duckula(达寇拉)",
|
||
"content": content,
|
||
"msg_type": "text",
|
||
"is_guidance": is_guidance,
|
||
"ai_reply_count": conversation.ai_substantive_reply_count,
|
||
"can_call_agent": conversation.ai_substantive_reply_count >= 3,
|
||
"conversation_status": conversation.status,
|
||
},
|
||
})
|
||
|
||
# 4. 广播坐席端(new_message + conversation_updated)
|
||
try:
|
||
await ws_manager.broadcast({
|
||
"type": "new_message",
|
||
"data": {
|
||
"conversation_id": str(conversation.id),
|
||
"message_id": str(ai_message.id),
|
||
"sender_type": "ai",
|
||
"sender_id": "ai_bot",
|
||
"sender_name": "Duckula(达寇拉)",
|
||
"content": content,
|
||
"msg_type": "text",
|
||
},
|
||
})
|
||
await ws_manager.broadcast({
|
||
"type": "conversation_updated",
|
||
"data": {
|
||
"conversation_id": str(conversation.id),
|
||
"status": conversation.status,
|
||
"assigned_agent_id": str(conversation.assigned_agent_id) if conversation.assigned_agent_id else None,
|
||
},
|
||
})
|
||
except Exception as ws_err:
|
||
# WS 广播失败不阻塞消息存储,只记录 warning
|
||
logger.warning(f"WS 广播 AI 回复给坐席失败(消息已存储): {ws_err}")
|
||
|
||
|
||
async def _handle_byod_query(db, conversation, employee_id, content):
|
||
"""处理 BYOD 自备电脑补贴查询。
|
||
|
||
在 H5 聊天消息流中拦截 BYOD 关键词后执行资格检查,并以 byod_card
|
||
卡片消息形式推送给员工端(前端 MessageBubble 据 msg_type 渲染
|
||
ByodSubsidyCard)。
|
||
|
||
流程:
|
||
1. 通过 WecomService 获取员工岗位(position)
|
||
2. 与 BYOD 资格清单匹配(_match_position)
|
||
3. 创建 byod_card 类型 AI 消息并落库
|
||
4. 经 WS 推送 ai_reply 给员工端(携带 extra_data.byod_result)
|
||
5. 广播 new_message + conversation_updated 给坐席端(与 _persist_and_push 一致)
|
||
|
||
Args:
|
||
db: 异步 DB session(process_h5_ai_reply 的 factory session)
|
||
conversation: 当前会话对象(Conversation)
|
||
employee_id: 员工企微 UserID
|
||
content: 用户消息原文(用于日志)
|
||
"""
|
||
# 延迟导入避免循环依赖(byod 模块注册路由时可能引用 app.main)
|
||
from app.api.byod import _match_position, BYOD_APPLICATION_URL, BYOD_NOTES, BYOD_REGISTER_NOTES
|
||
from app.services.wecom_service import WecomService
|
||
|
||
# 1. 获取员工岗位(企微通讯录 API)
|
||
position = ""
|
||
try:
|
||
wecom_service = WecomService()
|
||
try:
|
||
user_info = await wecom_service.get_user_info(employee_id)
|
||
position = user_info.get("position", "")
|
||
finally:
|
||
await wecom_service.close()
|
||
except Exception as e:
|
||
logger.error(f"BYOD: 获取员工岗位失败: {e}")
|
||
|
||
# 2. 岗位匹配(返回: 是否匹配, 匹配岗位, 匹配类别)
|
||
eligible, matched_pos, matched_category = _match_position(position)
|
||
|
||
# 3. 构建 BYOD 结果数据
|
||
# 字段与前端 ByodSubsidyCard.vue props 完全一致:
|
||
# eligible / position / matched_category / application_url / notes / reason
|
||
byod_result = {
|
||
"eligible": eligible,
|
||
"has_subsidy": eligible,
|
||
"position": position,
|
||
"matched_category": matched_category,
|
||
"application_url": BYOD_APPLICATION_URL, # 所有岗位都提供链接
|
||
"notes": BYOD_NOTES if eligible else BYOD_REGISTER_NOTES,
|
||
"reason": (
|
||
"" if eligible
|
||
else f"您的岗位「{position}」不在自备电脑补贴资格清单中,可进行自备电脑登记(无补贴)"
|
||
),
|
||
}
|
||
|
||
# 4. 展示文本(AI 气泡的 content,卡片下方不直接展示,但会话列表/坐席端可见)
|
||
if eligible:
|
||
display_text = f"您岗位为「{position}」,符合自备电脑补贴申请资格"
|
||
else:
|
||
display_text = f"您岗位为「{position}」,可进行自备电脑登记(无补贴)"
|
||
|
||
# 5. 创建 AI 消息(byod_card 类型,携带 byod_result)
|
||
ai_message = Message(
|
||
conversation_id=conversation.id,
|
||
sender_type="ai",
|
||
sender_id="ai_bot",
|
||
sender_name="Duckula(达寇拉)",
|
||
content=display_text,
|
||
msg_type="byod_card",
|
||
extra_data={"byod_result": byod_result},
|
||
is_read=True,
|
||
)
|
||
db.add(ai_message)
|
||
await db.flush()
|
||
|
||
# 6. 更新会话状态(计数 + 时间,BYOD 视为一次实质性 AI 回复)
|
||
conversation.ai_substantive_reply_count += 1
|
||
conversation.updated_at = datetime.now()
|
||
db.add(conversation)
|
||
await db.flush()
|
||
await db.commit()
|
||
|
||
# 7. 推送 ai_reply 给员工端(前端据 msg_type="byod_card" 渲染卡片)
|
||
await ws_manager.broadcast_to_employees([employee_id], {
|
||
"type": "ai_reply",
|
||
"data": {
|
||
"message_id": str(ai_message.id),
|
||
"conversation_id": str(conversation.id),
|
||
"sender_type": "ai",
|
||
"sender_id": "ai_bot",
|
||
"sender_name": "Duckula(达寇拉)",
|
||
"content": display_text,
|
||
"msg_type": "byod_card",
|
||
"extra_data": {"byod_result": byod_result},
|
||
"is_guidance": False,
|
||
"ai_reply_count": conversation.ai_substantive_reply_count,
|
||
"can_call_agent": conversation.ai_substantive_reply_count >= 3,
|
||
"conversation_status": conversation.status,
|
||
},
|
||
})
|
||
|
||
# 8. 广播坐席端(new_message + conversation_updated,与 _persist_and_push 一致)
|
||
try:
|
||
await ws_manager.broadcast({
|
||
"type": "new_message",
|
||
"data": {
|
||
"conversation_id": str(conversation.id),
|
||
"message_id": str(ai_message.id),
|
||
"sender_type": "ai",
|
||
"sender_id": "ai_bot",
|
||
"sender_name": "Duckula(达寇拉)",
|
||
"content": display_text,
|
||
"msg_type": "byod_card",
|
||
"extra_data": {"byod_result": byod_result},
|
||
},
|
||
})
|
||
await ws_manager.broadcast({
|
||
"type": "conversation_updated",
|
||
"data": {
|
||
"conversation_id": str(conversation.id),
|
||
"status": conversation.status,
|
||
"assigned_agent_id": (
|
||
str(conversation.assigned_agent_id)
|
||
if conversation.assigned_agent_id else None
|
||
),
|
||
},
|
||
})
|
||
except Exception as ws_err:
|
||
logger.warning(f"BYOD: WS 广播给坐席失败: {ws_err}")
|
||
|
||
logger.info(
|
||
f"BYOD 查询完成: employee_id={employee_id}, position={position}, "
|
||
f"eligible={eligible}, matched_category={matched_category}"
|
||
)
|
||
|
||
|
||
async def _handle_routing(
|
||
db,
|
||
conversation: Conversation,
|
||
employee_id: str,
|
||
content: str,
|
||
) -> bool:
|
||
"""处理非IT业务路由推荐。
|
||
|
||
在 H5 聊天消息流中拦截路由关键词后调用 Dify 统一意图识别,
|
||
判定为 non_it_routing 且 routing_confidence ≥ 阈值时发送名片三段式消息。
|
||
|
||
流程:
|
||
1. 调用 Dify 统一意图识别(detect_routing_intent)
|
||
2. 检查 intent_type == "non_it_routing" && routing_confidence ≥ 阈值
|
||
→ YES: 查询联系人 → 发送名片三段式消息 → 记录路由事件 → 返回 True
|
||
→ NO: 返回 False(继续走正常 AI 流程)
|
||
3. Dify 调用失败 → 关键词降级兜底(按 ROUTING_KEYWORD_TO_CATEGORY 映射)
|
||
|
||
Args:
|
||
db: 异步 DB session(process_h5_ai_reply 的 factory session)
|
||
conversation: 当前会话对象(Conversation)
|
||
employee_id: 员工企微 UserID
|
||
content: 用户消息原文
|
||
|
||
Returns:
|
||
bool: True 表示已发送路由名片(应 return 中断后续流程),
|
||
False 表示未触发路由(继续走正常 AI 流程)
|
||
"""
|
||
from app.config import settings
|
||
|
||
# 1. 调用 Dify 统一意图识别
|
||
try:
|
||
result = await detect_routing_intent(content, employee_id)
|
||
intent_type = result.get("intent_type", "chitchat")
|
||
business_category = result.get("business_category")
|
||
routing_confidence = result.get("routing_confidence", 0.0)
|
||
|
||
# 如果是审批意图,不拦截(让审批流程处理)
|
||
if intent_type == "approval":
|
||
return False
|
||
|
||
logger.info(
|
||
f"路由意图检测(Dify): intent_type={intent_type}, "
|
||
f"business_category={business_category}, "
|
||
f"routing_confidence={routing_confidence}"
|
||
)
|
||
|
||
# 2. 检查是否触发路由推荐
|
||
threshold = settings.routing_confidence_threshold
|
||
if intent_type != "non_it_routing" or routing_confidence < threshold:
|
||
# 置信度不足或非路由意图,走正常 AI 流程
|
||
return False
|
||
|
||
if not business_category:
|
||
logger.warning("路由意图为 non_it_routing 但 business_category 为空,跳过")
|
||
return False
|
||
|
||
except Exception as e:
|
||
logger.warning(f"Dify 路由意图识别失败,降级为关键词匹配: {e}")
|
||
# 3. 降级为关键词匹配
|
||
business_category = _keyword_fallback_category(content)
|
||
if not business_category:
|
||
# 关键词也未命中,走正常 AI 流程
|
||
return False
|
||
routing_confidence = 0.75 # 降级兜底给一个略高于阈值的置信度
|
||
logger.info(f"路由意图检测(兜底): business_category={business_category}")
|
||
|
||
# 4. 查询联系人
|
||
contact = await get_contact_by_category(db, business_category)
|
||
if not contact:
|
||
logger.warning(f"未找到 {business_category} 类别的联系人,跳过路由推荐")
|
||
return False
|
||
|
||
# 5. 构建路由说明文本
|
||
category_display = business_category.replace("行政-物业", "物业")
|
||
reason = (
|
||
f"您的问题属于{category_display}业务范畴,不在IT服务台服务范围内 😊\n\n"
|
||
f"为您推荐{category_display}服务相关联系人,您可以直接点击名片联系TA:"
|
||
)
|
||
|
||
# 6. 发送名片三段式消息
|
||
await send_contact_card(
|
||
db=db,
|
||
conversation=conversation,
|
||
employee_id=employee_id,
|
||
contact=contact,
|
||
reason=reason,
|
||
business_category=business_category,
|
||
routing_confidence=routing_confidence,
|
||
)
|
||
|
||
# 7. 记录路由事件(P1)
|
||
await record_routing_event(
|
||
db=db,
|
||
conversation_id=str(conversation.id),
|
||
employee_id=employee_id,
|
||
message_content=content,
|
||
business_category=business_category,
|
||
routing_confidence=routing_confidence,
|
||
contact=contact,
|
||
)
|
||
|
||
return True
|
||
|
||
|
||
async def process_h5_ai_reply(
|
||
conversation_id: str,
|
||
employee_id: str,
|
||
content: str,
|
||
dify_conversation_id=None,
|
||
):
|
||
"""H5 发送消息后的 AI 回复处理(asyncio.create_task 入口)。
|
||
|
||
流程:
|
||
- 本地快判断(打招呼 / 呼叫人工)→ 同步结果,整段推送(不调 Dify)
|
||
- 否则流式调 Dify,逐 chunk 推 ai_reply_chunk,流结束推 ai_reply 终态
|
||
- 任意异常 → 推 ai_reply_failed,不阻塞用户
|
||
"""
|
||
ai_handler = get_shared_ai_handler()
|
||
factory = _get_session_factory()
|
||
async with factory() as db:
|
||
try:
|
||
conversation = await db.get(Conversation, conversation_id)
|
||
if not conversation:
|
||
logger.warning(f"后台 AI 任务:会话不存在 {conversation_id}")
|
||
return
|
||
|
||
is_guidance = False
|
||
should_count = False
|
||
should_transfer = False
|
||
new_dify_conv_id = dify_conversation_id
|
||
full_parts: list = []
|
||
|
||
# === BYOD 关键词拦截 ===
|
||
# 在打招呼/呼叫人工判断之前,先检查是否为 BYOD(自备电脑补贴)意图。
|
||
# 命中关键词 → 执行 BYOD 资格检查并推送 byod_card 卡片,不走正常 AI 流程。
|
||
if _byod_keyword_prefilter(content):
|
||
await _handle_byod_query(db, conversation, employee_id, content)
|
||
return # BYOD 处理完毕,直接返回
|
||
|
||
# === 业务路由检测(新增)===
|
||
# 在 BYOD 检测之后、打招呼/呼叫人工检测之前,检查是否为非IT业务路由。
|
||
# 命中路由关键词 → 调用 Dify 统一意图识别 → non_it_routing && confidence≥0.7
|
||
# → 发送名片三段式消息(路由文本 + contact_card + 系统提示)
|
||
# 置信度不足或非路由意图 → 继续往下走正常 AI 流程
|
||
if routing_keyword_prefilter(content):
|
||
routed = await _handle_routing(db, conversation, employee_id, content)
|
||
if routed:
|
||
return # 路由名片已发送,直接返回
|
||
|
||
# 本地快判断(不打 Dify):打招呼 / 呼叫人工 → 同步路径
|
||
if ai_handler.is_greeting(content) or ai_handler.is_call_human(content):
|
||
result = await ai_handler.handle_message(
|
||
content=content,
|
||
dify_conversation_id=dify_conversation_id,
|
||
user_id=employee_id,
|
||
)
|
||
await _persist_and_push(
|
||
db, conversation, employee_id, result.content,
|
||
result.is_guidance, result.should_count,
|
||
result.should_transfer, result.dify_conversation_id,
|
||
)
|
||
return
|
||
|
||
# 流式调 Dify(get_reply_stream 内部已处理真 SSE / 非流式 fallback)
|
||
# 注意:首参是 message(用户文本),不是 content
|
||
async for chunk in ai_handler.ai_service.get_reply_stream(
|
||
message=content,
|
||
conversation_id=dify_conversation_id,
|
||
user_id=employee_id,
|
||
):
|
||
delta = chunk.get("delta", "")
|
||
if delta:
|
||
full_parts.append(delta)
|
||
await ws_manager.broadcast_to_employees([employee_id], {
|
||
"type": "ai_reply_chunk",
|
||
"data": {
|
||
"conversation_id": conversation_id,
|
||
"chunk": delta,
|
||
},
|
||
})
|
||
if chunk.get("finished"):
|
||
new_dify_conv_id = chunk.get("conversation_id") or dify_conversation_id
|
||
hit = chunk.get("hit")
|
||
# 命中 → 计数;未命中 → 转人工
|
||
should_count = bool(hit)
|
||
should_transfer = not bool(hit)
|
||
|
||
content_ai = "".join(full_parts)
|
||
if not content_ai:
|
||
# 流式无内容(极端情况),给降级提示,不转人工
|
||
content_ai = "⚠️ AI 暂时没有返回内容,请输入「IT」转人工。"
|
||
should_count = False
|
||
should_transfer = False
|
||
await _persist_and_push(
|
||
db, conversation, employee_id, content_ai,
|
||
is_guidance, should_count, should_transfer, new_dify_conv_id,
|
||
)
|
||
except Exception as e:
|
||
logger.error(f"后台 AI 任务异常: {e}", exc_info=True)
|
||
try:
|
||
await ws_manager.broadcast_to_employees([employee_id], {
|
||
"type": "ai_reply_failed",
|
||
"data": {
|
||
"conversation_id": conversation_id,
|
||
"message": "⚠️ AI 服务异常,请输入「IT」转人工或稍后重试。",
|
||
},
|
||
})
|
||
except Exception:
|
||
# 推送失败也无所谓,员工端 3 秒轮询兜底
|
||
pass
|