Files
syops/backend/app/services/maintenance_chat_service.py
T

218 lines
7.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/maintenance_chat_service.py
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称查询转换成设备台账卡片。
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、SQLAlchemy、SSE JSON 输出。
逻辑:chat.py 在设备维保助手命中查询意图时调用本服务;本服务查询台账和维修记录,写入聊天历史并返回结构化消息。
"""
from __future__ import annotations
import json
import re
import time
from typing import Any, Iterator
from flask import current_app
from sqlalchemy import or_
from app import db
from app.models import ChatLog, MaintenanceDevice, MaintenanceRecord
from app.services.maintenance_ledger_service import serialize_device
from app.services.maintenance_record_service import REPAIR_STATUS_LABELS, serialize_record
def _clean_text(value: Any) -> str:
return str(value or '').strip()
def extract_device_query_keyword(query: str) -> str | None:
"""
从用户自然语言里提取设备编号或设备名称关键词。
AI 触发时机:当用户在设备维保助手里询问“查询某设备/某编号/维修记录”时,用它判断是否走本地台账查询。
Args:
query: 用户原始问题。
Returns:
设备编号或名称关键词;无法判断时返回 None。
"""
text = _clean_text(query)
if not text:
return None
if not re.search(r'(设备|台账|台帳|维保|維保|维修|維修|保养|保養|查询|查詢|查看|检索)', text):
return None
code_match = re.search(r'\b[A-Za-z]{1,6}\d{4,}[A-Za-z0-9_-]*\b', text)
if code_match:
return code_match.group(0).strip()
digit_match = re.search(r'\b\d{6,}\b', text)
if digit_match:
return digit_match.group(0).strip()
cleaned = re.sub(
r'(查询|查詢|查看|检索|一下|这条|這條|这个|這個|设备|設備|台账|台帳|信息|資料|维保|維保|维修|維修|记录|記錄|历史|歷史|的|了|请|請|帮我|幫我)',
' ',
text,
)
cleaned = re.sub(r'[\s,。,.??!!::;;]+', ' ', cleaned).strip()
return cleaned[:80] or None
def _find_device(keyword: str) -> MaintenanceDevice | None:
"""按设备编号优先,其次按设备名称模糊匹配查找单台设备。"""
value = _clean_text(keyword)
if not value:
return None
exact = db.session.query(MaintenanceDevice).filter(MaintenanceDevice.device_code == value).first()
if exact:
return exact
like = f'%{value}%'
return (
db.session.query(MaintenanceDevice)
.filter(or_(MaintenanceDevice.device_code.ilike(like), MaintenanceDevice.device_name.ilike(like)))
.order_by(MaintenanceDevice.updated_at.desc(), MaintenanceDevice.id.desc())
.first()
)
def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
"""构建设备台账卡片 payload,包含设备信息和最近维修记录。"""
record_limit = max(0, min(20, int(record_limit or 0)))
records = (
db.session.query(MaintenanceRecord)
.filter(MaintenanceRecord.device_code == device.device_code)
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
.limit(record_limit)
.all()
) if include_records and record_limit > 0 else []
serialized_records = [serialize_record(item) for item in records]
status_counts: dict[str, int] = {}
for item in serialized_records:
key = str(item.get('repairStatus') or '')
status_counts[key] = status_counts.get(key, 0) + 1
return {
'source': 'maintenance_device_query',
'matched': True,
'device': serialize_device(device),
'records': serialized_records,
'summary': {
'recentRecordCount': len(serialized_records),
'statusCounts': status_counts,
'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]:
"""
查询设备台账并返回统一结构,供会话直答和 Dify Tool 共用。
Args:
keyword: 设备编号或设备名称。
include_records: 是否附带最近维修记录。
record_limit: 最近维修记录最大返回条数。
Returns:
设备查询结果 payload。
"""
device = _find_device(keyword)
if not device:
return {
'source': 'maintenance_device_query',
'matched': False,
'keyword': keyword,
'device': None,
'records': [],
}
return _build_payload(device, include_records=include_records, record_limit=record_limit)
def supports(query: str, agent: Any) -> bool:
"""
判断是否应由设备维保本地查询服务接管(仅看问句意图;Agent 门控由 router intent_routes 负责)。
Args:
query: 用户原始问题。
agent: 当前 Agent(保留参数以兼容调用签名)。
Returns:
True 表示命中设备查询意图。
"""
_ = agent
return bool(extract_device_query_keyword(query))
def stream_chat(
query: str,
user: Any,
agent: Any,
conversation_id: str | None = None,
session_id: str | None = None,
) -> Iterator[str]:
"""
以 SSE 返回设备查询结果,并写入 ChatLog 供历史会话回放。
Args:
query: 用户原始问题。
user: 当前用户代理对象。
agent: 当前 Agent 代理对象。
conversation_id: 外部会话 ID,设备本地查询会沿用本地 session。
session_id: 本地会话 ID。
Yields:
SSE data 帧。
"""
start_time = time.time()
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
keyword = extract_device_query_keyword(query) or ''
result = build_device_query_result(keyword, include_records=True, record_limit=5)
if result.get('matched'):
content = '已查询设备台账信息,下面是匹配结果。'
payload = result
message_type = 'maintenance-device-result'
else:
content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。'
payload = result
message_type = 'text'
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=message_type if message_type != 'text' else None,
payload=payload,
)
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 chat: %s', exc)
db.session.rollback()
yield f"data: {json.dumps({
'event': 'message_end',
'answer': content,
'replace_answer': True,
'type': message_type,
'payload': payload,
'message_payload': payload,
'chat_log_id': chat_log_id,
'conversation_id': final_conversation_id,
'metadata': {'source': 'maintenance_device_query'},
}, ensure_ascii=False)}\n\n"
class MaintenanceChatService:
"""设备维保助手会话查询服务门面,供 chat.py 按统一 Service 风格调用。"""
supports = staticmethod(supports)
stream_chat = staticmethod(stream_chat)