118 lines
4.0 KiB
Python
118 lines
4.0 KiB
Python
# apps/common/services/chat_service.py
|
||
import logging
|
||
import json
|
||
from uuid import uuid4
|
||
from django.db import transaction
|
||
from apps.user.models import User
|
||
from apps.chat.models import ChatHistory
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
class ChatService:
|
||
@transaction.atomic
|
||
def create_chat_record(self, user, data, conversation_id=None):
|
||
"""创建聊天记录,供chat、gmail、feishu模块复用"""
|
||
try:
|
||
# 验证必填字段
|
||
if 'question' not in data:
|
||
raise ValueError("缺少必填字段: question")
|
||
|
||
# 如果未提供conversation_id,生成新的
|
||
if not conversation_id:
|
||
conversation_id = str(uuid4())
|
||
logger.info(f"生成新的会话ID: {conversation_id}")
|
||
|
||
# 创建metadata
|
||
metadata = {
|
||
'model_id': data.get('model_id', '7a214d0e-e65e-11ef-9f4a-0242ac120006'),
|
||
}
|
||
|
||
# 设置标题
|
||
title = data.get('title', 'New chat')
|
||
|
||
# 创建用户问题记录
|
||
question_record = ChatHistory.objects.create(
|
||
user=user,
|
||
knowledge_base_id="b680a4fa-37be-11f0-a7cb-0242ac120002", # 使用默认知识库ID
|
||
conversation_id=conversation_id,
|
||
title=title,
|
||
role='user',
|
||
content=data['question'],
|
||
metadata=metadata
|
||
)
|
||
|
||
return question_record, conversation_id, metadata, [], []
|
||
|
||
except Exception as e:
|
||
logger.error(f"创建聊天记录失败: {str(e)}")
|
||
raise
|
||
|
||
def get_conversation_detail(self, user, conversation_id):
|
||
"""获取会话详情,供chat、gmail、feishu模块复用"""
|
||
try:
|
||
# 查询会话记录
|
||
messages = ChatHistory.objects.filter(
|
||
conversation_id=conversation_id,
|
||
user=user,
|
||
is_deleted=False
|
||
).order_by('created_at')
|
||
|
||
if not messages.exists():
|
||
raise ValueError("对话不存在或无权限")
|
||
|
||
# 构建消息列表
|
||
message_list = [
|
||
{
|
||
'id': str(msg.id),
|
||
'parent_id': msg.parent_id,
|
||
'role': msg.role,
|
||
'content': msg.content,
|
||
'created_at': msg.created_at.strftime('%Y-%m-%d %H:%M:%S'),
|
||
'metadata': msg.metadata
|
||
}
|
||
for msg in messages
|
||
]
|
||
|
||
return {
|
||
'conversation_id': conversation_id,
|
||
'messages': message_list
|
||
}
|
||
|
||
except Exception as e:
|
||
logger.error(f"获取会话详情失败: {str(e)}")
|
||
raise
|
||
|
||
def can_user_access_conversation(self, user, conversation_id):
|
||
"""检查用户是否有权限访问指定的对话"""
|
||
return ChatHistory.objects.filter(
|
||
conversation_id=conversation_id,
|
||
user=user,
|
||
is_deleted=False
|
||
).exists()
|
||
|
||
def format_chat_response(self, chat_history_list):
|
||
"""格式化聊天历史记录为前端需要的格式"""
|
||
try:
|
||
result = []
|
||
|
||
for item in chat_history_list:
|
||
formatted_item = {
|
||
"id": str(item.id),
|
||
"conversation_id": str(item.conversation_id),
|
||
"role": item.role,
|
||
"content": item.content,
|
||
"created_at": item.created_at.strftime('%Y-%m-%d %H:%M:%S'),
|
||
"title": item.title
|
||
}
|
||
|
||
# 添加parent_id如果存在
|
||
if item.parent_id:
|
||
formatted_item["parent_id"] = str(item.parent_id)
|
||
|
||
result.append(formatted_item)
|
||
|
||
return result
|
||
except Exception as e:
|
||
logger.error(f"格式化聊天响应失败: {e}")
|
||
return []
|
||
|