# Conflicts: # backend/app/services/maintenance_chat_service.py # backend/tests/test_maintenance_chat_service.py # frontend/src/features/chat/components/ChatViewContent.vue
715 lines
27 KiB
Python
715 lines
27 KiB
Python
"""
|
||
backend/app/services/maintenance_chat_service.py
|
||
|
||
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称或上下文指代转换成设备台账卡片。
|
||
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、agent_registry.resolver、SQLAlchemy、SSE JSON 输出。
|
||
逻辑:chat.py 先调用本服务尝试本地直答;识别到管理写入意图时返回固定引导文案;否则无法明确命中设备或记录时放行给 Dify。
|
||
"""
|
||
|
||
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
|
||
|
||
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:
|
||
"""
|
||
判断当前 Agent 是否声明 maintenance_chat Intent 快路径。
|
||
|
||
核心逻辑:只读 handler_config.intent_routes,不再根据 Agent 名称硬编码推断。
|
||
|
||
Args:
|
||
agent: Agent ORM 或代理对象。
|
||
Returns:
|
||
已配置 maintenance_chat route 时返回 True。
|
||
"""
|
||
from app.services.agent_registry.resolver import agent_has_intent_route
|
||
|
||
return agent_has_intent_route(agent, MAINTENANCE_INTENT_ROUTE)
|
||
|
||
|
||
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'(?<![A-Za-z0-9_-])([A-Za-z]{1,6}\d{4,}[A-Za-z0-9_-]*)', text)
|
||
if code_match:
|
||
return code_match.group(1).strip()
|
||
digit_match = re.search(r'(?<![A-Za-z0-9_-])(\d{6,})(?![A-Za-z0-9_-])', text)
|
||
if digit_match:
|
||
return digit_match.group(1).strip()
|
||
|
||
cleaned = re.sub(
|
||
r'(查询|查詢|查看|检索|查|一下|这条|這條|这个|這個|设备|設備|台账|台帳|信息|資料|维保|維保|维修|維修|记录|記錄|历史|歷史|的|了|请|請|帮我|幫我)',
|
||
' ',
|
||
text,
|
||
)
|
||
cleaned = re.sub(r'[\s,。,.??!!::;;]+', ' ', cleaned).strip()
|
||
return cleaned[:80] or None
|
||
|
||
|
||
def _looks_like_context_reference(query: str) -> bool:
|
||
"""
|
||
判断用户本轮问题是否在指代上一轮设备。
|
||
AI 触发时机:当用户追问“这个设备/这台/它的维修记录”时,用它把本轮问题接到最近命中的设备上下文。
|
||
Args:
|
||
query: 用户原始问题。
|
||
Returns:
|
||
True 表示问题包含设备指代词,适合尝试读取会话中的最近设备。
|
||
"""
|
||
return bool(REFERENCE_DEVICE_PATTERN.search(_clean_text(query)))
|
||
|
||
|
||
def _extract_device_code_from_payload(payload: Any) -> str | None:
|
||
"""
|
||
从维保卡片 payload 中提取设备编号。
|
||
Args:
|
||
payload: ChatLog.payload,通常来自 maintenance-device-result。
|
||
Returns:
|
||
设备编号;没有可用设备信息时返回 None。
|
||
"""
|
||
if not isinstance(payload, dict):
|
||
return None
|
||
device = payload.get('device')
|
||
if not isinstance(device, dict):
|
||
return None
|
||
code = _clean_text(device.get('deviceCode') or device.get('device_code'))
|
||
return code or None
|
||
|
||
|
||
def _find_recent_context_device_code(session_id: str | None, agent: Any) -> str | None:
|
||
"""
|
||
从同一会话最近的维保结果中恢复当前设备编号。
|
||
Args:
|
||
session_id: 本地 ChatSession.session_id。
|
||
agent: 当前 Agent,用于限制只读取同一助手的上下文。
|
||
Returns:
|
||
最近一次命中的设备编号;没有上下文时返回 None。
|
||
"""
|
||
session_key = _clean_text(session_id)
|
||
if not session_key:
|
||
return None
|
||
rows = (
|
||
db.session.query(ChatLog)
|
||
.filter(
|
||
ChatLog.session_id == session_key,
|
||
ChatLog.agent_id == getattr(agent, 'id', None),
|
||
ChatLog.message_type == MAINTENANCE_MESSAGE_TYPE,
|
||
)
|
||
.order_by(ChatLog.created_at.desc(), ChatLog.id.desc())
|
||
.limit(10)
|
||
.all()
|
||
)
|
||
for row in rows:
|
||
code = _extract_device_code_from_payload(row.payload)
|
||
if code:
|
||
current_app.logger.info(
|
||
'[maintenance-chat] context device resolved session_id=%s chat_log_id=%s device_code=%s',
|
||
session_key,
|
||
row.id,
|
||
code,
|
||
)
|
||
return code
|
||
current_app.logger.info('[maintenance-chat] context device missed session_id=%s', session_key)
|
||
return None
|
||
|
||
|
||
def resolve_device_query_keyword(query: str, agent: Any, *, session_id: str | None = None) -> tuple[str | None, str]:
|
||
"""
|
||
解析本轮维保查询关键词,优先使用显式编号,其次处理“这个设备”等上下文指代。
|
||
AI 触发时机:chat.py 分流前调用,用于判断本地维保服务是否能明确回答。
|
||
Args:
|
||
query: 用户原始问题。
|
||
agent: 当前 Agent。
|
||
session_id: 本地会话 ID,用于读取最近设备上下文。
|
||
Returns:
|
||
(keyword, source):source 为 explicit/context/none。
|
||
"""
|
||
if not _agent_has_maintenance_chat_route(agent):
|
||
return None, 'none'
|
||
if _looks_like_context_reference(query):
|
||
context_code = _find_recent_context_device_code(session_id, agent)
|
||
if context_code:
|
||
return context_code, 'context'
|
||
keyword = extract_device_query_keyword(query)
|
||
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)
|
||
if not value:
|
||
return None
|
||
exact = db.session.query(MaintenanceDevice).filter(MaintenanceDevice.device_code == value).first()
|
||
if exact:
|
||
current_app.logger.info('[maintenance-chat] device exact matched keyword=%s device_id=%s device_code=%s', value, exact.id, exact.device_code)
|
||
return exact
|
||
like = f'%{value}%'
|
||
device = (
|
||
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()
|
||
)
|
||
current_app.logger.info(
|
||
'[maintenance-chat] device fuzzy result keyword=%s matched=%s device_id=%s device_code=%s',
|
||
value,
|
||
bool(device),
|
||
getattr(device, 'id', None),
|
||
getattr(device, 'device_code', None),
|
||
)
|
||
return device
|
||
|
||
|
||
def _find_records(keyword: str, *, record_limit: int = 5) -> list[MaintenanceRecord]:
|
||
"""
|
||
按设备编号或设备名称查询维修记录。
|
||
AI 触发时机:本地会话直答未匹配台账时,用维修记录兜底,避免导入履历后问不到记录。
|
||
Args:
|
||
keyword: 从用户问题中提取出的设备编号或名称。
|
||
record_limit: 最大返回条数。
|
||
Returns:
|
||
按报修日期倒序排列的维修记录列表。
|
||
"""
|
||
value = _clean_text(keyword)
|
||
if not value:
|
||
return []
|
||
record_limit = max(1, min(20, int(record_limit or 5)))
|
||
query = db.session.query(MaintenanceRecord)
|
||
exact_rows = (
|
||
query.filter(MaintenanceRecord.device_code == value)
|
||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||
.limit(record_limit)
|
||
.all()
|
||
)
|
||
if exact_rows:
|
||
current_app.logger.info('[maintenance-chat] records exact matched keyword=%s count=%s', value, len(exact_rows))
|
||
return exact_rows
|
||
like = f'%{value}%'
|
||
rows = (
|
||
query.filter(or_(MaintenanceRecord.device_code.ilike(like), MaintenanceRecord.device_name.ilike(like)))
|
||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||
.limit(record_limit)
|
||
.all()
|
||
)
|
||
current_app.logger.info('[maintenance-chat] records fuzzy result keyword=%s count=%s', value, len(rows))
|
||
return rows
|
||
|
||
|
||
def _build_record_device_snapshot(record: MaintenanceRecord) -> dict[str, Any]:
|
||
"""把维修记录中的设备快照转成前端台账卡片可展示的设备结构。"""
|
||
return {
|
||
'id': record.device_id or 0,
|
||
'deviceCode': record.device_code,
|
||
'deviceName': record.device_name,
|
||
'modelSpec': record.model_spec,
|
||
'department': None,
|
||
'installLocation': record.install_location,
|
||
'deviceStatus': None,
|
||
'manufacturer': None,
|
||
'entryDate': None,
|
||
'productionDate': None,
|
||
'startDate': None,
|
||
'responsibleUser': None,
|
||
'maintenanceCycle': None,
|
||
'originalValue': None,
|
||
'residualValue': None,
|
||
'accountSet': None,
|
||
'remark': '仅来自维修记录快照,未匹配到设备台账',
|
||
'createdAt': None,
|
||
'updatedAt': None,
|
||
}
|
||
|
||
|
||
def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> dict[str, Any]:
|
||
"""构建仅命中维修记录时的会话 payload。"""
|
||
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_record_query',
|
||
'queryMode': 'records',
|
||
'matched': True,
|
||
'keyword': keyword,
|
||
'device': _build_record_device_snapshot(records[0]) if records else None,
|
||
'records': serialized_records,
|
||
'summary': {
|
||
'recentRecordCount': len(serialized_records),
|
||
'statusCounts': status_counts,
|
||
'statusLabels': REPAIR_STATUS_LABELS,
|
||
'ledgerMatched': False,
|
||
},
|
||
'actions': [
|
||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||
],
|
||
}
|
||
|
||
|
||
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',
|
||
'queryMode': 'device',
|
||
'matched': True,
|
||
'device': serialize_device(device),
|
||
'records': serialized_records,
|
||
'summary': {
|
||
'recentRecordCount': len(serialized_records),
|
||
'statusCounts': status_counts,
|
||
'statusLabels': REPAIR_STATUS_LABELS,
|
||
},
|
||
'actions': [
|
||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||
],
|
||
}
|
||
|
||
|
||
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。
|
||
"""
|
||
current_app.logger.info(
|
||
'[maintenance-chat] build query keyword=%s include_records=%s record_limit=%s',
|
||
keyword,
|
||
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:
|
||
current_app.logger.info('[maintenance-chat] fallback to records keyword=%s count=%s', keyword, len(records))
|
||
return _build_records_payload(keyword, records)
|
||
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,
|
||
'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
|
||
keyword = extract_device_query_keyword(query)
|
||
supported = bool(keyword)
|
||
current_app.logger.info(
|
||
'[maintenance-chat] support decision keyword=%s supported=%s query=%s',
|
||
keyword,
|
||
supported,
|
||
query,
|
||
)
|
||
return supported
|
||
|
||
|
||
def can_attempt(query: str, agent: Any, *, session_id: str | None = None) -> bool:
|
||
"""
|
||
判断本地维保服务是否具备明确查询关键词,可尝试直答。
|
||
Args:
|
||
query: 用户原始问题。
|
||
agent: 当前 Agent。
|
||
session_id: 本地会话 ID;用于支持“这个设备”等指代追问。
|
||
Returns:
|
||
True 表示已有显式关键词或上下文设备,可以先查本地库。
|
||
"""
|
||
keyword, source = resolve_device_query_keyword(query, agent, session_id=session_id)
|
||
supported = bool(keyword)
|
||
current_app.logger.info(
|
||
'[maintenance-chat] attempt decision agent_id=%s agent_name=%s keyword=%s source=%s supported=%s query=%s',
|
||
getattr(agent, 'id', None),
|
||
getattr(agent, 'name', None),
|
||
keyword,
|
||
source,
|
||
supported,
|
||
query,
|
||
)
|
||
return supported
|
||
|
||
|
||
def stream_chat(
|
||
query: str,
|
||
user: Any,
|
||
agent: Any,
|
||
conversation_id: str | None = None,
|
||
session_id: str | None = None,
|
||
request_id: str | None = None,
|
||
keyword: str | None = None,
|
||
keyword_source: str = 'explicit',
|
||
result: dict[str, Any] | None = None,
|
||
) -> Iterator[str]:
|
||
"""
|
||
以 SSE 返回设备查询结果,并写入 ChatLog 供历史会话回放。
|
||
Args:
|
||
query: 用户原始问题。
|
||
user: 当前用户代理对象。
|
||
agent: 当前 Agent 代理对象。
|
||
conversation_id: 外部会话 ID,设备本地查询会沿用本地 session。
|
||
session_id: 本地会话 ID。
|
||
keyword: 已解析的设备编号或名称;为空时在函数内重新解析。
|
||
keyword_source: 关键词来源,explicit 表示本轮明示,context 表示来自上一轮设备。
|
||
result: 已查询好的本地结果;为空时在函数内查询。
|
||
Yields:
|
||
SSE data 帧。
|
||
"""
|
||
start_time = time.time()
|
||
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
|
||
if keyword is None:
|
||
keyword, keyword_source = resolve_device_query_keyword(query, agent, session_id=session_id)
|
||
keyword = keyword or ''
|
||
current_app.logger.info(
|
||
'[maintenance-chat] stream start request_id=%s user_id=%s agent_id=%s session_id=%s conversation_id=%s keyword=%s keyword_source=%s query=%s',
|
||
request_id,
|
||
getattr(user, 'id', None),
|
||
getattr(agent, 'id', None),
|
||
session_id,
|
||
final_conversation_id,
|
||
keyword,
|
||
keyword_source,
|
||
query,
|
||
)
|
||
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 = '已查询设备信息,下面是匹配结果。'
|
||
if result.get('source') == 'maintenance_record_query':
|
||
content = '已查询设备维修记录,下面是匹配结果。'
|
||
if keyword_source == 'context':
|
||
content = f'已按上一轮设备({keyword})查询,下面是匹配结果。'
|
||
payload = result
|
||
message_type = MAINTENANCE_MESSAGE_TYPE
|
||
else:
|
||
content = f'未找到与“{keyword or query}”匹配的设备信息,请检查设备编号或设备名称。'
|
||
payload = result
|
||
message_type = 'text'
|
||
|
||
current_app.logger.info(
|
||
'[maintenance-chat] stream result request_id=%s source=%s matched=%s message_type=%s records=%s device_code=%s',
|
||
request_id,
|
||
result.get('source'),
|
||
result.get('matched'),
|
||
message_type,
|
||
len(result.get('records') or []),
|
||
(result.get('device') or {}).get('deviceCode') if isinstance(result.get('device'), dict) else None,
|
||
)
|
||
|
||
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', 'keyword_source': keyword_source},
|
||
}, 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,
|
||
agent: Any,
|
||
conversation_id: str | None = None,
|
||
session_id: str | None = None,
|
||
request_id: str | None = None,
|
||
) -> Iterator[str] | None:
|
||
"""
|
||
尝试用本地维保库回答;无法明确命中时返回 None 交给 Dify。
|
||
AI 触发时机:chat.py 分流时优先调用;只有设备台账或维修记录真实命中时才拦截 Dify。
|
||
Args:
|
||
query: 用户原始问题。
|
||
user: 当前用户代理对象。
|
||
agent: 当前 Agent 代理对象。
|
||
conversation_id: 外部 Dify 会话 ID。
|
||
session_id: 本地会话 ID。
|
||
request_id: 当前请求 ID,用于日志串联。
|
||
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(
|
||
'[maintenance-chat] bypass local no keyword request_id=%s agent_id=%s session_id=%s query=%s',
|
||
request_id,
|
||
getattr(agent, 'id', None),
|
||
session_id,
|
||
query,
|
||
)
|
||
return None
|
||
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',
|
||
request_id,
|
||
keyword,
|
||
keyword_source,
|
||
query,
|
||
)
|
||
return None
|
||
return stream_chat(
|
||
query,
|
||
user,
|
||
agent,
|
||
conversation_id,
|
||
session_id=session_id,
|
||
request_id=request_id,
|
||
keyword=keyword,
|
||
keyword_source=keyword_source,
|
||
result=result,
|
||
)
|
||
|
||
|
||
class MaintenanceChatService:
|
||
"""设备维保助手会话查询服务门面,供 chat.py 按统一 Service 风格调用。"""
|
||
|
||
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)
|