ad
ad
Topview AI logo

How to create an accurate Chat Bot Response System in Python Tutorial (2021)

Education


How to Create an Accurate Chat Bot Response System in Python Tutorial (2021)

In this tutorial, we're going to create a simple chat bot in Python using a straightforward algorithm that recognizes specific text and delivers appropriate responses. There are no complicated AI or machine learning techniques involved; instead, we'll use regular expression (regex) matching.

First, we'll build a basic response system that can handle a variety of user inputs, understanding important keywords to give a logical response. Here’s what the final product will do:

  1. Recognize greetings like "hello"
  2. Respond to questions like "how are you?"
  3. Offer generic suggestions or responses to certain inquiries
  4. Recognize and respond to statements about eating preferences

Let’s dive into the detailed steps to create this bot from scratch.

Step-by-Step Guide

  1. Project Setup:

    Create a new Python project using Python 3.8. Make sure your environment is set up to run vanilla Python; no external libraries are needed.

  2. Initial Imports:

    import re
    import long_responses as long
    
    • Import the re library for regex operations.
    • Create a new file named long_responses.py which will store longer bot responses.
  3. Main Loop & User Input:

    Create an infinite loop to continually prompt the user for input:

    while True:
        user_input = input("You: ")
        print(f"Bot: (get_response(user_input))")
    
  4. Splitting the User Message:

    Write a function to split the user input into individual words:

    def get_response(user_input):
        split_message = re.split(r'\s+|[,;?!.-]\s*', user_input.lower())
        response = check_all_messages(split_message)
        return response
    
  5. Message Probability Calculation:

    Define functions to calculate how likely a message matches predefined keywords:

    def message_probability(user_message, recognized_words, single_response=False, required_words=[]):
        message_certainty = 0
        has_required_words = True
    
        for word in user_message:
            if word in recognized_words:
                message_certainty += 1
    
        percentage = float(message_certainty) / float(len(recognized_words))
    
        for word in required_words:
            if word not in user_message:
                has_required_words = False
                break
    
        if has_required_words or single_response:
            return int(percentage * 100)
        return 0
    
  6. Response Checking:

    Create a function to check all possible responses and determine the best match:

    def check_all_messages(message):
        highest_prob_list = ()
    
        def response(bot_response, list_of_words, single_response=False, required_words=[]):
            nonlocal highest_prob_list
            highest_prob_list[bot_response] = message_probability(message, list_of_words, single_response, required_words)
    
        # Predefined responses
        response('Hello!', ['hello', 'hi', 'hey', 'sup', 'heyo'], single_response=True)
        response('I\'m doing fine, and you?', ['how', 'are', 'you', 'doing'], required_words=['how'])
        response('Thank you!', ['i', 'love', 'code', 'palace'], required_words=['code', 'palace'])
        response(long.R_EATING, ['what', 'you', 'eat'], required_words=['you', 'eat'])
    
        best_match = max(highest_prob_list, key=highest_prob_list.get)
        return long.unknown() if highest_prob_list[best_match] < 1 else best_match
    
  7. Handling Unrecognized Inputs:

    Define responses when the bot doesn't understand the input in long_responses.py:

    import random
    
    R_EATING = "I don't like eating anything because I'm a bot obviously!"
    
    def unknown():
        response = ['Could you please rephrase that?', '...', 'Sounds about right.', 'What does that mean?'][random.randrange(4)]
        return response
    
  8. Execution and Testing:

    Test your program by entering different sentences and ensure it responds appropriately.

Here’s how the complete script holds up as you input various statements and questions to the bot. To test, run your script and interact with your bot to see how it handles different scenarios.

Keywords

  • Python
  • Chat Bot
  • Regex
  • Response System
  • AI
  • Machine Learning
  • Text Recognition
  • Algorithm

FAQ

Q: What libraries do I need to install for this project?

A: No external libraries are needed. The project uses only Python's built-in libraries such as re for regex.

Q: How does the bot recognize user input?

A: The bot uses regex to split and match words in the user input against predefined keywords. It calculates the probability that the user input matches known phrases.

Q: Can I add more responses to the bot?

A: Yes, you can extend the response function with more predefined keywords and responses, both short and long, as needed.

Q: How does the bot handle unrecognized inputs?

A: The bot refers to a list of generic unknown responses stored in long_responses.py and replies with one of them when it can't determine an accurate match.

Q: How do I run the project?

A: Ensure you have Python 3.8 installed and run the main script. The bot will prompt you for input, and you can interact with it in your command line or terminal.

By following this guide, you can create a fundamental yet functional chat bot in Python capable of recognizing user input, offering appropriate responses, and gracefully handling unrecognized inputs. Feel free to expand and improve the bot by adding more keywords and sophisticated logic.