How to Create a Chatbot with Wit.ai and Node.js

Introduction

Chatbots are becoming increasingly popular for automating conversational tasks and providing a seamless user experience. In this tutorial, we will learn how to create a chatbot using Wit.ai, an open-source natural language processing (NLP) platform, and Node.js, a JavaScript runtime environment.

By the end of this tutorial, you will have a working chatbot that can understand and respond to user input in a natural and conversational manner.

Prerequisites

Before getting started, make sure you have the following prerequisites installed on your machine:

  • Node.js: Download and install Node.js from the official website (https://nodejs.org).
  • NPM: Node.js comes with the Node Package Manager (NPM) pre-installed. You will need this to install the required dependencies.

Step 1: Set Up a Wit.ai Account

To get started, we need to set up a Wit.ai account. Follow these steps:

  1. Go to the Wit.ai website (https://wit.ai) and sign in with your GitHub, Facebook, or Google account.
  2. Once logged in, create a new app by clicking on the “New App” button.
  3. Enter a name and description for your app, then click on the “Create” button.

Step 2: Set Up a Node.js Project

Now that we have a Wit.ai app, let’s set up a Node.js project to work with it. Follow these steps:

  1. Open your terminal and create a new directory for your project by running the following command:
    mkdir chatbot && cd chatbot
    
  2. Initialize a new Node.js project by running the following command:
    npm init -y
    

    This will create a package.json file with default configuration values.

  3. Install the required dependencies by running the following command:

    npm install express body-parser axios dotenv
    

    This will install the Express web framework, the Body Parser middleware for parsing JSON, the Axios HTTP client for making API requests, and the Dotenv module for managing environment variables.

Step 3: Create a Wit.ai Configuration File

To keep our API credentials and other sensitive information separate from our source code, let’s create a Wit.ai configuration file in the root directory of our project. Follow these steps:

  1. Create a new file named .env in the root directory of your project.
  2. Open the .env file and add the following content:
    WITAI_API_KEY=YOUR_API_KEY
    

    Replace YOUR_API_KEY with the API key for your Wit.ai app. You can find the API key by going to your Wit.ai app dashboard and clicking on the “Settings” tab.

  3. Save the changes to the .env file.

Step 4: Create an Express Server

Now, let’s create an Express server to handle incoming HTTP requests and interact with the Wit.ai API. Follow these steps:

  1. Create a new file named server.js in the root directory of your project.
  2. Open server.js and add the following content:
    // Import dependencies
    const express = require('express');
    const bodyParser = require('body-parser');
    const axios = require('axios');
    require('dotenv').config();
    
    // Initialize Express app
    const app = express();
    
    // Parse incoming JSON requests
    app.use(bodyParser.json());
    
    // Define route handler for receiving messages
    app.post('/messages', async (req, res) => {
      try {
        // Access the user's message from the request body
        const { message } = req.body;
    
        // Make a POST request to the Wit.ai API
        const response = await axios.post('https://api.wit.ai/message', {
          q: message,
          v: '20210805',
          access_token: process.env.WITAI_API_KEY,
        });
    
        // Send the response from Wit.ai back to the user
        res.json(response.data);
      } catch (error) {
        // Return an error response if something goes wrong
        res.status(500).json({ error: 'Something went wrong' });
      }
    });
    
    // Start the server
    const PORT = 3000;
    app.listen(PORT, () => {
      console.log(`Server is listening on port ${PORT}`);
    });
    
  3. Save the changes to server.js.

Step 5: Train the Wit.ai Chatbot

Before we can start using our chatbot, we need to train it with some examples. Follow these steps:

  1. Go to your Wit.ai app dashboard and click on the “Understanding” tab.
  2. Click on the “Create Entity” button and create a new entity named intent.
  3. Click on the “Create Entity Value” button and add some example values, such as greeting, bye, help, etc.
  4. Click on the “Train and Validate Model” button to train the Wit.ai model with the new entity and values.

Step 6: Test the Chatbot

Now that our chatbot is set up and trained, let’s test it with some messages. Follow these steps:

  1. Start the Express server by running the following command in your terminal:
    node server.js
    

    You should see the message “Server is listening on port 3000”.

  2. Open a new terminal tab and send a POST request to the /messages endpoint of the chatbot server. Replace YOUR_MESSAGE with the message you want to send:

    curl -X POST -H "Content-Type: application/json" -d '{"message": "YOUR_MESSAGE"}' http://localhost:3000/messages
    

    You should receive a JSON response containing the message interpretation from Wit.ai.

Step 7: Integrate the Chatbot into a Frontend Application

To use the chatbot in a frontend application, we need to make some modifications to our Express server. Follow these steps:

  1. Create a new file named index.html in the root directory of your project.
  2. Open index.html and add the following content:
    <!DOCTYPE html>
    <html>
      <head>
        <title>Chatbot</title>
        <style>
          .messages {
            height: 400px;
            overflow-y: scroll;
          }
        </style>
      </head>
      <body>
        <h1>Chatbot</h1>
        <div class="messages"></div>
        <form id="message-form">
          <input type="text" id="message-input" placeholder="Enter your message" autocomplete="off">
          <button type="submit">Send</button>
        </form>
    
        <script>
          const messagesContainer = document.querySelector('.messages');
          const messageForm = document.querySelector('#message-form');
          const messageInput = document.querySelector('#message-input');
    
          messageForm.addEventListener('submit', async (event) => {
            event.preventDefault();
    
            const message = messageInput.value.trim();
    
            if (message !== '') {
              const response = await fetch('/messages', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message }),
              });
    
              const data = await response.json();
              displayMessage(message, data.intents[0].name);
              messageInput.value = '';
            }
          });
    
          function displayMessage(message, intent) {
            const messageElement = document.createElement('div');
            messageElement.innerHTML = `<strong>You:</strong> ${message}<br><strong>Intent:</strong> ${intent}<br><br>`;
            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
          }
        </script>
      </body>
    </html>
    
  3. Save the changes to index.html.
  4. Modify server.js to serve the index.html file. Open server.js and replace the existing code with the following:

    // Import dependencies
    const express = require('express');
    const bodyParser = require('body-parser');
    const axios = require('axios');
    require('dotenv').config();
    
    // Initialize Express app
    const app = express();
    
    // Parse incoming JSON requests
    app.use(bodyParser.json());
    
    // Serve the index.html file
    app.use(express.static('public'));
    
    // Define route handler for receiving messages
    app.post('/messages', async (req, res) => {
      try {
        // Access the user's message from the request body
        const { message } = req.body;
    
        // Make a POST request to the Wit.ai API
        const response = await axios.post('https://api.wit.ai/message', {
          q: message,
          v: '20210805',
          access_token: process.env.WITAI_API_KEY,
        });
    
        // Send the response from Wit.ai back to the user
        res.json(response.data);
      } catch (error) {
        // Return an error response if something goes wrong
        res.status(500).json({ error: 'Something went wrong' });
      }
    });
    
    // Start the server
    const PORT = 3000;
    app.listen(PORT, () => {
      console.log(`Server is listening on port ${PORT}`);
    });
    
  5. Save the changes to server.js.
  6. Open a new terminal tab and start the Express server by running the following command:

    node server.js
    
  7. Open your web browser and navigate to http://localhost:3000. You should see a chat interface.
  8. Enter a message in the input field and press the “Send” button. The message and its interpreted intent should appear in the chat interface.

Conclusion

In this tutorial, we learned how to create a chatbot using Wit.ai and Node.js. We set up a Wit.ai app, created an Express server to handle incoming messages, trained the chatbot with some examples, and tested it using the Wit.ai API. Finally, we integrated the chatbot into a frontend application using HTML and JavaScript.

With the knowledge gained from this tutorial, you can now build and customize your own chatbots, enhancing the user experience and automating conversational tasks in your applications.

Related Post