A Simple Guide To Building A Chatbot Using Python Code
A chatbot or robot is a computer program that simulates or provides human-like answers to questions engaging a conversation via auditory or textual input, or both. Chatbots can perform tasks such as data entry and providing information, saving time for users. In recent times, there has been an increased focus on the potential for chatbots to better serve as interfaces between humans and businesses identifying it as a service marketed at solving conversational problems.
What is a Chatbot?
A chatbot is a computer program that simulates human conversation. It can be used to create automated customer service agents, marketing assistants, and other similar systems.
What is Python?
Python is a powerful programming language that enables developers to create sophisticated chatbots. In this guide, I'll show you how to build a simple chatbot using Python code.
Why build a chatbot?
If you're looking to build a chatbot but don't know where to start, this guide is for you. I'll be using Python code to create a basic chatbot.
There are many reasons why you might want to build a chatbot. Maybe you want to create a customer service chatbot to help answer common questions or reduce support requests. Or maybe you want to build a sales chatbot to help qualify leads or schedule appointments.
Whatever your reason, building a chatbot can be a fun and rewarding experience. Not only will you learn about artificial intelligence and natural language processing, but you'll also get to flex your creative muscles and come up with new and interesting ways to interact with users.
Types of Chatbots - Conversational, Informational, and Control
Conversational chatbots are perhaps the most popular type of chatbot. These chatbots are designed to simulate human conversation, and can be used to provide customer service, marketing, or even just entertainment.
Informational chatbots are designed to provide users with information about a particular topic. For example, an informational chatbot could be used to provide weather updates, sports scores, or stock prices.
Control chatbots are designed to help users control a particular device or system. For example, a control chatbot could be used to turn on/off a light, change the temperature of a thermostat, or even play music from a particular playlist.
How can you make a conversational chatbot?
If you're looking to build a chatbot using Python code, there are a few ways you can go about it. One way is to use a library such as ChatterBot, which makes it easy to create and train your own chatbot.
Another way is to use a tool such as Dialogflow, this machine learning cloud platform provided by Google is a visual editor for building chatbots. You can also find many tutorials online that show how to build chatbots using Python code.
Once you have your chatbot built, you'll need to host it somewhere so people can interact with it. There are a number of platforms that offer hosting for bots, such as Heroku, AWS Lambda, or Microsoft Azure, you could even run this on your desktop using the command prompt window (code to do this is provided later on).
Starting to code with Python
Python is a great language for building chatbots. In this simple guide, I'll walk you through the process of building a basic chatbot using Python code.
Building a chatbot with Python is relatively easy and requires only a few lines of code. Please note this is by no means a full tutorial, it's merely an insight into how to get started. There are many different use cases for chatbots, each requiring their own set of rules, intents, and conversational control. with that being said, it will give you a starting point if you or your business are heading in that direction.
Ready? Let's get started, open the command line to install the required packages:
pip install chatterbot
I use visual studio code which has a built in terminal for this, and there are many IDE's out there in the wild, by all means though, use the cmd line or choose which one works best for you. Regardless of IDE you must install the correct libraries and python version in your development environment for this to work. This part of the set up is beyond the scope of this article. That said, there are many online tutorials on how to get started with Python.
How ChatterBot Works
ChatterBot is a Python library that makes it easy to generate automated responses to a user’s input. ChatterBot uses a selection of machine learning algorithms to produce different types of responses. This makes it easy for developers to create chat bots and automate conversations with users. For more details about the ideas and concepts behind ChatterBot see the flow diagram below.
An untrained instance of ChatterBot starts off with no knowledge of how to communicate. Each time a user enters a statement, the library saves the text that they entered and the text that the statement was in response to. As ChatterBot receives more input the number of responses that it can reply and the accuracy of each response in relation to the input statement increase.
The program selects the closest matching response by searching for the closest matching known statement that matches the input, it then chooses a response from the selection of known responses to that statement.
Coding our chatbot
Once the required packages are installed, we can create a new file (chatbot.py for example).
Recommended by LinkedIn
Create a new chatbot instance and using the only parameter required here, give it a name, this can be anything you like. I've called mine Sir talksalot.
from chatterbot import ChatBot
chatbot = ChatBot("Sir talksalot")
Training your chatbot
As your bot will start off with essentially no knowledge and whilst training is not required, training the bot is a good way to ensure your bot is primed with the correct knowledge required to handle inputs from your users and deliver the correct/most accurate responses.
Implement a simple conversation flow to train the model.
from chatterbot.trainers import ListTrainer
conversation = [
"Hello", # This is an example training statement
"Hi there!", # This is an example training response
"How are you doing?",
"I'm doing great.",
"That is good to hear",
"Thank you.",
"You're welcome."
]
trainer = ListTrainer(chatbot)
trainer.train(conversation)
Get a response
response = chatbot.get_response("How are you doing?")
print(response))
That's it, run your program to see the response from your bot to the comment How are you doing?.
Note: Under the hood there are complex algorithms at work, with that being said, from our basic implementation you are able to train a model and get responses that mimic human conversation with just a few lines of code.
Where can you deploy your chatbot
There are a few different ways that you can deploy your chatbot. You can either choose to deploy it on your own servers or on Heroku.
If you want to deploy your chatbot on your own servers, then you will need to make sure that you have a strong understanding of how to set up and manage a server. This can be a difficult and time-consuming process, so it is important to make sure that you are fully prepared before embarking on this option.
If you would prefer to deploy your chatbot on Heroku, then you can follow the simple steps below:
1. Create a new account on Heroku.com.
2. Install the Heroku Command Line Interface (CLI).
3. Login to your Heroku account using the CLI.
4. Create a new app on Heroku.
5. Choose the region where you want to deploy your app.
6. Deploy your code to Heroku using git push heroku master.
(Please note I have used Heroku in the past and I like the platform, however, I'm in no way affiliated with the website. This is again, just a simple guide to get you started should you choose this route).
Create a terminal example chatbot
Not ready to use your chatbot in the wild? Creating a simple terminal chatbot allows you to run the chatbot and interact with it on your desktop, this example uses logic adapters available on ChatterBot.
Specifying logic adapters
The logic_adapters parameter is a list of logic adapters. In ChatterBot, a logic adapter is a class that takes an input statement and returns a response to that statement.
You can choose to use as many logic adapters as you would like. In this example we will use three logic adapters. The TimeLogicAdapter returns the current time when the input statement asks for it. The MathematicalEvaluation adapter solves math problems that use basic operations, and BestMatch adapter which finds the best response to the input.
from chatterbot import ChatBot
# Uncomment the following lines to enable verbose logging
# import logging
# logging.basicConfig(level=logging.INFO)
# Create a new instance of a ChatBot
bot = ChatBot(
'Terminal',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
logic_adapters=[
'chatterbot.logic.MathematicalEvaluation',
'chatterbot.logic.TimeLogicAdapter',
'chatterbot.logic.BestMatch'
],
database_uri='sqlite:///database.db'
)
print('Type something to begin...')
# The following loop will execute each time the user enters input
while True:
try:
user_input = input()
bot_response = bot.get_response(user_input)
print(bot_response)
# Press ctrl-c or ctrl-d on the keyboard to exit
except (KeyboardInterrupt, EOFError, SystemExit):
break
Conclusion
Building a chatbot using Python code can be a simple process, as long as you have the right tools and knowledge. In this article, I've provided you with a basic guide to get started. Once you have your chatbot up and running, it'll be able to handle simple tasks and conversations. If you want to take your chatbot to the next level, you can consider adding more features or connecting it to other services.
System Reliability Engineer Intern @Nutanix | CCNA | Virtualization
1yCan chatterbot be used to build customized chatbots? (ex. for health)
Interesting read. Thank you for sharing 😁