Spaces:
Sleeping
Sleeping
File size: 6,359 Bytes
0b355ec | 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 | const mongoose = require('mongoose');
const messageSchema = new mongoose.Schema({
role: {
type: String,
enum: ['user', 'assistant', 'system'],
required: true
},
content: {
type: String,
required: true
},
timestamp: {
type: Date,
default: Date.now
},
metadata: {
confidence: Number,
intent: String,
entities: [String],
ugaSystemUsed: String, // Track which UGA system was accessed
responseTime: Number // Time taken to generate response
}
});
const conversationSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
sessionId: {
type: String,
required: true
},
title: {
type: String,
default: 'New Conversation'
},
// Conversation metadata
category: {
type: String,
enum: [
'academic', 'administrative', 'technical-support',
'campus-life', 'financial', 'registration',
'grades', 'courses', 'general'
],
default: 'general'
},
messages: [messageSchema],
// UGA-specific context
ugaContext: {
semester: String,
academicYear: String,
coursesInvolved: [String],
systemsAccessed: [String] // Track which UGA systems were used
},
// Conversation state
isActive: {
type: Boolean,
default: true
},
lastActivity: {
type: Date,
default: Date.now
},
// Analytics
stats: {
messageCount: { type: Number, default: 0 },
totalTokens: { type: Number, default: 0 },
avgResponseTime: { type: Number, default: 0 },
userSatisfaction: {
rating: { type: Number, min: 1, max: 5 },
feedback: String
}
},
// Privacy and retention
retentionDate: {
type: Date,
default: function() {
// Default retention: 1 year from creation
const date = new Date();
date.setFullYear(date.getFullYear() + 1);
return date;
}
},
isArchived: {
type: Boolean,
default: false
}
}, {
timestamps: true
});
// Indexes for performance
conversationSchema.index({ userId: 1, createdAt: -1 });
conversationSchema.index({ sessionId: 1 });
conversationSchema.index({ category: 1 });
conversationSchema.index({ isActive: 1, lastActivity: -1 });
conversationSchema.index({ retentionDate: 1 }); // For cleanup jobs
// Virtual for message count
conversationSchema.virtual('messageCount').get(function() {
return this.messages.length;
});
// Method to add a message
conversationSchema.methods.addMessage = function(role, content, metadata = {}) {
const message = {
role,
content,
metadata,
timestamp: new Date()
};
this.messages.push(message);
this.stats.messageCount = this.messages.length;
this.lastActivity = new Date();
// Update conversation title based on first user message
if (role === 'user' && this.messages.length === 1) {
this.title = content.substring(0, 50) + (content.length > 50 ? '...' : '');
}
// Categorize conversation based on content
if (!this.category || this.category === 'general') {
this.category = this.categorizeContent(content);
}
return this.save();
};
// Method to categorize conversation content
conversationSchema.methods.categorizeContent = function(content) {
const lowerContent = content.toLowerCase();
if (lowerContent.includes('grade') || lowerContent.includes('gpa') || lowerContent.includes('transcript')) {
return 'grades';
} else if (lowerContent.includes('course') || lowerContent.includes('class') || lowerContent.includes('schedule')) {
return 'courses';
} else if (lowerContent.includes('register') || lowerContent.includes('enroll') || lowerContent.includes('drop')) {
return 'registration';
} else if (lowerContent.includes('elc') || lowerContent.includes('athena') || lowerContent.includes('myid')) {
return 'technical-support';
} else if (lowerContent.includes('financial') || lowerContent.includes('tuition') || lowerContent.includes('fee')) {
return 'financial';
} else if (lowerContent.includes('campus') || lowerContent.includes('dining') || lowerContent.includes('parking')) {
return 'campus-life';
} else if (lowerContent.includes('degree') || lowerContent.includes('graduation') || lowerContent.includes('academic')) {
return 'academic';
} else {
return 'general';
}
};
// Method to update statistics
conversationSchema.methods.updateStats = function(tokens = 0, responseTime = 0) {
this.stats.totalTokens += tokens;
if (responseTime > 0) {
const currentAvg = this.stats.avgResponseTime || 0;
const messageCount = this.stats.messageCount || 1;
this.stats.avgResponseTime = ((currentAvg * (messageCount - 1)) + responseTime) / messageCount;
}
return this.save();
};
// Method to set user satisfaction
conversationSchema.methods.setSatisfaction = function(rating, feedback = '') {
this.stats.userSatisfaction = { rating, feedback };
return this.save();
};
// Static method to find conversations by category
conversationSchema.statics.findByCategory = function(category, limit = 50) {
return this.find({ category, isActive: true })
.populate('userId', 'firstName lastName role')
.sort({ lastActivity: -1 })
.limit(limit);
};
// Static method to find recent conversations for a user
conversationSchema.statics.findRecentForUser = function(userId, limit = 10) {
return this.find({ userId, isActive: true })
.sort({ lastActivity: -1 })
.limit(limit);
};
// Static method for analytics
conversationSchema.statics.getAnalytics = function(startDate, endDate) {
return this.aggregate([
{
$match: {
createdAt: { $gte: startDate, $lte: endDate }
}
},
{
$group: {
_id: '$category',
count: { $sum: 1 },
avgMessageCount: { $avg: '$stats.messageCount' },
avgResponseTime: { $avg: '$stats.avgResponseTime' },
avgSatisfaction: { $avg: '$stats.userSatisfaction.rating' }
}
},
{
$sort: { count: -1 }
}
]);
};
// Clean up old conversations (for scheduled job)
conversationSchema.statics.cleanupExpired = function() {
const now = new Date();
return this.updateMany(
{ retentionDate: { $lt: now }, isArchived: false },
{ $set: { isArchived: true } }
);
};
module.exports = mongoose.model('Conversation', conversationSchema); |