Building Chatbots in Python


A chatbot is a computer program designed to simulate conversations with human users via text or voice. It uses AI and NLP techniques to help understand and interpret user’s messages and provide relevant responses. In this article, we will see how to create a chatbot with the help of Python.

Chatbots like chatGPT have become popular since the end of 2022 and have a wide-scale use case for people of different fields. Chatbots are also integrated with mobile apps like Swiggy and Zomato to provide faster resolution to customer complaints.

Chatbots are of multiple types which are as follows:

  • Rule-based chatbots − They are designed to respond to user input based on a predefined set of rules or decision trees. They can be very simple of complicated and are mainly used to handle basic user requests only.

  • Retrieval-Based Chatbots − They make use of NLP to analyse user input and then match it with a pre existing database which consists of responses. The chatbot then selects the best match using logic adapters and presents it the users.

  • Generative Chatbots − They make use of AI and ML algorithms to generate unique responses to users’ inputs. They are highly advanced and are capable of learning from user interactions to improve their responses.

  • Hybrid Chatbots − They are a combination or rule based and generative approached to provide the best response to user input. They often include additional features like sentiment analysis, context awareness as well as personalized recommendations.

Steps to Build a Chatbot in Python

Building a chatbot involves several steps. The following is an overview of this process:

1. Defining the purpose and scope

Here we decide what our chatbot has to accomplish. What is its target audience and what kind of language and tone should our chatbot use?

2. Chabot framework

Python offers a variety of frameworks like ChatterBot, NLTK, RASA and many more to help make chatbots, all of which have their own pros and cons. The best fit depends upon your needs.

3. Collect and pre-process data

Training the chatbot requires data like conversation logs, customer support emails etc to be cleaned and then transformed into a format which the chatbot framework can benefit from.

4. Training the chatbot

Once data is pre-processed, it can be used to train the chatbot depending upon the framework used and use case you may choose how to create a knowledge base.

5. Integration with a messaging platform

The chatbot created, alone has no purpose and has to be given a user interface and be connected with a platform like Facebook messenger, telegram or WhatsApp. Every platform has its own set of APIs and documentations which help in the connection of this chatbot. Chatbots like those of swiggy are connected in the app itself.

6. Test your chatbot

Before finally deploying the chatbot and making it available to users, it should be tested manually or with the help of automated testing. Great care should be taken to ensure the chatbot does not provide responses which might lead to legal trouble.

7. Deploy your chatbot

Once the tester is satisfied with the chatbot, it can be deployed to a server or a cloud platform. Configuration of the environment setting up a webhook or using a chatbot hosting service are common parts of this step.

8. Monitor and improve your chatbot

Once the chatbot has been deployed, it’s performance has to be monitored and the user feedback has to be taken into consideration. Analytical tools like google analytics or Mixpanel help to track common metrics such as user engagement, retention and satisfaction.

Before going forward with creating chatbots in python, we have to install the chatterbot library using the following command:

pip install chatterbot

and

pip install chatterbot-corpus

Greeting Chatbot

This is a simple chatbot that makes use of some pre-existing conversational data from the english.greetings and english.conversations corpora to train the bot. With the help of this code, the bot can answer basic questions. Of course one can customize and improve the chatbot by training it with more data and implementing additional features.

After completion of training, the chatbot runs an infinite while loop to create a back and forth conversation with the users. The loop is terminated when any of the strings in the “end” list are given as a response by users.

Example

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

bot = ChatBot('TPTBot')
trainer = ChatterBotCorpusTrainer(bot)

# if user enters any of the list elements, program is terminated
end=["q","exit", "end", "stop", "quit"]
trainer.train('chatterbot.corpus.english.greetings', 'chatterbot.corpus.english.conversations')
while True:
  # take user input
    user_input = input("You: ")    
    if user_input in end:
      break
    else:
      response = bot.get_response(user_input)
      print("TPTBot: ", response)

Output

Training greetings.yml: [########         ] 40%
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data]    /root/nltk_data...
[nltk_data]   Package averaged_perceptron_tagger is already up-to-
[nltk_data]      date!
Training greetings.yml: [####################] 100%
Training conversations.yml: [####################] 100%
You: Hi
TPTBot:  Hello
You: How are you?
TPTBot:  I am doing well.
You: end

Therapy Chatbot

Therapy chatbots are AI-powered tools that assists psychologists, psychotherapists, and other healthcare providers in enhancing the well being of patients who may or are dealing with psychiatric disorders, stress and or trauma. Online therapy chatbots can also benefit people who are not comfortable in a face to face therapy session or have a financial set back as real time therapy can be costly and often not covered by insurances.

Here we make use of logic adapters which determine the logic for how ChatterBot selects a response to a given input statement. The 2 logic adapters used here are BestMatch which helps select the best response based on similarity to the user's input and MathematicalEvaluation which allows the bot to handle math-related queries.

There are also 2 pre-processors specified to clean up the input before passing it to the logic adapters. We then train the chatbot with a corpus of therapy related data. For this example, we make use of the “chatterbot.corpus.english” corpus and a custom “therapy_corpus.yml” file that contains therapy-related responses and is available here.

Make sure download the “therapy_corpus.yml” file and specify the path in the code if it is not in the same folder as the script.

Example

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('TherapyBot',
   logic_adapters=[
      'chatterbot.logic.BestMatch',
      'chatterbot.logic.MathematicalEvaluation'
   ],
   preprocessors=[
   'chatterbot.preprocessors.clean_whitespace',
   'chatterbot.preprocessors.unescape_html'
])

trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train('chatterbot.corpus.english')

# therapy_corpus.yml will be created seperately
trainer.train('/content/therapy_corpus.yml')
end=["q","exit", "end", "stop", "quit"]
while True:
    message = input('You: ')
    if message in end:
      break
    else:
      response = chatbot.get_response(message)
      print('TherapyBot:', response)

Output

Training ai.yml: [##              ] 10%
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data]    /root/nltk_data...
[nltk_data]   Package averaged_perceptron_tagger is already up-to-
[nltk_data]      date!
Training ai.yml: [####################] 100%
Training botprofile.yml: [####################] 100%
Training computers.yml: [####################] 100%
Training conversations.yml: [####################] 100%
Training emotion.yml: [####################] 100%
Training food.yml: [####################] 100%
Training gossip.yml: [####################] 100%
Training greetings.yml: [####################] 100%
Training health.yml: [####################] 100%
Training history.yml: [####################] 100%
Training humor.yml: [####################] 100%
Training literature.yml: [####################] 100%
Training money.yml: [####################] 100%
Training movies.yml: [####################] 100%
Training politics.yml: [####################] 100%
Training psychology.yml: [####################] 100%
Training science.yml: [####################] 100%
Training sports.yml: [####################] 100%
Training trivia.yml: [####################] 100%
Training therapy_corpus.yml: [####################] 100%
You: Hi
TherapyBot: Hello
You: I'm feeling really stressed out lately
TherapyBot: I'm sorry to hear that. Can you tell me more about what's been going on?
You: nothing
TherapyBot: Or something
You: end

Conclusion

Chatbots are a highly useful tool and have use cases ranging from automated customer complaint resolution to home automation. Alexa which is a voice based chatbot and Chat Generative Pretrained Transformer or simply chatGPT are common examples in today’s world. Python is popular for building chatbots and offers a variety of libraries. On the whole chatbots have the potential to revolutionize the way businesses and organizations interact with their users. They not only provide 24/7 support but also deliver personalized recommendations. There are numerous kinds of chatbots available and the choice varies from use case to use case.

Updated on: 04-Oct-2023

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements