only the two most recent messages for context

galleryApi
Kar 2024-11-11 12:27:23 +05:30
parent 5e23f73645
commit 02ec79b262
1 changed files with 65 additions and 57 deletions

View File

@ -1,5 +1,4 @@
const aiFollowupQuestion = async (req, res) => {
const { MongoClient } = require('mongodb');
const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
@ -29,7 +28,6 @@ const aiFollowupQuestion = async (req, res) => {
return data;
}
try {
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 200 } = req.body;
if (!conversationsCollection) {
@ -38,11 +36,13 @@ const aiFollowupQuestion = async (req, res) => {
error: 'MongoDB is not connected yet. Please try again later.',
});
}
let conversation;
if (!sessionId) {
const newSessionId = uuidv4();
// New conversation, start with system and user message
conversation = {
sessionId: newSessionId,
conversationHistory: [
@ -52,6 +52,7 @@ const aiFollowupQuestion = async (req, res) => {
};
await conversationsCollection.insertOne(conversation);
} else {
// Existing conversation, find it by sessionId
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
if (!conversation) {
return res.status(400).json({
@ -59,13 +60,22 @@ const aiFollowupQuestion = async (req, res) => {
error: 'Invalid session ID.',
});
}
// Keep only the last 2 messages (1 user and 1 assistant)
conversation.conversationHistory.push({ role: 'user', content: prompt });
// Limit conversation history to the last two entries: one user, one assistant
const lastTwoMessages = conversation.conversationHistory.slice(-2);
conversation.conversationHistory = lastTwoMessages;
}
// Fetch AI response based on the last two messages (user + assistant)
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
// Add the AI response to conversation history
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices[0].message.content });
// Update conversation in the database with new history
await conversationsCollection.updateOne(
{ sessionId: conversation.sessionId },
{ $set: { conversationHistory: conversation.conversationHistory } }
@ -84,8 +94,6 @@ const aiFollowupQuestion = async (req, res) => {
error: 'Something went wrong. Please try again later.',
});
}
}
}
module.exports = aiFollowupQuestion;
module.exports = aiFollowupQuestion;