{"id":85717,"date":"2021-12-27T09:00:38","date_gmt":"2021-12-27T03:30:38","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=85717"},"modified":"2026-06-03T15:06:29","modified_gmt":"2026-06-03T09:36:29","slug":"chatbot-project-python-ai","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/","title":{"rendered":"Create Chatbot with Python &amp; Artificial Intelligence"},"content":{"rendered":"<p>Do you want your friend to solve your problems instantly? and most importantly Do you want your friend to be with you for the rest of your life? Then you don&#8217;t have to be worried. All of these qualities may be found in the most widely used AI application, the <strong>CHATBOT!<\/strong><\/p>\n<h3>What is Chatbot?<\/h3>\n<p>Chat bot is a software application that uses artificial intelligence and natural language processing to allow you to have a text-based or text-to-speech conversation.<\/p>\n<h3>Types of Chatbots:<\/h3>\n<p><strong>1. Rule-based Chatbots:<\/strong> Rule-based chatbots are often known as decision tree bots since they understand queries using a tree-like flow. For each query, it has a set of predefined responses. They aren&#8217;t aware of the context of the user&#8217;s query.<\/p>\n<p><strong>2. AI based Chatbots:<\/strong> AI chatbots uses natural language processing (NLP) and machine learning to understand the context and intent of a user&#8217;s query pattern and to create connections between different queries which are asked in different ways in order to provide a better response.<\/p>\n<h3>About the Python Chatbot Project:<\/h3>\n<p>So in this Chatbot project, we are going to make an AI-based contextual chatbot that will maintain the context or in which sense or proportion the user is asking a query. Further using deep learning techniques in Python, we will construct a Sequential model for our training sets of data. The intents, patterns, and responses will all be used to train the chatbot. The user&#8217;s query will be mapped to the intents class using neural networks, which will maintain context and then return a random response.<\/p>\n<h3>Prerequisites for Python Deep Learning Chatbot project:<\/h3>\n<p>Modules required: nltk, pickle, tensorflow, numpy, sklearn<\/p>\n<p>The versions which are used in this project for python and its corresponding modules are as follows:<\/p>\n<ol>\n<li>Python: 3.8.5<\/li>\n<li>Tensorflow: 2.3.1 <em>Note: TensorFlow version should be 2.2 or higher in order to use keras or else install keras directly<\/em><\/li>\n<li>sklearn: 0.24.2<\/li>\n<li>pickle: 4.0<\/li>\n<li>numpy: 1.19.5<\/li>\n<li>nltk: 3.2.5<\/li>\n<\/ol>\n<h3>Download Chatbot Project Code &amp; Dataset<\/h3>\n<p>The dataset for python chatbot project will be \u2018intents.json\u2019. This file contains the required patterns we need to find and corresponding responses we want to return to the end users.<\/p>\n<p>Please download chatbot project code &amp; dataset from the following link: <a href=\"https:\/\/drive.google.com\/file\/d\/1b24d_nCMP7S-oATfTEiVE_wR7rHvD9bc\/view?usp=drive_link\"><strong>Python Chatbot Project<\/strong><\/a><\/p>\n<h3>How to Create a Chatbot in Python?<\/h3>\n<p>Before creating the chatbot let\u2019s have a glance through the project file structure.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/python-chat-bot-files.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-85743\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/python-chat-bot-files.webp\" alt=\"python chat bot files\" width=\"1366\" height=\"726\" \/><\/a><\/p>\n<ul>\n<li><strong>intents.json<\/strong> &#8211; This file contains sets of tags, patterns, and responses. The intent of every class has a set and filter to check in which contexts the user query belong to.<\/li>\n<li><strong>training.py<\/strong>: This file is used to create the model and train our python chatbot.<\/li>\n<li><strong>training_data.file<\/strong>: This file contains lists of words, patterns, and training sets in a binary format which we get when we train our chat bot model.<\/li>\n<li><strong>chatbot_model.h5<\/strong>: This file stores the trained model neurons weights and also the configuration of the model.<\/li>\n<li><strong>testing.py<\/strong>: This file is used to predict in which tag(classes) the user\u2019s query belongs to and return a random response from that tag.<\/li>\n<li><strong>chatbot_gui.py<\/strong>: This file is the GUI for the Chatbot where users can interact with the bot and also they can train their bot.<\/li>\n<\/ul>\n<h4>1. Import modules and load intents file<\/h4>\n<p>Make a file with the name \u2018training.py\u2019 and import all required modules<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#TechVidvan ChatBot project\r\nimport nltk, random, json , pickle\r\nnltk.download('punkt');nltk.download('wordnet')\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk import flatten\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense,Activation,Dropout\r\nfrom tensorflow.keras.optimizers import SGD<\/pre>\n<p>Create a class with the name \u201cTraining\u201d. In the constructor of this class we will initialize all variables which will be accessible through all class methods. So firstly we will read the \u2018intents.json\u2019 file and will parse the intents file which is in JSON format by json module into the \u2018intents\u2019 variable using json. The \u2018ignore words\u2019 variable will contain all the symbols which we are going to remove from patterns.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">lemmatizer=WordNetLemmatizer()\r\nclass Training:\r\ndef __init__(self):\r\n    #read and load the intent file\r\n    data_file=open('intents.json').read()\r\n    self.intents=json.loads(data_file)['intents']\r\n    self.ignore_words=list(\"!@#$%^&amp;*?\")\r\n    self.process_data()<\/pre>\n<p>Intents.json file :<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/intents-file.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-85744\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/intents-file.webp\" alt=\"intents file\" width=\"1349\" height=\"665\" \/><\/a><\/p>\n<h4>2. Preprocessing the Data<\/h4>\n<p>Preprocess is required to transform textual data into a clean data set that will eventually be fed in our python chatbot models. We&#8217;ll create a class method process_data() which will perform various operations on our text data.<\/p>\n<p><strong>a. Tokenizing:<\/strong> Tokenizing is the process of splitting a stream of texts like sentences into smaller chunks(tokens) like words.<\/p>\n<p>We will be using a natural language processing module named \u2018nltk\u2019 which contains the \u2018word_tokenize()\u2019 function for the tokenizing process. In this method we will iterate through patterns and tokenize each sentence. For iteration, we are going to use the in-built python map function.<\/p>\n<p>Map function is used to link \u201cFunctions\u201d with every element of the \u201cIterables\u201d and return the generator. This generator can be later converted to lists or any other data type. Let\u2019s see what are arguments of map functions are:<\/p>\n<p><strong>1. Function:<\/strong> you can create your function using the \u201cdef\u201d keyword and put the function name in Map as the first parameter or you can use lambda function expression. For more details on lambda function you can visit <a href=\"https:\/\/data-flair.training\/blogs\/python-lambda-expression\/\">Python Lambda Expression<\/a>.<\/p>\n<p><strong>2. Iterables:<\/strong> Iterables are nothing but a python object which can return its member one at a time. Examples can be strings, lists, sets, tuples etc. If you want, you can apply more iterables separated by commas in the map function.<\/p>\n<p>Now you know how the map function works. Let\u2019s use it in our code.<\/p>\n<p>As I said earlier, we are iterating over patterns and tokenizing each sentence. So for this we are going to use map function. First argument will be the \u201cword_tokenize\u201d function and the second argument will be the patterns.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def process_data(self):\r\n   #fetch patterns and tokenize them into words\r\n   self.pattern=list(map(lambda x:x[\"patterns\"],self.intents))\r\n   self.words=list(map(word_tokenize,flatten(self.pattern)))<\/pre>\n<p>After every iteration, we will get words or chunks from these sentences which we will store into the \u2018words\u2019 variable. After that we will make a \u201cdocument\u201d variable which will have a tuple object containing two data\u2019s. First will be the tokenized words and second will be its respective tag or class name.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#fetch classes i.e. tags and store in documents along with tokenized patterns\r\nself.classes= flatten( [[x[\"tag\"]]*len(y) for x,y in zip(self.intents,self.pattern)])\r\nself.documents=list(map(lambda x,y:(x,y),self.words,self.classes))<\/pre>\n<p>After splitting words from patterns, the next step is to know the meaning of words. For this we we can use:<\/p>\n<p><strong>a. Stemming<\/strong><\/p>\n<p>Stemming is the process of reducing words into their word stem i.e. root of the words. If a user&#8217;s query contains an error word like &#8220;crazie&#8221;, stemming will reduce it to &#8220;crazy,&#8221; which is the root word. The main issue with stemming is that it might result in wrong meaning. For example, if the error word is \u2018orde&#8217; it will stem to the root word \u2018ord.&#8217; We can&#8217;t conclude that the user is looking for the word &#8220;order&#8221; or &#8220;ordeal&#8221; based on this.<\/p>\n<p><strong>b. Lemmatization<\/strong><\/p>\n<p>Lemmatization is the process of reducing words into their root words and ensures that the word is meaningful or in dictionary form. In Lemmatization the root word is called Lemma. Lemmatization is able to maintain the context of the user&#8217;s query pattern which helps to get meaningful words.<\/p>\n<p>In this project we are going to use the Lemmatization method, you can also try the stemming method. After lemmatizing words, store them in the \u201cwords\u201d variable and also remove all symbols if they are present in the tokenized words and lower case all the words.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#lower case and filter all the symbols from words\r\nself.words=list(map(str.lower,flatten(self.words)))\r\nself.words=list(filter(lambda x:x not in self.ignore_words,self.words))\r\n\r\n#lemmatize the words and sort the class and word lists\r\nself.words=list(map(lemmatizer.lemmatize,self.words))\r\nself.words=sorted(list(set(self.words)))\r\nself.classes=sorted(list(set(self.classes)))<\/pre>\n<h4>3. Bag of words and Training sets<\/h4>\n<p>Bag of words is the process that one-hot encodes textual data and converts into a fixed-size vector length. Since we require numerical data for our model, we need to transform textual data ( \u201cwords\u201d ) into numerical data. So we will vectorize chunks of words from sentences(pattern).<\/p>\n<p>We&#8217;ll use sklearn\u2019s CountVectorizer() method which will fit the words and return a list containing 0s if the word isn&#8217;t included in the intent&#8217;s pattern list and 1s if it is.<\/p>\n<p>Also, we will create training sets which will contain input sets and output sets for our model. Our input will patterns and output will be the class respective to those patterns. Also shuffle the training sets to avoid the model getting trained on the same data again and again.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def train_data(self):\r\n#initialize and set analyzer=word as we want to vectorize words not characters\r\ncv=CountVectorizer(tokenizer=lambda txt: \r\ntxt.split(),analyzer=\"word\",stop_words=None)\r\n#create the training sets for model\r\ntraining=[]\r\nfor doc in self.documents:\r\n#lower case and lemmatize the pattern words\r\npattern_words=list(map(str.lower,doc[0]))\r\npattern_words=' '.join(list(map(lemmatizer.lemmatize,pattern_words)))\r\n\r\n#train or fit the vectorizer with all words\r\n#and transform into one-hot encoded vector\r\nvectorize=cv.fit([' '.join(self.words)])\r\nword_vector=vectorize.transform([pattern_words]).toarray().tolist()[0]\r\n\r\n#create output for the respective input\r\n#output size will be equal to total numbers of classes\r\noutput_row=[0]*len(self.classes)\r\n\r\n#if the pattern is from current class put 1 in list else 0\r\noutput_row[self.classes.index(doc[1])]=1\r\ncvop=cv.fit([' '.join(self.classes)])\r\nout_p=cvop.transform([doc[1]]).toarray().tolist()[0]\r\n\r\n#store vectorized word list long with its class\r\ntraining.append([word_vector,output_row])\r\n\r\n#shuffle training sets to avoid model to train on same data again\r\nrandom.shuffle(training)\r\ntraining=np.array(training,dtype=object)\r\ntrain_x=list(training[:,0]) #patterns\r\ntrain_y=list(training[:,1]) #classes\r\nreturn train_x,train_y<\/pre>\n<h4>4. Build the machine learning model<\/h4>\n<p>Now we can use our training sets to build the sequential model. This model will have 3 layers i.e Input Layer, hidden layer, and output layer. We will use TensorFlow&#8217;s Keras function to create a model. We will use Dropout to prevent overfitting between layers. Also, our input and the hidden layer will have \u2018relu\u2019 activation function and output Dense layer will have \u2018softmax\u2019 activation function. We are going to use SGD optimizer with a learning rate of 0.01 and train our model for 200 epochs in a batch size of 10.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def build(self):\r\n #load the data from train_data function\r\n train_x,train_y = self.train_data()\r\n\r\n##Create a Sequential model with 3 layers.\r\nmodel=Sequential()\r\n#input layer with latent dimension of 128 neurons and ReLU activation function\r\nmodel.add(Dense(128,input_shape=(len(train_x[0]),),activation='relu'))\r\nmodel.add(Dropout(0.5)) #Dropout to avoid overfitting\r\n#second layer with the latent dimension of 64 neurons\r\nmodel.add(Dense(64,activation='relu'))\r\nmodel.add(Dropout(0.5))\r\n#fully connected output layer with softmax activation function\r\nmodel.add(Dense(len(train_y[0]),activation='softmax'))\r\n'''Compile model with Stochastic Gradient Descent with learning rate and\r\nnesterov accelerated gradient descent'''\r\nsgd=SGD(lr=1e-2,decay=1e-6,momentum=0.9,nesterov=True)\r\nmodel.compile(loss='categorical_crossentropy',\r\noptimizer=sgd,metrics=['accuracy'])\r\n#fit the model with training input and output sets\r\nhist=model.fit(np.array(train_x),np.array(train_y),\r\nepochs=200,batch_size=10,verbose=1)<\/pre>\n<p>After training the model we will get 100% accuracy.<\/p>\n<p>Let&#8217;s save this trained model in chatbot_model.h5\u2019 file and also store \u201cwords\u201d, \u201cclasses\u201d and \u201ctraining\u201d (input and output) sets to \u2018training_data.file\u2019 using pickle which will help while predicting the response.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#save model and words,classes which can be used for prediction.\r\nmodel.save('chatbot_model.h5',hist)\r\npickle.dump({'words':self.words,'classes':self.classes,\r\n'train_x':train_x,'train_y':train_y},open(\"training_data\",\"wb\"))<\/pre>\n<h4>5. Predicting the response for user\u2019s query<\/h4>\n<p>For predicting we will firstly create a \u2018testing.py\u2019 file and load all the required modules.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#TechVidvan ChatBot project\r\nimport nltk, random, json , pickle\r\n#nltk.download('punkt');nltk.download('wordnet')\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.tokenize import word_tokenize\r\nimport numpy as np\r\nfrom tensorflow.keras.models import load_model\r\nfrom sklearn.feature_extraction.text import CountVectorizer<\/pre>\n<p>Create a \u2018Testing\u2019 class where we will initialize all variables and load \u2018intent.json\u2019, \u2018training_data.file\u2019 and \u2018chatbot_model.h5\u2019 file. which will be accessible to all class methods. As you know our \u2018training_data.file\u2019 contains \u201cwords\u201d, \u201cclasses\u201d and \u201ctraining\u201d (input and output) sets from the training.py file.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">lemmatizer=WordNetLemmatizer()\r\ncontext={};\r\nclass Testing:\r\n def __init__(self):\r\n  #load the intent file\r\n  self.intents = json.loads(open('intents.json').read())\r\n  #load the training_data file which contains training.py file data\r\n  data=pickle.load(open(\"training_data\",\"rb\"))\r\n  self.words=data['words']\r\n  self.classes=data['classes']\r\n  self.model=load_model('chatbot_model.h5')\r\n  #set the error threshold value\r\n  self.ERROR_THRESHOLD=0.5\r\n  self.ignore_words=list(\"!@#$%^&amp;*?\")<\/pre>\n<p>Our prediction will depend on the user\u2019s query so our input sentence for prediction will be a user query. So do the same process of lemmatization and vectorization(Bag of words) that we have done for patterns in our training.py file.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def clean_up_sentence(self,sentence):\r\n #tokenize each sentence (user's query)\r\n sentence_words=word_tokenize(sentence.lower())\r\n #lemmatize the word to root word and filter symbols words\r\n sentence_words=list(map(lemmatizer.lemmatize,sentence_words))\r\n sentence_words=list(filter(lambda x:x not in \r\nself.ignore_words,sentence_words))\r\n return set(sentence_words)\r\n\r\ndef wordvector(self,sentence):\r\n #initialize CountVectorizer\r\n #txt.split helps to tokenize single character\r\n cv=CountVectorizer(tokenizer=lambda txt: txt.split())\r\n sentence_words=' '.join(self.clean_up_sentence(sentence))\r\n words=' '.join(self.words)\r\n\r\n #fit the words into cv and transform into one-hot encoded vector\r\n vectorize=cv.fit([words])\r\n word_vector=vectorize.transform([sentence_words]).toarray().tolist()[0]\r\n return(np.array(word_vector))<\/pre>\n<p>Now we will create a function \u201cclassify\u201d. This function will predict the tag(classes) for the user\u2019s query. Our python chatbot model will give us the probability value of every class(tag) for the user\u2019s query. We will consider tag(classes) probability which are higher than the Threshold value that is 0.5 in our case. After that, sort them in descending order and consider the highest probability value class(tag).<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def classify(self,sentence):\r\n #predict to which class(tag) user's query belongs to\r\n results=self.model.predict(np.array([self.wordvector(sentence)]))[0]\r\n #store the class name and probability of that class\r\n results = list(map(lambda x: [x[0],x[1]], enumerate(results)))\r\n #accept those class probability which are greater then threshold value,0.5\r\n results = list(filter(lambda x: x[1]&gt;self.ERROR_THRESHOLD ,results))\r\n\r\n #sort class probability value in descending order\r\n results.sort(key=lambda x: x[1], reverse=True)\r\n return_list = []\r\n\r\n for i in results:\r\n  return_list.append((self.classes[i[0]],str(i[1])))\r\n return return_list<\/pre>\n<p>So we are now ready for the response of the user query. As I said earlier, we are making a contextual chatbot. So we have to also check if the user\u2019s query is a response to the previous query. For that we create a context dictionary and check if the user query falls into any context and then filter the query according to the context set.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def results(self,sentence,userID):\r\n #if context is maintained then filter class(tag) accordingly\r\n if sentence.isdecimal():\r\n if context[userID]==\"historydetails\":\r\n   return self.classify('ordernumber')\r\nreturn self.classify(sentence)<\/pre>\n<p>For example in the \u201cintents.json\u201d file, you will see a tag named \u2018offers\u2019 which has a set key with the value \u201cproductoffers\u201d as context which means that the user is looking for those products which have offers on it. So store the value \u201cproductoffers\u201d in the context dictionary with the key as \u201cuserID\u201d. Now the context is ready for the user\u2019s next query. Finally we will return response of those intent\u2019s tag which have a filter key with the value as \u201cproductoffers\u201d<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def response(self,sentence,userID='TechVidvan'):\r\n #get class of users query\r\n results=self.results(sentence,userID)\r\n print(sentence,results)\r\n #store random response to the query\r\n ans=\"\"\r\n if results:\r\n  while results:\r\n   for i in self.intents['intents']:\r\n    #check if tag == query's class\r\n     if i['tag'] == results[0][0]:\r\n\r\n       #if class contains key as \"set\"\r\n       #then store key as userid along with its value in\r\n       #context dictionary\r\n       if 'set' in i and not 'filter' in i:\r\n          context[userID] = i['set']\r\n       #if the tag doesn't have any filter return response\r\n       if not 'filter' in i:\r\n         ans=random.choice(i['responses'])\r\n\r\n       #if a class has key as filter then check if context dictionary key's value is same as filter value\r\n       #return the random response\r\n       if userID in context and 'filter' in i and i['filter']==context[userID]:\r\n        if 'set' in i:\r\n         context[userID] = i['set']\r\n        ans=random.choice(i['responses'])\r\n\r\nresults.pop(0)\r\n#if ans contains some value then return response to user's query else return some message\r\nreturn ans if ans!=\"\" else \"Sorry ! I am still Learning.\\nYou can train me by providing more datas.\"<\/pre>\n<p>Now we&#8217;ll utilise Python&#8217;s Tkinter module to create a graphical user interface. The Tkinter library provides the quickest and easiest way to construct GUI applications as it&#8217;s equipped with several helpful libraries. We will accept the user&#8217;s input query and then on click of send button return the response of that query.<\/p>\n<p><strong>Import modules and files. Initialize the window<\/strong><\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from tkinter import *\r\nfrom tkinter import ttk\r\nimport json\r\n#import the training.py\r\n#and testing.py file\r\nimport testing as testpy\r\nimport training as trainpy\r\nBG_GRAY=\"#ABB2B9\"\r\nBG_COLOR=\"#000\"\r\nTEXT_COLOR=\"#FFF\"\r\nFONT=\"Helvetica 14\"\r\nFONT_BOLD=\"Helvetica 13 bold\"\r\n\r\nclass ChatBot:\r\ndef __init__(self):\r\n #initialize tkinter window\r\n self.window=Tk()\r\n self.main_window()\r\n self.test=testpy.Testing()\r\n\r\n#run window\r\n def run(self):\r\n  self.window.mainloop()<\/pre>\n<p>Create the main window for the conversation between user and chatbot.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def main_window(self):\r\n #add title to window and configure it\r\n self.window.title(\"ChatBot\")\r\n self.window.resizable(width=False,height=False)\r\n self.window.configure(width=520,height=520,bg=BG_COLOR)\r\n #add tab for Chatbot and Train Bot in Notebook frame\r\n self.tab = ttk.Notebook(self.window)\r\n self.tab.pack(expand=1,fill='both')\r\n self.bot_frame=ttk.Frame(self.tab,width=520,height=520)\r\n self.train_frame=ttk.Frame(self.tab,width=520,height=520)\r\n self.tab.add(self.bot_frame,text='TechVidvanBot'.center(100))\r\n self.tab.add(self.train_frame,text='Train Bot'.center(100))\r\n self.add_bot()\r\n self.add_train()<\/pre>\n<p>Create heading for the window, text-area where the text will be displayed and input entry where the user will type the query along with the Send button.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def add_bot(self):\r\n #Add heading to the Chabot window\r\nhead_label=Label(self.bot_frame,bg=BG_COLOR,fg=TEXT_COLOR,text=\"Welcome to TechVidvan\",font=FONT_BOLD,pady=10)\r\n head_label.place(relwidth=1)\r\n line = Label(self.bot_frame,width=450,bg=BG_COLOR)\r\n line.place(relwidth=1,rely=0.07,relheight=0.012)\r\n\r\n #create text widget where conversation will be displayed\r\n\r\nself.text_widget=Text(self.bot_frame,width=20,height=2,bg=\"#fff\",fg=\"#000\",font=FONT,padx=5,pady=5)\r\n self.text_widget.place(relheight=0.745,relwidth=1,rely=0.08)\r\n self.text_widget.configure(cursor=\"arrow\",state=DISABLED)\r\n\r\n #create scrollbar\r\n scrollbar=Scrollbar(self.text_widget)\r\n scrollbar.place(relheight=1,relx=0.974)\r\n scrollbar.configure(command=self.text_widget.yview)\r\n\r\n #create bottom label where message widget will placed\r\n bottom_label=Label(self.bot_frame,bg=BG_GRAY,height=80)\r\n bottom_label.place(relwidth=1,rely=0.825)\r\n #this is for user to put query\r\n\r\nself.msg_entry=Entry(bottom_label,bg=\"#2C3E50\",fg=TEXT_COLOR,font=FONT)\r\n self.msg_entry.place(relwidth=0.788,relheight=0.06,rely=0.008,relx=0.008)\r\n self.msg_entry.focus()\r\n self.msg_entry.bind(\"&lt;Return&gt;\",self.on_enter)\r\n #send button which will call on_enter function to send the query\r\nsend_button=Button(bottom_label,text=\"Send\",font=FONT_BOLD,width=8,bg=\"Green\",command=lambda: self.on_enter(None))\r\n send_button.place(relx=0.80,rely=0.008,relheight=0.06,relwidth=0.20)<\/pre>\n<p>If the user pressed the send button, the button should perform some event(action) , that is the query should be displayed on the text-area along with the bot prediction.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def on_enter(self,event):\r\n #get user query and bot response\r\n msg=self.msg_entry.get()\r\n self.my_msg(msg,\"You\")\r\n self.bot_response(msg,\"Bot\")\r\n\r\ndef bot_response(self,msg,sender):\r\n self.text_widget.configure(state=NORMAL)\r\n #get the response for the user's query from testing.py file\r\n self.text_widget.insert(END,str(sender)+\" : \"+self.test.response(msg)+\"\\n\\n\")\r\n self.text_widget.configure(state=DISABLED)\r\n self.text_widget.see(END)\r\n\r\ndef my_msg(self,msg,sender):\r\n #it will display user query and bot response in text_widget\r\n if not msg:\r\n return\r\n self.msg_entry.delete(0,END)\r\n self.text_widget.configure(state=NORMAL)\r\n self.text_widget.insert(END,str(sender)+\" : \"+str(msg)+\"\\n\")\r\n self.text_widget.configure(state=DISABLED)<\/pre>\n<p>We can also train the model by creating our own intent\u2019s. We can achieve this by creating a \u2018Train Bot\u2019 section which will accept tags, patterns and responses from the user and utilise them to train our model for giving the best response which will eventually make your work easier.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def add_train(self):\r\n #Add heading to the Train Bot window\r\n\r\nhead_label=Label(self.train_frame,bg=BG_COLOR,fg=TEXT_COLOR,text=\"Train Bot\",font=FONT_BOLD,pady=10)\r\n head_label.place(relwidth=1)\r\n\r\n #Tag Label and Entry for intents tag.\r\n taglabel=Label(self.train_frame,fg=\"#000\",text=\"Tag\",font=FONT)\r\n taglabel.place(relwidth=0.2,rely=0.14,relx=0.008)\r\n self.tag=Entry(self.train_frame,bg=\"#fff\",fg=\"#000\",font=FONT)\r\n self.tag.place(relwidth=0.7,relheight=0.06,rely=0.14,relx=0.22)\r\n #Pattern Label and Entry for pattern to our tag.\r\n self.pattern=[]\r\n for i in range(2):\r\n\r\npatternlabel=Label(self.train_frame,fg=\"#000\",text=\"Pattern%d\"%(i+1),font=FONT)\r\n patternlabel.place(relwidth=0.2,rely=0.28+0.08*i,relx=0.008)\r\n self.pattern.append(Entry(self.train_frame,bg=\"#fff\",fg=\"#000\",font=FONT))\r\n self.pattern[i].place(relwidth=0.7,relheight=0.06,rely=0.28+0.08*i,relx=0.22)\r\n\r\n#Response Label and Entry for response to our pattern.\r\n self.response=[]\r\n for i in range(2):\r\n responselabel=Label(self.train_frame,fg=\"#000\",text=\"Response%d\"%(i+1),font=FONT)\r\n responselabel.place(relwidth=0.2,rely=0.50+0.08*i,relx=0.008)\r\n self.response.append(Entry(self.train_frame,bg=\"#fff\",fg=\"#000\",font=FONT))\r\n self.response[i].place(relwidth=0.7,relheight=0.06,rely=0.50+0.08*i,relx=0.22)\r\n\r\n#to train our bot create Train Bot button which will call on_train function\r\nbottom_label=Label(self.train_frame,bg=BG_GRAY,height=80)\r\nbottom_label.place(relwidth=1,rely=0.825)\r\n\r\ntrain_button=Button(bottom_label,text=\"Train Bot\",font=FONT_BOLD,width=12,bg=\"Green\",command=lambda: self.on_train(None))\r\ntrain_button.place(relx=0.20,rely=0.008,relheight=0.06,relwidth=0.60)<\/pre>\n<p>After the \u201cTrain Bot\u201d button is pressed the data should be inserted into the intents.json file and the model should train on new data.<\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def on_train(self,event):\r\n #read intent file and append created tag,pattern and responses from add_train function\r\n with open('intents.json','r+') as json_file:\r\n  file_data=json.load(json_file)\r\n  file_data['intents'].append({\r\n  \"tag\": self.tag.get(),\r\n  \"patterns\": [i.get() for i in self.pattern],\r\n  \"responses\": [i.get() for i in self.response],\r\n  \"context\": \"\"\r\n  })\r\n  json_file.seek(0)\r\n  json.dump(file_data, json_file, indent = 1)\r\n #run and compile model from our training.py file.\r\n train=trainpy.Training()\r\n train.build(); print(\"Trained Successfully\")\r\n self.test=testpy.Testing()<\/pre>\n<h4>6. Run the Python Chatbot Project<\/h4>\n<p>In order to run the chatbot, we need to run chatbot_gui.py.<\/p>\n<p>Run the following command on the terminal<\/p>\n<p><strong>python chatbotgui.py<\/strong><\/p>\n<h3>Python Chatbot Output<\/h3>\n<p><strong>Training the Model :<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/chatbot-model-training.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-85745\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/chatbot-model-training.webp\" alt=\"chatbot model training\" width=\"1117\" height=\"641\" \/><\/a><\/p>\n<p><strong>User query and Bot response:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/python-chat-bot-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-85746\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/python-chat-bot-output.webp\" alt=\"python chat bot output\" width=\"680\" height=\"576\" \/><\/a><\/p>\n<p>As you can see in the above screenshot, when the user asked for order details, the context dictionary was set with the value as \u201corderid\u201d. So after the user provided the orderid as 9910 the bot predicted the class in the intents.json having the filter key with the value as \u201corderid\u201d. This is how the contextual chatbot works.<\/p>\n<h4>Train the Bot with new classes, patterns, and responses :<\/h4>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/chatbot-training-gui.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-85747\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/12\/chatbot-training-gui.webp\" alt=\"chatbot training gui\" width=\"682\" height=\"578\" \/><\/a><\/p>\n<p>Congratulations! Now you will be able to chat easily with your ChatBot friend which will have all the qualities.<\/p>\n<h3>Summary<\/h3>\n<p>In this Python Chatbot Project, we understood the implementation of Chatbot using Deep Learning algorithms. The chatbot can be customised and trained to meet specific needs with its accurate response. AI Chatbots are now being used in nearly all industries for the convenience of users and company stakeholders. Well trained Chatbot makes one to one conversation easier and faster.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Do you want your friend to solve your problems instantly? and most importantly Do you want your friend to be with you for the rest of your life? Then you don&#8217;t have to be&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":85748,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[210],"tags":[4569,4570,4571,4572,4573,4574],"class_list":["post-85717","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-machine-learning","tag-chatbot-project","tag-chatbot-python","tag-chatterbot-project","tag-deep-learning-chatbot-project","tag-machine-learning-chat-bot","tag-python-chat-bot-project"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Create Chatbot with Python &amp; Artificial Intelligence - TechVidvan<\/title>\n<meta name=\"description\" content=\"Implement Chatbot project using Python &amp; Deep Learning algorithms. It can be customized &amp; trained to meet specific needs\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Create Chatbot with Python &amp; Artificial Intelligence - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Implement Chatbot project using Python &amp; Deep Learning algorithms. It can be customized &amp; trained to meet specific needs\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-12-27T03:30:38+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-06-03T09:36:29+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/12\/python-chatbot-project-nltk-ai.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Create Chatbot with Python &amp; Artificial Intelligence - TechVidvan","description":"Implement Chatbot project using Python & Deep Learning algorithms. It can be customized & trained to meet specific needs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/","og_locale":"en_US","og_type":"article","og_title":"Create Chatbot with Python &amp; Artificial Intelligence - TechVidvan","og_description":"Implement Chatbot project using Python & Deep Learning algorithms. It can be customized & trained to meet specific needs","og_url":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-12-27T03:30:38+00:00","article_modified_time":"2026-06-03T09:36:29+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/12\/python-chatbot-project-nltk-ai.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Create Chatbot with Python &amp; Artificial Intelligence","datePublished":"2021-12-27T03:30:38+00:00","dateModified":"2026-06-03T09:36:29+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/"},"wordCount":2196,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/12\/python-chatbot-project-nltk-ai.webp","keywords":["Chatbot Project","Chatbot python","chatterbot project","Deep Learning Chatbot Project","machine learning chat bot","python chat bot project"],"articleSection":["Machine Learning Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/","url":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/","name":"Create Chatbot with Python &amp; Artificial Intelligence - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/12\/python-chatbot-project-nltk-ai.webp","datePublished":"2021-12-27T03:30:38+00:00","dateModified":"2026-06-03T09:36:29+00:00","description":"Implement Chatbot project using Python & Deep Learning algorithms. It can be customized & trained to meet specific needs","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/12\/python-chatbot-project-nltk-ai.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/12\/python-chatbot-project-nltk-ai.webp","width":1200,"height":628},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/chatbot-project-python-ai\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Create Chatbot with Python &amp; Artificial Intelligence"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/85717","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=85717"}],"version-history":[{"count":2,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/85717\/revisions"}],"predecessor-version":[{"id":448033,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/85717\/revisions\/448033"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/85748"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=85717"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=85717"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=85717"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}