Chatbots Examples with ChatterBot – How to Add Logic

In the previous post How to Create a Chatbot with ChatBot Open Source and Deploy It on the Web I wrote how to deploy ChatterBot on pythonanywhere hosting site with Django webfamework. In this post we will look at few useful chatbots examples for implementing logic in our chatbot. This chatbot was developed in the previous post and is based on ChatterBot python library.

Making Chatbot Start Conversation with Specific Question

Suppose we want to start conversation with specific sentence that chatbot needs to show. For example, when the user open website, the chatbot can start with the specific question: “Did you find what you were looking for?”
Or, if you are building chatbot for conversation about previous day/week work, you probably want to start with “How was you previous day/week in terms of progress to goal?” How can we do this with ChatterBot framework?

Conversation diagram

It turns out, that ChatterBot has several logic adapters that allow to build conversation per different requirements.

Here is how I used logic adapter SpecificResponseAdapter for chatbot to start with initial predefined question:

 chatbot = ChatBot("mybot",
       logic_adapters=[
       {
            'import_path': 'chatterbot.logic.SpecificResponseAdapter',
            'input_text': 'prev_day_disk',
            'output_text': 'How much did you do toward your goal on previous day?'
        }
        .....

In views.py that was created in prev. post[1], I put input “prev_day_disk” to runbot instead of blank string. Because in the beginning of chat there is no user input and I used this to enter input_text and get desired output as specified in output_text.

def press_my_buttons(request):
    resp=""
    conv=""
    if request.POST:
        conv=request.POST.get('conv', '')
        user_input=request.POST.get('user_input', '')

        userid=request.POST.get('userid', '')
        if (userid == ""):
            userid=uuid.uuid4()

        resp=runbot(user_input, request, userid)

     
        conv=conv + "" + str(user_input) + "\n" + "BOT:"+ str(resp) + "\n"
    else:
        resp=runbot("prev_day_disk", request, "")
        conv =  "BOT:"+ str(resp) + "\n";
   
    return render(request, 'my_template.html', {'conv': conv })

SpecificResponseAdapter can be used also in other places of conversation (not just in the beginning). For example we could use criteria if there is no input from user during 15 secs and user is not typing anything (not sure yet how easily it is to check if user typing or not) then switch conversation to new topic by making chatbot app send new question.

How to Add Intelligence to Chatbot App

After the user replied to response how was his/her week, I want chatbot to be able to recognize the response as belonging to one of the 3 groups: bad, so-so, good. This is a machine learning classification problem. However here we will not create text classification algorithm, instead we will use built in functionality.

We will use another logic adapter, called BestMatch.
With this adapter we need specify statement_comparison_function and response_selection_method :

chatbot = ChatBot("mybot",
       logic_adapters=[
       {
            'import_path': 'chatterbot.logic.SpecificResponseAdapter',
            'input_text': 'How much did you do toward your goal on previous day?',
            'output_text': 'How much did you do toward your goal on previous day?'
        },
        {
            "import_path": "chatterbot.logic.BestMatch",
            "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
            "response_selection_method": "chatterbot.response_selection.get_first_response"
        }

Best Match Adapter – is a logic adapter that returns a response based on known responses to the closest matches to the input statement. [2]

The best match adapter uses a function to compare the input statement to known statements. Once it finds the closest match to the input statement, it uses another function to select one of the known responses to that statement.

To use this adapter for the above example I need at minimum create 1 samples per each group. In the below example I used following for testing of chatbot on 2 groups (skipped so-so).

 if (train_bot == True):
  chatbot.train([
    "I did not do much this week",
    "Did you run into the problems with programs or just did not have time?"
  ])


  chatbot.train([
    "I did a lot of progress",
    "Fantastic! Keep going on"
  ])

After the training, if the user enters something close to “I did not do much this week” the chatbot will respond with “Did you run into the problems with programs or just did not have time?”, and if user enters something like “Did a lot of progress” the bot response will be “Fantastic! Keep going on” even if the input is slightly different from training.

So we looked how to build a chatbot with logic that makes chatbot able to ask questions as needed or classify user input in several buckets and respond to user input accordingly. The code for this post is provided at the link listed below[3]

References
1. How to Create a Chatbot with ChatBot Open Source and Deploy It on the Web
2. ChatterBot – Logic
3.Python Chatterbot Example with Added Logic – source code