total_tokens
parent
5775c45d8c
commit
2cbf1ebbaa
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "iimttapi",
|
"name": "iimttapi",
|
||||||
"version": "0.0.1",
|
"version": "1.0.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "iimttapi",
|
"name": "iimttapi",
|
||||||
"version": "0.0.1",
|
"version": "1.0.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"aws-sdk": "^2.1669.0",
|
"aws-sdk": "^2.1669.0",
|
||||||
|
|
|
@ -24,7 +24,7 @@
|
||||||
"docker:dev": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
|
"docker:dev": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
|
||||||
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up",
|
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up",
|
||||||
"prepare": "husky install"
|
"prepare": "husky install"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"node",
|
"node",
|
||||||
"node.js",
|
"node.js",
|
||||||
|
|
|
@ -1,94 +1,91 @@
|
||||||
const aiFollowupQuestion = async (req, res) => {
|
const aiFollowupQuestion = async (req, res) => {
|
||||||
|
|
||||||
const { MongoClient } = require('mongodb');
|
const { MongoClient } = require('mongodb');
|
||||||
const fetch = require('node-fetch');
|
const fetch = require('node-fetch');
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require('uuid');
|
||||||
const url = process.env.MONGODB_URL;
|
const url = process.env.MONGODB_URL;
|
||||||
const dbName = process.env.MONGO_DB_NAME;
|
const dbName = process.env.MONGO_DB_NAME;
|
||||||
const client = new MongoClient(url);
|
const client = new MongoClient(url);
|
||||||
|
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const database = client.db(dbName); // Replace with your database name
|
const database = client.db(dbName);
|
||||||
const conversationsCollection = database.collection('conversations'); // Replace with your collection name
|
const conversationsCollection = database.collection('conversations');
|
||||||
|
|
||||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-4o-mini", max_tokens = 200) {
|
async function fetchOpenAICompletion(prompt, messages, model = "gpt-4o-mini", max_tokens = 200) {
|
||||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
|
'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
model: model,
|
model: model,
|
||||||
messages: messages,
|
messages: messages,
|
||||||
max_tokens: max_tokens,
|
max_tokens: max_tokens,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data.choices[0].message.content;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 200 } = req.body;
|
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 200 } = req.body;
|
||||||
if (!conversationsCollection) {
|
if (!conversationsCollection) {
|
||||||
return res.status(500).json({
|
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: 'You are a helpful assistant.' },
|
|
||||||
{ role: 'user', content: prompt },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
await conversationsCollection.insertOne(conversation);
|
|
||||||
} else {
|
|
||||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
|
||||||
if (!conversation) {
|
|
||||||
return res.status(400).json({
|
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Invalid session ID.',
|
error: 'MongoDB is not connected yet. Please try again later.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
let conversation;
|
||||||
|
|
||||||
|
if (!sessionId) {
|
||||||
|
const newSessionId = uuidv4();
|
||||||
|
|
||||||
|
conversation = {
|
||||||
|
sessionId: newSessionId,
|
||||||
|
conversationHistory: [
|
||||||
|
{ role: 'system', content: 'answer within 50 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.',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call OpenAI API with the conversation history
|
|
||||||
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
|
||||||
|
|
||||||
// Add the AI's response to the conversation history
|
|
||||||
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse });
|
|
||||||
|
|
||||||
// Update the conversation in MongoDB
|
|
||||||
await conversationsCollection.updateOne(
|
|
||||||
{ sessionId: conversation.sessionId },
|
|
||||||
{ $set: { conversationHistory: conversation.conversationHistory } }
|
|
||||||
);
|
|
||||||
|
|
||||||
// Send the AI's response and session ID back to the frontend
|
|
||||||
res.json({
|
|
||||||
success: true,
|
|
||||||
data: aiResponse,
|
|
||||||
sessionId: conversation.sessionId, // Return the session ID for subsequent queries
|
|
||||||
});
|
|
||||||
} 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;
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = aiFollowupQuestion;
|
|
Loading…
Reference in New Issue