How to Build a Chatbot with Dialogflow and React.js
作者:禅与计算机程序设计艺术
1.简介
The name implies that chatbots function as digital agents capable of interacting with users through both textual and audio messages. These bots are gaining increasing popularity due to their diverse capabilities such as providing customer service support, assisting with FAQs, offering product recommendations, and contributing to efficient business operations.
To create a chatbot, we need to use several tools and technologies:
It serves as an application for developing conversational agents that feature stateful management, NLP capabilities, API integrations, data analytics, and system integrations.
-
React.js: A JavaScript library used for building user interfaces, specifically designed to create single-page web applications.
-
Node.js: 是基于Chrome的V8JavaScript引擎构建的一种异步事件驱动型运行时。开发人员能够利用npm注册库中的模块迅速且轻松地构建可扩展的网络应用。
In this article, I will explore techniques for integrating Dialogflow with React.js in order to develop a basic chatbot designed to process textual information requests from end-users and offer appropriate responses. I presume familiarity with JavaScript programming and working with APIs. If not, I recommend starting with the foundational concepts outlined in this guide before continuing further.
Upon completion of this tutorial, our objective is to ensure that readers can learn how to create a chatbot utilizing Dialogflow and React.js, while also acquiring practical knowledge for developing conversational AI systems grounded in machine learning algorithms.
2.基本概念术语说明
Dialogflow
作为云服务的自然语言处理(NLP)工具,Dialogflow专为机器与人类之间的文本与语音交流而设计。开发者可以通过设定意图和实体来训练他们的聊天机器人——这些设定决定了当机器人在面对特定用户查询或句子时应采取的行为方式。The dialogflow agent则负责处理NLP任务——识别模式、提取关键术语、分析情感并识别诸如名字、日期、数字等一类的关键信息。随后该系统会将相关信息传输回服务器应用程序以完成额外的处理流程——例如存储数据或执行特定操作。
Upon being trained, the chatbot is capable of engaging interactively with users without human intervention. This renders it particularly suited for business automation contexts such as customer service support; FAQ answering; and order fulfillment; among other applications.
Intents
Intents represent various types of user inquiries that the chatbot must respond to by offering appropriate answers. For example, in a retail setting, there could be intents related to checkout processes, payment methods tied to items, and customer inquiries about purchases. Each intent is accompanied by its own training data set that includes sample phrases representing typical communication patterns people use when posing similar inquiries.
When a user receives a query, the dialogflow agent determines the most appropriate intent using predefined rules and heuristics. Following this determination, the agent accesses the response linked to the identified intent and delivers it to the user as output. In simpler terms, intents convert incoming user requests into bot-generated responses.
Entities
在对话机器人中扮演着关键角色的实体组件不仅能够从用户查询中提取关键信息而且还能显著提升对话机器人的智能化水平。在本质上来说实体有助于代理学习如何解析和分类用户的输入信息。它们可以根据常见名词、形容词、动词以及用户查询中常见的其他语言构造进行定义。当一个句子包含多个实体时对话流代理将每个实体与相应的意图相关联。
举个例子来说吧,假设我们要开发一个用于酒店预订系统的聊天机器人。我们的目标是实时根据用户的查询来识别入住日期、离店日期、客人数、房型以及位置。要做到这一点,我们可以分别定义四个实体:入住日期(Check-In Date)、离店日期(Check-Out Date)、客人数(Guest Count)、房型(Room Type)和位置(Location),并将它们与BookHotel意图关联起来。这样一来,在执行任务时,“The agent would know which parts of the query refer to each parameter and retrieve the correct values for those parameters accordingly”就可以相应地提取出正确的参数值并完成任务。
We can also integrate custom entities into our chatbot's functionality to augment its operations beyond the default set provided by Dialogflow. Custom entities offer a means for capturing field-specific terminology, thereby enhancing comprehension of complex user interactions.
Knowledge Base
A knowledge base functions as a storehouse of information intended to enhance conversation flow and address unanswered queries for a chatbot. The types of information stored within a knowledge base may encompass articles, videos, images, and frequently asked questions (FAQs). It serves as an asset for answering user inquiries that might not be accessible through typical content provided by the bot. By leveraging queries from the knowledge base as needed, the chatbot is capable of generating precise and informative responses irrespective of user expertise or proficiency levels.
React.js
React is a declarable-based, highly efficient and versatile JavaScript library designed for building user interfaces. It provides a framework for creating complex user interfaces by enabling the creation of intricate user interfaces by assembling small, independent code segments known as components.
React的核心理念是基于可重用的用户界面组件。组件概括了应用程序界面的外观特征而不涉及其内部实现细节。它们将渲染逻辑委托给其他函数来处理。渲染器实现了组件的行为并返回了一个虚拟DOM树结构。虚拟DOM是一种轻量化的表示方法,在更新界面时提高效率
React提供了构建大型Web应用程序模块化组件的框架。Components可以通过组织在一起形成层次结构。这种设计增强了代码复用、简化了调试,并提升了维护性。By利用React,我们能够轻松开发交互式和动态的用户界面.
3.核心算法原理及具体操作步骤
创建 Dialogflow Agent
To begin constructing our chatbot with Dialogflow and React.js, it's necessary to first establish a Dialogflow agent. Please refer to the steps outlined below for guidance.
Generate an agent by selecting the "+ CREATE AGENT" button located in the top-right corner area.
Assign a name to your agent freely and specify the region.
You will be directed to a screen that prompts you to upload your logo.
You may opt to bypass this step if desired.
Once completed, navigate to the left panel and click on the "Intents" tab to access it. To create a new intent, press the "+ CREATE INTENT" button located there. Assign meaningful names to each intent, such as "Greeting", "Booking", or "FAQ". Within this section, add several sample responses that users might employ when interacting with your system related to these intents—like initiating contact ("Hi"), inquiring about reservations ("How can I book a room?"), or checking status updates ("What is my booking status?"). Once all intents are established, save them by clicking the green "Save" icon found at the bottom right of the interface.
After having created the agent we built and integrated our intents, let's proceed to set up the webhook URL.
设置 Webhook URL
Webhook是一个回调函数,在每次用户发送消息时由Dialogflow代理调用。
当代理接收到一条消息时,它会将请求传递到指定在URL中的服务器。
因此,我们需要配置该URL以确保消息能够发送至我们的React.js应用程序。
Follow the steps below to configure the webhook URL:
navigate到agent设置页面,请在左上角附近找到您的代理名称旁边的齿轮图标并点击它。
Click on "Webhooks" located in the left-hand side menu. Configure the URL endpoint as https://[YourHerokuAppName].herokuapp.com/webhook. Replace [YourHerokuAppName] with your specific Heroku app name.
- Switch on the 'Enable webhook for all projects' setting and save your changes. Now, each time a message is sent to the Dialogflow agent, it will be forwarded by our React.js app using its webhook URL. Please note that you must host your React.js app on a hosting provider like Heroku in order to access its webhook URL.
安装依赖库
Next, we need to install two dependencies for our project:
react-dialogflow: An SDK designed to support communication with Dialogflow within the React framework.
- express: A Node.js framework for running our server application.
You can install both packages via the npm package manager when you type the subsequent commands required in your terminal.
npm i react-dialogflow express --save
Note: Make sure node.js is installed on your computer before proceeding with the installation of these packages. Additionally, ensure to update npm to the latest version using the command npm update -g npm.
Once the packages are installed, set up a new file named 'server.js' under your project’s root directory.
配置 Express Server
Open the 'server.js' file in order to set up our Express server, and in addition, write the following code to initialize it.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server listening on port ${port}`));
代码解读
Here, the express and body-parser libraries are being invoked, and we initialize the server object. Next, we configure these middlewares to parse JSON and urlencoded data formats. Finally, we launch the server on the specified port number.
创建 Dialogflow Component
Create a dedicated folder named 'chatbot' within your project directory. Locate within this designated area and execute the following instruction: cd chatbot.
npx create-react-app.
Creating a new React application in this project's current directory is straightforward. Subsequently, navigate into the src folder and set up a new file called 'Chatbot.jsx'.
import React, { useState } from'react';
import './App.css';
import DialogflowAgent from'react-dialogflow';
function App() {
const [response, setResponse] = useState('');
const handleSend = async (text) => {
try {
const res = await fetch('/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text,
}),
});
const jsonRes = await res.json();
setResponse(jsonRes);
} catch (error) {
console.log(error);
}
};
return (
<div className="App">
<header className="App-header">
<h1>Welcome to My Chatbot</h1>
</header>
<main className="App-content">
<DialogflowAgent
authorizationKey="<Your_Dialogflow_API_KEY>" // replace with your API Key obtained from Dialogflow Console
agentName="MyBot" // replace with your agent name
style={{ backgroundColor: '#f7f7f7' }}
onMessage={handleSend}
/>
<div>{response}</div>
</main>
</div>
);
}
export default App;
代码解读
Here, we are utilizing both the useState hook from React and the DialogflowAgent component sourced from the react-dialogflow library. Additionally, we have developed a new function named handleSend, which is automatically invoked when the user interacts with our interface by clicking on the "send" button. Within this function's execution flow, we send a POST request to our /send route, incorporating any user input provided through our chatbox. Upon receiving this request, our system expects to retrieve a JSON-formatted response containing Dialogflow Agent's generated reply text and will then display it beneath the chatbox area for visibility.
Replace <Your_Dialogflow_API_KEY> with an API Key obtained from Dialogflow Console. Please ensure that 'MyBot' is replaced with the name of your Dialogflow Agent. She can retrieve her API key directly from the Settings section on her Dialogflow console.
添加服务器端路由
Add the following routes to the server.js file:
// Import the Dialogflow module
const Dialogflow = require('dialogflow');
// Initialize the Dialogflow client with your credentials
const projectId = '<Your_Project_ID>'; // replace with your Project ID obtained from Google Cloud Platform Console
const sessionId = 'quickstart-session-id';
const languageCode = 'en-US';
const sessionClient = new Dialogflow.SessionsClient({
keyFilename: 'path/to/keyfile.json',
});
// Define the /webhook route handler
app.post('/webhook', (req, res) => {
const reqData = req.body.queryResult.queryText;
console.log('User Query:', reqData);
detectIntentStream(projectId, sessionId, reqData).then((responses) => {
console.log('Detected Intent Responses:', responses[0].queryResult.fulfillmentMessages);
res.json({
speech: responses[0].queryResult.fulfillmentText,
displayText: responses[0].queryResult.fulfillmentText,
});
});
});
async function detectIntentStream(projectId, sessionId, queryText) {
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
const queryInput = {
text: {
text: queryText,
languageCode,
},
};
const request = {
session: sessionPath,
queryInput,
};
const responses = [];
const stream = sessionClient.streamingDetectIntent();
stream.write(request);
stream.on('data', (response) => {
responses.push(response);
console.log('Partial Detect Intent Response:', response);
});
stream.on('end', () => {
console.log('Finished Streaming Detect Intent.');
});
await stream.promise();
return responses;
}
代码解读
Here, we are accessing the dialogflow module, setting up a sessionClient, and configuring a /webhook route endpoint handler. The system acquires a user's request body from the Dialogflow Agent and logs it into the console. Subsequently, we invoke the detectIntentStream function to pass along this request body to Dialogflow, resulting in a Promise that encapsulates both detected intents and corresponding responses.
Within the detectIntentStream function, we create a new Session Path and request object utilizing the sessionClient. We send this request to the Dialogflow Stream, establish callbacks to handle Partial and Final responses, and await all responses being received. Finally, we log the Detected Intent Response to the console and return an array of responses.
运行项目
Currently, we possess all the necessary components required to establish our chatbot. To begin with, it is essential to set up your React.js application on a hosting service like Heroku. The subsequent step involves accessing the root directory of your project and initiating the server by entering the appropriate command sequence.
npm start
After completing all setup steps, browse your web browser and visit http://localhost:3000/. You can now view the live demonstration of the chatbot interface.
