Spaces:
Sleeping

File size: 6,795 Bytes
7851df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
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);