daren/apps/chat/models.py
2025-05-23 19:25:35 +08:00

74 lines
2.6 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.

# apps/chat/models.py
from django.db import models
from django.utils import timezone
import uuid
from itertools import count
from apps.user.models import User
class ChatHistory(models.Model):
"""聊天历史记录"""
ROLE_CHOICES = [
('user', '用户'),
('assistant', 'AI助手'),
('system', '系统')
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
# 改为使用字符串字段而非外键关联
knowledge_base_id = models.CharField(max_length=100, default="b680a4fa-37be-11f0-a7cb-0242ac120002", help_text="知识库ID用于兼容原有结构")
# 用于标识知识库组合的对话
conversation_id = models.CharField(max_length=100, db_index=True)
# 对话标题
title = models.CharField(max_length=100, null=True, blank=True, default='New chat', help_text="对话标题")
parent_id = models.CharField(max_length=100, null=True, blank=True)
role = models.CharField(max_length=20, choices=ROLE_CHOICES)
content = models.TextField()
tokens = models.IntegerField(default=0, help_text="消息token数")
# 扩展metadata字段
metadata = models.JSONField(default=dict, blank=True, help_text="存储额外信息")
created_at = models.DateTimeField(auto_now_add=True)
is_deleted = models.BooleanField(default=False)
class Meta:
ordering = ['created_at']
indexes = [
models.Index(fields=['conversation_id', 'created_at']),
models.Index(fields=['user', 'created_at']),
models.Index(fields=['conversation_id', 'is_deleted']),
]
def __str__(self):
return f"{self.user.email} - {self.title} - {self.created_at}"
@classmethod
def get_conversation(cls, conversation_id):
"""获取完整对话历史"""
return cls.objects.filter(
conversation_id=conversation_id,
is_deleted=False
).order_by('created_at')
@classmethod
def get_conversations_by_user(cls, user):
"""根据用户获取对话历史"""
return cls.objects.filter(
user=user,
is_deleted=False
).order_by('created_at')
def soft_delete(self):
"""软删除消息"""
self.is_deleted = True
self.save()
def to_dict(self):
"""转换为字典格式"""
return {
'id': str(self.id),
'conversation_id': self.conversation_id,
'role': self.role,
'content': self.content,
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
'metadata': self.metadata
}