Directory structure
- node_modules
- .env
- index.js
- package.json
package.json
{
"name": "chatbot",
"version": "1.0.0",
"description": "Chatbot powered by ChatGPT",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "t3b",
"license": "MIT",
"dependencies": {
"colors": "^1.4.0",
"dotenv": "^16.3.1",
"openai": "^4.35.0",
"readline-sync": "^1.4.10"
}
}
New and shorter syntax for OpenAI's 4.x completions.
index.js
const openai = require('openai');
const dotenv = require('dotenv');
const readlineSync = require('readline-sync');
const colors = require('colors');
/*
import openai from './config/open-ai.js';
import readlineSync from 'readline-sync';
import colors from 'colors';
*/
dotenv.config();
/*
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
*/
const client = new openai.OpenAI(process.env.OPENAI_API_KEY);
async function main() {
console.log(colors.bold.green('Welcome to the Chatbot Program!'));
console.log(colors.bold.green('You can start chatting with the bot.'));
const chatHistory = []; // Store conversation history
while (true) {
const userInput = readlineSync.question(colors.yellow('You: '));
try {
// Construct messages by iterating over the history
const messages = chatHistory.map(([role, content]) => ({
role,
content,
}));
// Add latest user input
messages.push({ role: 'user', content: userInput });
// Call the API with user input & history
const completion = await client.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: messages,
temperature: 0.8,
max_tokens: 2500
});
// Get completion text/content
const completionText = completion.choices[0].message.content;
if (userInput.toLowerCase() === 'exit') {
console.log(colors.green('Bot: ') + completionText);
return;
}
console.log(colors.green('Bot: ') + completionText);
// Update history with user input and assistant response
chatHistory.push(['user', userInput]);
chatHistory.push(['assistant', completionText]);
} catch (error) {
console.error(colors.red(error));
}
}
}
main();
.env
OPENAI_API_KEY=Lorem-Ipsum