Introduction
Chatbots are one of the most common applications of artificial intelligence that we encounter daily. They are the computer programs designed to simulate conversation with human users, especially over the internet. Chatbots can be used in a wide range of industries, including customer service, healthcare, and education, among others. Because they offer 24/7 service, they are more efficient than human employees and provide greater customer satisfaction. In this tutorial, we will develop a chatbot using the Dialogflow platform.
Prerequisites
Before starting with this tutorial, We need to install the following tools and software:
- Node.js
- Dialogflow account
- Ngrok
Setting Up Dialogflow Account
Dialogflow is a Google-owned platform that provides developers with a powerful natural language processing (NLP) toolkit for building conversational interfaces. With Dialogflow, you can create chatbots that can understand natural language input and deliver appropriate responses to users.
- To get started, we need to create a new Google Cloud Project and enable the Dialogflow API service. Follow the instructions provided in the official documentation to set up and configure Dialogflow.
-
Once the project is created, navigate to the Dialogflow console and create a new agent. Give your agent a name and select the default time zone.
-
Next, we need to define the intents and entities that our chatbot will understand and respond to. Intents represent the various types of user requests that the chatbot can handle. Entities represent objects or concepts that are relevant to the user’s request.
-
To create a new intent, click on the “Create Intent” button on the left-hand side of the Dialogflow console. Give the intent a name and enter sample user requests that the intent should handle. For example, if we are creating an intent to answer questions about the weather, we could provide sample requests like “What is the weather like in New York?” or “Will it rain tomorrow?”
-
Next, we need to define the responses that our chatbot will provide when the user requests that intent. We can define different responses for different contexts within the same intent. For example, if the user asks for the weather in New York, we could provide a different response if it is raining than we would if it is sunny.
-
We can also define entities that our chatbot will recognize and extract from the user’s request. For example, if the user asks for the weather in a specific location, we can define a “location” entity that our chatbot will extract from the user’s request. To create a new entity, click on the “Create Entity” button on the left-hand side of the Dialogflow console.
Setting Up Node.js
To create a chatbot using Dialogflow, we will use the Dialogflow Node.js client library. This library allows us to interact with the Dialogflow API from our Node.js environment.
- First, we need to install Node.js. To do so, visit the official website and download the appropriate package for your operating system.
-
Next, we will create a new Node.js project. Open a terminal window and run the following command:
mkdir chatbot cd chatbot npm init
This will create a new directory called “chatbot” and initialize a new Node.js project in that directory.
-
Next, we will install the Dialogflow Node.js client library. Run the following command in your terminal window:
npm install [email protected]
This will install the latest version of the Dialogflow Node.js client library.
-
Create a new file called “index.js” in your project directory. In this file, we will define the code that will handle incoming messages from the user and respond with appropriate responses.
Setting Up Ngrok
Before testing our chatbot, we need to expose our Node.js server running on our computer to the internet. To do this, we will use Ngrok, which creates a secure tunnel to our local machine and allows remote access to our application.
- Download the Ngrok tool from the official website and extract it to a directory on your computer.
-
Next, start a new tunnel by running the following command in your terminal window:
./ngrok http 5000
This will start a new tunnel that exposes our Node.js application running on port 5000.
-
Ngrok will provide you with a public URL that you can use to access the exposed application. Keep this URL handy as we will need it later to set up our Dialogflow webhook.
Developing the Chatbot
-
First, we need to import the Dialogflow Node.js client library in our “index.js” file. Add the following code to the top of the file:
const dialogflow = require('dialogflow');
- Next, we need to define a function that will handle incoming messages from the user and respond with the appropriate response. Add the following code to your file:
function processMessage(text) { return new Promise((resolve, reject) => { const projectId = '<your-project-id>'; const sessionId = '<your-session-id>'; const languageCode = 'en-US'; const sessionClient = new dialogflow.SessionsClient(); const sessionPath = sessionClient.sessionPath(projectId, sessionId); const request = { session: sessionPath, queryInput: { text: { text: text, languageCode: languageCode, }, }, }; sessionClient .detectIntent(request) .then(responses => { const result = responses[0].queryResult; console.log(`Query text: ${result.queryText}`); console.log(`Response text: ${result.fulfillmentText}`); resolve(result.fulfillmentText); }) .catch(err => { console.error('ERROR:', err); reject(err); }); }); }
This function creates a new session client and session path using the project ID and session ID for your Dialogflow agent. It then creates a new request object and sends it to Dialogflow for processing. When the response is received, the function extracts the fulfillment text and returns it as a response.
-
Next, we need to create a new HTTP server that listens for incoming requests from Dialogflow. Add the following code to your file:
const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/webhook') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { const json = JSON.parse(body); const query = json.queryResult.queryText; processMessage(query).then(response => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.write(JSON.stringify({ fulfillmentText: response })); res.end(); }); }); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('404 Not Foundn'); res.end(); } });
This code creates a new HTTP server that listens for incoming POST requests to the “/webhook” URL. When a request is received, it extracts the query text from the request body and passes it to the “processMessage” function we defined earlier. When a response is received from Dialogflow, it sends back a JSON response containing the fulfillment text.
-
Next, we need to start the server and listen for incoming requests. Add the following code to your file:
server.listen(process.env.PORT || 5000, () => { console.log(`Server running on port ${process.env.PORT || 5000}`); });
This code starts the HTTP server and listens for incoming requests on the specified port. When the server is started, it logs a message to the console.
-
Finally, we need to configure our Dialogflow agent to send incoming requests to our server. To do this, open the Settings page for your agent and click on the “Fulfillment” tab. Enable Webhook and enter the URL provided by Ngrok followed by “/webhook”. For example, if Ngrok provided the URL “http://12345.ngrok.io”, then the webhook URL would be “http://12345.ngrok.io/webhook”.
Testing the Chatbot
To test our chatbot, we can start a conversation in the Dialogflow console or use an external chat client such as Facebook Messenger or Slack.
- Open the Dialogflow console and click on the “Try it now” button in the top right corner. This will open a chat window where we can enter requests and get responses from our chatbot.
-
Enter a sample request and see if the chatbot responds correctly.
-
If the chatbot is not responding correctly, check the logs in your Node.js console to see if there are any errors. You can also use the Ngrok console to monitor incoming requests and responses.
Conclusion
In this tutorial, we learned how to develop a chatbot using the Dialogflow platform and the Dialogflow Node.js client library. We learned how to define intents and entities in Dialogflow, and how to create an HTTP server that listens for incoming requests from Dialogflow. We also learned how to use Ngrok to expose our local Node.js server to the internet and how to configure Dialogflow to send incoming requests to our server. With this information, we can now create powerful chatbots that can understand natural language input and provide appropriate responses to users.