Spaces:
Sleeping

edi.chat.test / backend /src /models /ChatHistory.js
Claude Code Bot
Fix AI responses - implement direct Ollama integration with no fallbacks
7851df6
Raw History Blame Contribute Delete
6.8 kB
const mongoose = require('mongoose');
const chatHistorySchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
index: true
},
sessionId: {
type: String,
required: true,
index: true
},
// Chat metadata
title: {
type: String,
default: 'New Chat',
maxlength: 100
},
tags: [String], // e.g., ['homework', 'schedule', 'uga-info']
// Messages array
messages: [{
role: {
type: String,
enum: ['user', 'assistant', 'system'],
required: true
},
content: {
type: String,
required: true
},
timestamp: {
type: Date,
default: Date.now
},
metadata: {
model: String, // which AI model was used
tokens: Number,
responseTime: Number, // ms
hasWebSearch: Boolean,
searchQueries: [String],
confidence: Number,
provider: {
type: String,
enum: ['ollama', 'openai', 'huggingface', 'local'],
default: 'ollama'
}
}
}],
// Chat session info
startTime: {
type: Date,
default: Date.now
},
lastMessage: {
type: Date,
default: Date.now
},
messageCount: {
type: Number,
default: 0
},
// AI interaction tracking
aiModel: {
type: String,
default: 'llama3'
},
totalTokens: {
type: Number,
default: 0
},
webSearchUsed: {
type: Boolean,
default: false
},
// Status and organization
isArchived: {
type: Boolean,
default: false
},
isFavorite: {
type: Boolean,
default: false
},
category: {
type: String,
enum: ['academic', 'personal', 'research', 'help', 'dining', 'events', 'housing', 'other'],
default: 'other'
},
// Analytics
totalDuration: {
type: Number, // milliseconds
default: 0
},
avgResponseTime: {
type: Number, // milliseconds
default: 0
}
}, {
timestamps: true
});
// Enhanced compound indexes for efficient querying
chatHistorySchema.index({ userId: 1, lastMessage: -1 });
chatHistorySchema.index({ userId: 1, category: 1, lastMessage: -1 });
chatHistorySchema.index({ userId: 1, tags: 1 });
chatHistorySchema.index({ userId: 1, isArchived: 1, lastMessage: -1 });
chatHistorySchema.index({ sessionId: 1, userId: 1 });
// Text search index for messages
chatHistorySchema.index({
title: 'text',
'messages.content': 'text',
tags: 'text'
});
// Virtual for formatted duration
chatHistorySchema.virtual('duration').get(function() {
if (this.lastMessage && this.startTime) {
return this.lastMessage - this.startTime;
}
return 0;
});
// Method to add a message
chatHistorySchema.methods.addMessage = function(role, content, metadata = {}) {
const timestamp = new Date();
this.messages.push({
role,
content,
timestamp,
metadata
});
this.lastMessage = timestamp;
this.messageCount = this.messages.length;
// Auto-generate title from first user message
if (!this.title || this.title === 'New Chat') {
if (role === 'user' && content.length > 0) {
this.title = content.substring(0, 50) + (content.length > 50 ? '...' : '');
}
}
// Update token count
if (metadata.tokens) {
this.totalTokens += metadata.tokens;
}
// Track web search usage
if (metadata.hasWebSearch) {
this.webSearchUsed = true;
}
// Update analytics
this.updateAnalytics();
return this.save();
};
// Method to update analytics
chatHistorySchema.methods.updateAnalytics = function() {
if (this.lastMessage && this.startTime) {
this.totalDuration = this.lastMessage - this.startTime;
}
// Calculate average response time
const responseTimes = this.messages
.filter(msg => msg.role === 'assistant' && msg.metadata && msg.metadata.responseTime)
.map(msg => msg.metadata.responseTime);
if (responseTimes.length > 0) {
this.avgResponseTime = responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length;
}
};
// Static method to get user's recent chats
chatHistorySchema.statics.getRecentChats = function(userId, limit = 10) {
return this.find({ userId, isArchived: false })
.sort({ lastMessage: -1 })
.limit(limit)
.select('title lastMessage messageCount category tags isFavorite totalDuration avgResponseTime');
};
// Static method to search chats
chatHistorySchema.statics.searchChats = function(userId, query, options = {}) {
const searchCriteria = {
userId,
$or: [
{ title: { $regex: query, $options: 'i' } },
{ tags: { $regex: query, $options: 'i' } },
{ 'messages.content': { $regex: query, $options: 'i' } }
]
};
if (options.category) {
searchCriteria.category = options.category;
}
if (options.isArchived !== undefined) {
searchCriteria.isArchived = options.isArchived;
}
if (options.startDate || options.endDate) {
searchCriteria.lastMessage = {};
if (options.startDate) searchCriteria.lastMessage.$gte = options.startDate;
if (options.endDate) searchCriteria.lastMessage.$lte = options.endDate;
}
return this.find(searchCriteria)
.sort({ lastMessage: -1 })
.limit(options.limit || 20);
};
// Static method to get chat statistics for a user
chatHistorySchema.statics.getUserChatStats = function(userId) {
return this.aggregate([
{ $match: { userId: mongoose.Types.ObjectId(userId) } },
{
$group: {
_id: null,
totalChats: { $sum: 1 },
totalMessages: { $sum: '$messageCount' },
totalTokens: { $sum: '$totalTokens' },
avgMessagesPerChat: { $avg: '$messageCount' },
totalTimeSpent: { $sum: '$totalDuration' },
categoryCounts: {
$push: '$category'
}
}
},
{
$project: {
_id: 0,
totalChats: 1,
totalMessages: 1,
totalTokens: 1,
avgMessagesPerChat: { $round: ['$avgMessagesPerChat', 1] },
totalTimeSpent: 1,
categoryCounts: 1
}
}
]);
};
// Static method to get user's favorite chats
chatHistorySchema.statics.getFavoriteChats = function(userId, limit = 10) {
return this.find({ userId, isFavorite: true })
.sort({ lastMessage: -1 })
.limit(limit)
.select('title lastMessage messageCount category tags totalDuration');
};
// Instance method to mark as favorite
chatHistorySchema.methods.toggleFavorite = function() {
this.isFavorite = !this.isFavorite;
return this.save();
};
// Instance method to archive
chatHistorySchema.methods.archive = function() {
this.isArchived = true;
return this.save();
};
// Instance method to unarchive
chatHistorySchema.methods.unarchive = function() {
this.isArchived = false;
return this.save();
};
module.exports = mongoose.model('ChatHistory', chatHistorySchema);