Create chatbot with NodeJS
By Prgmaz 16 May 2021

THUMBNAIL HERE

What we need for this tutorial

  • NPM and NodeJS installed
  • node-nlp module

Setting up our project

First create a folder in which you want to create your project, I created folder named chatbot_nodejs. Initialized repo in that folder with command npm init and install modules with npm i node-nlp.

INSTALLATION HERE

Create a file named index.js in that folder.

Now our project is setup.

INSTALLATION HERE

Creating Intents

Create a folder named intents inside our project folder. We will create our intents in JSON, So I created two json file named greetings.bye.json and greetings.hello.json. Inside it, I structured our questions and answers like this.

{
	"questions": [
		"goodbye",
		"bye take care",
		"see you later",
		"bye for now",
		"i must go"
	],
	"answers": [
		"see you soon!",
		"Till next time",
		"bye bye",
		"have a great day"
	]
}
{
    "questions": [
        "hello",
        "hi",
        "howdy",
        "Greetings"
    ],
    "answers": [
        "Hey there!",
        "Hello",
        "Hi",
        "Greetings"
    ]
}

INSTALLATION HERE

You can add more as you like by creating new json files and structuring your intents like this.

Training and Saving chatbot

Create a file named train.js in our project folder. Let’s write some code to train the model.

// Let's start with importing `NlpManager` from `node-nlp`. This will be responsible for training, saving, loading and processing.
const { NlpManager } = require("node-nlp");
// Creating new Instance of NlpManager class.
const manager = new NlpManager({ languages: ["en"] });

// Let's import fs module to read our json files.
const fs = require("fs");

// Let's read all our intents files in the folder intents
const files = fs.readdirSync("./intents");

// Looping through the files and Parsing the string to object and passing it to manager instance to train and process it.
for (const file of files) {
	let data = fs.readFileSync(`./intents/${file}`);
	data = JSON.parse(data);

	const intent = file.replace(".json", "");

	for (const question of data.questions) {
		manager.addDocument("en", question, intent);
	}

	for (const answer of data.answers) {
		manager.addAnswer("en", intent, answer);
	}
}

// let's create a function that will be responsible for Training and saving the manager instance.
async function train_save(){
    await manager.train();
	manager.save();
}

// Calling the above function
train_save();

Our train.js file is now complete, Now let’s create our index.js files.

// Let's start with importing `NlpManager` from `node-nlp`. This will be responsible for training, saving, loading and processing.
const { NlpManager } = require("node-nlp");
console.log("Starting Chatbot ...");

// Creating new Instance of NlpManager class.
const manager = new NlpManager({ languages: ["en"] });
// Loading our saved model
manager.load();

// Loading a module readline, this will be able to take input from the terminal.
var readline = require("readline");
var rl = readline.createInterface(process.stdin, process.stdout);

console.log("Chatbot started!");
rl.setPrompt("> ");
rl.prompt();

rl.on("line", async function (line) {
    // Here Passing our input text to the manager to get response and display response answer.
	const response = await manager.process("en", line);
	console.log(response.answer);
	rl.prompt();
}).on("close", function () {
	process.exit(0);
});

Now our files are complete. All we need to do now is create two scripts train and start. Open package.json and Add two scripts.

"scripts": {
    "train": "node train.js",
    "start": "node index.js"
  },
  • train script will run the train.js file.
  • start script will run the index.js file.

INSTALLATION HERE

INSTALLATION HERE

Now our project is complete.

You can download this source code from my Github.

Visit this Project on Github

Naman Baranwal
Hi, I’m Prgmaz. I’m a Web, Game and App Developer.

Tags