Create a Chatbot With Python and Chatterbot
On the go? Have Polly read to you.
Chatterbot is a Python framework for creating chatbots. It relies on a machine learning model which makes it possible to generate responses based on collections of previous conversations.
** see example below
sudo pip install chatterbot
Make sure you have Git installed, if not you can do so here.
Once Git is installed, run
pip install git+git://github.com/gunthercox/ChatterBot.git@master
git clone https://github.com/gunthercox/ChatterBot.git
pip install ./ChatterBot
Train your Chatbot
Chatterbot allows you to train your own responses as a Python list, where the first value is the input message and the second list item is a possible response for the preceding input message.
So here I could train the chatterbot to respond to the messages “hey” and “who created you?”, like this:
chatbot.train([ "Hey", "Hello there, human" ]) chatbot.train([ "Who created you?", "My creator's name is Patrick. Patrick Harris" ])
You can also train the chatbot like
from chatterbot.trainers import ListTrainer conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome." ] chatbot.set_trainer(ListTrainer) chatbot.train(conversation)
Where each item in the list is a possible response to the item above it. So
“hello” yields “hi there”
“Hi there” yields “How are you doing?”
“Thank you” yields “you’re welcome”
Chatterbot involves updating example dialogue into the chatbot’s database, thus allowing it to “learn” as it continues to interact with people.
The chatterbot framework also comes with built-in training classes. To use a native training class you must import it and pass it to the set_trainer() method before calling train() like
from chatterbot.trainers import ListTrainer from chatterbot.trainers import ChatterBotCorpusTrainer chatterbot = ChatBot("Training Example") chatterbot.set_trainer(ListTrainer) #and add your specific responses on top the base conversational model after training the #built in classes: chatbot.train([ "Who created you?", "My creators name is Patrick. Patrick Harris" ]) chatbot.train([ "Thank you", "You're welcome" ]) chatbot.train(["What are you doing?", "I'm just studying to be the first AI to pass the Turing Test"])
Play with it:
Deploying your Chatbot
The commands to install a flask chatterbot example from git and push it to Heroku:
If you wish to deploy to Heroku, remember that their servers don’t accommodate sqlite3, so you’ll need to use a separate database. MongoDB is a good alternative. You can download MongoDB here.
To tell ChatterBot to use the Mongo DB adapter, you will need to set the storage_adapter parameter
MongoDB implementation example from their documentation (you may need to refresh the page to load the gists):
To use the SQL adapter:
For more information, see Chatterbot’s documentation here.