Have you ever wondered how a chatbot assistant works when you’ve visited a website that uses one?
Well, in this article I’m going to be showing you how to build a chatbot assistant using Dialogflow. And the best part? We are going to be doing this with React. We’ll go over what Dialogflow is, explain its various components, and integrate it with a React app.
By the end of this article, you’ll have a functioning Dialogflow chatbot assistant, built with React, to add to your portfolio. Yay!!!
You can clone this project from my GitHub, please leave a star if you like it. 😊
To set up our Dialogflow chatbot, we will need the following:
But first, let’s find out what Dialogflow CX is…
Dialogflow CX is a conversational AI Platform, CAIP for short, used for building conversational UIs. It can be used to implement several types of virtual agents, such as voice bots, chatbots, and phone gateways, and the best part is that it supports over 50 different languages.
Now that we know what Dialogflow CX is, let’s set up our environment.
The first step is opening up a Google Cloud Project.
You’ll be asked to sign in, and if you have a Gmail account, log in with your credentials. After that, you’ll be redirected to a dashboard.
Next, click on CREATE PROJECT.
After that, we have to enter the project name. In our case, we’ll use blog-post-bot
.
The second thing to choose is the parent organization, then click CREATE:
After that, you’ll see a dashboard similar to the below image:
Now let’s enable the Dialogflow API.
To make use of Dialogflow, we have to Enable Dialogflow API for our project. We can do that on the dashboard that pops up, similar to the below image:
Select the project we created initially, and you’ll be presented with the below screen. Click on Enable API:
You’ll then be prompted with another screen asking to create an agent. Complete the form for the initial basic agent settings:
us-central1 (Iowa, USA)
(GMT+1:00) Africa/Casablanca
After our agent is created, we are presented with a dashboard called the “Default Start Flow.” A mini pop-up at the bottom of the dashboard tells us that our agent is successfully created:
Flows are a new concept in Dialogflow CX. They enable us to create complex dialogs that involve a lot of topics.
The bot we are building will give us different articles, such as blog post articles categories, article suggestions, and most popular articles.
With this, we will have three conversation topics that we’ll break into three different flows:
Next, we’ll set up our flows.
In the above image, you can see the + icon on the left sidebar. Click on Create flow and enter the name “Categories.” Hit the Enter
key.
We have successfully created our first flow! Now, go ahead and do the same for “Suggested articles” and “Best articles.”
On the Dialogflow CX dashboard, we have a simulator. This allows us to simulate our bot and test our conversations.
At the top right of our dashboard, click on Test Agent.
To quickly test our bot we can say Hi
. Our virtual agent will respond with a default welcome message, just like the image below:
Let’s change our welcome text to something more personalized — something more friendly, welcoming, and fun.
On the left of your dashboard, click on Default Start Flow, then click on the Start Tree node to open the page.
N.B., on the Pages section in the left sidebar, it automatically selects Start
In Start, under Routes, click Default Welcome Intent. To the right, another panel will open, and in this panel look for the Fulfillment section and delete all the Agent says entries. Add our custom text below:
You are most welcome, I am Chinedu, a blog bot. I can do many things. You can read tech articles from many categories, get the best articles, and I can suggest great articles in case you don't have any in mind, I'm sure you'd love it! Let's get reading…
Next, we make some quick reply buttons similar to what we see on regular bots. We call them suggestion chips.
Under the Fulfillment, there is a link called Add dialogue options. Click on it, then click on Custom payload and paste in the below code snippet before hitting Save:
{ "richContent": [ [ { "type": "chips", "options": [ { "text": "Categories" }, { "text": "Best articles" }, { "text": "Suggested articles" } ] } ] ] }
Now let’s go ahead and test our welcome intent in the simulator:
When we send Hi
, we get our custom message. You may have noticed that we can’t view our chip. For us to be able to achieve that, we need integration. We’ll be using React for this, and we’ll set up our React app to integrate with our Dialogflow bot.
But before we do that, we need to enable a web integration as such:
After this, another pop-up will be shown that contains the JavaScript code we need for the integration:
To do a quick demo, we can click on the Try it now button.
In your terminal, create a new React project by running the below code:
npx create-react-app blogbotapp
Next, cd
into our application, open it with your favorite code editor and type run npm start
.
Next, we add our code snippet to the body of our HTML file in the public folder within our React application:
All set! With this, we have successfully set up our React app, and we can see that everything works well like in our simulator on the Dialogflow CX dashboard.
Let’s get back to configuring our bot and setting up our entities.
Entities are used for identifying and extracting useful data from user input.
We will be creating our entities shortly, but Dialogflow provides ones that can be used to match dates, emails, colors, currency, phone numbers, addresses, etc.
There are three types of entities in Dialogflow:
Let’s go ahead and create our custom entities for our category, best articles, and suggested articles options.
First, click on Manage and then Entity types. If the dashboard opens up, click the button that says Create new.
A dashboard will show up where you can enter the display name. In the table that shows the entity, enter the following entities and their synonyms:
After that, click on the Advanced settings dropdown, and check the Fuzzy matching and Redact in Log checkbox.
Fuzzy matching helps in the case where if we spell a name wrong, it can match it to the right entity.
Redact in log helps to correct the name in the log in a case where we spell them wrong.
After that, click Save and do the same for the other two entities.
After saving our first entity, return to the dashboard and we can see our first entity, @Categories. To create a new entity, click + Create.
Next, we set up our intents.
In Dialogflow CX, intents contain the logic that detects what the user wants. They only contain training phrases and are therefore reusable.
N.B., According to the documentation, training phrases in intents make use of entities. This helps to get variable inputs, therefore it’s good practice to create entity types before creating intents
Training phrases are example phrases of what the user might type or say. If the user input is similar to one of the defined phrases, Dialogflow matches the intent.
Also, we don’t need to match everything because Dialogflow has an inbuilt machine learning functionality that expands our list with other similar phrases.
Intents use three different prefixes:
To create intents, click on Manage and then Intents. At the top of the dashboard, click on the + Create button.
I’ll go ahead and create the intents for the @Catergories entity, then I will give phrases for the other entities to enable you to do that on your own.
You can add your imagination for more training phrases. It’s advisable to have more than 10 training phrases for each intent to cover the different ways the user might trigger it.
In the input box that says Display name, input redirect.categories.overview
.
Do the same for the description:
Categories.description: The types of articles we have.
After that, we scroll down and create the training phrases:
Can I see a list of all the available categories of articles?
What articles can I read?
I would like to see the categories of articles available
Which categories of tech articles do you have
Which categories are currently available
Which category
Which articles
What articles can I read?
After all, this is done, click on Save.
Now, go ahead and create new intents.
Dialogflow CX conversations can be described as finite-state automation.
Let me explain with an example…
Take an automated teller machine (ATM). The ATM has the following states: waiting for credit/debit cards, inputting your pin/passcode, selecting your bank, selecting the withdrawal amount, giving money, and when a certain input is provided by the user, moving between different states.
Slotting in your card will change the state of the ATM Machine from waiting for credit/debit cards to inputting your pin/passcode.
In Dialogflow CX virtual agent, we use pages to model these states.
There are three types of routes that control the conversation state by handling the transition between pages:
The response sent back to the user is known as the conversation utterances. And they are defined by fulfillment which can be of two types:
We won’t be going into creating dynamic fulfillment. For our blog bots, we will focus on static fulfillment responses.
We’ll create the pages in the default start flow:
redirect.categories.overview
redirect.bestArticles.overview
, redirect.reactjs
, redirect.nodejs
, redirect.datastructures-and-algorithims
, redirect.suggestedArticles.overview
, and redirect.end
You might have noticed End Session and Flow. End Flow closes the flow and jumps back to the last active flow, while End Session closes the full chat session.
Next, we create pages for flows, starting with Category. The below chat transcript is for the “Category” flow:
Message from user: "Hello" Bot response: "You are most welcome, I am Chinedu, a certified comrade and a blog bot. I can do many things. You can read tech articles from many categories, get the best articles, and I can suggest great articles in case you don't have any in mind, I'm sure you'd love it! Let's get reading…" Message from user: "Can I see a list of all the available categories of articles?" Bot response: "We have the following categories you could read from: React.js, Node.js, Data Structures and Algorithms.Which categories would you love to read from?" Message from user: "React.js" Bot response: "Awesome! Everyone loves React.js"
Let’s connect our pages:
redirect.categories.overview
Category Overview
redirect.bestArticles.overview
, redirect.reactjs
, redirect.nodejs
, redirect.datastructures-and-algorithims
, and redirect.suggestedArticles.overview
We’ll continue adding static fulfilments:
We have the following categories you could read from: React.js, Node.js, Data Structures and Algorithms.
We do the same thing for the “Best articles” overview and “Suggested articles” overview:
Do you want to read some of our best articles?
You don't have anything in mind to read? I could suggest articles for you to read.
Let’s look at the parameters and what they are used for.
Parameters are used to capture values that we expect to be supplied by the user in a session.
Each parameter has an entity and name.
Let’s create parameters for the “Category Overview” page:
category
@Category
If the virtual agent hasn’t collected the category parameter, we could send the user a response:
Please, what category of article do you have in mind?
Next, let’s add a dialogue option that’ll provide rich suggestions.
Click Add dialogue option and add the below JSON code:
{ "richContent": [ [ { "options": [ { "text": "React.js" }, { "text": "Node.js" }, { "text": "Data Structures and Algorithms" } ], "type": "chips" } ] ] }
We can handle different fallback fulfillment prompts. We do this with parameter event handlers. There are various inbuilt event handlers to choose from, such as no-match default and no-input default, which we are going to be using.
No-match default
I could not get that, can you specify the category you need? You can choose React.js, Node.js, and Data Structures and Algorithms. What category of articles would you like to read?
No-input default
I am sorry, I could not get the category you need. You can choose React.js, Node.js, and Data Structures and Algorithms. What category of articles would you like to read?
Page condition routes
Parameters tend to be very powerful when combined with a page conditional route. When a condition evaluates to true
, the respective page route is called.
For our blog bot, we collect a sequence of parameters, hence we will create a form to check if our condition is met.
Creating the conditional routes on the “Category Overview” page.
Here, we are creating a conditional route that will transition to the next page once the artist is known.
After we have selected the category we want, our bot does something really simple. It sends us a nice message “React.js, nice choice.”
In the “Best articles” flow, we click bestArticle, hit the + beside the route, and paste the following into the custom payload:
{ "richContent": [ [ { "options": [ { "link": "https://blog.logrocket.com/add-redis-cache-nestjs-app/", "text": "Redis in Nestjs" }, { "link": "https://blog.logrocket.com/build-strongly-typed-polymorphic-components-react-typescript/", "text": "React.js polymorphic component" } ], "type": "chips" } ] ] }
Change the intent to the “Best articles” page that we created initially and set the condition to At least match one rule
.
After that, we want to create another route where we end the session.
We do the same thing for the suggested article. Creating a new intent called “Suggested articles” while pasting the below payload and creating the end session route:
{ "richContent": [ [ { "options": [ { "link": "https://www.ddevguys.com/bigo-notation-summarized", "text": "Big O Notation Summarized" }, { "link": "https://www.ddevguys.com/javascript-how-to-implement-the-linked-list-data-structure-part3", "text": "Linked-list" }, { "link": "https://www.ddevguys.com/javascript-how-to-implement-a-queue", "text": "Implement a queue." } ], "type": "chips" } ] ] }
With this, we have been able to build a very simple bot that sends us a cool message after we have chosen a category, sends us our best articles, and also suggests articles to us.
Phew…
We went over the process of building a chatbot using Dialogflow CX and React. This app and chatbot could be improved in a lot of ways depending on your project requirement and the goal you want to achieve.
This was just a basic overview of what could and can be done with Dialogflow CX and how powerful it is.
If you got to this point, you are indeed a legend, because this was a long one. And I really appreciate you for taking the time to read this.
Do leave feedback if you enjoyed it! Reach out on Twitter if you want to dive really deep into Dialogflow CX, I’d love to hear from you all.
Until then, keep coding. Much love.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.