330 lines
13 KiB
Python
330 lines
13 KiB
Python
"""
|
|
api/chat/sessions.py
|
|
|
|
用途:处理聊天会话、历史消息与本地结构化消息路由。
|
|
依赖:chat.shared、chat.core、ChatSession、ChatLog。
|
|
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from .shared import * # noqa: F403
|
|
from .shared import _normalize_user_attachments
|
|
from . import chat_bp
|
|
from .core import (
|
|
_chat_logs_for_session,
|
|
_ensure_chat_session,
|
|
_fallback_title_from_contract_review_log,
|
|
_get_chat_session,
|
|
_looks_like_review_auto_title,
|
|
_serialize_session,
|
|
_session_title_from_text,
|
|
_user_facing_chat_query,
|
|
)
|
|
|
|
|
|
@chat_bp.route('/sessions', methods=['GET'])
|
|
@require_agent_permission
|
|
def get_chat_sessions():
|
|
"""
|
|
获取当前用户与当前 Agent 的历史会话列表
|
|
"""
|
|
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 context', http_status=500)
|
|
|
|
session_rows = db.session.query(ChatSession).filter(
|
|
ChatSession.user_id == user.id,
|
|
ChatSession.agent_id == agent.id,
|
|
or_(
|
|
ChatSession.status == 'running',
|
|
exists().where(
|
|
and_(
|
|
ChatLog.session_id == ChatSession.session_id,
|
|
ChatLog.user_id == user.id,
|
|
ChatLog.agent_id == agent.id,
|
|
)
|
|
),
|
|
),
|
|
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
|
|
|
|
# 纠偏历史:审查结果卡曾把 headline 写成标题时,改用合同文件名展示
|
|
title_repaired = False
|
|
for item in session_rows:
|
|
if not _looks_like_review_auto_title(item.title or ''):
|
|
continue
|
|
review_log = (
|
|
db.session.query(ChatLog)
|
|
.filter(
|
|
ChatLog.user_id == user.id,
|
|
ChatLog.agent_id == agent.id,
|
|
ChatLog.message_type == 'procurement-contract-review',
|
|
or_(
|
|
ChatLog.session_id == item.session_id,
|
|
ChatLog.conversation_id == item.session_id,
|
|
),
|
|
)
|
|
.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
|
.first()
|
|
)
|
|
better = _fallback_title_from_contract_review_log(review_log)
|
|
if better:
|
|
item.title = better
|
|
title_repaired = True
|
|
if title_repaired:
|
|
db.session.commit()
|
|
|
|
sessions = [_serialize_session(item) for item in session_rows]
|
|
session_ids = {item['conversation_id'] for item in sessions}
|
|
|
|
# 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。
|
|
subquery = db.session.query(
|
|
ChatLog.conversation_id,
|
|
func.max(ChatLog.created_at).label('last_active')
|
|
).filter(
|
|
ChatLog.user_id == user.id,
|
|
ChatLog.agent_id == agent.id,
|
|
ChatLog.session_id.is_(None),
|
|
ChatLog.conversation_id.isnot(None),
|
|
ChatLog.conversation_id != '',
|
|
).group_by(ChatLog.conversation_id).subquery()
|
|
|
|
legacy_rows = db.session.query(
|
|
subquery.c.conversation_id,
|
|
subquery.c.last_active,
|
|
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
|
|
|
for row in legacy_rows:
|
|
if not row.conversation_id or row.conversation_id in session_ids:
|
|
continue
|
|
latest_query_row = db.session.query(ChatLog.query).filter(ChatLog.user_id == user.id, ChatLog.agent_id == agent.id, ChatLog.conversation_id == row.conversation_id, ChatLog.query.isnot(None), ChatLog.query != '').order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
|
|
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
|
|
sessions.append({
|
|
'id': 0,
|
|
'conversation_id': row.conversation_id,
|
|
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
|
|
'created_at': row.last_active.isoformat(),
|
|
'status': 'done',
|
|
})
|
|
|
|
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
|
return jsonify(sessions[:20])
|
|
|
|
@chat_bp.route('/sessions', methods=['DELETE'])
|
|
@require_agent_permission
|
|
def delete_all_chat_sessions():
|
|
"""
|
|
删除当前用户与当前 Agent 的所有历史会话
|
|
"""
|
|
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 context', http_status=500)
|
|
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
|
chat_log_ids = [log.id for log in chat_logs]
|
|
if chat_log_ids:
|
|
from app.models import GeneralFeedback
|
|
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
|
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
|
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
|
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
|
db.session.commit()
|
|
|
|
return jsonify({'status': 'ok'})
|
|
|
|
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
|
@require_agent_permission
|
|
def delete_chat_session(conversation_id):
|
|
"""
|
|
删除指定的会话记录
|
|
"""
|
|
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 context', http_status=500)
|
|
|
|
session = _get_chat_session(user.id, agent.id, conversation_id)
|
|
if session:
|
|
chat_logs = db.session.query(ChatLog).filter(
|
|
ChatLog.user_id == user.id,
|
|
ChatLog.agent_id == agent.id,
|
|
or_(
|
|
ChatLog.session_id == session.session_id,
|
|
ChatLog.conversation_id == session.external_conversation_id,
|
|
)
|
|
).all()
|
|
else:
|
|
chat_logs = db.session.query(ChatLog).filter_by(
|
|
user_id=user.id,
|
|
agent_id=agent.id,
|
|
conversation_id=conversation_id
|
|
).all()
|
|
|
|
chat_log_ids = [log.id for log in chat_logs]
|
|
if chat_log_ids:
|
|
from app.models import GeneralFeedback
|
|
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
|
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
|
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
|
if session:
|
|
db.session.delete(session)
|
|
db.session.commit()
|
|
|
|
return jsonify({'status': 'ok'})
|
|
|
|
@chat_bp.route('/messages', methods=['GET'])
|
|
@require_agent_permission
|
|
def get_chat_messages():
|
|
"""
|
|
获取指定会话的消息记录
|
|
"""
|
|
conversation_id = request.args.get('conversation_id')
|
|
if not conversation_id:
|
|
return jsonify([])
|
|
|
|
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
|
|
if session:
|
|
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
|
|
else:
|
|
logs = db.session.query(ChatLog).filter(
|
|
ChatLog.user_id == g.current_user.id,
|
|
ChatLog.agent_id == g.current_agent.id,
|
|
ChatLog.conversation_id == conversation_id,
|
|
).order_by(ChatLog.created_at.asc()).all()
|
|
|
|
messages = []
|
|
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
|
for log in logs:
|
|
raw_payload = log.payload if isinstance(log.payload, dict) else {}
|
|
user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments'))
|
|
assistant_payload = {
|
|
key: value
|
|
for key, value in raw_payload.items()
|
|
if key != 'user_attachments'
|
|
}
|
|
if log.query or user_attachments:
|
|
user_msg = {
|
|
'role': 'user',
|
|
'content': _user_facing_chat_query(log.query or '', agent_code=agent_code),
|
|
}
|
|
if user_attachments:
|
|
user_msg['attachments'] = user_attachments
|
|
messages.append(user_msg)
|
|
if (
|
|
not log.answer
|
|
and not log.message_type
|
|
and not assistant_payload
|
|
):
|
|
continue
|
|
if (
|
|
log.query
|
|
and log.answer == log.query
|
|
and (not log.message_type or log.message_type == 'text')
|
|
and not assistant_payload
|
|
):
|
|
continue
|
|
assistant_msg = {
|
|
'role': 'assistant',
|
|
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
|
'chat_log_id': log.id,
|
|
'retriever_resources': log.retriever_resources or [],
|
|
'attribution_parts': log.attribution_parts or [],
|
|
}
|
|
if log.run_id:
|
|
assistant_msg['run_id'] = log.run_id
|
|
if log.message_type:
|
|
assistant_msg['type'] = log.message_type
|
|
if assistant_payload:
|
|
assistant_msg['payload'] = assistant_payload
|
|
messages.append(assistant_msg)
|
|
return jsonify(messages)
|
|
|
|
@chat_bp.route('/messages/local', methods=['POST'])
|
|
@require_agent_permission
|
|
def save_local_message():
|
|
"""
|
|
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
|
|
|
|
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
|
|
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
|
|
"""
|
|
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 context', http_status=500)
|
|
data = request.get_json() or {}
|
|
conversation_id = (data.get('conversation_id') or '').strip()
|
|
role = (data.get('role') or 'assistant').strip()
|
|
message_type = data.get('type')
|
|
content = data.get('content', '')
|
|
payload = data.get('payload')
|
|
user_query = data.get('query', '')
|
|
if role == 'user':
|
|
user_query = user_query or content
|
|
content = ''
|
|
else:
|
|
# [STEP] 纯文本助手消息忽略误传的 query,避免与已落库用户气泡重复(见回归测试)
|
|
# 结构化结果卡必须保留 query,否则刷新后用户提问与历史标题都会丢失
|
|
if not message_type or message_type == 'text':
|
|
user_query = ''
|
|
|
|
if not message_type:
|
|
raise ValidationError('type is required')
|
|
|
|
title = user_query or content
|
|
external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None
|
|
session = _ensure_chat_session(
|
|
user.id,
|
|
agent.id,
|
|
conversation_id or None,
|
|
title=title,
|
|
status='done',
|
|
external_conversation_id=external_conversation_id,
|
|
)
|
|
conversation_id = session.session_id
|
|
# 纠偏:已有会话若误用审查 headline 作标题,有用户提问时改回提问摘要
|
|
if user_query and _looks_like_review_auto_title(session.title or ''):
|
|
session.title = _session_title_from_text(user_query)
|
|
|
|
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
|
# 这样能保证前端表单状态(例如已确认)被持久化
|
|
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
|
chat_log = None
|
|
if local_id:
|
|
# 在 payload 中查找是否已存在相同 formId 的同类型消息
|
|
# SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配
|
|
logs = db.session.query(ChatLog).filter_by(
|
|
user_id=user.id,
|
|
agent_id=agent.id,
|
|
session_id=conversation_id,
|
|
message_type=message_type
|
|
).order_by(ChatLog.created_at.desc()).limit(20).all()
|
|
|
|
for log in logs:
|
|
if log.payload and isinstance(log.payload, dict) and (log.payload.get('formId') == local_id):
|
|
chat_log = log
|
|
break
|
|
if chat_log:
|
|
chat_log.content = content
|
|
chat_log.answer = content
|
|
chat_log.payload = payload
|
|
if user_query and (not chat_log.query):
|
|
chat_log.query = user_query
|
|
else:
|
|
chat_log = ChatLog(
|
|
user_id=user.id,
|
|
agent_id=agent.id,
|
|
conversation_id=session.external_conversation_id or conversation_id,
|
|
session_id=conversation_id,
|
|
query=user_query,
|
|
answer=content,
|
|
message_type=message_type,
|
|
payload=payload
|
|
)
|
|
db.session.add(chat_log)
|
|
session.status = 'done'
|
|
session.last_active_at = datetime.utcnow()
|
|
session.updated_at = datetime.utcnow()
|
|
db.session.commit()
|
|
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|