Dialogflow chatbot with webhooks using Python
Hi All once again I am back with a new topic which i believe would encourage you build a chatbot. I would try my best to give you all a great piece of work that it will support you in building your own chatbot. So let’s dive in.
So anyone who would start with building chatbots will be puzzled with webhooks. No problem that’s normal. I am here to explain. Let’s have a brief explanation about dialogflow and then we will move to webhooks.
What’s a webhook?
A webhook is basically a HTTP push API or web call back. we can also refer it sometimes as reverse API, because it sends data from the application to the consumers as it happens, you don’t have to poll the data every now then to get it in real time. I am taking it to a deeper level. Let’s wrap for now on webhooks.
What’s a Dialogflow?
Dialogflow is and end-to-end build once deploy anywhere development platform by Google which helps us building serverless chatbots and makes it very easy to deploy in popular social-media platforms like facebook, hike, viber, kik and easily integrate with google assistant. We have multiple components in dialogflow which helps us with flow. So let’s talk about the components.
1 — Agent
2 — Intents
3 —E ntities
4 — Integration
5 — Fullfillment
These are the four primary parts of the platform.
Agent: An agent is one which is going to handle all the conversations and route all the necessary actions. It is a natural language understanding module which gets trained frequently to cater use specific requirements.
Intents: Intents classifies the end user’s intention into one group, so the user’s intention is around particular topic. You can define as many as intents you want depending on the use case. It has elements such as context,training phase,actions and parameters and response.
Entities: It basically groups a set of words under defined entity. For example pen,pencil,paper,eraser and notebook can be termed as stationaries. So dialogflow offers pre-built entities which are already trained or we can build our custom entity and train them. This helps in reducing the redundancy of training phrases.
Integrations: Dialogflow integrates with all the popular conversation platforms like Google Assistant, Facebook, kik, viber etc.,
Fullfillment: It’s a connecting service which allows you to take actions based on the end-user expressions and send dynamic responses back to the user.For example if the user is looking for employee details, your service can fetch details from the database and respond to the user immediately the results.
Let’s move on to the example.
I have used sample cars_sales.csv data which contains list of countries and their total sales 2019.(I have used only specific list of countries). You can download the data from the below link.
Login to dialogflow with your google account.
You’ll find the homescreen as below.
Click on create agent and give a name of your choice. I have given it as bluebot. Once it is created,let’s start with creating intents for our use case. so i would segment our requirement into three parts. introduction, fetch sales details and conversation end. It’s very simple.
I am going to create two intents: (1) sales, whose introduction is covered with the default welcome intent and (2) exit intent which will mark the end of the conversation.
In this we will see about creating follow-ups as well. First open default welcome intent and provide response as required.
It follows the below flow.
User: Hi
Bot: Hi I am bluebot. I can provide information on car sales across countries. would you like to know more?
User: yes.
Bot: Try asking like what is the total sales in US?
User:what is the total sales in India?
Bot: The total sales in India is $###
User: Alright.
Bot:would you to know comparative analysis between states?
User:Yes.
Bot: The comparative sales between two countries.
User: Thanks.
Bot: Thank you. See you soon.
Introduction — ->Sales — →Exit.
Introduction: Hi →welcome message →if yes →more information. The design for the introduction is as below.
Let’s add follow-up intent which you can see on hovering the intent. Click on it and select yes follow-up and enter response for that.
Sales Intent:
Create an intent named sales or anything of your choice and provide appropriate training phrases.
Mark all the countries you type in under prebuilt @sys.geo-country-code. It will automatically come under actions and parameters. Based on these actions only we are going to build our webhook. Enable fullfillment in the sales intent.
The below conversation will be covered with the above design.
User:what is the total sales in India?
Bot: The total sales in India is $###
User: Alright.
Bot:would you to know comparative analysis between states?
User:Yes.
Bot: The comparative sales between two countries.
So we will be designing the webhook to fetch the sales data and the comparative results from the csv.
Exit Intent:
To write a webhook you’ll need
1 — Python
2 — VS code(preferably).
3 — ngrok
sudo apt update
sudo apt install snapd
sudo snap install ngrok
example: ngrok http port-no
Please find the below code which explains the logic performed.
# import flask dependencies
from flask import Flask, request, make_response, jsonify
import pandas as pd# initialize the flask app
app = Flask(__name__)df = pd.read_csv("car_sales.csv")# default route
@app.route('/')def index():
return 'Hello World!'#function for responses
def results():
# build a request object
req = request.get_json(force=True) #fetch action from json
action = req.get('queryResult').get('action') if action == 'sales_results':
res = calculate_sales(req)
elif action == 'country_list':
res = sales_comparison(req)
#action = 'Hi, I just wanted to check' #return a fulfillment response
return {'fulfillmentText': res}def sales_comparison(req):
element1 = req.get('queryResult').get('parameters').get('geo country-code')[0].get('name') element2 = req.get('queryResult').get('parameters').get('geo-country-code')[1].get('name') a = list(df["Total Sales"][df['Countries ']==element1]) b = list(df["Total Sales"][df['Countries ']==element2]) c = ((int(a[0].replace(",","")) - int(b[0].replace(",","")))/int(b[0].replace(",","")))*100 result = "The comparitive difference in sales between "+element1+" and "+element2+" is %"+str(c) return(result)def calculate_sales(req):
element = req.get('queryResult').get('parameters').get('geo-country-code').get('name') total_sales = list(df["Total Sales"][df['Countries ']==element].values) result = 'The total sales in '+element+' is $'+total_sales[0] return(result)
#create a route for webhook
@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
# return response
return make_response(jsonify(results()))#run the app
if __name__ == '__main__':
app.run(port=8000,debug=True)
once dialogflow set-up is done,
Run the script
python webhook.py
Parallely run
ngrok http 8000
Use https://22a1af55.ngrok.io/webhook
Now open click on fullfillment in dialogflow, enable webhook and paste the above link in URL and save. We have successfully created a chatbot with actions involved. This is how is how it looks.
That’s all folks. Hope you enjoyed. See you all soon with new post.