Spaces:
Sleeping

edi.chat.test / backend /src /models /Conversation.js
Claude Code Bot
Claude
Deploy edi.chat UGA AI Assistant to Hugging Face Spaces
0b355ec
Raw History Blame Contribute Delete
6.36 kB
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);