163 lines
5.1 KiB
Python
163 lines
5.1 KiB
Python
![]() |
import logging
|
|||
|
from datetime import datetime
|
|||
|
from apps.chat.models import ChatHistory
|
|||
|
from apps.common.services.ai_service import AIService
|
|||
|
import traceback
|
|||
|
from django.db.models import Q
|
|||
|
|
|||
|
|
|||
|
logger = logging.getLogger(__name__)
|
|||
|
|
|||
|
def get_conversation(conversation_id):
|
|||
|
"""
|
|||
|
获取给定对话ID的对话内容
|
|||
|
|
|||
|
参数:
|
|||
|
- conversation_id: 对话ID
|
|||
|
|
|||
|
返回:
|
|||
|
- 对话数据,包含消息列表,如无法获取则返回None
|
|||
|
"""
|
|||
|
try:
|
|||
|
# 获取对话消息
|
|||
|
messages = ChatHistory.objects.filter(
|
|||
|
conversation_id=conversation_id,
|
|||
|
is_deleted=False
|
|||
|
).order_by('created_at')
|
|||
|
|
|||
|
if not messages:
|
|||
|
logger.warning(f"对话 {conversation_id} 没有消息记录")
|
|||
|
return None
|
|||
|
|
|||
|
# 构造消息列表
|
|||
|
message_list = []
|
|||
|
for msg in messages:
|
|||
|
message_list.append({
|
|||
|
'id': str(msg.id),
|
|||
|
'content': msg.content,
|
|||
|
'is_user': msg.role == 'user',
|
|||
|
'timestamp': msg.created_at.isoformat(),
|
|||
|
'metadata': msg.metadata or {}
|
|||
|
})
|
|||
|
|
|||
|
# 获取对话标题
|
|||
|
title = messages.first().title if messages.exists() else "新对话"
|
|||
|
|
|||
|
return {
|
|||
|
'id': conversation_id,
|
|||
|
'title': title,
|
|||
|
'messages': message_list
|
|||
|
}
|
|||
|
|
|||
|
except Exception as e:
|
|||
|
logger.error(f"获取对话时发生错误: {str(e)}")
|
|||
|
logger.error(traceback.format_exc())
|
|||
|
return None
|
|||
|
|
|||
|
def get_conversation_summary(conversation_id):
|
|||
|
"""
|
|||
|
获取对话摘要
|
|||
|
|
|||
|
Args:
|
|||
|
conversation_id: 对话ID
|
|||
|
|
|||
|
Returns:
|
|||
|
str: 摘要内容或None
|
|||
|
"""
|
|||
|
try:
|
|||
|
# 获取对话消息
|
|||
|
chat_history = ChatHistory.objects.filter(
|
|||
|
conversation_id=conversation_id,
|
|||
|
is_deleted=False
|
|||
|
).order_by('-created_at')[:5]
|
|||
|
|
|||
|
if not chat_history:
|
|||
|
return None
|
|||
|
|
|||
|
# 生成简单摘要(最近几条消息)
|
|||
|
messages = []
|
|||
|
for msg in chat_history:
|
|||
|
if len(messages) < 3: # 只取最新的3条
|
|||
|
role = "用户" if msg.role == "user" else "助手"
|
|||
|
content = msg.content
|
|||
|
if len(content) > 100:
|
|||
|
content = content[:100] + "..."
|
|||
|
messages.append(f"{role}: {content}")
|
|||
|
|
|||
|
if messages:
|
|||
|
return "最近对话: " + " | ".join(reversed(messages))
|
|||
|
|
|||
|
# 如果简单摘要方式不行,可以通过AI服务生成摘要
|
|||
|
conversation_data = get_conversation(conversation_id)
|
|||
|
if conversation_data and conversation_data.get('messages'):
|
|||
|
# 将消息数据转换为AI服务需要的格式
|
|||
|
conv_messages = []
|
|||
|
for msg in conversation_data['messages']:
|
|||
|
conv_messages.append({
|
|||
|
'content': msg['content'],
|
|||
|
'is_from_user': msg['is_user']
|
|||
|
})
|
|||
|
|
|||
|
# 调用AI服务生成摘要
|
|||
|
summary, error = AIService.generate_conversation_summary(conv_messages)
|
|||
|
if not error and summary:
|
|||
|
return summary
|
|||
|
|
|||
|
return None
|
|||
|
except Exception as e:
|
|||
|
logger.error(f"获取对话摘要失败: {str(e)}")
|
|||
|
logger.error(traceback.format_exc())
|
|||
|
return None
|
|||
|
|
|||
|
def get_last_message(conversation_id):
|
|||
|
"""
|
|||
|
获取给定对话的最后一条消息
|
|||
|
|
|||
|
参数:
|
|||
|
- conversation_id: 对话ID
|
|||
|
|
|||
|
返回:
|
|||
|
- 最后一条消息文本,如果无法获取则返回None
|
|||
|
"""
|
|||
|
try:
|
|||
|
# 获取对话消息
|
|||
|
chat_messages = ChatHistory.objects.filter(
|
|||
|
conversation_id=conversation_id,
|
|||
|
is_deleted=False
|
|||
|
).order_by('created_at')
|
|||
|
|
|||
|
if not chat_messages:
|
|||
|
logger.warning(f"对话 {conversation_id} 没有消息记录")
|
|||
|
return None
|
|||
|
|
|||
|
# 过滤出助手发送的消息
|
|||
|
assistant_messages = [msg for msg in chat_messages if msg.role == 'assistant']
|
|||
|
|
|||
|
if not assistant_messages:
|
|||
|
logger.warning(f"对话 {conversation_id} 中没有助手发送的消息")
|
|||
|
return None
|
|||
|
|
|||
|
# 返回最后一条助手消息
|
|||
|
last_message = assistant_messages[-1].content
|
|||
|
return last_message
|
|||
|
|
|||
|
except Exception as e:
|
|||
|
logger.error(f"获取最后一条消息时发生错误: {str(e)}")
|
|||
|
logger.error(traceback.format_exc())
|
|||
|
return None
|
|||
|
|
|||
|
def generate_recommended_reply(user, goal_description, conversation_summary, last_message):
|
|||
|
"""
|
|||
|
根据用户目标、对话摘要和最后一条消息生成推荐话术
|
|||
|
|
|||
|
Args:
|
|||
|
user: 用户对象
|
|||
|
goal_description: 用户目标描述
|
|||
|
conversation_summary: 对话摘要
|
|||
|
last_message: 助手最后发送的消息内容
|
|||
|
|
|||
|
Returns:
|
|||
|
tuple: (推荐话术内容, 错误信息)
|
|||
|
"""
|
|||
|
# 直接调用AIService生成回复
|
|||
|
return AIService.generate_email_reply(goal_description, conversation_summary, last_message)
|