Solution: Training Your House AI
The solution to the coding task of training Jordan.
We'll cover the following
Code
# function to create the chatbot # we have the read_only to false so the chatbot learns from the user input as def create_bot(name): from chatterbot import ChatBot Bot = ChatBot(name = name, read_only = False, logic_adapters = ["chatterbot.logic.BestMatch"], storage_adapter = "chatterbot.storage.SQLStorageAdapter") return Bot # function to train the bot with a variety of topics # the language we have chosen is english # we can train the bot for other languages as well def train_all_data(Bot): from chatterbot.trainers import ChatterBotCorpusTrainer corpus_trainer = ChatterBotCorpusTrainer(Bot) corpus_trainer.train("chatterbot.corpus.english") # function to train the bot with custom data # it uses ListTrainer to train data from lists def custom_train(Bot, conversation): from chatterbot.trainers import ListTrainer trainer = ListTrainer(Bot) trainer.train(conversation) # function to start and take responses from the chatbot # the chatbot stays running unless a word is typed from the bye_list def start_chatbot(Bot): print('\033c') print("Hello, I am Jordan. How can I help you") bye_list = ["bye jordan", "bye", "good bye"] while (True): user_input = input("me: ") if user_input.lower() in bye_list: print("Jordan: Good bye and have a blessed day!") break response = Bot.get_response(user_input) print("Jordan:", response)
Explanation
-
After checking for the identity of the user in line 10, we have written rules and facts for responding to the different identities.
-
If the
identity
isMark
, we skip all the cases below and go straight to line 23. Otherwise, we check if theidentity
isJane
. -
If the identity is unknown, we respond accordingly and exit the program using the
exit()
command. -
Once the identity is confirmed as
Mark
orJane
, the program skips to line 24, and the code below is executed. -
In line 32, we check whether the identity is
Mark
before we train the bot with Mark’s personal information. Otherwise, code jumps to line 51 and starts the bot. -
If the identity is
Mark
, we add our custom data in the form of lists from lines 33-51. The first object of the list is the question, and the second object of the list is the answer. -
Once we have added all of our new data, we train the bot with the custom data using the
custom_train()
function from lines 53-56. The bot will not learn the answers to the questions by simply adding the custom data in the code. We will need to explicitly train the bot with all the custom data. -
After training the bot with our custom data, we start the bot using the
start_chatbot()
function.
Create a free account to access the full course.
Learn to code, grow your skills, and succeed in your tech interview
By signing up, you agree to Educative's Terms of Service and Privacy Policy