💬 Building a Chatbot with Memory in Node.js


We’ve built text generation, a CLI tool, and image generation.
In this, we’ll create a chatbot that remembers your conversation — similar to ChatGPT.
🎯 What We’re Building
A chatbot that:
Stores conversation history in memory
Sends the full chat log to the AI each time
Feels more natural and context-aware
🛠 Setup
Install dependencies:
npm install openai dotenv inquirer chalk
💻 Code – chatbot.js
const { Configuration, OpenAIApi } = require("openai");
const inquirer = require("inquirer");
const chalk = require("chalk");
require("dotenv").config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
let conversationHistory = [
{ role: "system", content: "You are a helpful AI assistant." }
];
async function chat() {
while (true) {
const { prompt } = await inquirer.prompt([
{ type: "input", name: "prompt", message: chalk.cyan("You:") }
]);
if (prompt.toLowerCase() === "exit") {
console.log(chalk.yellow("👋 Goodbye!"));
break;
}
conversationHistory.push({ role: "user", content: prompt });
try {
const res = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: conversationHistory
});
const aiReply = res.data.choices[0].message.content.trim();
console.log(chalk.green("\nAI:"), aiReply);
conversationHistory.push({ role: "assistant", content: aiReply });
} catch (err) {
console.error(chalk.red("❌ Error:"), err.message);
}
}
}
chat();
🧪 How to Run
node chatbot.js
Type messages and enjoy a natural AI conversation.
Type exit to quit.
🔍 What You Learned Today
✅ How to persist conversation context in memory
✅ How to build a chat loop in Node.js
✅ How to make AI output feel more like ChatGPT
Subscribe to my newsletter
Read articles from Anuj varshney directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anuj varshney
Anuj varshney
Hey, I am Anuj Varshney a software developer with over a year of experience at iQuinceSoft Pvt Ltd, specializing in web development using various programming languages and tools. He holds a Bachelor of Computer Application degree from Dr. BR Ambedkar University and is currently pursuing a Master of Computer Application from Chandigarh University via distance learning. Anuj has worked on a variety of projects, including the maintenance and updates of CaritasRevolution.com, iQuinceSoft.com, and OdontologiaVejarno.com. His skills include proficiency in programming languages such as JavaScript, C++, C, HTML, and CSS, as well as front-end development using React.js and Nuxt.js. He is also familiar with Node.js, Express.js, MongoDB, and various other tools such as WordPress REST API, Firebase, Redux, Stripe, and Material UI. Anuj is a quick learner with strong analytical skills, and attention to detail, and is committed to delivering high-quality work within tight deadlines.