Spaces:
Runtime error
Runtime error
File size: 8,561 Bytes
0ad3564 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | """
Core models that map to existing FastAPI database tables.
These are 'unmanaged' models - Django reads from them but doesn't create/modify tables.
"""
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.contrib.auth.hashers import make_password, check_password
class UserManager(BaseUserManager):
"""Custom manager for shared FastAPI/Django users."""
use_in_migrations = False
def get_by_natural_key(self, username):
return self.get(username=username)
def create_user(self, username, email, password=None, **extra_fields):
if not username:
raise ValueError("Username is required")
if not email:
raise ValueError("Email is required")
email = self.normalize_email(email)
user = self.model(
username=username,
email=email,
**extra_fields
)
if password:
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
extra_fields.setdefault("is_active", True)
return self.create_user(
username,
email,
password,
**extra_fields
)
class User(AbstractBaseUser, PermissionsMixin):
"""
User model mapping to FastAPI's users table.
"""
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=150, unique=True)
email = models.EmailField(unique=True)
hashed_password = models.CharField(max_length=255, db_column='hashed_password')
role = models.CharField(max_length=50, default='user')
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(default=timezone.now)
# Django admin fields
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
managed = False # Don't let Django manage this table
db_table = 'users'
ordering = ['-created_at']
def __str__(self):
return self.username
# -------------------------
# Django compatibility only
# -------------------------
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_username(self):
return self.username
# -------------------------
# Password helpers
# -------------------------
def set_password(self, raw_password):
self.hashed_password = make_password(raw_password)
def check_password(self, raw_password):
return check_password(raw_password, self.hashed_password)
def save(self, *args, **kwargs):
"""Override save to handle password hashing."""
# If password was set directly, hash it
if hasattr(self, '_password_to_hash'):
self.set_password(self._password_to_hash)
delattr(self, '_password_to_hash')
super().save(*args, **kwargs)
class Conversation(models.Model):
id = models.AutoField(primary_key=True) # Changed from CharField to AutoField
user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id', related_name='conversations')
title = models.CharField(max_length=255, default="New Conversation")
model_name = models.CharField(max_length=50)
metadata_json = models.TextField(null=True, blank=True) # Matches SQLAlchemy Text column
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
managed = False
db_table = 'conversations'
ordering = ['-updated_at']
def __str__(self):
return f"{self.title or 'Untitled'} - User {self.user_id}"
class Message(models.Model):
id = models.AutoField(primary_key=True)
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, db_column='conversation_id', related_name='messages')
role = models.CharField(max_length=20) # user, assistant, system
content = models.TextField()
metadata_json = models.TextField(null=True, blank=True)
prompt_tokens = models.IntegerField(null=True, blank=True)
completion_tokens = models.IntegerField(null=True, blank=True)
total_tokens = models.IntegerField(null=True, blank=True)
created_at = models.DateTimeField(default=timezone.now)
class Meta:
managed = False
db_table = 'messages'
def __str__(self):
return f"{self.role}: {self.content[:50]}..."
class RAGCollection:
"""
Virtual model - NOT DB backed.
Collections are derived from document_embeddings.
"""
def __init__(self, name, document_count=0):
self.name = name
self.document_count = document_count
self.status = "active"
class RAGSource(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id')
collection_name = models.CharField(max_length=255)
source_type = models.CharField(max_length=50) # manual, github
source_identifier = models.CharField(max_length=500)
display_name = models.CharField(max_length=255)
auto_sync = models.BooleanField(default=False)
sync_interval_hours = models.IntegerField(default=24)
last_sync_at = models.DateTimeField(null=True, blank=True)
last_sync_status = models.CharField(max_length=50, default='pending')
last_sync_error = models.CharField(max_length=1000, null=True, blank=True)
total_files = models.IntegerField(default=0)
total_chunks = models.IntegerField(default=0)
last_commit_sha = models.CharField(max_length=255, null=True, blank=True)
config = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
managed = False
db_table = 'rag_sources'
def __str__(self):
return f"{self.source_type}: {self.source_url}"
class Agent(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
agent_type = models.CharField(max_length=50) # order_taking, appointment_booking, etc.
description = models.TextField(null=True, blank=True)
status = models.CharField(max_length=20, default='draft') # active, inactive, draft
user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id') # Fixed from created_by_id
config = models.TextField(null=True, blank=True)
welcome_message = models.TextField(null=True, blank=True)
completion_message = models.TextField(null=True, blank=True)
error_message = models.TextField(null=True, blank=True)
max_retries = models.IntegerField(default=3)
timeout_minutes = models.IntegerField(default=30)
enable_fallback_human = models.BooleanField(default=False)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
managed = False
db_table = 'agents'
def __str__(self):
return self.name
class AgentSession(models.Model):
id = models.AutoField(primary_key=True)
agent = models.ForeignKey(Agent, on_delete=models.CASCADE, db_column='agent_id')
conversation = models.ForeignKey(Conversation, on_delete=models.SET_NULL, null=True, db_column='conversation_id')
user_id = models.IntegerField(null=True, blank=True)
status = models.CharField(max_length=20, default='in_progress') # Match SQLAlchemy enum: in_progress
current_step = models.CharField(max_length=100, null=True, blank=True)
collected_data = models.TextField(null=True, blank=True)
retry_count = models.IntegerField(default=0)
started_at = models.DateTimeField(default=timezone.now)
completed_at = models.DateTimeField(null=True, blank=True)
last_activity_at = models.DateTimeField(default=timezone.now)
metadata = models.TextField(null=True, blank=True, db_column='metadata')
class Meta:
managed = False
db_table = 'agent_sessions'
def __str__(self):
return f"Session {self.id} - Agent {self.agent_id}"
|