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.

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

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.

ChatterBot dialog processing flow

Common logic adapter attributes

Each logic adapter inherits the following attributes and methods.

class chatterbot.logic.LogicAdapter(chatbot, **kwargs)[source]

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

Parameters:
  • search_algorithm_name – The name of the search algorithm that should be used to search for close matches to the provided input. Defaults to the value of Search.name.
  • maximum_similarity_threshold – The maximum amount of similarity between two statement that is required before the search process is halted. The search for a matching statement will continue until a statement with a greater than or equal similarity is found or the search set is exhausted. Defaults to 0.95
  • response_selection_method (collections.abc.Callable) – The a response selection method. Defaults to get_first_response
  • default_response (str or list or tuple) – The default response returned by this logic adaper if there is no other possible response to return.
can_process(statement)[source]

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.

Return type:bool
class_name

Return the name of the current logic adapter class. This is typically used for logging and debugging.

get_default_response(input_statement)[source]

This method is called when a logic adapter is unable to generate any other meaningful response.

process(statement, additional_response_selection_parameters=None)[source]

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.

Parameters:
  • statement (Statement) – An input statement to be processed by the logic adapter.
  • additional_response_selection_parameters (dict) – Parameters to be used when filtering results to choose a response from.
Return type:

Statement

Best Match Adapter

chatterbot.logic.BestMatch(chatbot, **kwargs)[source]

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

Parameters:excluded_words (list) – The excluded_words parameter allows a list of words to be set that will prevent the logic adapter from returning statements that have text containing any of those words. This can be useful for preventing your chat bot from saying swears when it is being demonstrated in front of an audience. Defaults to None

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.LevenshteinDistance,
            "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

chatterbot.logic.TimeLogicAdapter(chatbot, **kwargs)[source]

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

chatterbot.logic.MathematicalEvaluation(chatbot, **kwargs)[source]

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 (object) – The language is set to chatterbot.languages.ENG for English by default.

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

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.

chatterbot.logic.SpecificResponseAdapter(chatbot, **kwargs)[source]

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

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'
        }
    ]
)

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

Low confidence response example

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer


# Create a new instance of a ChatBot
bot = ChatBot(
    'Example Bot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.BestMatch',
            'default_response': 'I am sorry, but I do not understand.',
            'maximum_similarity_threshold': 0.90
        }
    ]
)

trainer = ListTrainer(bot)

# Train the chat bot with a few responses
trainer.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)