Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/services/maintenance_chat_service.py
#	backend/tests/test_maintenance_chat_service.py
#	frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
hugo committed 2026-07-08 16:23:30 +08:00
commit 2ce1aca023
25 files changed
+1609 -304

No files matched your search

@@ -3,7 +3,7 @@ backend/app/services/maintenance_chat_service.py
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称或上下文指代转换成设备台账卡片。
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、agent_registry.resolver、SQLAlchemy、SSE JSON 输出。
逻辑:chat intent_routes/maintenance_chat 与 try_stream_chat 调用本服务;Agent 门控读 handler_config.intent_routes。
逻辑:chat.py 先调用本服务尝试本地直答;识别到管理写入意图时返回固定引导文案;否则无法明确命中设备或记录时放行给 Dify。
"""
from __future__ import annotations
@@ -23,7 +23,16 @@ from app.services.maintenance_record_service import REPAIR_STATUS_LABELS, serial
MAINTENANCE_INTENT_ROUTE = 'maintenance_chat'
MAINTENANCE_MESSAGE_TYPE = 'maintenance-device-result'
MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE = (
'该操作属于管理配置功能,请在设备维保助手底部点击“台账配置”或“登记维修”按钮进行操作。'
'会话只处理查询和问答,不执行新增、修改、删除、导入、导出。'
)
REFERENCE_DEVICE_PATTERN = re.compile(r'(这个设备|這個設備|这台|這台|该设备|該設備|它|刚才那个|剛才那個|上一个设备|上一個設備|当前设备|當前設備)')
RECORD_QUERY_PATTERN = re.compile(r'(维修|維修|报修|報修|故障|修复|修復|维修记录|維修記錄|维修历史|維修歷史|维修履历|維修履歷|记录|記錄|历史|歷史)')
QUERY_HINT_PATTERN = re.compile(r'(查询|查詢|查看|检索|查一下|查下|最近|有哪些|是什么|多少|吗|嗎|么|麼|\?)')
MANAGEMENT_WRITE_PATTERN = re.compile(
r'(新增|新建|添加|修改|更新|编辑|編輯|删除|刪除|导入|導入|导出|導出|登记|登記|提交|配置|台账配置|台帳配置|设备配置|設備配置|报修|報修)'
)
def _agent_has_maintenance_chat_route(agent: Any) -> bool:
@@ -164,6 +173,38 @@ def resolve_device_query_keyword(query: str, agent: Any, *, session_id: str | No
return (keyword, 'explicit') if keyword else (None, 'none')
def detect_query_mode(query: str) -> str:
"""
判断本轮维保查询应展示设备信息还是维修记录。
AI 触发时机:本地直答生成卡片前调用,用于避免“查设备”和“查维修记录”渲染成同一张卡。
Args:
query: 用户原始问题。
Returns:
records 表示维修记录查询;device 表示设备信息查询。
"""
return 'records' if RECORD_QUERY_PATTERN.search(_clean_text(query)) else 'device'
def detect_management_write_intent(query: str) -> bool:
"""
判断用户是否在会话里尝试执行台账/维修记录的写入或管理配置动作。
核心逻辑:出现新增、导入、删除等写入动词时拦截并引导到底部管理按钮;纯查询语句放行给本地直答或 Dify。
Args:
query: 用户原始问题。
Returns:
True 表示应返回管理操作引导文案,不应继续走 Dify 写入流程。
"""
text = _clean_text(query)
if not text or not MANAGEMENT_WRITE_PATTERN.search(text):
return False
if QUERY_HINT_PATTERN.search(text) and not re.search(
r'(新增|新建|添加|修改|更新|编辑|編輯|删除|刪除|导入|導入|导出|導出|登记|登記|提交|配置|报修|報修)',
text,
):
return False
return True
def _find_device(keyword: str) -> MaintenanceDevice | None:
"""按设备编号优先,其次按设备名称模糊匹配查找单台设备。"""
value = _clean_text(keyword)
@@ -259,6 +300,7 @@ def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> di
status_counts[key] = status_counts.get(key, 0) + 1
return {
'source': 'maintenance_record_query',
'queryMode': 'records',
'matched': True,
'keyword': keyword,
'device': _build_record_device_snapshot(records[0]) if records else None,
@@ -270,7 +312,6 @@ def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> di
'ledgerMatched': False,
},
'actions': [
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
],
}
@@ -293,6 +334,7 @@ def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, r
status_counts[key] = status_counts.get(key, 0) + 1
return {
'source': 'maintenance_device_query',
'queryMode': 'device',
'matched': True,
'device': serialize_device(device),
'records': serialized_records,
@@ -302,19 +344,19 @@ def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, r
'statusLabels': REPAIR_STATUS_LABELS,
},
'actions': [
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
],
}
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5, query_mode: str = 'device') -> dict[str, Any]:
"""
查询设备台账并返回统一结构,供会话直答和 Dify Tool 共用。
Args:
keyword: 设备编号或设备名称。
include_records: 是否附带最近维修记录。
record_limit: 最近维修记录最大返回条数。
query_mode: device 展示设备信息;records 展示维修记录。
Returns:
设备查询结果 payload。
"""
@@ -324,7 +366,38 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
include_records,
record_limit,
)
normalized_mode = 'records' if query_mode == 'records' else 'device'
device = _find_device(keyword)
if normalized_mode == 'records':
records = _find_records(keyword, record_limit=record_limit) if include_records else []
if records:
current_app.logger.info('[maintenance-chat] records mode matched keyword=%s count=%s', keyword, len(records))
payload = _build_records_payload(keyword, records)
if device:
payload['device'] = serialize_device(device)
payload.setdefault('summary', {})['ledgerMatched'] = True
return payload
if device:
payload = _build_payload(device, include_records=False, record_limit=0)
payload['source'] = 'maintenance_record_query'
payload['queryMode'] = 'records'
payload['records'] = []
payload['summary'] = {
'recentRecordCount': 0,
'statusCounts': {},
'statusLabels': REPAIR_STATUS_LABELS,
'ledgerMatched': True,
}
return payload
current_app.logger.info('[maintenance-chat] no records matched keyword=%s', keyword)
return {
'source': 'maintenance_record_query',
'queryMode': 'records',
'matched': False,
'keyword': keyword,
'device': None,
'records': [],
}
if not device:
records = _find_records(keyword, record_limit=record_limit) if include_records else []
if records:
@@ -333,6 +406,7 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
current_app.logger.info('[maintenance-chat] no device or records matched keyword=%s', keyword)
return {
'source': 'maintenance_device_query',
'queryMode': 'device',
'matched': False,
'keyword': keyword,
'device': None,
@@ -428,10 +502,16 @@ def stream_chat(
keyword_source,
query,
)
result = result or build_device_query_result(keyword, include_records=True, record_limit=5)
query_mode = detect_query_mode(query)
result = result or build_device_query_result(
keyword,
include_records=query_mode == 'records',
record_limit=10 if query_mode == 'records' else 0,
query_mode=query_mode,
)
if result.get('matched'):
content = '已查询设备台账信息,下面是匹配结果。'
content = '已查询设备信息,下面是匹配结果。'
if result.get('source') == 'maintenance_record_query':
content = '已查询设备维修记录,下面是匹配结果。'
if keyword_source == 'context':
@@ -439,7 +519,7 @@ def stream_chat(
payload = result
message_type = MAINTENANCE_MESSAGE_TYPE
else:
content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。'
content = f'未找到与“{keyword or query}”匹配的设备信息,请检查设备编号或设备名称。'
payload = result
message_type = 'text'
@@ -489,6 +569,69 @@ def stream_chat(
}, ensure_ascii=False)}\n\n"
def stream_management_redirect(
query: str,
user: Any,
agent: Any,
conversation_id: str | None = None,
session_id: str | None = None,
request_id: str | None = None,
) -> Iterator[str]:
"""
返回管理配置类操作的统一引导文案,阻止会话内直接执行写入动作。
Args:
query: 用户原始问题。
user: 当前用户代理对象。
agent: 当前 Agent 代理对象。
conversation_id: 外部会话 ID。
session_id: 本地会话 ID。
request_id: 当前请求 ID。
Yields:
SSE data 帧。
"""
start_time = time.time()
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
content = MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE
current_app.logger.info(
'[maintenance-chat] management redirect request_id=%s user_id=%s agent_id=%s query=%s',
request_id,
getattr(user, 'id', None),
getattr(agent, 'id', None),
query,
)
yield f"data: {json.dumps({'event': 'message', 'answer': content}, ensure_ascii=False)}\n\n"
chat_log_id = None
try:
chat_log = ChatLog(
user_id=getattr(user, 'id', None),
agent_id=getattr(agent, 'id', None),
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=content,
tokens_used=0,
latency=int((time.time() - start_time) * 1000),
message_type='text',
)
db.session.add(chat_log)
db.session.commit()
chat_log_id = chat_log.id
except Exception as exc:
current_app.logger.exception('[maintenance-chat] failed to log management redirect: %s', exc)
db.session.rollback()
yield f"data: {json.dumps({
'event': 'message_end',
'answer': content,
'replace_answer': True,
'type': 'text',
'chat_log_id': chat_log_id,
'conversation_id': final_conversation_id,
'metadata': {'source': 'maintenance_management_redirect'},
}, ensure_ascii=False)}\n\n"
def try_stream_chat(
query: str,
user: Any,
@@ -510,6 +653,17 @@ def try_stream_chat(
Returns:
SSE 生成器;返回 None 表示本地无法处理,应继续走 Dify。
"""
if not is_maintenance_chat_agent(agent):
return None
if detect_management_write_intent(query):
return stream_management_redirect(
query,
user,
agent,
conversation_id,
session_id=session_id,
request_id=request_id,
)
keyword, keyword_source = resolve_device_query_keyword(query, agent, session_id=session_id)
if not keyword:
current_app.logger.info(
@@ -520,7 +674,13 @@ def try_stream_chat(
query,
)
return None
result = build_device_query_result(keyword, include_records=True, record_limit=5)
query_mode = detect_query_mode(query)
result = build_device_query_result(
keyword,
include_records=query_mode == 'records',
record_limit=10 if query_mode == 'records' else 0,
query_mode=query_mode,
)
if not result.get('matched'):
current_app.logger.info(
'[maintenance-chat] bypass local unmatched request_id=%s keyword=%s keyword_source=%s query=%s',
@@ -548,5 +708,7 @@ class MaintenanceChatService:
supports = staticmethod(supports)
can_attempt = staticmethod(can_attempt)
detect_management_write_intent = staticmethod(detect_management_write_intent)
stream_management_redirect = staticmethod(stream_management_redirect)
stream_chat = staticmethod(stream_chat)
try_stream_chat = staticmethod(try_stream_chat)