How to Create a Chatbot In Python
Natural language processing (NLP) is one of the most promising fields of artificial intelligence that uses natural languages to enable human interactions with machines. There are two main approaches to NLP: – rule-based methods, – statistical methods, i.e., methods related to machine learning.
There are several exciting Python libraries for NLP, such as Natural Language Toolkit (NLTK), spaCy, TextBlob, etc.
A chatbot is a computer software able to interact with humans using a natural language. They usually rely on machine learning, especially on NLP. Apple’s Siri, Amazon’s Alexa, Google Assitant, and Microsoft’s Cortana are some well-known examples of software able to process natural languages.
This article shows how to create a simple chatbot in Python using the library ChatterBot. Our bot will be used for small talk, as well as to answer some math questions. Here, we’ll scratch the surface of what’s possible in building custom chatbots and NLP in general.
Preparing Dependencies
You’re only going to install the library ChatterBot for now. I recommend creating and using a new Python virtual environment for this purpose. Execute the following commands in your Python (or Anaconda) terminal:
pip install chatterbot
pip install chatterbot_corpus
You can also try upgrading them:
pip install --upgrade chatterbot_corpus
pip install --upgrade chatterbot
That’s it. We’re ready to go.
Importing Classes
You’ll need to import two classes for this purpose: ChatBot from chatterbot and ListTrainer from chatterbot.trainers:
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
We’re now prepared to create and train our math bot.
Creating and Training a Bot
Our bot will be an instance of the class ChatBot:
my_bot = ChatBot(name='PyBot', read_only=True,
logic_adapters=
['chatterbot.logic.MathematicalEvaluation',
'chatterbot.logic.BestMatch'])
The only required argument corresponds to the parameter name. It represents the name of the bot. You can provide read_only=True if you want to disable the bot’s ability to learn after the training (i.e. from actual conversations). logic_adapters is the list of adapters used to train the bot. There are several of them provided by chatterbot, like the two from our example. chatterbot.logic.MathematicalEvaluation enables the bot to solve math problems, while chatterbot.logic.BestMatch chooses the best match from the already provided responses.
So, we have to provide responses. We do that by specifying the lists of strings later used to train the bot and find the best match for each question. This is what I want our bot to learn for now:
small_talk = ['hi there!',
'hi!',
'how do you do?',
'how are you?',
'i\'m cool.',
'fine, you?',
'always cool.',
'i\'m ok',
'glad to hear that.',
'i\'m fine',
'glad to hear that.',
'i feel awesome',
'excellent, glad to hear that.',
'not so good',
'sorry to hear that.',
'what\'s your name?',
'i\'m pybot. ask me a math question, please.']
math_talk_1 = ['pythagorean theorem',
'a squared plus b squared equals c squared.']
math_talk_2 = ['law of cosines',
'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']
We can create and train the bot by creating an instance of ListTrainer and supplying it with the lists of strings:
list_trainer = ListTrainer(my_bot)
for item in (small_talk, math_talk_1, math_talk_2):
list_trainer.train(item)
The bot should now be trained and ready to communicate.
Communicating with a Bot
You can communicate with your bot using its method .get_response(). Here’s an example of how that might look like:
>>> print(my_bot.get_response("hi"))
how do you do?
>>> print(my_bot.get_response("i feel awesome today"))
excellent, glad to hear that.
>>> print(my_bot.get_response("what's your name?"))
i'm pybot. ask me a math question, please.
>>> print(my_bot.get_response("show me the pythagorean theorem"))
a squared plus b squared equals c squared.
>>> print(my_bot.get_response("do you know the law of cosines?"))
c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)
Don’t expect the bot to answer each question well! Its knowledge is limited to the stuff similar to what it has learned. Many times, you’ll find it answering nonsense, especially if you don’t provide comprehensive training.
Training a Bot with a Corpus of Data
You can use your own or an existing corpus of data to train a bot. For example, you can use some corpus provided by chatterbot:
from chatterbot.trainers import ChatterBotCorpusTrainer
corpus_trainer = ChatterBotCorpusTrainer(my_bot)
corpus_trainer.train('chatterbot.corpus.english')
chatterbot offers this functionality in several languages. You can also specify a subset of a corpus you’d like to use.
Conclusion
Now you know how to create and use a simple chatbot.
This is just a small illustration of what you can do with natural language processing and chatbots. There are many more possibilities out there. If you’re interested in exploring them, you can start by getting familiar with NLTK and ChatterBot.