Introduction:
In this tutorial we will be building a chatbot that learns in Python. Chatbot’s are simple but sometimes complex programs to write. from simple chatbots to machine learning backed chatbots. All chatbots have a common ground the ability to carry out conversations and ability to learn in the process (though not all follow this).
I used a simple algorithm LCA(Learning Chatbot Algorithm) as I like to call it. It is really easy. The the algorithm is shown below.:
Function LCA(text):
Brain —> datasource for conversations
If learning:
Return(Learn)
Else:
Return best suited response for text
That’s just it, we will implement this simple stuff in Python.
Python implementation:
This project is object oriented so we will make use of Python’s class method.
Creating the class and declaring variables we will be using:
class Chatbot(object):
def __init__(self,name,**kwargs):
self.name = name
self.read_only = kwargs.get("read_only",False)
self.filex = open("LCA.txt","a+")
# show learning mode
if not self.read_only:
print(self.name+" now in learning mode")
else:
if self.read_only: print (self.name+" now in read only mode")
else: print(self.name+" now in learning mode")
#define some local variables
self.threshold = 70
self.temp_memory = []
self.response = None
self.msg = "learning disable please enable learning by setting the read only flag to False"
We will be needing 4 helper functions to implement our algorithm.
learn_response_from
Learner
Generate_response
is_learning
will now explain this functions one by one.
learn_response_from accepts 2 arguments input, response and saves them up in a text file with a newline as the separation between them.
def learn_response_from(self,inputx,response):
self.filex = open("LCA.txt","a+")
self.filex.write(("%s\n%s\n"%(inputx,response)))
self.filex.close()
Learner : The function that let’s our chatbot learn, when our bot doesn’t know the response to query it asks us what should be the response.
def Learner(self,input):
"""
learns a new response if there is no response to an input
or returns an response if there is one
"""
self.response = None
self.brain = [i.strip() for i in open("LCA.txt")]
# are we allowed to learn new response
if self.read_only:
return self.msg
# checks wether we are learning a new sentence
elif len(self.temp_memory) == 1:
self.temp_memory.append(input)
sentence = self.temp_memory[0]
response = self.temp_memory[1]
if response != "":
self.temp_memory = []
self.learn_response_from(sentence,response)
return(response)
else:
self.temp_memory = []
return("discarded learning")
# checks wether we already know the input parsed
elif input in self.brain:
pass
# since we don't recognize the input we LEARN it
else:
self.temp_memory.append(input)
return("%s ?"%"please what should be my response")
Generate_response : This function makes use of the euclidean similarity index to find our match of our query in our bot’s brain. A response is the next sentence in our chatbot’s brain or the previous Incase of an end of file error.
def Generate_response(self,input,data_source):
"""
Generates a list of responses for the LCA to choose from
"""
for id,text in enumerate (data_source):
#print(text +"==="+ input,euclidean_similarity(text,input))
if euclidean_similarity(text,input) >= self.threshold:
try:
return(data_source[id+1])
except:
return(data_source[id-1])
is_learning returns True or False after validating whether or not to learn a given input.
def is_learning(self,input):
"""
checks wether the chatbot is supposed to learn a new response to an input
returns True or False
"""
self.brain = [i.strip() for i in open("LCA.txt")]
if len(self.temp_memory) == 1:
return True
elif input in self.brain:
return False
elif self.Generate_response(input,self.brain) != None :
return(False)
else:
return True
Our algorithm implemented in Python.
def LCA(self,input):
"""
the engine box of the entire program balances between learning and response generation
"""
response = None
self.brain = [i.strip() for i in open("LCA.txt")]
if self.is_learning(input):
return self.Learner(input)
else:
response = self.Generate_response(input,self.brain)
if input == "":return("Null input")
if input not in self.brain and self.read_only != True:
if type(response) == list:
response = choice(response)
response = (len(self.brain)+1,response[1])
self.learn_response_from(input,response[1])
else:
self.learn_response_from(input,response)
else:pass
return(response)
Our chatbot in action:

Learning a response to a query.:

Learning chatbot
Easy huh?? Get the full code. The chatbot’s learning could still be improved. I hope you completed the building a chatbot that learns in Python tutorial with ease, you can use comment section to ask questions, I promise to reply ASAP.