Login With Github

ChatterBot Logic Adapters

Logic adapters determine the logic for how ChatterBot selects a response to a given input statement.

The logic adapter that your bot uses can be specified by setting the logic_adapters parameter to the import path of the logic adapter you want to use.

It is possible to enter any number of logic adapters for your bot to use. If multiple adapters are used, then the bot will return the response with the highest calculated confidence value. If multiple adapters return the same confidence, then the adapter that is entered into the list first will take priority.

chatbot = ChatBot(
    "My ChatterBot",
    logic_adapters=[
        "chatterbot.logic.BestMatch"
    ]
)

The MultiLogicAdapter

ChatterBot internally uses a special logic adapter that allows it to choose the best response generated by any number of other logic adapters.

Selecting a response from multiple logic adapters

The MultiLogicAdapter is used to select a single response from the responses returned by all of the logic adapters that the chat bot has been configured to use. Each response returned by the logic adapters includes a confidence score that indicates the likeliness that the returned statement is a valid response to the input.

Response selection

The MultiLogicAdapter will return the response statement that has the greatest confidence score. The only exception to this is a case where multiple logic adapters return the same statement and therefore agree on that response.

For this example, consider a scenario where multiple logic adapters are being used. Assume the following results were returned by a chat bot's logic adapters.

Confidence Statement
0.2 Good morning
0.5 Good morning
0.7 Good night

In this case, two of the logic adapters have generated the same result. When multiple logic adapters come to the same conclusion, that statement is given priority over another response with a possibly higher confidence score. The fact that the multiple adapters agreed on a response is a significant indicator that a particular statement has a greater probability of being a more accurate response to the input.

When multiple adapters agree on a response, the greatest confidence score that was generated for that response will be returned with it.

Methods

MultiLogicAdapter allows ChatterBot to use multiple logic adapters. It has methods that allow ChatterBot to add an adapter, set the chat bot, and process an input statement to get a response.

from __future__ import unicode_literals
from collections import Counter
from chatterbot import utils
from .logic_adapter import LogicAdapter


class MultiLogicAdapter(LogicAdapter):
    """
    MultiLogicAdapter allows ChatterBot to use multiple logic
    adapters. It has methods that allow ChatterBot to add an
    adapter, set the chat bot, and process an input statement
    to get a response.
    """

    def __init__(self, **kwargs):
        super(MultiLogicAdapter, self).__init__(**kwargs)

        # Logic adapters added by the chat bot
        self.adapters = []

        # Required logic adapters that must always be present
        self.system_adapters = []

    def get_initialization_functions(self):
        """
        Get the initialization functions for each logic adapter.
        """
        functions_dict = {}

        # Iterate over each adapter and get its initialization functions
        for logic_adapter in self.get_adapters():
            functions = logic_adapter.get_initialization_functions()
            functions_dict.update(functions)

        return functions_dict


    def process(self, statement):
        """
        Returns the output of a selection of logic adapters
        for a given input statement.

        :param statement: The input statement to be processed.
        """
        results = []
        result = None
        max_confidence = -1

        for adapter in self.get_adapters():
            if adapter.can_process(statement):

                output = adapter.process(statement)
                results.append((output.confidence, output, ))

                self.logger.info(
                    '{} selected "{}" as a response with a confidence of {}'.format(
                        adapter.class_name, output.text, output.confidence
                    )
                )

                if output.confidence > max_confidence:
                    result = output
                    max_confidence = output.confidence
            else:
                self.logger.info(
                    'Not processing the statement using {}'.format(adapter.class_name)
                )

        # If multiple adapters agree on the same statement,
        # then that statement is more likely to be the correct response
        if len(results) >= 3:
            statements = [s[1] for s in results]
            count = Counter(statements)
            most_common = count.most_common()
            if most_common[0][1] > 1:
                result = most_common[0][0]
                max_confidence = self.get_greatest_confidence(result, results)

        result.confidence = max_confidence
        return result


    def get_greatest_confidence(self, statement, options):
        """
        Returns the greatest confidence value for a statement that occurs
        multiple times in the set of options.

        :param statement: A statement object.
        :param options: A tuple in the format of (confidence, statement).
        """
        values = []
        for option in options:
            if option[1] == statement:
                values.append(option[0])

        return max(values)


    def get_adapters(self):
        """
        Return a list of all logic adapters being used, including system logic adapters.
        """
        adapters = []
        adapters.extend(self.adapters)
        adapters.extend(self.system_adapters)
        return adapters


    def add_adapter(self, adapter, **kwargs):
        """
        Appends a logic adapter to the list of logic adapters being used.

        :param adapter: The logic adapter to be added.
        :type adapter: `LogicAdapter`
        """
        utils.validate_adapter_class(adapter, LogicAdapter)
        adapter = utils.initialize_class(adapter, **kwargs)
        self.adapters.append(adapter)


    def insert_logic_adapter(self, logic_adapter, insert_index, **kwargs):
        """
        Adds a logic adapter at a specified index.

        :param logic_adapter: The string path to the logic adapter to add.
        :type logic_adapter: str

        :param insert_index: The index to insert the logic adapter into the list at.
        :type insert_index: int
        """
        utils.validate_adapter_class(logic_adapter, LogicAdapter)

        NewAdapter = utils.import_module(logic_adapter)
        adapter = NewAdapter(**kwargs)

        self.adapters.insert(insert_index, adapter)


    def remove_logic_adapter(self, adapter_name):
        """
        Removes a logic adapter from the chat bot.

        :param adapter_name: The class name of the adapter to remove.
        :type adapter_name: str
        """
        for index, adapter in enumerate(self.adapters):
            if adapter_name == type(adapter).__name__:
                del self.adapters[index]
                return True
        return False


    def set_chatbot(self, chatbot):
        """
        Set the chatbot for each of the contained logic adapters.
        """
        super(MultiLogicAdapter, self).set_chatbot(chatbot)

        for adapter in self.get_adapters():
            adapter.set_chatbot(chatbot)
Method Name Parameters: Description
add_adapter(adapter**kwargs) adapter (LogicAdapter) – The logic adapter to be added. Appends a logic adapter to the list of logic adapters being used.
get_adapters()   Return a list of all logic adapters being used, including system logic adapters.
get_greatest_confidence(statementoptions)

statement – A statement object.

options – A tuple in the format of (confidence, statement).

Returns the greatest confidence value for a statement that occurs multiple times in the set of options.
get_initialization_functions()   Get the initialization functions for each logic adapter.
insert_logic_adapter(logic_adapterinsert_index**kwargs)

logic_adapter (str) – The string path to the logic adapter to add.

insert_index (int) – The index to insert the logic adapter into the list at.

Adds a logic adapter at a specified index.

process(statement) statement – The input statement to be processed. Returns the output of a selection of logic adapters for a given input statement.
remove_logic_adapter(adapter_name) adapter_name (str) – The class name of the adapter to remove. Removes a logic adapter from the chat bot.
set_chatbot(chatbot)   Set the chatbot for each of the contained logic adapters.

How logic adapters select a response

A typical logic adapter designed to return a response to an input statement will use two main steps to do this. The first step involves searching the database for a known statement that matches or closely matches the input statement. Once a match is selected, the second step involves selecting a known response to the selected match. Frequently, there will be a number of existing statements that are responses to the known match.

To help with the selection of the response, several methods are built into ChatterBot for selecting a response from the available options.

Response selection methods

Response selection methods determines which response should be used in the event that multiple responses are generated within a logic adapter.

"""
Response selection methods determines which response should be used in
the event that multiple responses are generated within a logic adapter.
"""
import logging


def get_most_frequent_response(input_statement, response_list):
    """
    :param input_statement: A statement, that closely matches an input to the chat bot.
    :type input_statement: Statement

    :param response_list: A list of statement options to choose a response from.
    :type response_list: list

    :return: The response statement with the greatest number of occurrences.
    :rtype: Statement
    """
    matching_response = None
    occurrence_count = -1

    logger = logging.getLogger(__name__)
    logger.info(u'Selecting response with greatest number of occurrences.')

    for statement in response_list:
        count = statement.get_response_count(input_statement)

        # Keep the more common statement
        if count >= occurrence_count:
            matching_response = statement
            occurrence_count = count

    # Choose the most commonly occuring matching response
    return matching_response



def get_first_response(input_statement, response_list):
    """
    :param input_statement: A statement, that closely matches an input to the chat bot.
    :type input_statement: Statement

    :param response_list: A list of statement options to choose a response from.
    :type response_list: list

    :return: Return the first statement in the response list.
    :rtype: Statement
    """
    logger = logging.getLogger(__name__)
    logger.info(u'Selecting first response from list of {} options.'.format(
        len(response_list)
    ))
    return response_list[0]



def get_random_response(input_statement, response_list):
    """
    :param input_statement: A statement, that closely matches an input to the chat bot.
    :type input_statement: Statement

    :param response_list: A list of statement options to choose a response from.
    :type response_list: list

    :return: Choose a random response from the selection.
    :rtype: Statement
    """
    from random import choice
    logger = logging.getLogger(__name__)
    logger.info(u'Selecting a response from list of {} options.'.format(
        len(response_list)
    ))
    return choice(response_list)
Method Name Parameters Returns Return Type
get_first_response(input_statementresponse_list)
  • input_statement (Statement) – A statement, that closely matches an input to the chat bot.
  • response_list (list) – A list of statement options to choose a response from.
Return the first statement in the response list. Statement
get_most_frequent_response(input_statementresponse_list)
  • input_statement (Statement) – A statement, that closely matches an input to the chat bot.
  • response_list (list) – A list of statement options to choose a response from.
The response statement with the greatest number of occurrences. Statement
get_random_response(input_statementresponse_list)
  • input_statement (Statement) – A statement, that closely matches an input to the chat bot.
  • response_list (list) – A list of statement options to choose a response from.
Choose a random response from the selection. Statement

Use your own response selection method

You can create your own response selection method and use it as long as the function takes two parameters (a statements and a list of statements). The method must return a statement.

def select_response(statement, statement_list):

    # Your selection logic

    return selected_statement

Setting the response selection method

To set the response selection method for your chat bot, you will need to pass the response_selection_method parameter to your chat bot when you initialize it. An example of this is shown below.

from chatterbot import ChatBot
from chatterbot.response_selection import get_most_frequent_response

chatbot = ChatBot(
    # ...
    response_selection_method=get_most_frequent_response
)

Response selection in logic adapters

When a logic adapter is initialized, the response selection method parameter that was passed to it can be called using self.select_response as shown below.

response = self.select_response(
    input_statement, list_of_response_options
)

Creating a new logic adapter

You can write your own logic adapters by creating a new class that inherits from LogicAdapter and overrides the necessary methods established in the LogicAdapter base class.

Logic adapter methods

from __future__ import unicode_literals
from chatterbot.adapters import Adapter
from chatterbot.utils import import_module


class LogicAdapter(Adapter):
    """
    This is an abstract class that represents the interface
    that all logic adapters should implement.

    :param statement_comparison_function: The dot-notated import path to a statement comparison function.
                                          Defaults to ``levenshtein_distance``.

    :param response_selection_method: The a response selection method.
                                      Defaults to ``get_first_response``.
    """

    def __init__(self, **kwargs):
        super(LogicAdapter, self).__init__(**kwargs)
        from chatterbot.comparisons import levenshtein_distance
        from chatterbot.response_selection import get_first_response

        # Import string module parameters
        if 'statement_comparison_function' in kwargs:
            import_path = kwargs.get('statement_comparison_function')
            if isinstance(import_path, str):
                kwargs['statement_comparison_function'] = import_module(import_path)

        if 'response_selection_method' in kwargs:
            import_path = kwargs.get('response_selection_method')
            if isinstance(import_path, str):
                kwargs['response_selection_method'] = import_module(import_path)

        # By default, compare statements using Levenshtein distance
        self.compare_statements = kwargs.get(
            'statement_comparison_function',
            levenshtein_distance
        )

        # By default, select the first available response
        self.select_response = kwargs.get(
            'response_selection_method',
            get_first_response
        )

    def get_initialization_functions(self):
        """
        Return a dictionary of functions to be run once when the chat bot is instantiated.
        """
        return self.compare_statements.get_initialization_functions()


    def initialize(self):
        for function in self.get_initialization_functions().values():
            function()

    def can_process(self, statement):
        """
        A preliminary check that is called to determine if a
        logic adapter can process a given statement. By default,
        this method returns true but it can be overridden in
        child classes as needed.

        :rtype: bool
        """
        return True


    def process(self, statement):
        """
        Override this method and implement your logic for selecting a response to an input statement.

        A confidence value and the selected response statement should be returned.
        The confidence value represents a rating of how accurate the logic adapter
        expects the selected response to be. Confidence scores are used to select
        the best response from multiple logic adapters.

        The confidence value should be a number between 0 and 1 where 0 is the
        lowest confidence level and 1 is the highest.

        :param statement: An input statement to be processed by the logic adapter.
        :type statement: Statement

        :rtype: Statement
        """
        raise self.AdapterMethodNotImplementedError()


    @property
    def class_name(self):
        """
        Return the name of the current logic adapter class.
        This is typically used for logging and debugging.
        """
        return str(self.__class__.__name__)

    class EmptyDatasetException(Exception):

        def __init__(self, value='An empty set was received when at least one statement was expected.'):
            self.value = value

        def __str__(self):
            return repr(self.value)

This is an abstract class that represents the interface that all logic adapters should implement.

Parameters:

  • statement_comparison_function – The dot-notated import path to a statement comparison function. Defaults to levenshtein_distance.
  • response_selection_method – The a response selection method. Defaults to get_first_response.
Method/Property Name Parameters Return Type Description
can_process(statement)   bool A preliminary check that is called to determine if a logic adapter can process a given statement. By default, this method returns true but it can be overridden in child classes as needed.
class_name     Return the name of the current logic adapter class. This is typically used for logging and debugging.
get_initialization_functions()     Return a dictionary of functions to be run once when the chat bot is instantiated.
process(statement) statement (Statement) – An input statement to be processed by the logic adapter. Statement

Override this method and implement your logic for selecting a response to an input statement.

A confidence value and the selected response statement should be returned. The confidence value represents a rating of how accurate the logic adapter expects the selected response to be. Confidence scores are used to select the best response from multiple logic adapters.

The confidence value should be a number between 0 and 1 where 0 is the lowest confidence level and 1 is the highest.

Example logic adapter

from chatterbot.logic import LogicAdapter


class MyLogicAdapter(LogicAdapter):
    def __init__(self, **kwargs):
        super(MyLogicAdapter, self).__init__(**kwargs)

    def can_process(self, statement):
        return True

    def process(self, statement):
        import random

        # Randomly select a confidence between 0 and 1
        confidence = random.uniform(0, 1)

        # For this example, we will just return the input as output
        selected_statement = statement
        selected_statement.confidence = confidence

        return selected_statement

Directory structure

If you create your own logic adapter you will need to have it in a separate file from your chat bot. Your directory setup should look something like the following:

project_directory
|__ cool_chatbot.py
|__ cool_adapter.py

Then assuming that you have a class named MyLogicAdapter in your cool_adapter.py file, you should be able to specify the following when you initialize your chat bot.

ChatBot(
    # ...
    logic_adapters=[
        {
            'import_path': 'cool_adapter.MyLogicAdapter'
        }
    ]
)

Responding to specific input

If you want a particular logic adapter to only respond to a unique type of input, the best way to do this is by overriding the can_process method on your own logic adapter.

Here is a simple example. Let's say that we only want this logic adapter to generate a response when the input statement starts with "Hey Mike". This way, statements such as "Hey Mike, what time is it?" will be processed, but statements such as "Do you know what time it is?" will not be processed.

def can_process(self, statement):
    if statement.text.startswith('Hey Mike')
        return True
    else:
        return False

Interacting with services

In some cases, it is useful to have a logic adapter that can interact with an external service or api in order to complete its task. Here is an example that demonstrates how this could be done. For this example we will use a fictitious API endpoint that returns the current temperature.

def can_process(self, statement):
    """
    Return true if the input statement contains
    'what' and 'is' and 'temperature'.
    """
    words = ['what', 'is', 'temperature']
    if all(x in statement.text.split() for x in words)
        return True
    else:
        return False

def process(self, statement):
    from chatterbot.conversation import Statement
    import requests

    # Make a request to the temperature API
    response = requests.get('https://api.temperature.com/current?units=celsius')
    data = response.json()

    # Let's base the confidence value on if the request was successful
    if response.status_code == 200:
        confidence = 1
    else:
        confidence = 0

    temperature = data.get('temperature', 'unavailable')

    response_statement = Statement('The current temperature is {}'.format(temperature))

    return confidence, response_statement

Providing extra arguments

All key word arguments that have been set in your ChatBot class's constructor will also be passed to the __init__ method of each logic adapter. This allows you to access these variables if you need to use them in your logic adapter. (An API key might be an example of a parameter you would want to access here.)

You can override the __init__ method on your logic adapter to store additional information passed to it by the ChatBot class.

class MyLogicAdapter(LogicAdapter):
    def __init__(self, **kwargs):
        super(MyLogicAdapter, self).__init__(**kwargs)

        self.api_key = kwargs.get('secret_key')

The secret_key variable would then be passed to the ChatBot class as shown below.

chatbot = ChatBot(
    # ...
    secret_key='************************'
 )

Best Match Adapter

from __future__ import unicode_literals
from .logic_adapter import LogicAdapter


[docs]class BestMatch(LogicAdapter):
    """
    A logic adapter that returns a response based on known responses to
    the closest matches to the input statement.
    """

    def get(self, input_statement):
        """
        Takes a statement string and a list of statement strings.
        Returns the closest matching statement from the list.
        """
        statement_list = self.chatbot.storage.get_response_statements()

        if not statement_list:
            if self.chatbot.storage.count():
                # Use a randomly picked statement
                self.logger.info(
                    'No statements have known responses. ' +
                    'Choosing a random response to return.'
                )
                random_response = self.chatbot.storage.get_random()
                random_response.confidence = 0
                return random_response
            else:
                raise self.EmptyDatasetException()

        closest_match = input_statement
        closest_match.confidence = 0

        # Find the closest matching known statement
        for statement in statement_list:
            confidence = self.compare_statements(input_statement, statement)

            if confidence > closest_match.confidence:
                statement.confidence = confidence
                closest_match = statement

        return closest_match

    def can_process(self, statement):
        """
        Check that the chatbot's storage adapter is available to the logic
        adapter and there is at least one statement in the database.
        """
        return self.chatbot.storage.count()

    def process(self, input_statement):

        # Select the closest match to the input statement
        closest_match = self.get(input_statement)
        self.logger.info('Using "{}" as a close match to "{}"'.format(
            input_statement.text, closest_match.text
        ))

        # Get all statements that are in response to the closest match
        response_list = self.chatbot.storage.filter(
            in_response_to__contains=closest_match.text
        )

        if response_list:
            self.logger.info(
                'Selecting response from {} optimal responses.'.format(
                    len(response_list)
                )
            )
            response = self.select_response(input_statement, response_list)
            response.confidence = closest_match.confidence
            self.logger.info('Response selected. Using "{}"'.format(response.text))
        else:
            response = self.chatbot.storage.get_random()
            self.logger.info(
                'No response to "{}" found. Selecting a random response.'.format(
                    closest_match.text
                )
            )

            # Set confidence to zero because a random response is selected
            response.confidence = 0

        return response

A logic adapter that returns a response based on known responses to the closest matches to the input statement.

The BestMatch logic adapter selects a response based on the best known match to a given statement.

How it works

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.

Setting parameters

chatbot = ChatBot(
    "My ChatterBot",
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
            "response_selection_method": "chatterbot.response_selection.get_first_response"
        }
    ]
)

Note:The values for response_selection_method and statement_comparison_function can be a string of the path to the function, or a callable.

See the Statement comparison documentation for the list of functions included with ChatterBot.

See the Response selection methods documentation for the list of response selection methods included with ChatterBot.

Time Logic Adapter

from __future__ import unicode_literals
from datetime import datetime
from .logic_adapter import LogicAdapter


[docs]class TimeLogicAdapter(LogicAdapter):
    """
    The TimeLogicAdapter returns the current time.

    :kwargs:
        * *positive* (``list``) --
          The time-related questions used to identify time questions.
          Defaults to a list of English sentences.
        * *negative* (``list``) --
          The non-time-related questions used to identify time questions.
          Defaults to a list of English sentences.
    """

    def __init__(self, **kwargs):
        super(TimeLogicAdapter, self).__init__(**kwargs)
        from nltk import NaiveBayesClassifier

        self.positive = kwargs.get('positive', [
            'what time is it',
            'hey what time is it',
            'do you have the time',
            'do you know the time',
            'do you know what time it is',
            'what is the time'
        ])

        self.negative = kwargs.get('negative', [
            'it is time to go to sleep',
            'what is your favorite color',
            'i had a great time',
            'thyme is my favorite herb',
            'do you have time to look at my essay',
            'how do you have the time to do all this'
            'what is it'
        ])

        labeled_data = (
            [(name, 0) for name in self.negative] +
            [(name, 1) for name in self.positive]
        )

        train_set = [
            (self.time_question_features(text), n) for (text, n) in labeled_data
        ]

        self.classifier = NaiveBayesClassifier.train(train_set)

    def time_question_features(self, text):
        """
        Provide an analysis of significant features in the string.
        """
        features = {}

        # A list of all words from the known sentences
        all_words = " ".join(self.positive + self.negative).split()

        # A list of the first word in each of the known sentence
        all_first_words = []
        for sentence in self.positive + self.negative:
            all_first_words.append(
                sentence.split(' ', 1)[0]
            )

        for word in text.split():
            features['first_word({})'.format(word)] = (word in all_first_words)

        for word in text.split():
            features['contains({})'.format(word)] = (word in all_words)

        for letter in 'abcdefghijklmnopqrstuvwxyz':
            features['count({})'.format(letter)] = text.lower().count(letter)
            features['has({})'.format(letter)] = (letter in text.lower())

        return features

    def process(self, statement):
        from chatterbot.conversation import Statement

        now = datetime.now()

        time_features = self.time_question_features(statement.text.lower())
        confidence = self.classifier.classify(time_features)
        response = Statement('The current time is ' + now.strftime('%I:%M %p'))

        response.confidence = confidence
        return response

The TimeLogicAdapter returns the current time.

Kwargs:

  • positive (list) – The time-related questions used to identify time questions. Defaults to a list of English sentences.
  • negative (list) – The non-time-related questions used to identify time questions. Defaults to a list of English sentences.

The TimeLogicAdapter identifies statements in which a question about the current time is asked. If a matching question is detected, then a response containing the current time is returned.

User: What time is it?
Bot: The current time is 4:45PM.

 Mathematical Evaluation Adapter

from __future__ import unicode_literals
from chatterbot.logic import LogicAdapter
from chatterbot.conversation import Statement


[docs]class MathematicalEvaluation(LogicAdapter):
    """
    The MathematicalEvaluation logic adapter parses input to determine
    whether the user is asking a question that requires math to be done.
    If so, the equation is extracted from the input and returned with
    the evaluated result.

    For example:
        User: 'What is three plus five?'
        Bot: 'Three plus five equals eight'

    :kwargs:
        * *language* (``str``) --
          The language is set to 'ENG' for English by default.
    """

    def __init__(self, **kwargs):
        super(MathematicalEvaluation, self).__init__(**kwargs)

        self.language = kwargs.get('language', 'ENG')
        self.cache = {}

    def can_process(self, statement):
        """
        Determines whether it is appropriate for this
        adapter to respond to the user input.
        """
        response = self.process(statement)
        self.cache[statement.text] = response
        return response.confidence == 1

    def process(self, statement):
        """
        Takes a statement string.
        Returns the equation from the statement with the mathematical terms solved.
        """
        from mathparse import mathparse

        input_text = statement.text

        # Use the result cached by the process method if it exists
        if input_text in self.cache:
            cached_result = self.cache[input_text]
            self.cache = {}
            return cached_result

        # Getting the mathematical terms within the input statement
        expression = mathparse.extract_expression(input_text, language=self.language)

        response = Statement(text=expression)

        try:
            response.text += ' = ' + str(
                mathparse.parse(expression, language=self.language)
            )

            # The confidence is 1 if the expression could be evaluated
            response.confidence = 1
        except mathparse.PostfixTokenEvaluationException:
            response.confidence = 0

        return response

The MathematicalEvaluation logic adapter parses input to determine whether the user is asking a question that requires math to be done. If so, the equation is extracted from the input and returned with the evaluated result.

Kwargs:

  • language (str) – The language is set to ‘ENG' for English by default.

For example:

User: ‘What is three plus five?' Bot: ‘Three plus five equals eight'

The MathematicalEvaluation logic adapter checks a given statement to see if it contains a mathematical expression that can be evaluated. If one exists, then it returns a response containing the result. This adapter is able to handle any combination of word and numeric operators.

User: What is four plus four?
Bot: (4 + 4) = 8

Low Confidence Response Adapter

This adapter returns a specified default response if a response can not be determined with a high amount of confidence.

from __future__ import unicode_literals
from chatterbot.conversation import Statement
from .best_match import BestMatch


[docs]class LowConfidenceAdapter(BestMatch):
    """
    Returns a default response with a high confidence
    when a high confidence response is not known.

    :kwargs:
        * *threshold* (``float``) --
          The low confidence value that triggers this adapter.
          Defaults to 0.65.
        * *default_response* (``str``) or (``iterable``)--
          The response returned by this logic adaper.
        * *response_selection_method* (``str``) or (``callable``)
          The a response selection method.
          Defaults to ``get_first_response``.
    """

    def __init__(self, **kwargs):
        super(LowConfidenceAdapter, self).__init__(**kwargs)

        self.confidence_threshold = kwargs.get('threshold', 0.65)

        default_responses = kwargs.get(
            'default_response', "I'm sorry, I do not understand."
        )

        # Convert a single string into a list
        if isinstance(default_responses, str):
            default_responses = [
                default_responses
            ]

        self.default_responses = [
            Statement(text=default) for default in default_responses
        ]

    def process(self, input_statement):
        """
        Return a default response with a high confidence if
        a high confidence response is not known.
        """
        # Select the closest match to the input statement
        closest_match = self.get(input_statement)

        # Choose a response from the list of options
        response = self.select_response(input_statement, self.default_responses)

        # Confidence should be high only if it is less than the threshold
        if closest_match.confidence < self.confidence_threshold:
            response.confidence = 1
        else:
            response.confidence = 0

        return response

Returns a default response with a high confidence when a high confidence response is not known.

Kwargs:

  • threshold (float) – The low confidence value that triggers this adapter. Defaults to 0.65.
  • default_response (str) or (iterable)– The response returned by this logic adaper.
  • response_selection_method (str) or (callable) The a response selection method. Defaults to get_first_response.

Low confidence response example

# -*- coding: utf-8 -*-
from chatterbot import ChatBot


# Create a new instance of a ChatBot
bot = ChatBot(
    'Default Response Example Bot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.BestMatch'
        },
        {
            'import_path': 'chatterbot.logic.LowConfidenceAdapter',
            'threshold': 0.65,
            'default_response': 'I am sorry, but I do not understand.'
        }
    ],
    trainer='chatterbot.trainers.ListTrainer'
)

# Train the chat bot with a few responses
bot.train([
    'How can I help you?',
    'I want to create a chat bot',
    'Have you read the documentation?',
    'No, I have not',
    'This should help get you started: http://chatterbot.rtfd.org/en/latest/quickstart.html'
])

# Get a response for some unexpected input
response = bot.get_response('How do I make an omelette?')
print(response)

Specific Response Adapter

If the input that the chat bot receives, matches the input text specified for this adapter, the specified response will be returned.

from __future__ import unicode_literals
from .logic_adapter import LogicAdapter


[docs]class SpecificResponseAdapter(LogicAdapter):
    """
    Return a specific response to a specific input.

    :kwargs:
        * *input_text* (``str``) --
          The input text that triggers this logic adapter.
        * *output_text* (``str``) --
          The output text returned by this logic adapter.
    """

    def __init__(self, **kwargs):
        super(SpecificResponseAdapter, self).__init__(**kwargs)
        from chatterbot.conversation import Statement

        self.input_text = kwargs.get('input_text')

        output_text = kwargs.get('output_text')
        self.response_statement = Statement(output_text)

    def can_process(self, statement):
        if statement == self.input_text:
            return True

        return False

    def process(self, statement):

        if statement == self.input_text:
            self.response_statement.confidence = 1
        else:
            self.response_statement.confidence = 0

        return self.response_statement

Return a specific response to a specific input.

Kwargs:

  • input_text (str) – The input text that triggers this logic adapter.
  • output_text (str) – The output text returned by this logic adapter.

Specific response example

# -*- coding: utf-8 -*-
from chatterbot import ChatBot


# Create a new instance of a ChatBot
bot = ChatBot(
    'Exact Response Example Bot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.BestMatch'
        },
        {
            'import_path': 'chatterbot.logic.SpecificResponseAdapter',
            'input_text': 'Help me!',
            'output_text': 'Ok, here is a link: http://chatterbot.rtfd.org'
        }
    ],
    trainer='chatterbot.trainers.ListTrainer'
)

# Get a response given the specific input
response = bot.get_response('Help me!')
print(response)

0 Comment

temp