iimtt-api/src/routes/api/aiFollowupQuestion.js

124 lines
3.9 KiB
JavaScript

const aiFollowupQuestion = async (req, res) => {
// curl -X POST http://localhost:3000/your-endpoint-path \
// -H "Content-Type: application/json" \
// -d '{
// "prompt": "Why is the sky blue?",
// "sessionId": "",
// "model": "gpt-3.5-turbo-16k",
// "max_tokens": 200
// }'
// curl -X POST http://localhost:5174/api/aiFollowupQuestion \
// -H "Content-Type: application/json" \
// -d '{
// "prompt": "Why is the sky blue?",
// "sessionId": "",
// "model": "gpt-3.5-turbo-16k",
// "sessionId" : "8c641aca-582d-4ea7-8e56-4f94318efe74",
// "max_tokens": 200
// }'
// {
// "success": true,
// "data": "The sky looks blue because of how sunlight scatters in the air. Great question! Ask me more!",
// "total_tokens": 45,
// "sessionId": "2a3b3cc4-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
// }
const { MongoClient } = require('mongodb');
// const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
const url = process.env.MONGODB_URL;
const dbName = process.env.MONGO_DB_NAME;
const client = new MongoClient(url);
await client.connect();
const database = client.db(dbName);
const conversationsCollection = database.collection('conversations');
async function fetchOpenAICompletion(prompt, messages, model = 'gpt-3.5-turbo-16k', max_tokens = 200) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.OPENAI_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: model,
messages: messages,
// messages: [
// { role: "system", content: "reply must not exceed 20 words" },
// { role: "user", content: messages }
// ],
max_tokens: max_tokens,
}),
});
const data = await response.json();
// console.log(process.env.OPENAI_KEY)
// console.log(data)
return data;
}
try {
const { prompt, sessionId, model = 'gpt-3.5-turbo-16k', max_tokens = 200 } = req.body;
if (!conversationsCollection) {
return res.status(500).json({
success: false,
error: 'MongoDB is not connected yet. Please try again later.',
});
}
let conversation;
if (!sessionId) {
const newSessionId = uuidv4();
conversation = {
sessionId: newSessionId,
conversationHistory: [
{
role: 'system',
content:
'Reply to the questions asked by a kindergarten child, Sound excited to answer and encourage the child to ask more questions in 30 words',
},
{ role: 'user', content: prompt },
],
};
await conversationsCollection.insertOne(conversation);
} else {
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
if (!conversation) {
return res.status(400).json({
success: false,
error: 'Invalid session ID.',
});
}
conversation.conversationHistory.push({ role: 'user', content: prompt });
}
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices[0].message.content });
await conversationsCollection.updateOne(
{ sessionId: conversation.sessionId },
{ $set: { conversationHistory: conversation.conversationHistory } }
);
res.json({
success: true,
data: aiResponse.choices[0].message.content,
total_tokens: aiResponse.usage.total_tokens,
sessionId: conversation.sessionId,
});
} catch (error) {
console.error('Error generating response:', error.message);
res.status(500).json({
success: false,
error: 'Something went wrong. Please try again later.',
});
}
};
module.exports = aiFollowupQuestion;