@peopl-health/nexus 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  const llmConfig = require('../config/llmConfig');
2
2
  const { Thread } = require('../models/threadModel');
3
- const { getLastNMessages } = require('../helpers/assistantHelper');
3
+ const { Message } = require('../models/messageModel');
4
+ const { formatMessage } = require('../helpers/assistantHelper');
4
5
  const { createProvider } = require('../providers/createProvider');
5
6
 
6
7
  const DEFAULT_MAX_HISTORICAL_MESSAGES = parseInt(process.env.MAX_HISTORICAL_MESSAGES || '50', 10);
@@ -165,11 +166,6 @@ class BaseAssistant {
165
166
  this._ensureClient();
166
167
  this.status = 'active';
167
168
 
168
- const whatsappId = context?.whatsapp_id || code;
169
- if (whatsappId) {
170
- this.lastMessages = await getLastNMessages(whatsappId, DEFAULT_MAX_HISTORICAL_MESSAGES);
171
- }
172
-
173
169
  const provider = createProvider({ variant: process.env.VARIANT || 'assistants' });
174
170
  if (!provider || typeof provider.createConversation !== 'function') {
175
171
  throw new Error('Provider not configured. Cannot create conversation.');
@@ -189,12 +185,39 @@ class BaseAssistant {
189
185
  return this.thread;
190
186
  }
191
187
 
192
- async buildInitialMessages({ code }) {
193
- if (!this.lastMessages) return [];
194
- return [{
195
- role: 'assistant',
196
- content: `Últimos mensajes para ${code}: \n${this.lastMessages}`
197
- }];
188
+ async buildInitialMessages({ code, context = {} }) {
189
+ const whatsappId = context?.whatsapp_id || code;
190
+ if (!whatsappId) {
191
+ return [];
192
+ }
193
+
194
+ try {
195
+ const lastMessages = await Message.find({ numero: whatsappId })
196
+ .sort({ createdAt: -1 })
197
+ .limit(DEFAULT_MAX_HISTORICAL_MESSAGES);
198
+
199
+ if (!lastMessages || lastMessages.length === 0) {
200
+ return [];
201
+ }
202
+
203
+ const messagesInOrder = lastMessages.reverse();
204
+
205
+ // Messages with from_me: true are assistant messages, from_me: false are user messages
206
+ const formattedMessages = messagesInOrder
207
+ .filter(message => message && message.timestamp && message.body && message.body.trim() !== '')
208
+ .map(message => {
209
+ const formattedText = formatMessage(message);
210
+ return formattedText ? { role: message.from_me ? 'assistant' : 'user', content: formattedText } : null;
211
+ })
212
+ .filter(message => message !== null); // Remove any null entries
213
+
214
+ console.log(`[buildInitialMessages] Built ${formattedMessages.length} initial messages for ${code}`);
215
+
216
+ return formattedMessages;
217
+ } catch (error) {
218
+ console.error('[buildInitialMessages] Error fetching messages:', error);
219
+ return [];
220
+ }
198
221
  }
199
222
 
200
223
  async close() {
@@ -6,7 +6,7 @@ async function logBugReportToAirtable(reporter, whatsapp_id, description, severi
6
6
  try {
7
7
  let conversation = null;
8
8
  if (messageIds && messageIds.length > 0) {
9
- const messageObjects = await Message.find({ _id: { $in: messageIds } }).sort({ timestamp: 1 });
9
+ const messageObjects = await Message.find({ _id: { $in: messageIds } }).sort({ createdAt: 1 });
10
10
  conversation = messageObjects.map(msg => {
11
11
  const timestamp = new Date(msg.timestamp).toISOString().slice(0, 16).replace('T', ' ');
12
12
  const role = msg.from_me ? 'Assistant' : 'Patient';
@@ -409,14 +409,14 @@ const getConversationsByNameController = async (req, res) => {
409
409
  try {
410
410
  const conversations = await Message.aggregate([
411
411
  { $match: { from_me: false, is_group: false } },
412
- { $sort: { timestamp: -1 } },
412
+ { $sort: { createdAt: -1 } },
413
413
  { $group: {
414
414
  _id: '$numero',
415
415
  name: { $first: '$nombre_whatsapp' },
416
416
  latestMessage: { $first: '$$ROOT' },
417
417
  messageCount: { $sum: 1 }
418
418
  }},
419
- { $sort: { 'latestMessage.timestamp': -1 } }
419
+ { $sort: { 'latestMessage.createdAt': -1 } }
420
420
  ]);
421
421
 
422
422
  res.status(200).json({
@@ -48,7 +48,7 @@ async function getLastMessages(code) {
48
48
  query.is_group = false;
49
49
  }
50
50
 
51
- const lastMessages = await Message.find(query).sort({ timestamp: -1 });
51
+ const lastMessages = await Message.find(query).sort({ createdAt: -1 });
52
52
  console.log('[getLastMessages] lastMessages', lastMessages.map(msg => msg.body).join('\n\n'));
53
53
 
54
54
  if (lastMessages.length === 0) return [];
@@ -73,7 +73,7 @@ async function getLastMessages(code) {
73
73
  async function getLastNMessages(code, n) {
74
74
  try {
75
75
  const lastMessages = await Message.find({ numero: code })
76
- .sort({ timestamp: -1 })
76
+ .sort({ createdAt: -1 })
77
77
  .limit(n);
78
78
 
79
79
  // Format each message and concatenate them with skip lines
@@ -110,15 +110,15 @@ async function isRecentMessage(chatId) {
110
110
 
111
111
  const recentMessage = await Message.find({
112
112
  $or: [{ group_id: chatId }, { numero: chatId }],
113
- timestamp: { $gte: fiveMinutesAgo.toISOString() }
114
- }).sort({ timestamp: -1 }).limit(1);
113
+ createdAt: { $gte: fiveMinutesAgo }
114
+ }).sort({ createdAt: -1 }).limit(1);
115
115
 
116
116
  return !!recentMessage;
117
117
  }
118
118
 
119
119
  async function getLastMessages(chatId, n) {
120
120
  const messages = await Message.find({ group_id: chatId })
121
- .sort({ timestamp: -1 })
121
+ .sort({ createdAt: -1 })
122
122
  .limit(n)
123
123
  .select('timestamp numero nombre_whatsapp body');
124
124
 
@@ -70,8 +70,8 @@ async function isRecentMessage(chatId) {
70
70
 
71
71
  const recentMessage = await Message.find({
72
72
  $or: [{ group_id: chatId }, { numero: chatId }],
73
- timestamp: { $gte: fiveMinutesAgo.toISOString() }
74
- }).sort({ timestamp: -1 }).limit(1);
73
+ createdAt: { $gte: fiveMinutesAgo }
74
+ }).sort({ createdAt: -1 }).limit(1);
75
75
 
76
76
  return !!recentMessage;
77
77
  }
@@ -79,7 +79,7 @@ async function isRecentMessage(chatId) {
79
79
 
80
80
  async function getLastMessages(chatId, n) {
81
81
  const messages = await Message.find({ numero: chatId })
82
- .sort({ timestamp: -1 })
82
+ .sort({ createdAt: -1 })
83
83
  .limit(n)
84
84
  .select('timestamp numero nombre_whatsapp body');
85
85
 
@@ -57,6 +57,7 @@ const messageSchema = new mongoose.Schema({
57
57
  }, { timestamps: true });
58
58
 
59
59
  messageSchema.index({ message_id: 1, timestamp: 1 }, { unique: true });
60
+ messageSchema.index({ numero: 1, createdAt: -1 });
60
61
 
61
62
  messageSchema.pre('save', function (next) {
62
63
  if (this.timestamp) {
@@ -157,7 +158,10 @@ function getMessageValues(message, content, reply, is_media) {
157
158
 
158
159
  async function getContactDisplayName(contactNumber) {
159
160
  try {
160
- const latestMessage = await Message.findOne({ numero: contactNumber })
161
+ const latestMessage = await Message.findOne({
162
+ numero: contactNumber,
163
+ from_me: false
164
+ })
161
165
  .sort({ createdAt: -1 })
162
166
  .select('nombre_whatsapp');
163
167
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",