Login With Github

The ChatBot Class

The main class ChatBot is a connecting point between each of ChatterBot's adapters. In this class, an input statement is returned from the input adapter, processed and stored by the logic adapterand storage adapter, and then passed to the output adapter to be returned to the user.

A conversational dialog chat bot.

from __future__ import unicode_literals
import logging
from .storage import StorageAdapter
from .input import InputAdapter
from .output import OutputAdapter
from . import utils


[docs]class ChatBot(object):
    """
    A conversational dialog chat bot.
    """

    def __init__(self, name, **kwargs):
        from .logic import MultiLogicAdapter

        self.name = name
        kwargs['name'] = name
        kwargs['chatbot'] = self

        self.default_session = None

        storage_adapter = kwargs.get('storage_adapter', 'chatterbot.storage.SQLStorageAdapter')

        # These are logic adapters that are required for normal operation
        system_logic_adapters = kwargs.get('system_logic_adapters', (
            'chatterbot.logic.NoKnowledgeAdapter',
        ))

        logic_adapters = kwargs.get('logic_adapters', [
            'chatterbot.logic.BestMatch'
        ])

        input_adapter = kwargs.get('input_adapter', 'chatterbot.input.VariableInputTypeAdapter')

        output_adapter = kwargs.get('output_adapter', 'chatterbot.output.OutputAdapter')

        # Check that each adapter is a valid subclass of it's respective parent
        utils.validate_adapter_class(storage_adapter, StorageAdapter)
        utils.validate_adapter_class(input_adapter, InputAdapter)
        utils.validate_adapter_class(output_adapter, OutputAdapter)

        self.logic = MultiLogicAdapter(**kwargs)
        self.storage = utils.initialize_class(storage_adapter, **kwargs)
        self.input = utils.initialize_class(input_adapter, **kwargs)
        self.output = utils.initialize_class(output_adapter, **kwargs)

        filters = kwargs.get('filters', tuple())
        self.filters = tuple([utils.import_module(F)() for F in filters])

        # Add required system logic adapter
        for system_logic_adapter in system_logic_adapters:
            self.logic.system_adapters.append(
                utils.initialize_class(system_logic_adapter, **kwargs)
            )

        for adapter in logic_adapters:
            self.logic.add_adapter(adapter, **kwargs)

        # Add the chatbot instance to each adapter to share information such as
        # the name, the current conversation, or other adapters
        self.logic.set_chatbot(self)
        self.input.set_chatbot(self)
        self.output.set_chatbot(self)

        preprocessors = kwargs.get(
            'preprocessors', [
                'chatterbot.preprocessors.clean_whitespace'
            ]
        )

        self.preprocessors = []

        for preprocessor in preprocessors:
            self.preprocessors.append(utils.import_module(preprocessor))

        # Use specified trainer or fall back to the default
        trainer = kwargs.get('trainer', 'chatterbot.trainers.Trainer')
        TrainerClass = utils.import_module(trainer)
        self.trainer = TrainerClass(self.storage, **kwargs)
        self.training_data = kwargs.get('training_data')

        self.default_conversation_id = None

        self.logger = kwargs.get('logger', logging.getLogger(__name__))

        # Allow the bot to save input it receives so that it can learn
        self.read_only = kwargs.get('read_only', False)

        if kwargs.get('initialize', True):
            self.initialize()

[docs]    def initialize(self):
        """
        Do any work that needs to be done before the responses can be returned.
        """
        self.logic.initialize()


[docs]    def get_response(self, input_item, conversation_id=None):
        """
        Return the bot's response based on the input.

        :param input_item: An input value.
        :param conversation_id: The id of a conversation.
        :returns: A response to the input.
        :rtype: Statement
        """
        if not conversation_id:
            if not self.default_conversation_id:
                self.default_conversation_id = self.storage.create_conversation()
            conversation_id = self.default_conversation_id

        input_statement = self.input.process_input_statement(input_item)

        # Preprocess the input statement
        for preprocessor in self.preprocessors:
            input_statement = preprocessor(self, input_statement)

        statement, response = self.generate_response(input_statement, conversation_id)

        # Learn that the user's input was a valid response to the chat bot's previous output
        previous_statement = self.storage.get_latest_response(conversation_id)

        if not self.read_only:
            self.learn_response(statement, previous_statement)
            self.storage.add_to_conversation(conversation_id, statement, response)

        # Process the response output with the output adapter
        return self.output.process_response(response, conversation_id)


[docs]    def generate_response(self, input_statement, conversation_id):
        """
        Return a response based on a given input statement.
        """
        self.storage.generate_base_query(self, conversation_id)

        # Select a response to the input statement
        response = self.logic.process(input_statement)

        return input_statement, response


[docs]    def learn_response(self, statement, previous_statement):
        """
        Learn that the statement provided is a valid response.
        """
        from .conversation import Response

        if previous_statement:
            statement.add_response(
                Response(previous_statement.text)
            )
            self.logger.info('Adding "{}" as a response to "{}"'.format(
                statement.text,
                previous_statement.text
            ))

        # Save the statement after selecting a response
        self.storage.update(statement)


[docs]    def set_trainer(self, training_class, **kwargs):
        """
        Set the module used to train the chatbot.

        :param training_class: The training class to use for the chat bot.
        :type training_class: `Trainer`

        :param \**kwargs: Any parameters that should be passed to the training class.
        """
        if 'chatbot' not in kwargs:
            kwargs['chatbot'] = self

        self.trainer = training_class(self.storage, **kwargs)


    @property
    def train(self):
        """
        Proxy method to the chat bot's trainer class.
        """
        return self.trainer.train

Parameters:

  • name (str) – A name is the only required parameter for the ChatBot class.
  • storage_adapter (str) – The dot-notated import path to a storage adapter class. Defaults to "chatterbot.storage.SQLStorageAdapter".
  • logic_adapters (list) – A list of dot-notated import paths to each logic adapter the bot uses. Defaults to ["chatterbot.logic.BestMatch"].
  • input_adapter (str) – The dot-notated import path to an input adapter class. Defaults to "chatterbot.input.VariableInputTypeAdapter".
  • output_adapter (str) – The dot-notated import path to an output adapter class. Defaults to "chatterbot.output.OutputAdapter".
  • trainer (str) – The dot-notated import path to the training class to be used with the chat bot.
  • filters (list) – A list of dot-notated import paths to filter classes to be used by the chat bot.
  • logger (logging.Logger) – A Logger object.
Method Name Parameters Returns Return Type Description
generate_response(input_statementconversation_id)       Return a response based on a given input statement.
get_response(input_itemconversation_id=None)
  • input_item – An input value.
  • conversation_id – The id of a conversation.
A response to the input. Statement Return the bot's response based on the input.
initialize()       Do any work that needs to be done before the responses can be returned.
learn_response(statementprevious_statement)       Learn that the statement provided is a valid response.
set_trainer(training_class**kwargs)
  • training_class (Trainer) – The training class to use for the chat bot.
  • **kwargs – Any parameters that should be passed to the training class.
    Set the module used to train the chatbot.
train       Proxy method to the chat bot's trainer class.

Example chat bot parameters

ChatBot(
    'Northumberland',
    storage_adapter='my.storage.AdapterClass',
    logic_adapters=[
        'my.logic.AdapterClass1',
        'my.logic.AdapterClass2'
    ],
    input_adapter='my.input.AdapterClass',
    output_adapter='my.output.AdapterClass',
    trainer='my.trainer.TrainerClass',
    filters=[
        'my.filter.FilterClass1',
        'my.filter.FilterClass2'
    ],
    logger=custom_logger
)

Example expanded chat bot parameters

It is also possible to pass parameters directly to individual adapters. To do this, you must use a dictionary that contains a key called import_path which specifies the import path to the adapter class.

ChatBot(
    'Leander Jenkins',
    storage_adapter={
        'import_path': 'my.storage.AdapterClass',
        'database_name': 'my-database'
    },
    logic_adapters=[
        {
            'import_path': 'my.logic.AdapterClass1',
            'statement_comparison_function': 'chatterbot.comparisons.levenshtein_distance'
            'response_selection_method': 'chatterbot.response_selection.get_first_response'
        },
        {
            'import_path': 'my.logic.AdapterClass2',
            'statement_comparison_function': 'my.custom.comparison_function'
            'response_selection_method': 'my.custom.selection_method'
        }
    ],
    input_adapter={
        'import_path': 'my.input.AdapterClass',
        'api_key': '0000-1111-2222-3333-DDDD'
    },
    output_adapter={
        'import_path': 'my.output.AdapterClass',
        'api_key': '0000-1111-2222-3333-DDDD'
    }
)

Enable logging

ChatterBot has built in logging. You can enable ChatterBot's logging by setting the logging level in your code.

import logging

logging.basicConfig(level=logging.INFO)

ChatBot(
    # ...
)

The logging levels available are CRITICALERRORWARNINGINFODEBUG, and NOTSET. See the Python logging documentation for more information.

Using a custom logger

You can choose to use your own custom logging class with your chat bot. This can be useful when testing and debugging your code.

import logging

custom_logger = logging.getLogger(__name__)

ChatBot(
    # ...
    logger=custom_logger
)

Adapters

ChatterBot uses adapter modules to control the behavior of specific types of tasks. There are four distinct types of adapters that ChatterBot uses, these are storage adapters, input adapters, output adapters and logic adapters.

Adapters types

  1. Storage adapters - Provide an interface for ChatterBot to connect to various storage systems such as MongoDB or local file storage.
  2. Input adapters - Provide methods that allow ChatterBot to get input from a defined data source.
  3. Output adapters - Provide methods that allow ChatterBot to return a response to a defined data source.
  4. Logic adapters - Define the logic that ChatterBot uses to respond to input it receives.

Accessing the chatbot instance

When ChatterBot initializes each adapter, it sets an attribute named chatbot. The chatbot variable makes it possible for each adapter to have access to all of the other adapters being used. Suppose two input and output adapters need to share some information or perhaps you want to give your logic adapter direct access to the storage adapter. These are just a few cases where this functionality is useful.

Each adapter can be accessed on the chatbot object from within an adapter by referencing self.chatbot. Then, self.chatbot.storage refers to the storage adapter, self.chatbot.input refers to the input adapter, self.chatbot.output refers to the current output adapter, and self.chatbot.logicrefers to the logic adapters.

0 Comment

temp