ChatterBot Documentation

ChatterBot is a machine learning, conversational dialog engine for creating chat bots

14,522 stars Python Python 1 file · ~39,273 tokens #bot#chatbot#chatterbot#conversation#language#machine-learning#python
RAW Doc

Technical Documentation: gunthercox/ChatterBot

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

ChatterBot

ChatterBot is a machine-learning based conversational dialog engine built in
Python which makes it possible to generate responses based on collections of
known conversations. The language independent design of ChatterBot allows it
to be trained to speak any language.





An example of typical input would be something like this:

user: Good morning! How are you doing?
bot: I am doing very well, thank you for asking.
user: You're welcome.
bot: Do you like hats?

How it works

An untrained instance of ChatterBot starts off with no knowledge of how to communicate. Each time a user enters a statement, the library saves the text that they entered and the text that the statement was in response to. As ChatterBot receives more input the number of responses that it can reply to, and the accuracy of each response in relation to the input statement increases. The program selects the closest matching response by searching for the closest matching known statement that matches the input, it then returns the most likely response to that statement based on how frequently each response is issued by the people the bot communicates with.

[Documentation](https://docs.chatterbot.us)

View the documentation
for ChatterBot.

Installation

This package can be installed from PyPi by running:

bash
pip install chatterbot

Basic Usage

python
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

chatbot = ChatBot('Ron Obvious')

# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)

# Train the chatbot based on the english corpus
trainer.train("chatterbot.corpus.english")

# Get a response to an input statement
chatbot.get_response("Hello, how are you today?")

Training data

ChatterBot comes with a data utility module that can be used to train chat bots.
At the moment there is training data for over a dozen languages in this module.
Contributions of additional training data or training data
in other languages would be greatly appreciated. Take a look at the data files
in the chatterbot-corpus
package if you are interested in contributing.

python
from chatterbot.trainers import ChatterBotCorpusTrainer

# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)

# Train based on the english corpus
trainer.train("chatterbot.corpus.english")

# Train based on english greetings corpus
trainer.train("chatterbot.corpus.english.greetings")

# Train based on the english conversations corpus
trainer.train("chatterbot.corpus.english.conversations")

Corpus contributions are welcome! Please make a pull request.

Examples

For examples, see the examples
section of the documentation.

History

See release notes for changes https://github.com/gunthercox/ChatterBot/releases

Contributing

Contributions are welcomed, to help ensure a smooth process please start with the contributing guidelines in our documentation:
https://docs.chatterbot.us/contributing/

Sponsors

ChatterBot is sponsored by:

License

ChatterBot is licensed under the BSD 3-clause license.


Overview (`graphics/README.md`)

ChatterBot Graphics

Concept art and imagery for ChatterBot was designed by Griffin Cox.

Files using a .xcf format can be viewed and edited using GIMP.


Chatterbot (`docs/chatterbot.rst`)

========== ChatterBot

The main class ChatBot is a connecting point between each of
ChatterBot's :term:adapters. In this class, an input statement is
processed and stored by the :term:logic adapter and :term:storage adapter.
A response to the input is then generated and returned.

.. autoclass:: chatterbot.ChatBot
:members:

Example chat bot parameters

.. code-block:: python

ChatBot(
'Northumberland',
storage_adapter='my.storage.AdapterClass',
logic_adapters=[
'my.logic.AdapterClass1',
'my.logic.AdapterClass2'
],
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.

.. code-block:: python

ChatBot(
'Leander Jenkins',
storage_adapter={
'import_path': 'my.storage.AdapterClass',
'database_uri': 'protocol://my-database'
},
logic_adapters=[
{
'import_path': 'my.logic.AdapterClass1',
'statement_comparison_function': chatterbot.comparisons.LevenshteinDistance
'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
}
]
)

Enable logging

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

.. code-block:: python

import logging

logging.basicConfig(level=logging.INFO)

ChatBot(
# ...
)

The logging levels available are
CRITICAL, ERROR, WARNING, INFO, DEBUG, 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.

.. code-block:: python

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 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. 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 logic 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, and self.chatbot.logic refers to the logic adapters.

.. _MongoDB: https://docs.mongodb.com/
.. _Python logging documentation: https://docs.python.org/3/library/logging.html#logging-levels


Commands (`docs/commands.rst`)

================== Command line tools

ChatterBot comes with a few command line tools that can help
with general packaging-related tasks.

Get the installed ChatterBot version

If have ChatterBot installed and you want to check what version
you have then you can run the following command.

.. code-block:: bash

python -m chatterbot --version

List available commands

To see a list of all available commands you can run the following:

.. code-block:: bash

python -m chatterbot --help


Comparisons (`docs/comparisons.rst`)

=========== Comparisons

.. _statement-comparison:

Statement comparison

ChatterBot uses Statement objects to hold information
about things that can be said. An important part of how a chat bot
selects a response is based on its ability to compare two statements
to each other. There are a number of ways to do this, and ChatterBot
comes with a handful of methods built in for you to use.

.. automodule:: chatterbot.comparisons
:members:

Use your own comparison function
++++++++++++++++++++++++++++++++

You can create your own comparison function and use it as long as the function takes two statements
as parameters and returns a numeric value between 0 and 1. A 0 should represent the lowest possible
similarity and a 1 should represent the highest possible similarity.

.. code-block:: python

def comparison_function(statement, other_statement):

text
# Your comparison logic

   # Return your calculated value here
   return 0.0

Setting the comparison method

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

.. code-block:: python

from chatterbot import ChatBot
from chatterbot.comparisons import LevenshteinDistance

chatbot = ChatBot(
# ...
statement_comparison_function=LevenshteinDistance
)

Taggers

ChatterBot supports a number of different taggers that can be used to
process the input text. The taggers are used to identify the parts of speech
in the input text and can be used to improve the accuracy of the response selection.

.. automodule:: chatterbot.tagging
:members:
:undoc-members:

Languages

ChatterBot's languages module contains helper classes for working with
language codes and names.

.. autoclass:: chatterbot.languages.ENG

.. autoclass:: chatterbot.languages.FRE

.. autoclass:: chatterbot.languages.GER

.. autoclass:: chatterbot.languages.ITA

.. autoclass:: chatterbot.languages.JPN

.. autoclass:: chatterbot.languages.KOR

.. autoclass:: chatterbot.languages.POR

.. autoclass:: chatterbot.languages.RUS

.. autoclass:: chatterbot.languages.SPA

.. autoclass:: chatterbot.languages.SWE

.. autoclass:: chatterbot.languages.TUR

.. autoclass:: chatterbot.languages.ZHT

See chatterbot.languages for the full list of languages.


Contributing (`docs/contributing.rst`)

========================== Contributing to ChatterBot

There are numerous ways to contribute to ChatterBot. All of which are highly encouraged.

  • Contributing bug reports and feature requests

  • Contributing documentation

  • Contributing code for new features

  • Contributing fixes for bugs

Every bit of help received on this project is highly appreciated.

Setting Up a Development Environment

To contribute to ChatterBot's development, you simply need:

  • Python

  • pip

  • A few python packages. You can install them from this projects pyproject.yml file by running:

.. code-block:: bash

pip .[dev,test]

  • A text editor

Reporting a Bug

If you discover a bug in ChatterBot and wish to report it, please be
sure that you adhere to the following when you report it on GitHub.

  1. Before creating a new bug report, please search to see if an open or closed report matching yours already exists.
  2. Please include a description that will allow others to recreate the problem you encountered.

Requesting New Features

When requesting a new feature in ChatterBot, please make sure to include
the following details in your request.

  1. Your use case. Describe what you are doing that requires this new functionality.

Contributing Documentation

ChatterBot's documentation is written in reStructuredText and is
compiled by Sphinx. The reStructuredText source of the documentation
is located in the docs/ directory.

To build the documentation yourself, run:

.. code-block:: bash

text
sphinx-build -nW -b dirhtml docs/ html/

A useful way to view the documentation is to use the Python built-in HTTP server. You can do this by running:

.. code-block:: bash

text
python -m http.server

Then navigate to http://localhost:8000/ in your web browser.

Contributing Code

The development of ChatterBot happens on GitHub. Code contributions should be
submitted there in the form of pull requests.

Pull requests should meet the following criteria.

  1. Fix one issue and fix it well.
  2. Do not include extraneous changes that do not relate to the issue being fixed.
  3. Include a descriptive title and description for the pull request.
  4. Have descriptive commit messages.

Development pattern for contributors

  1. Create a fork of
    the main ChatterBot repository on GitHub.
  2. Make your changes in a branch named something different from master, e.g. create
    a new branch my-pull-request.
  3. Create a pull request.
  4. Please follow the Python style guide for PEP-8.
  5. Use the projects built-in testing.
    to help make sure that your contribution is free from errors.

Conversations (`docs/conversations.rst`)

============= Conversations

ChatterBot supports the ability to have multiple concurrent conversations.
A conversations is where the :term:chat bot interacts with a person, and supporting
multiple concurrent conversations means that the chat bot can have multiple
different conversations with different people at the same time.

Conversation scope

If two ChatBot instances are created, each will have conversations separate from each other.

An adapter can access any conversation as long as the unique identifier for the conversation is provided.

Conversation example

The following example is taken from the Django ChatterBotApiView built into ChatterBot.
In this method, the unique identifiers for each chat session are being stored in Django's
session objects. This allows different users who interact with the bot through different
web browsers to have separate conversations with the chat bot.

.. literalinclude:: ../examples/django_example/django_example/views.py
:caption: examples/django_example/django_example/views.py
:language: python
:pyobject: ChatterBotApiView.post
:dedent: 4

.. _conversation_statements:

Statements

ChatterBot's statement objects represent either an input statement that the
chat bot has received from a user, or an output statement that the chat bot
has returned based on some input.

.. autoclass:: chatterbot.conversation.Statement
:members:

.. autoattribute:: chatterbot.conversation.Statement.confidence

text
ChatterBot's logic adapters assign a confidence score to the statement
  before it is returned. The confidence score indicates the degree of
  certainty with which the chat bot believes this is the correct response
  to the given input.

.. autoattribute:: chatterbot.conversation.Statement.in_response_to

text
The response attribute represents the relationship between two statements.
  This value of this field indicates that one statement was issued in response
  to another statement.

Statement-response relationship

ChatterBot stores knowledge of conversations as statements. Each statement can have any
number of possible responses.

.. image:: _static/statement-response-relationship.svg
:alt: ChatterBot statement-response relationship

Each Statement object has an in_response_to reference which links the
statement to a number of other statements that it has been learned to be in response to.
The in_response_to attribute is essentially a reference to all parent statements
of the current statement.

.. image:: _static/statement-relationship.svg
:alt: ChatterBot statement relationship

The count of recorded statements with matching, or similar text indicates the number of
times that the statement has been given as a response. This makes it possible for the
chat bot to determine if a particular response is more commonly used than another.


Corpus (`docs/corpus.rst`)

ChatterBot Corpus

This is a :term:corpus of dialog data that is included in the chatterbot module.

Additional information about the chatterbot-corpus module can be found
in the ChatterBot Corpus Documentation_.

Corpus language availability

Corpus data is user contributed, but it is also not difficult to create one if you are familiar with the language.
This is because each corpus is just a sample of various input statements and their responses for the bot to train itself with.

To explore what languages and collections of corpora are available,
check out the chatterbot_corpus/data_ directory in the separate chatterbot-corpus repository.

.. note::
If you are interested in contributing content to the corpus, please feel free to
submit a pull request on ChatterBot's corpus GitHub page. Contributions are welcomed!

https://github.com/gunthercox/chatterbot-corpus

The chatterbot-corpus is distributed in its own Python package so that it can
be released and upgraded independently from the chatterbot package.

Exporting your chat bot's database as a training corpus

Now that you have created your chat bot and sent it out into the world, perhaps
you are looking for a way to share what it has learned with other chat bots?
ChatterBot's training module provides methods that allow you to export the
content of your chat bot's database as a training corpus that can be used to
train other chat bots.

Here is an example:

.. literalinclude:: ../examples/export_example.py
:caption: /examples/export_example.py
:language: python

.. _chatterbot_corpus/data: https://github.com/gunthercox/chatterbot-corpus/tree/master/chatterbot_corpus/data
.. _ChatterBot Corpus Documentation: https://corpus.chatterbot.us/


Development (`docs/development.rst`)

=========== Development

As the code for ChatterBot is written, the developers attempt to describe
the logic and reasoning for the various decisions that go into creating the
internal structure of the software. This internal documentation is intended
for future developers and maintainers of the project. A majority of this
information is unnecessary for the typical developer using ChatterBot.

It is not always possible for every idea to be documented. As a result, the
need may arise to question the developers and maintainers of this project
in order to pull concepts from their minds and place them in these documents.
Please pull gently.

.. toctree::
:maxdepth: 2
:caption: Contents:

text
contributing
releases
Release Notes <https://github.com/gunthercox/ChatterBot/releases>
testing
packaging

Suggested Development Tools

To help developers work with ChatterBot and projects built using it, the
following tools are suggested. Keep in mind that none of these are required,
but this list has been assembled because it is often useful to have a
tool or technology recommended by people who have experience using it.

Text Editors

Visual Studio Code
++++++++++++++++++

Website: https://code.visualstudio.com/

| I find Visual Studio Code to be an optimally light-weight
| and versatile editor.
|
| ~ Gunther Cox

Database Clients

SQLite Viewer
+++++++++++++

| This is a very simple SQLite viewer extension for VS Code that allows you to
| sqlite databases.

Website: https://marketplace.visualstudio.com/items?itemName=qwtel.sqlite-viewer

pgAdmin
+++++++

| pgAdmin a pretty good database client when working with PostgreSQL.

Website: https://www.pgadmin.org/


Encoding (`docs/encoding.rst`)

====================== Python String Encoding

The Python developer community has published a great article that covers the
details of unicode character processing.

The following notes are intended to help answer some common questions and issues
that developers frequently encounter while learning to properly work with different
character encodings in Python.

Does ChatterBot handle non-ascii characters?

ChatterBot is able to handle unicode values correctly. You can pass to it
non-encoded data and it should be able to process it properly
(you will need to make sure that you decode the output that is returned).

Below is one of ChatterBot's tests from tests/test_chatbot.py_,
this is just a simple check that a unicode response can be processed.

.. code-block:: python

def test_get_response_unicode(self):
"""
Test the case that a unicode string is passed in.
"""
response = self.chatbot.get_response(u'سلام')
self.assertGreater(len(response.text), 0)

This test passes Python 3. It also verifies that
ChatterBot can take unicode input without issue.

How do I fix Python encoding errors?

When working with string type data in Python, it is possible to encounter errors
such as the following.

.. code-block:: text

UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 48: invalid start byte

Depending on what your code looks like, there are a few things that you can do
to prevent errors like this.

Unicode header

.. code-block:: python

-*- coding: utf-8 -*-

When to use the unicode header
++++++++++++++++++++++++++++++

If your strings use escaped unicode characters (they look like u'\u00b0C') then
you do not need to add the header. If you use strings like 'ØÆÅ' then you are required
to use the header.

If you are using this header it must be the first line in your Python file.

Unicode escape characters

.. code-block:: text

print u'\u0420\u043e\u0441\u0441\u0438\u044f'
Россия

When to use escape characters
+++++++++++++++++++++++++++++

Prefix your strings with the unicode escape character u'...' when you are
using escaped unicode characters.

Import unicode literals from future

.. code-block:: python

from future import unicode_literals

When to import unicode literals
+++++++++++++++++++++++++++++++

Use this when you need to make sure that Python 3 code also works in Python 2.

A good article on this can be found here: http://python-future.org/unicode_literals.html

.. _tests/test_chatbot.py: https://github.com/gunthercox/ChatterBot/blob/master/tests/test_chatbot.py


Examples (`docs/examples.rst`)

======== Examples

The following examples are available to help you get started with ChatterBot.

.. note::
Before you run any example, you will need to install ChatterBot on your system.
See the :ref:Setup guide for instructions.

All of these examples and more are available in the examples <https://github.com/gunthercox/ChatterBot/tree/master/examples>_ directory of the ChatterBot repository on GitHub.

Simple Example

.. literalinclude:: ../examples/basic_example.py
:caption: examples/basic_example.py
:language: python

Terminal Example

This example program shows how to create a simple terminal client
that allows you to communicate with your chat bot by typing into
your terminal.

.. image:: _static/terminal-example.gif
:alt: ChatterBot terminal example running in Python console

.. literalinclude:: ../examples/terminal_example.py
:caption: examples/terminal_example.py
:language: python

Using MongoDB

Before you can use ChatterBot's built in adapter for MongoDB,
you will need to install MongoDB_. Make sure MongoDB is
running in your environment before you execute your program.
To tell ChatterBot to use this adapter, you will need to set
the storage_adapter parameter.

.. code-block:: python

storage_adapter="chatterbot.storage.MongoDatabaseAdapter"

.. literalinclude:: ../examples/terminal_mongo_example.py
:caption: examples/terminal_mongo_example.py
:language: python

Time and Mathematics Example

ChatterBot has natural language evaluation capabilities that
allow it to process and evaluate mathematical and time-based
inputs.

.. literalinclude:: ../examples/math_and_time.py
:caption: examples/math_and_time.py
:language: python

Using SQL Adapter

ChatterBot data can be saved and retrieved from SQL databases.

.. literalinclude:: ../examples/memory_sql_example.py
:caption: examples/memory_sql_example.py
:language: python

Read only mode

Your chat bot will learn based on each new input statement it receives.
If you want to disable this learning feature after your bot has been trained,
you can set read_only=True as a parameter when initializing the bot.

.. code-block:: python

chatbot = ChatBot("Johnny Five", read_only=True)

Using Large Language Models

Support for large language models (LLMs) is in ChatterBot is still experimental
(as of version 1.2.7). Notes and current usage example can be found in the
:ref:LLM Roadmap.

Django and Flask

  1. Django: A number of :ref:example views are documented <Example API Views>, as well as full example Django app.
  2. Flask: There is a separately maintained example Flask project using ChatterBot <https://github.com/chamkank/flask-chatterbot>_.

.. _install MongoDB: https://docs.mongodb.com/manual/installation/


Faq (`docs/faq.rst`)

========================== Frequently Asked Questions

This document is comprised of questions that are frequently
asked about ChatterBot and chat bots in general.

.. toctree::
:maxdepth: 2

encoding

How do I deploy my chat bot to the web?

There are a number of excellent web frameworks for creating
Python projects out there. Django and Flask are two excellent
examples of these. ChatterBot is designed to be agnostic to
the platform it is deployed on and it is very easy to get set up.

To run ChatterBot inside of a web application you just need a way
for your application to receive incoming data and to return data.
You can do this any way you want, HTTP requests, web sockets, etc.

There are a number of existing examples that show how to do this.

  1. An example using Django: https://github.com/gunthercox/ChatterBot/tree/master/examples/django_example
  2. An example using Flask: https://github.com/chamkank/flask-chatterbot/blob/master/app.py

Additional details and recommendations for configuring Django can be found
in the :ref:Webservices section of ChatterBot's Django documentation.

What kinds of machine learning does ChatterBot use?

In brief, ChatterBot uses a number of different machine learning techniques to
generate its responses. The specific algorithms depend on how the chat bot is
used and the settings that it is configured with.

Here is a general overview of some of the various machine learning techniques
that are employed throughout ChatterBot's codebase.

  1. Search algorithms
    ++++++++++++++++++++

Searching is the most rudimentary form of artificial intelligence. To be fair,
there are differences between machine learning and artificial intelligence but
lets avoid those for now and instead focus on the topic of algorithms that make
the chat bot talk intelligently.

Search is a crucial part of how a chat bot quickly and efficiently retrieves
the possible candidate statements that it can respond with.

Some examples of attributes that help the chat bot select a response include

  • the similarity of an input statement to known statements
  • the frequency in which similar known responses occur
  • the likeliness of an input statement to fit into a category that known statements are a part of
  1. Classification algorithms
    ++++++++++++++++++++++++++++

Several logic adapters in ChatterBot use naive Bayesian classification_
algorithms to determine if an input statement meets a particular set of
criteria that warrant a response to be generated from that logic adapter.

.. _naive Bayesian classification: https://en.wikipedia.org/wiki/Naive_Bayes_classifier


Filters (`docs/filters.rst`)

======= Filters

Filters are an efficient way to create queries that can be passed to ChatterBot's storage adapters.
Filters will reduce the number of statements that a chat bot has to process when it is selecting a response.

Setting filters

.. code-block:: python

chatbot = ChatBot(
"My ChatterBot",
filters=[filters.get_recent_repeated_responses]
)

.. automodule:: chatterbot.filters
:members:


Glossary (`docs/glossary.rst`)

======== Glossary

.. glossary::

adapters
A base class that allows a ChatBot instance to execute some kind of functionality.

chat bot
Computer software that can converse conversation with human users or other chat bots [1]_.

logic adapter
An adapter class that allows a ChatBot instance to select a response to

RAG
Retrieval-Augmented Generation. A method of by which a large language model
can retrieve information from a database or other source of information.

storage adapter
A class that allows a chat bot to store information somewhere, such as a database.

corpus
In linguistics, a corpus (plural corpora) or text corpus is a large
and structured set of texts. They are used to do statistical analysis
and hypothesis testing, checking occurrences or validating linguistic
rules within a specific language territory [2]_.

large language models
A type of artificial intelligence model that can generate generate
human-like text, often trained on a significantly large corpus of
text data.

MCP
Model Context Protocol. A protocol for providing context data to a large
language model to enable or improve its ability to perform various tasks.

preprocessors
A member of a list of functions that can be used to modify text
input that the chat bot receives before the text is passed to
the logic adapter for processing.

statement
A single string of text representing something that can be said.

search word
A word that is not a stop word and has been trimmed in some way (
for example through stemming).

stemming
A process through which a word is reduced into a derivative form.

stop word
A common word that is often filtered out during the process of
analyzing text.

response
A single string of text that is uttered as an answer, a reply or
an acknowledgement to a statement.

untrained instance
An untrained instance of the chat bot has an empty database.

vector
A mathematical representation of text that can be used to calculate
the similarity between two pieces of text based on the distance
between their vectors.

vector database
Any database capable of storing vectors.


.. [1] https://en.wikipedia.org/wiki/Chatbot
.. [2] https://en.wikipedia.org/wiki/Text_corpus


Index (`docs/index.rst`)

.. meta::
:description: ChatterBot documentation: Python machine learning chatbot library with semantic vector search, AI conversational dialog engine supporting multiple languages and vector databases
:keywords: ChatterBot, chatbot, chat, bot, natural language processing, nlp, artificial intelligence, ai, machine learning, vector database, semantic search, vector embeddings, conversational ai, python chatbot library

.. container:: banner

.. image:: ../graphics/banner.png
:alt: ChatterBot Banner
:align: center

About ChatterBot

ChatterBot is a Python library that makes it easy to generate automated
responses to a user's input. ChatterBot uses a selection of machine learning
algorithms to produce different types of responses. This makes it easy for
developers to create chat bots and automate conversations with users.

Modern AI Capabilities (2025):

  • Semantic Vector Search: Advanced context understanding using vector embeddings and Redis vector database
  • Large Language Model (LLM) Integration: Experimental support for Ollama and OpenAI models
  • Storage-Aware Architecture: Automatic optimization based on storage backend capabilities
  • Multi-Language Support: Language-independent design with spaCy integration

For more details about the ideas and concepts behind ChatterBot see the
:ref:process flow diagram .

An example of typical input would be something like this:

.. code-block:: text

user: Good morning! How are you doing?
bot: I am doing very well, thank you for asking.
user: You're welcome.
bot: Do you like hats?

Originally, ChatterBot was created as a part of the codebase for the humanoid robot Salvius_. As the project grew, the :code:chatterbot library was released as a separate open-source project.

Language Independence

The language independent design of ChatterBot allows it to be trained to speak any language.
Additionally, the machine-learning nature of ChatterBot allows an agent instance to improve
it's own knowledge of possible responses as it interacts with humans and other sources of informative data.

.. note::

Starting in version 1.2.0 ChatterBot has started to implement some features that are
language specific. This change is being made to improve the quality of responses that
ChatterBot can generate.

How ChatterBot Works

ChatterBot is a Python library designed to make it easy to create software that can engage in conversation.

An :term:untrained instance of ChatterBot starts off with no knowledge of how to communicate.
Each time a user enters a :term:statement, the library saves the text that they entered and the text
that the statement was in response to. As ChatterBot receives more input the number of responses
that it can reply to, and the accuracy of each response in relation to the input statement increases.

The program selects the closest matching :term:response by searching for the closest matching known
statement that matches the input, it then chooses a response from the selection of known responses
to that statement.

.. admonition:: April 2025

The dialog processing flow will be slightly different when using
large language models (LLMs). See the :ref:LLM Roadmap for more details.

.. _process_flow_diagram:

Process flow diagram

.. image:: _static/chatterbot-process-flow.svg
:alt: ChatterBot process flow diagram

Contents:

.. toctree::
:maxdepth: 4

About
setup
quickstart
tutorial
examples
training
preprocessors
security
large-language-models
logic/index
storage/index
filters
chatterbot
conversations
comparisons
utils
corpus
django/index
faq
commands
development
glossary

Report an Issue

Please direct all bug reports and feature requests to the project's issue
tracker on GitHub_.

Indices and tables

  • :ref:genindex
  • :ref:modindex
  • :ref:search

Sponsors

ChatterBot is sponsored by:

.. raw:: html

text
<a href="https://www.testmuai.com/?utm_source=chatterbot&utm_medium=sponsor" target="_blank">
     
  </a>



  If you, or your organization is interested in sponsoring the ChatterBot project, you can do so directly via [GitHub Sponsors](https://github.com/sponsors/gunthercox) as well as reach out directly via `[email protected]` for more information and to discuss sponsorship opportunities.

.. _GitHub: https://github.com/gunthercox/ChatterBot/issues/
.. _Salvius: https://salvius.org


Large Language Models (`docs/large-language-models.rst`)

===================== Large Language Models

.. warning::

text
Starting in ChatterBot 1.2.7 experimental support for :term:`large language models`
is being added. This support is not yet complete and is not yet ready for general
use beyond experimental purposes. The API will likely change in the future and the
functionality may not be fully implemented.

.. warning::

text
**Do not deploy LLM-enabled ChatterBot applications in production without:**

* Comprehensive security review and hardening
* Enabling security scanning (see :doc:`security`)
* Additional rate limiting and abuse prevention
* Monitoring and alerting for security violations
* Understanding of OWASP Top 10 for LLM Applications
* Regular security audits and penetration testing

The API may change in future releases as LLM support matures.

**Security Considerations:**

LLM applications are vulnerable to prompt injection, jailbreaking, and other
attacks. ChatterBot provides optional security scanning via llm-guard (see
:doc:`security`), but this is a baseline defense and not sufficient for
production deployment without additional hardening.

Review the `OWASP Top 10 for LLM Applications <https://owasp.org/www-project-top-10-for-large-language-model-applications/>`_
before deploying any LLM-enabled application.

LLM Roadmap

The following phases of development are the general roadmap for LLM support
in ChatterBot. The goal is to provide a simple and consistent interface for
LLM integration, and to make it easy to add support for new LLMs as they
become available.

.. note::
* Added April 1st, 2025
* Last updated: February 2nd, 2026

Phase 1:

Support for local and remote LLMs.

  1. ☑ Support for Ollama LLMs_, which at the current time appear to be the easiest to set up and run on local hardware.
  2. ☑ Support for accessing LLMs that use the OpenAI API.

Phase 2:

  • ☐ Streaming response support across features in ChatterBot.

.. note::
This functionality is being skipped for now, but may be reprioritized in the future.
This would be more important to implement if streaming inputs, eg. text from streaming
audio or video sources were being supported (which is not currently something this
project aims to address, nor do most LLMs support).

Phase 3:

LLM integration with specific logic adapter features via MCP tool calling.

  • ☑ Mathematical operations :class:~chatterbot.logic.MathematicalEvaluation via :mod:mathparse
  • ☑ Date and time :class:~chatterbot.logic.TimeLogicAdapter
  • ☑ Unit conversion UnitConversion

One of the concepts / theories here that we want to evaluate is, for example,
that it may be easier (and more efficient) to teach AI to use a calculator
than it is to teach it the rules of mathematics. Whether this is because it
lets us use smaller LLMs that don't have a strong understanding of math, or
because in general it allows us to offload processing of other complex tasks,
there is likely a strong use case here.

Both interestingly and conveniently, ChatterBot's existing architecture used
for its logic adapters is already very similar to approaches used to provide
additional tools to LLMs. The Model Context Protocol (:term:MCP) supported by a
range of MCP server implementations <https://github.com/punkpeye/awesome-mcp-servers?tab=readme-ov-file#what-is-mcp>_
currently seems like a strong candidate for this.

Phase 3 has been implemented using the MCP tool format to allow LLMs to invoke
logic adapters as tools.

The implementation supports:

  • Native tool calling for models that support it (Ollama llama3.1+, mistral, qwen2.5; all OpenAI models)
  • Prompt-based fallback for models without native tool support using structured JSON
  • Hybrid configurations where LLM adapters work alongside traditional logic adapters in consensus voting

.. list-table:: Comparison of ChatterBot Architectures
:class: table-justified
:header-rows: 1

    • Classic ChatterBot (Logic Adapters)
    • LLM with MCP
    • .. image:: _static/dialog-processing-flow.svg
    • .. image:: _static/dialog-processing-flow-llm.svg

LLM adapters now participate in ChatterBot's consensus voting mechanism alongside
traditional logic adapters. This allows multiple adapters (LLM and non-LLM) to
"vote" on the best response, with the highest confidence response winning.

Basic LLM Configuration

.. code-block:: python

text
from chatterbot import ChatBot

bot = ChatBot(
    'My Bot',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.OllamaLogicAdapter',
            'model': 'llama3.1',
            'host': 'http://localhost:11434'
        }
    ]
)

LLM with Tool Support

Enable specialized tools by passing logic adapters in the logic_adapters_as_tools parameter:

.. code-block:: python

text
bot = ChatBot(
    'My Bot',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.OllamaLogicAdapter',
            'model': 'llama3.1',
            'logic_adapters_as_tools': [
                'chatterbot.logic.MathematicalEvaluation',
                'chatterbot.logic.TimeLogicAdapter',
                'chatterbot.logic.UnitConversion'
            ]
        }
    ]
)

When a tool-capable model is used (e.g., llama3.1, mistral, qwen2.5, or any OpenAI model),
the LLM will be able to invoke these tools using native function calling. For models without
native support, the adapter automatically falls back to prompt-based tool calling.

Hybrid Configuration

Combine LLM adapters with traditional logic adapters for consensus voting:

.. code-block:: python

text
bot = ChatBot(
    'My Bot',
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.OllamaLogicAdapter',
            'model': 'llama3.1',
            'logic_adapters_as_tools': [
                'chatterbot.logic.MathematicalEvaluation',
                'chatterbot.logic.TimeLogicAdapter'
            ],
            'min_confidence': 0.6,
            'max_confidence': 0.9
        },
        'chatterbot.logic.BestMatch',
        'chatterbot.logic.SpecificResponseAdapter'
    ]
)

In this configuration, the LLM adapter votes alongside BestMatch and SpecificResponseAdapter,
with the highest confidence response being selected. The min_confidence and max_confidence
parameters control the LLM's confidence range for voting purposes.

Phase 4:

  • ☐ LLM integration with the ChatterBot training process

The ideal outcome for this phase would be the ability to use the existing training
pipelines to fine-tune LLMs. It isn't clear yet if this will be possible to do with
common hardware, but right now this is the goal. An alternative may be to use a RAG
approach to allow the LLM to access the chat bot's database when generating responses.

Ollama Support

ChatterBot's experimental support for using Ollama LLMs can be tested using the following setup:

  1. Have Docker installed and running
  2. Install ChatterBot and the Ollama client library
  3. Use the following docker-compose file to run the Ollama server:

.. code-block:: yaml
:caption: docker-compose.yml

services:

text
# NOTE: This setup is for AMD GPUs
ollama:
    image: ollama/ollama:rocm
    ports:
    - "11434:11434"
    volumes:
    - ./.database/ollama:/root/.ollama
    devices:
    - /dev/kfd
    - /dev/dri

The following commands can be used to download various Ollama models:

.. code-block:: bash

text
docker compose up -d

.. code-block:: bash

text
# Create a shell in the docker container
docker compose exec ollama bash

# Download and run the Gemma 3 model
ollama run gemma3:1b

The following is an example of how to use the Ollama LLM in ChatterBot. Before running
them you will need to install the ollama client library. This can be done directly
using pip or by using the extra option from the ChatterBot package that includes it:

.. code-block:: bash

text
pip install chatterbot[dev]

.. literalinclude:: ../examples/ollama_example.py
:caption: examples/ollama_example.py
:language: python

Using the OpenAI client

The following is an example of how to use the OpenAI client in ChatterBot. Before running
the example you will need to install the openai client library. This can be done directly
using pip or by using the extra option from the ChatterBot package that includes it:

.. code-block:: bash

text
pip install chatterbot[dev] python-dotenv
  1. Obtain an OpenAI API key: https://platform.openai.com/settings/organization/api-keys
  2. Create a .env file to hold your API key in the parent directory from where your code is running.

.. code-block:: bash
:caption: ../.env

text
OPENAI_API_KEY="API Key Here"

.. literalinclude:: ../examples/openai_example.py
:caption: examples/openai_example.py
:language: python

.. _Ollama LLMs: https://ollama.com/library?sort=popular


Packaging (`docs/packaging.rst`)

================================== Packaging your code for ChatterBot

There are cases where developers may want to contribute code to ChatterBot but for
various reasons it doesn't make sense or isn't possible to add the code to the
main ChatterBot repository on GitHub.

Common reasons that code can't be contributed include:

  • Licensing: It may not be possible to contribute code to ChatterBot due to a licensing restriction or a copyright.
  • Demand: There needs to be a general demand from the open source community for a particular feature so that there are developers who will want to fix and improve the feature if it requires maintenance.

In addition, all code should be well documented and thoroughly tested.

Package directory structure

Suppose we want to create a new logic adapter for ChatterBot and add it the
Python Package Index (PyPI) so that other developers can install it and use it.
We would begin doing this by setting up a directory file the following structure.

.. literalinclude:: _includes/python_module_structure.txt
:caption: Python Module Structure

More information on creating Python packages can be found here:
https://packaging.python.org/tutorials/distributing-packages/

Register on PyPI

Create an account: https://pypi.python.org/pypi?%3Aaction=register_form

Create a .pypirc configuration file.

.. code-block:: bash
:caption: .pypirc file contents

[distutils]
index-servers =
pypi

[pypi]
username=my_username
password=my_password

Generate packages

.. code-block:: bash

python -m build

Upload packages

The official tool for uploading Python packages is called twine.
You can install twine with pip if you don't already have it installed.

.. code-block:: bash

pip install twine

.. code-block:: bash

twine upload dist/*

Install your package locally

.. code-block:: bash

cd IronyAdapter
pip install . --upgrade

Using your package

If you are creating a module that ChatterBot imports from a dotted module path then you
can set the following in your chat bot.

.. code-block:: python

chatbot = ChatBot(
"My ChatBot",
logic_adapters=[
"irony_adapter.logic.IronyAdapter"
]
)

Testing your code

.. code-block:: python

from unittest import TestCase

class IronyAdapterTestCase(TestCase):
"""
Test that the irony adapter allows
the chat bot to understand irony.
"""

text
def test_irony(self):
      # TODO: Implement test logic
      self.assertTrue(response.irony)

Preprocessors (`docs/preprocessors.rst`)

============= Preprocessors

ChatterBot's :term:preprocessors are simple functions that modify the input statement
that a chat bot receives before the statement gets processed by the logic adaper.

Here is an example of how to set preprocessors. The preprocessors
parameter should be a list of strings of the import paths to your preprocessors.

.. code-block:: python

chatbot = ChatBot(
'Bob the Bot',
preprocessors=[
'chatterbot.preprocessors.clean_whitespace'
]
)

Preprocessor functions

ChatterBot comes with several built-in preprocessors.

.. autofunction:: chatterbot.preprocessors.clean_whitespace

.. autofunction:: chatterbot.preprocessors.unescape_html

.. autofunction:: chatterbot.preprocessors.convert_to_ascii

Creating new preprocessors

It is simple to create your own preprocessors. A preprocessor is just a function
with a few requirements.

  1. It must take one parameter, a Statement instance.
  2. It must return a statement instance.

Quickstart (`docs/quickstart.rst`)

================= Quick Start Guide

The first thing you'll need to do to get started is install ChatterBot.

.. code-block:: bash

pip install chatterbot

See :ref:Installation for options for alternative installation methods.

Create a new chat bot

.. code-block:: python

from chatterbot import ChatBot
chatbot = ChatBot("Ron Obvious")

.. note::

The only required parameter for the ChatBot is a name.
This can be anything you want.

Training your ChatBot

After creating a new ChatterBot instance it is also possible to train the bot.
Training is a good way to ensure that the bot starts off with knowledge about
specific responses. The current training method takes a list of statements that
represent a conversation.
Additional notes on training can be found in the :ref:Training documentation.

.. note::

Training is not required but it is recommended.

.. code-block:: python

from chatterbot.trainers import ListTrainer

conversation = [
"Hello",
"Hi there!",
"How are you doing?",
"I'm doing great.",
"That is good to hear",
"Thank you.",
"You're welcome."
]

trainer = ListTrainer(chatbot)

trainer.train(conversation)

Get a response

.. code-block:: python

response = chatbot.get_response("Good morning!")
print(response)


Releases (`docs/releases.rst`)

==================== Releasing ChatterBot

ChatterBot follows the following rules when it comes to new versions and updates.

Versioning

ChatterBot follows semantic versioning as a set of guidelines for release versions.

  • Major releases (2.0.0, 3.0.0, etc.) are used for large, almost
    entirely backwards incompatible changes.

  • Minor releases (2.1.0, 2.2.0, 3.1.0, 3.2.0, etc.) are used for
    releases that contain small, backwards incompatible changes. Known
    backwards incompatibilities will be described in the release notes.

  • Patch releases (e.g., 2.1.1, 2.1.2, 3.0.1, 3.0.10, etc.) are used
    for releases that contain bug fixes, features and dependency changes.

Release Process

The following procedure is used to finalize a new version of ChatterBot.

  1. We make sure that all CI tests on the master branch are passing.

  2. We tag the release on GitHub.

  3. A new package is generated from the latest version of the master branch.

.. code-block:: bash

python -m build

  1. The Python package files are uploaded to PyPi.

.. code-block:: bash

twine upload dist/*


Robots (`docs/robots.txt`)

User-agent: *
Disallow:

Sitemap: https:docs.chatterbot.us/sitemap.xml


Security (`docs/security.rst`)

======== Security

Deploying chat bots to production environments requires due diligence,
especially in cases where LLMs are involved. At minimum, the following
precautions should be considered:

  • Comprehensive security review
  • Additional rate limiting and abuse prevention
  • Monitoring and alerting for security violations
  • Regular security audits and penetration testing
  • Understanding of the OWASP Top 10 for LLM Applications

Overview

When using ChatterBot, you may want to add security scanning to protect
against common vulnerabilities outlined in the OWASP Top 10 for LLM Applications <https://owasp.org/www-project-top-10-for-large-language-model-applications/>_.

ChatterBot does not include built-in security scanning. Instead, you can integrate
third-party security tools like llm-guard <https://protectai.github.io/llm-guard/>,
Prompt-Guard
, or other scanning solution at the application level to scan inputs
before they reach the chatbot and outputs before they are shown to users.

Depending on your use case, the following are examples of best practices you might consider:

  1. Always scan user input for prompt injection
  2. Always scan bot output scan bot output to prevent PII leakage
  3. Start with strict thresholds and relax if false positives occur
  4. Log security violations for monitoring and analysis
  5. Test with adversarial inputs before deployment
  6. Implement rate limiting at application layer
  7. Never execute LLM outputs as code without validation
  8. Review OWASP LLM Top 10 regularly

Additional Resources

  • llm-guard Documentation <https://protectai.github.io/llm-guard/>_
  • OWASP Top 10 for LLM Applications <https://owasp.org/www-project-top-10-for-large-language-model-applications/>_
  • ProtectAI GitHub <https://github.com/protectai/llm-guard>_
  • ChatterBot LLM Documentation <large-language-models.html>_
  • Prompt-Guard <https://huggingface.co/meta-llama/Prompt-Guard-86M>_

Setup (`docs/setup.rst`)

============ Installation

The recommended method for installing ChatterBot is by using pip_.

Installing from PyPi

If you are just getting started with ChatterBot, it is recommended that you
start by installing the latest version from the Python Package Index (PyPi_).
To install ChatterBot from PyPi using pip run the following command in your terminal.

.. code-block:: bash

pip install chatterbot

Optional dependencies

ChatterBot offers two collections of optional dependencies: dev and test. Neither of these are required for all ChatterBot use cases, but both provide full support for additional features. The dev collection includes dependencies such as pymongo, and pint (which are useful for working on various changes during development but are not required to use all chatterbot features). Separately the test collection includes dependencies such as flake8, and coverage. The specifics of each collection of optional dependencies can be reviewed via the project's pyproject.yml_ file. To install these optional dependencies, you can use the following commands.

.. code-block:: bash

pip install chatterbot[dev]

.. code-block:: bash

pip install chatterbot[test]

.. code-block:: bash

pip install chatterbot[dev,test]

Similarly, if you have cloned the repository <#installing-from-source>_ and want to install the optional dependencies, you can run commands in the following format:

.. code-block:: bash

pip install .[dev,test]

Installing from GitHub

You can install the latest development version of ChatterBot directly from GitHub using pip.

.. code-block:: bash

pip install git+git://github.com/gunthercox/ChatterBot.git@master

Installing from source

  1. Download a copy of the code from GitHub. You may need to install git_.

.. code-block:: bash

git clone https://github.com/gunthercox/ChatterBot.git

  1. Install the code you have just downloaded using pip

.. code-block:: bash

pip install ./ChatterBot

Checking the version of ChatterBot that you have installed

If you already have ChatterBot installed and you want to check what version you
have installed you can run the following command.

.. code-block:: bash

text
python -m chatterbot --version

Upgrading ChatterBot to the latest version

.. toctree::
:maxdepth: 4

upgrading

.. _git: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
.. _pip: https://pip.pypa.io/en/stable/installing/
.. _PyPi: https://pypi.python.org/pypi
.. _pyproject.yml: https://github.com/gunthercox/ChatterBot/blob/master/pyproject.toml


Testing (`docs/testing.rst`)

============ Unit Testing

"A true professional does not waste the time and money of other people by handing over software that is not reasonably free of obvious bugs;
that has not undergone minimal unit testing; that does not meet the specifications and requirements;
that is gold-plated with unnecessary features; or that looks like junk."
– Daniel Read

Running tests

You can run ChatterBot's main test suite using Python's built-in test runner. For example:

.. sourcecode:: sh

python -m unittest discover -s tests -v

This command will run all tests including Django integration tests (if Django is installed).

Note that the unittest command also allows you to specify individual test cases to run.
For example, the following command will run all tests in the test-module tests/logic/

.. sourcecode:: sh

python -m unittest discover -s tests/logic/ -v

To run a specific test in a test class you can specify the test method name using the following pattern:

.. sourcecode:: sh

python -m unittest tests.logic.test_best_match.BestMatchTestCase.test_match_with_response

Tests can also be run in "fail fast" mode, in which case they will run until the first test failure is encountered.

.. sourcecode:: sh

python -m unittest discover -f tests

Django integration tests

Django integration tests are included in tests/django_integration/ and will automatically run
when you execute the main test suite (if Django is installed). If Django is not available,
these tests will be gracefully skipped.

To run only Django integration tests:

.. sourcecode:: sh

python -m unittest discover -s tests/django_integration/ -v

The Django example app tests can be run separately with the following command from within
the examples/django_example directory:

.. sourcecode:: sh

python manage.py test

Benchmark tests

You can run a series of benchmark tests that test a variety of different chat bot configurations for
performance by running the following command.

.. sourcecode:: sh

python tests/benchmarks.py

Testing documentation builds

The HTML documentation for ChatterBot can be compiled using using Sphinx_. To build it run the following command from the root directory of the project:

.. sourcecode:: sh

sphinx-build -nW -b dirhtml docs/ html/

.. _Sphinx: http://www.sphinx-doc.org/
.. _unittest documentation: https://docs.python.org/3/library/unittest.html#command-line-interface


Training (`docs/training.rst`)

======== Training

ChatterBot includes tools that help simplify the process of training a chat bot instance.
ChatterBot's training process involves loading example dialog into the chat bot's database.
This either creates or builds upon the graph data structure that represents the sets of
known statements and responses. When a chat bot trainer is provided with a data set,
it creates the necessary entries in the chat bot's knowledge graph so that the statement
inputs and responses are correctly represented.

.. image:: _static/training-graph.svg
:alt: ChatterBot training statement graph

Several training classes come built-in with ChatterBot. These utilities range from allowing
you to update the chat bot's database knowledge graph based on a list of statements
representing a conversation, to tools that allow you to train your bot based on a corpus of
pre-loaded training data.

You can also create your own training class. This is recommended if you wish to train your bot
with data you have stored in a format that is not already supported by one of the pre-built
classes listed below.

Training classes

ChatterBot comes with training classes built in, or you can create your own
if needed.

To use a training class you call train() on an instance that
has been initialized with your chat bot as shown in the following examples.

Training via list data

.. autoclass:: chatterbot.trainers.ListTrainer
:members: train

For the training process, you will need to pass in a list of statements where the order of each statement is based
on its placement in a given conversation.

For example, if you were to run bot of the following training calls, then the resulting chatterbot would respond to
both statements of "Hi there!" and "Greetings!" by saying "Hello".

.. code-block:: python
:caption: chatbot.py

text
chatbot = ChatBot('Training Example')

.. code-block:: python
:caption: train.py

from chatbot import chatbot
from chatterbot.trainers import ListTrainer

trainer = ListTrainer(chatbot)

trainer.train([
"Hi there!",
"Hello",
])

trainer.train([
"Greetings!",
"Hello",
])

You can also provide longer lists of training conversations.
This will establish each item in the list as a possible response to it's predecessor in the list.

.. code-block:: python
:caption: train.py

trainer.train([
"How are you?",
"I am good.",
"That is good to hear.",
"Thank you",
"You are welcome.",
])

Training with corpus data

.. autoclass:: chatterbot.trainers.ChatterBotCorpusTrainer
:members: train

ChatterBot comes with a corpus data and utility module that makes it easy to
quickly train your bot to communicate. To do so, simply specify the corpus
data modules you want to use.

.. code-block:: python
:caption: chatbot.py

chatbot = ChatBot('Training Example')

.. code-block:: python
:caption: train.py

from chatbot import chatbot
from chatterbot.trainers import ChatterBotCorpusTrainer

trainer = ChatterBotCorpusTrainer(chatbot)

trainer.train(
"chatterbot.corpus.english"
)

Specifying corpus scope
+++++++++++++++++++++++

It is also possible to import individual subsets of ChatterBot's corpus at once.
For example, if you only wish to train based on the english greetings and
conversations corpora then you would simply specify them.

.. code-block:: python
:caption: train.py

trainer.train(
"chatterbot.corpus.english.greetings",
"chatterbot.corpus.english.conversations"
)

You can also specify file paths to corpus files or directories of corpus files when calling the train method.

.. code-block:: python
:caption: train.py

trainer.train(
"./data/greetings_corpus/custom.corpus.yml",
"./data/my_corpus/"
)

Training with CSV or TSV formatted data

.. autoclass:: chatterbot.trainers.CsvFileTrainer
:members: train

.. autoattribute:: chatterbot.trainers.CsvFileTrainer.DEFAULT_STATEMENT_TO_HEADER_MAPPING

Example CSV data format:

.. literalinclude:: ../tests/training/test_data/csv_corpus/1.csv
:caption: /data/training_data_1.csv

.. code-block:: python
:caption: train.py

from chatterbot.trainers import CsvFileTrainer

trainer = CsvFileTrainer(
chatbot,
field_map={
'created_at': 0,
'persona': 1,
'text': 2,
'conversation': 3
}
)

trainer.train('./data/training_data_1.csv')

Training with JSON formatted data

.. autoclass:: chatterbot.trainers.JsonFileTrainer
:members: train

.. autoattribute:: chatterbot.trainers.JsonFileTrainer.DEFAULT_STATEMENT_TO_KEY_MAPPING

Example JSON data format:

.. literalinclude:: ../tests/training/test_data/json_corpus/1.json
:caption: /data/training_data_1.json
:language: json

.. code-block:: python
:caption: train.py

from chatterbot.trainers import JsonFileTrainer

trainer = JsonFileTrainer(
chatbot,
field_map={
'persona': 'persona',
'text': 'text',
'conversation': 'conversation',
'in_response_to': 'in_response_to',
}
)

trainer.train('./data/training_data_1.json')

Training with the Ubuntu dialog corpus

.. warning::

The Ubuntu dialog corpus is a massive data set. Developers will currently
experience significantly decreased performance in the form of delayed
training and response times from the chat bot when using this corpus.

.. autoclass:: chatterbot.trainers.UbuntuCorpusTrainer
:members: train

This training class makes it possible to train your chat bot using the Ubuntu
dialog corpus. Because of the file size of the Ubuntu dialog corpus, the download
and training process may take a considerable amount of time.

This training class will handle the process of downloading the compressed corpus
file and extracting it. If the file has already been downloaded, it will not be
downloaded again. If the file is already extracted, it will not be extracted again.

Creating a new training class

You can create a new trainer to train your chat bot from your own
data files. You may choose to do this if you want to train your
chat bot from a data source in a format that is not directly supported
by ChatterBot.

Your custom trainer should inherit chatterbot.trainers.Trainer class.
Your trainer will need to have a method named train, that can take any
parameters you choose.

Take a look at the existing trainer classes on GitHub_ for examples.

.. _trainer classes on GitHub: https://github.com/gunthercox/ChatterBot/blob/master/chatterbot/trainers.py


Tutorial (`docs/tutorial.rst`)

=================== ChatterBot Tutorial

This tutorial will guide you through the process of creating a simple command-line chat bot using ChatterBot.

Getting help

If you’re having trouble with this tutorial, you can post a message on Gitter_
to chat with other ChatterBot users who might be able to help.

You can also ask questions_ on Stack Overflow_ under the chatterbot tag.

If you believe that you have encountered an error in ChatterBot, please open a
ticket on GitHub: https://github.com/gunthercox/ChatterBot/issues/new

Installing ChatterBot

You can install ChatterBot on your system using Python's pip command.

.. code-block:: bash

pip install chatterbot

See :ref:Installation for alternative installation options.

Creating your first chat bot

Create a new file named chatbot.py.
Then open chatbot.py in your editor of choice.

Before we do anything else, ChatterBot needs to be imported.
The import for ChatterBot should look like the following line.

.. code-block:: python
:caption: chatbot.py

from chatterbot import ChatBot

Create a new instance of the ChatBot class.

.. code-block:: python
:caption: chatbot.py

bot = ChatBot('Norman')

This line of code has created a new chat bot named Norman.
There is a few more parameters that we will want to specify
before we run our program for the first time.

Setting the storage adapter

ChatterBot comes with built in adapter classes that allow it to connect
to different types of databases. In this tutorial, we will be using the
SQLStorageAdapter which allows the chat bot to connect to SQL databases.
By default, this adapter will create a SQLite_ database.

The database parameter is used to specify the path to the database
that the chat bot will use. For this example we will call the database
sqlite:///database.sqlite3. this file will be created automatically if it doesn't
already exist.

.. code-block:: python
:caption: chatbot.py

bot = ChatBot(
'Norman',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
database_uri='sqlite:///database.sqlite3'
)

.. note::

The SQLStorageAdapter is ChatterBot's default adapter.
If you do not specify an adapter in your constructor,
the SQLStorageAdapter adapter will be used automatically.

Specifying logic adapters

The logic_adapters parameter is a list of logic adapters.
In ChatterBot, a logic adapter is a class that takes an input statement
and returns a response to that statement.

You can choose to use as many logic adapters as you would like.
In this example we will use two logic adapters. The TimeLogicAdapter returns
the current time when the input statement asks for it.
The MathematicalEvaluation adapter solves math problems that use basic
operations.

.. code-block:: python
:caption: chatbot.py

bot = ChatBot(
'Norman',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
logic_adapters=[
'chatterbot.logic.MathematicalEvaluation',
'chatterbot.logic.TimeLogicAdapter'
],
database_uri='sqlite:///database.sqlite3'
)

Getting a response from your chat bot

Next, you will want to create a while loop for your chat bot to run in.
By breaking out of the loop when specific exceptions are triggered,
we can exit the loop and stop the program when a user enters ctrl+c.

.. code-block:: python
:caption: chatbot.py

while True:
try:
bot_input = bot.get_response(input())
print(bot_input)

text
except(KeyboardInterrupt, EOFError, SystemExit):
       break

Training your chat bot

At this point your chat bot, Norman will learn to communicate as you talk to him.
You can speed up this process by training him with examples of existing conversations.

.. code-block:: python
:caption: chatbot.py

from chatterbot.trainers import ListTrainer

trainer = ListTrainer(bot)

trainer.train([
'How are you?',
'I am good.',
'That is good to hear.',
'Thank you',
'You are welcome.',
])

You can run the training process multiple times to reinforce preferred responses
to particular input statements. You can also run the train command on a number
of different example dialogs to increase the breadth of inputs that your chat
bot can respond to.

Conclusion and Next Steps

This concludes this ChatterBot tutorial. Please see other sections of the
documentation for more details and examples.

For more examples of using ChatterBot, see the :doc:./examples section. Additional tutorials and other articles that cover topic beyond the scope of this one can be found at the ChatterBot homepage: https://chatterbot.us/

.. _Gitter: https://gitter.im/chatterbot/Lobby
.. _SQLite: https://www.sqlite.org/
.. _Stack Overflow: https://stackoverflow.com/questions/tagged/chatterbot
.. _ask questions: https://stackoverflow.com/questions/ask


Upgrading (`docs/upgrading.rst`)

=========================== Upgrading to Newer Releases

Like any software, changes will be made to ChatterBot over time.
Most of these changes are improvements. Frequently, you don't have
to change anything in your code to benefit from a new release.

Occasionally there are changes that will require modifications in
your code or there will be changes that make it possible for you
to improve your code by taking advantage of new features.

To view a record of ChatterBot's history of changes, visit the
releases tab on ChatterBot's GitHub page.

Use the pip command to upgrade your existing ChatterBot
installation by providing the --upgrade parameter:

.. code-block:: bash

pip install chatterbot --upgrade

Also see :ref:Versioning for information about ChatterBot's versioning policy.


Utils (`docs/utils.rst`)

=============== Utility Methods

ChatterBot has a utility module that contains
a collection of miscellaneous but useful functions.

Module imports

.. autofunction:: chatterbot.utils.import_module

Class initialization

.. autofunction:: chatterbot.utils.initialize_class

ChatBot response time

.. autofunction:: chatterbot.utils.get_response_time

Parsing datetime information

.. autofunction:: chatterbot.parsing.datetime_parsing


Includes Python Module Structure (`docs/_includes/python_module_structure.txt`)

IronyAdapter/
|── README
|── pyproject.toml
|── irony_adapter
| |── init.py
| └── logic.py
└── tests
|── init.py
└── test_logic.py


Django Custom Models (`docs/django/custom-models.rst`)

======================= Custom Statement Models

ChatterBot allows you to replace the default Statement and Tag models with custom versions,
using a pattern similar to Django's AUTH_USER_MODEL setting. This enables you to add
custom fields, business logic, and integrations specific to your application.

Why Use Custom Models?

Custom models allow you to:

  • Add custom fields - User ratings, sentiment scores, metadata, timestamps
  • Implement business logic - Custom validation, automated tagging, calculations
  • Integrate with existing schemas - Foreign keys to User models, related data
  • Optimize performance - Custom indexes, database-specific features
  • Track analytics - Views, feedback, response times

Creating Custom Models

Step 1: Inherit from Abstract Base Classes

ChatterBot provides abstract base classes that define the required fields and methods.
Inherit from these to create your custom models:

.. code-block:: python
:caption: myapp/models.py

from chatterbot.ext.django_chatterbot.abstract_models import (
AbstractBaseStatement,
AbstractBaseTag
)
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class CustomStatement(AbstractBaseStatement):
"""
Custom Statement model with user feedback tracking.
"""

text
# Add your custom fields
   upvotes = models.IntegerField(default=0)
   downvotes = models.IntegerField(default=0)
   sentiment_score = models.FloatField(null=True, blank=True)
   metadata = models.JSONField(default=dict, blank=True)

   # Track which users interacted
   upvoted_by = models.ManyToManyField(
       User,
       related_name='upvoted_statements',
       blank=True
   )

   # Required: ManyToMany relationship to a Tag model
   # (Can be a custom Tag model or the default)
   tags = models.ManyToManyField(
       'CustomTag',
       related_name='statements',
       blank=True
   )

   class Meta:
       swappable = 'CHATTERBOT_STATEMENT_MODEL'
       indexes = [
           models.Index(fields=['upvotes']),
           models.Index(fields=['sentiment_score']),
       ]

   # Custom properties and methods
   @property
   def score(self):
       """
       Calculate net score.
       """
       return self.upvotes - self.downvotes

   def upvote(self, user):
       """
       Record an upvote from a user.
       """
       if not self.upvoted_by.filter(pk=user.pk).exists():
           self.upvoted_by.add(user)
           self.upvotes += 1
           self.save()

class CustomTag(AbstractBaseTag):
"""
Custom Tag model with categorization.
"""

text
# Add your custom fields
   category = models.CharField(max_length=64, blank=True)
   is_active = models.BooleanField(default=True)
   priority = models.IntegerField(default=0)

   class Meta:
       swappable = 'CHATTERBOT_TAG_MODEL'
       ordering = ['-priority', 'name']

Step 2: Configure Django Settings

Tell ChatterBot to use your custom models by adding these settings:

.. code-block:: python
:caption: settings.py

Swappable model configuration (like AUTH_USER_MODEL)

CHATTERBOT_STATEMENT_MODEL = 'myapp.CustomStatement'
CHATTERBOT_TAG_MODEL = 'myapp.CustomTag'

Standard ChatterBot configuration

CHATTERBOT = {
'name': 'My Bot',
'storage_adapter': 'chatterbot.storage.DjangoStorageAdapter',
'logic_adapters': [
'chatterbot.logic.BestMatch',
]
}

Add your app to INSTALLED_APPS

INSTALLED_APPS = [
# ... other apps
'django_chatterbot', # ChatterBot's Django app
'myapp', # Your app with custom models
]

Step 3: Create and Run Migrations

Generate and apply migrations for your custom models:

.. code-block:: bash

Create migrations for your custom models

python manage.py makemigrations myapp

Apply migrations

python manage.py migrate

ChatterBot will now use your custom models automatically.

Required Fields and Methods

Your custom Statement model must include:

Required Fields (from AbstractBaseStatement)

  • text - The statement text (CharField, max_length from constants)
  • search_text - Indexed search text (CharField)
  • conversation - Conversation identifier (CharField)
  • created_at - Timestamp (DateTimeField)
  • in_response_to - Previous statement text (CharField, nullable)
  • search_in_response_to - Indexed previous text (CharField)
  • persona - Speaker identifier (CharField)
  • tags - ManyToManyField to your Tag model

Required Methods

  • get_tags() - Returns list of tag name strings
  • add_tags(*tags) - Adds tags to the statement
  • __str__() - String representation

.. note::
These methods are already implemented in AbstractBaseStatement and will work correctly
with your custom Tag model through automatic detection. You only need to override them if
you need custom behavior.

Your custom Tag model must include:

Required Fields (from AbstractBaseTag)

  • name - Unique tag name (SlugField, unique=True)

Alternative: Per-Instance Configuration

You can also specify custom models per ChatBot instance without changing Django settings.
This is useful when running multiple bots with different schemas:

.. code-block:: python
:caption: views.py

from chatterbot import ChatBot

Bot with custom models

custom_bot = ChatBot(
'Custom Bot',
storage_adapter='chatterbot.storage.DjangoStorageAdapter',
statement_model='myapp.CustomStatement',
tag_model='myapp.CustomTag'
)

Bot with default models

default_bot = ChatBot(
'Default Bot',
storage_adapter='chatterbot.storage.DjangoStorageAdapter'
)

The statement_model and tag_model kwargs take precedence over Django settings.

Tag Model Detection

ChatterBot automatically detects which Tag model to use through a smart fallback system:

  1. Django Settings - First checks CHATTERBOT_TAG_MODEL setting (project-wide config)
  2. Field Introspection - If no setting exists, introspects the Statement model's tags
    field to determine which Tag model it references (handles per-instance kwargs)
  3. Default Fallback - Falls back to 'django_chatterbot.Tag' if detection fails

This ensures that add_tags() always uses the correct Tag model, whether you configure
custom models via Django settings or storage adapter kwargs.

.. code-block:: python
:caption: Example: Field introspection in action

When you define your Statement model like this:

class CustomStatement(AbstractBaseStatement):
tags = models.ManyToManyField('CustomTag', related_name='statements')
# ...

ChatterBot's get_tag_model() will introspect the tags field

and automatically detect that it should use CustomTag,

even if CHATTERBOT_TAG_MODEL is not set in settings.

This automatic detection is especially important when using the per-instance configuration
approach, as it ensures consistent behavior without requiring Django settings changes.

Usage Examples

Example: User Feedback

Track user ratings on responses:

.. code-block:: python
:caption: myapp/models.py

from chatterbot.ext.django_chatterbot.abstract_models import AbstractBaseStatement
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class FeedbackStatement(AbstractBaseStatement):
"""
Statement with user feedback.
"""

text
helpful_count = models.IntegerField(default=0)
   not_helpful_count = models.IntegerField(default=0)

   rated_by = models.ManyToManyField(
       User,
       through='StatementRating',
       related_name='rated_statements'
   )

   tags = models.ManyToManyField(
       'Tag',
       related_name='statements'
   )

   class Meta:
       swappable = 'CHATTERBOT_STATEMENT_MODEL'

class StatementRating(models.Model):
"""
Track individual user ratings.
"""
user = models.ForeignKey(User, on_delete=models.CASCADE)
statement = models.ForeignKey(FeedbackStatement, on_delete=models.CASCADE)
is_helpful = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)

text
class Meta:
       unique_together = ('user', 'statement')

.. code-block:: python
:caption: myapp/views.py

from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from myapp.models import FeedbackStatement, StatementRating

@login_required
@require_POST
def rate_statement(request, statement_id):
statement = FeedbackStatement.objects.get(pk=statement_id)
is_helpful = request.POST.get('helpful') == 'true'

text
rating, created = StatementRating.objects.update_or_create(
       user=request.user,
       statement=statement,
       defaults={'is_helpful': is_helpful}
   )

   # Update counts
   statement.helpful_count = statement.rated_by.filter(
       statementrating__is_helpful=True
   ).count()
   statement.not_helpful_count = statement.rated_by.filter(
       statementrating__is_helpful=False
   ).count()
   statement.save()

   return JsonResponse({
       'helpful': statement.helpful_count,
       'not_helpful': statement.not_helpful_count
   })

Migrating from Default Models

If you need to migrate an existing project from default to custom models:

  1. Create Custom Models

Create your custom models inheriting from the abstract base classes.

  1. Update Settings

Add CHATTERBOT_STATEMENT_MODEL and CHATTERBOT_TAG_MODEL to settings.

  1. Create Initial Migration

.. code-block:: bash

python manage.py makemigrations myapp

  1. Create Data Migration

Write a data migration to copy existing data:

.. code-block:: python
:caption: myapp/migrations/0002_copy_chatterbot_data.py

from django.db import migrations

def copy_statements(apps, schema_editor):
# Get old and new models
OldStatement = apps.get_model('django_chatterbot', 'Statement')
NewStatement = apps.get_model('myapp', 'CustomStatement')
OldTag = apps.get_model('django_chatterbot', 'Tag')

text
# Copy all statements
   for old_stmt in OldStatement.objects.all():
       new_stmt = NewStatement.objects.create(
           text=old_stmt.text,
           search_text=old_stmt.search_text,
           conversation=old_stmt.conversation,
           created_at=old_stmt.created_at,
           in_response_to=old_stmt.in_response_to,
           search_in_response_to=old_stmt.search_in_response_to,
           persona=old_stmt.persona,
       )

       # Copy tags
       new_stmt.tags.set(old_stmt.tags.all())

def reverse_copy(apps, schema_editor):
# Optionally implement reverse migration
pass

class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
('django_chatterbot', 'latest'),
]

text
operations = [
       migrations.RunPython(copy_statements, reverse_copy),
   ]
  1. Apply Migrations

.. code-block:: bash

python manage.py migrate myapp

Best Practices

  1. Always inherit from abstract base classes - This ensures compatibility with ChatterBot's storage adapter.

  2. Set swappable in Meta - Add swappable = 'CHATTERBOT_STATEMENT_MODEL' to enable model swapping.

  3. Implement required methods - get_tags() and add_tags() are essential for ChatterBot's operation.

  4. Use indexes wisely - Add database indexes to fields you'll frequently query or filter on.

  5. Test thoroughly - Test your custom models with ChatterBot's training and conversation features.

  6. Document your schema - Clearly document any custom fields and their purposes for future maintainers.

Troubleshooting

Model Not Found Error

If you see errors like LookupError: No installed app with label 'myapp':

  • Ensure your app is in INSTALLED_APPS
  • Check that migrations have been run
  • Verify the model path in settings (format: 'app_label.ModelName')

Tags Relationship Error

If you get errors about the tags relationship:

  • Ensure your Statement model has a tags ManyToManyField
  • The field must reference your custom Tag model (e.g., 'CustomTag' or 'myapp.CustomTag')
  • Use related_name='statements'

.. note::
ChatterBot automatically detects which Tag model to use by introspecting your Statement
model's tags field. This means add_tags() will work correctly even when you
specify custom models via storage adapter kwargs instead of Django settings.

Migration Conflicts

If migrations conflict:

  • Run python manage.py makemigrations --merge
  • Check migration dependencies
  • Ensure ChatterBot is migrated before your custom models

See Also

  • :doc:settings - Django settings reference
  • :doc:index - Django integration overview
  • :doc:/training - Training your chatbot

Django Index (`docs/django/index.rst`)

================== Django Integration

ChatterBot has direct support for integration with Django's ORM.
It is relatively easy to use ChatterBot within your Django application
to create conversational pages and endpoints.

Install packages

Begin by making sure that you have installed both django and chatterbot.

.. sourcecode:: sh

pip install django chatterbot

For more details on installing and using Django, see the Django documentation_.

Installed Apps

Add chatterbot.ext.django_chatterbot to your INSTALLED_APPS in the
settings.py file of your Django project.

.. code-block:: python

INSTALLED_APPS = (
# ...
'chatterbot.ext.django_chatterbot',
)

Migrations

You can run the Django database migrations for your chat bot with the
following command.

.. sourcecode:: sh

python manage.py migrate django_chatterbot

MongoDB and Django

ChatterBot has a storage adapter for MongoDB but it does not work with Django.
If you want to use MongoDB as your database for Django and your chat bot then
you will need to install a Django storage backend such as Django MongoDB Engine_.

The reason this is required is because Django's storage backends are different
and completely separate from ChatterBot's storage adapters.

Django App Development

.. toctree::
:maxdepth: 2

settings
custom-models
views
wsgi

General Django Tutorials

These are general tutorials related to Django and are not specific to ChatterBot. The goal of these tutorials is to help provide a foundation of knowledge around building Django applications and APIs.

.. toctree::
:maxdepth: 4

tutorial/index

.. _Django documentation: https://docs.djangoproject.com/en/dev/intro/install/
.. _Django MongoDB Engine: https://django-mongodb-engine.readthedocs.io/


Django Settings (`docs/django/settings.rst`)

========================== ChatterBot Django Settings

You can edit the ChatterBot configuration through your Django settings.py file.

.. code-block:: python
:caption: settings.py

CHATTERBOT = {
'name': 'Tech Support Bot',
'logic_adapters': [
'chatterbot.logic.MathematicalEvaluation',
'chatterbot.logic.TimeLogicAdapter',
'chatterbot.logic.BestMatch'
]
}

Any setting that gets set in the CHATTERBOT dictionary will be passed to the chat bot that powers your django app.

Additional Django settings

  • django_app_name [default: 'django_chatterbot'] The Django app name to look up the models from.
  • database [default: 'default'] The Django database alias to use for ChatterBot data storage.

Swappable Model Settings

ChatterBot supports custom Statement and Tag models similar to Django's AUTH_USER_MODEL pattern:

  • CHATTERBOT_STATEMENT_MODEL [default: 'django_chatterbot.Statement'] The Statement model to use.
  • CHATTERBOT_TAG_MODEL [default: 'django_chatterbot.Tag'] The Tag model to use.

.. code-block:: python
:caption: settings.py

Use custom models

CHATTERBOT_STATEMENT_MODEL = 'myapp.CustomStatement'
CHATTERBOT_TAG_MODEL = 'myapp.CustomTag'

These settings can be overridden per ChatBot instance using the statement_model and
tag_model kwargs on the storage adapter. See :doc:custom-models for details.

.. code-block:: python
:caption: Per-instance configuration

from chatterbot import ChatBot

bot = ChatBot(
'My Bot',
storage_adapter='chatterbot.storage.DjangoStorageAdapter',
statement_model='myapp.CustomStatement',
tag_model='myapp.CustomTag'
)

Using a Secondary Database

ChatterBot can store its data in a separate database from your main Django application. This is useful for:

  • Data isolation - Separate backups and maintenance schedules
  • Performance - Reduce load on your main application database
  • Organization - Clear separation between conversational data and application data
  • Scalability - Different database engines or servers for different needs

Configuration

  1. Define your databases in settings.py:

.. code-block:: python
:caption: settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'chatbot_db': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'chatbot.sqlite3'),
}
}

  1. Configure ChatterBot to use the secondary database:

.. code-block:: python
:caption: settings.py

CHATTERBOT = {
'name': 'Tech Support Bot',
'storage_adapter': 'chatterbot.storage.DjangoStorageAdapter',
'database': 'chatbot_db', # Specify the database alias
'logic_adapters': [
'chatterbot.logic.BestMatch'
]
}

  1. Run migrations on the secondary database:

.. code-block:: bash

python manage.py migrate --database=chatbot_db

ChatterBot will now utilize the secondary database to store and query its data.

Example with PostgreSQL

You can use different database engines for your main app and ChatterBot:

.. code-block:: python
:caption: settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'myapp_db',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
},
'chatbot_db': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'chatbot_db',
'USER': 'chatbot_user',
'PASSWORD': 'chatbot_password',
'HOST': 'chatbot.example.com',
'PORT': '5432',
}
}

CHATTERBOT = {
'name': 'Support Bot',
'storage_adapter': 'chatterbot.storage.DjangoStorageAdapter',
'database': 'chatbot_db',
}


Django Views (`docs/django/views.rst`)

============================= ChatterBot Django Sample Code

.. note::

Looking for the full example app? Check it out on GitHub:
https://github.com/gunthercox/ChatterBot/tree/master/examples/django_example

Example API Views

ChatterBot's Django example comes with an API view that demonstrates
one way to use ChatterBot to create an conversational API endpoint
for your application.

The endpoint expects a JSON request in the following format:

.. code-block:: json

{"text": "My input statement"}

.. literalinclude:: ../../examples/django_example/django_example/views.py
:caption: examples/django_example/django_example/views.py
:language: python
:pyobject: ChatterBotApiView

Example Django Management Commands

ChatterBot's Django example includes a management command that
demonstrates a simple example of training. This can be used as
a basis for other custom management commands used with other
:ref:training options .

.. literalinclude:: ../../examples/django_example/django_example/management/commands/train.py
:caption: examples/django_example/django_example/management/commands/train.py
:language: python


Django Wsgi (`docs/django/wsgi.rst`)

Webservices

Hosting and serving web applications typically involves setting up a few additional components. A few common items are noted here to help you get started.

Environments

If you want to host your Django app, you need to choose a method through
which it will be hosted. There are a few free services that you can use
to do this such as Heroku_ and PythonAnyWhere_.

Another good option is DigitalOcean, which is notoriously easy to use and offers a number of affordable hosting plans. If you're interested in trying out DigitalOcean we have a referral link <https://m.do.co/c/c9a695f20505>_ from them that will give you $200 in credit over 60 days.

WSGI

A common method for serving Python web applications involves using a
Web Server Gateway Interface (WSGI_) package.

Gunicorn_ is a great choice for a WSGI server. They have detailed
documentation and installation instructions on their website.

Serving static files

There are numerous ways to host static files for your Django application.
One extremely easy way to do this is by using WhiteNoise_, a python package
designed to make it possible to serve static files from just about any web application.

.. _Heroku: https://heroku.com/
.. _PythonAnyWhere: https://www.pythonanywhere.com/details/django_hosting
.. _Gunicorn: http://gunicorn.org/
.. _WhiteNoise: http://whitenoise.evans.io/en/stable/
.. _WSGI: http://wsgi.readthedocs.io/en/latest/what.html


Logic Create A Logic Adapter (`docs/logic/create-a-logic-adapter.rst`)

============================ 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.

Example logic adapter

.. code-block:: python

from chatterbot.logic import LogicAdapter

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

text
def can_process(self, statement):
       return True

   def process(self, input_statement, additional_response_selection_parameters):
       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 = input_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:

.. code-block:: text

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.

.. code-block:: python

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.

.. code-block:: python

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.

.. code-block:: python

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, input_statement, additional_response_selection_parameters):
from chatterbot.conversation import Statement
import requests

text
# Make a request to the temperature API
   response = requests.get('https://temperature.example.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(text='The current temperature is {}'.format(temperature))
   response_statement.confidence = confidence

   return 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.

.. code-block:: python

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

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

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

.. code-block:: python

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


Logic Index (`docs/logic/index.rst`)

============== Logic Adapters

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

.. toctree::
:maxdepth: 1

response-selection
create-a-logic-adapter

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.

.. code-block:: python

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.

.. image:: ../_static/dialog-processing-flow.svg
:alt: ChatterBot dialog processing flow

Common logic adapter attributes

Each logic adapter inherits the following attributes and methods.

.. autoclass:: chatterbot.logic.LogicAdapter
:members:

Best Match Adapter

.. autofunction:: chatterbot.logic.BestMatch

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

.. code-block:: python

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.

text
See the :ref:`statement-comparison` documentation for the list of functions included with ChatterBot.

See the :ref:`response-selection` documentation for the list of response selection methods included with ChatterBot.

Time Logic Adapter

.. autofunction:: chatterbot.logic.TimeLogicAdapter

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.

.. code-block:: text

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

Mathematical Evaluation Adapter

.. autofunction:: chatterbot.logic.MathematicalEvaluation

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.

.. code-block:: text

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.

.. autofunction:: chatterbot.logic.SpecificResponseAdapter

Specific response example

.. literalinclude:: ../../examples/specific_response_example.py
:language: python

Low confidence response example

.. literalinclude:: ../../examples/default_response_example.py
:language: python


Logic Response Selection (`docs/logic/response-selection.rst`)

==================================== 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:

Response selection methods

.. automodule:: chatterbot.response_selection
:members:

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.

.. code-block:: python

def select_response(statement, statement_list, storage=None):

text
# 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.

.. code-block:: python

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.

.. code-block:: python

response = self.select_response(
input_statement,
list_of_response_options,
self.chatbot.storage
)

Selecting a response from multiple logic adapters

The generate_response method 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 generate_response 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.


Storage Create A Storage Adapter (`docs/storage/create-a-storage-adapter.rst`)

Creating a new storage adapter

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

You will then need to implement the interface established by the StorageAdapter class.

.. literalinclude:: ../../chatterbot/storage/storage_adapter.py
:language: python


Storage Index (`docs/storage/index.rst`)

================ Storage Adapters

.. meta::
:description: ChatterBot storage adapters: SQL, Redis vector database, MongoDB. Semantic search with vector embeddings for AI-powered contextual responses
:keywords: storage adapter, database, SQL, Redis, MongoDB, vector database, semantic search, vector embeddings

Storage adapters provide an interface that allows ChatterBot
to connect to different storage technologies. Each adapter is optimized
for different use cases:

  • Redis Vector Storage: Semantic similarity search using vector embeddings (best for contextual AI responses)
  • SQL Storage: Traditional pattern matching with POS-lemma indexing (best for exact phrase matching)
  • MongoDB Storage: NoSQL document storage with flexible schema
  • Django Storage: Integrated with Django ORM for web applications

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

.. code-block:: python

chatbot = ChatBot(
"My ChatterBot",
storage_adapter="chatterbot.storage.SQLStorageAdapter"
)

Built-in Storage Adapters

ChatterBot includes multiple storage adapters for different AI and database technologies:

.. toctree::
:maxdepth: 2

redis
mongodb
sql
../django/index

Choosing a Storage Adapter

For Semantic AI Chatbots (Recommended for modern conversational AI):

Note that as of December 2025, the Redis Vector Storage Adapter is still an experimental beta feature.

Use Redis Vector Storage when you need:

  • Context-aware responses based on meaning, not keywords
  • Vector embeddings for semantic similarity search
  • Automatic confidence scoring from cosine similarity
  • Best match for conversational AI and natural language understanding

For Pattern-Based Matching:

Use SQL Storage when you need:

  • Exact phrase or pattern matching
  • POS-lemma bigram indexing
  • Traditional database features (ACID compliance)
  • Lower memory footprint

For Flexibility:

Use MongoDB or Django Storage for schema flexibility and web framework integration.

Common storage adapter attributes

Each storage adapter inherits the following attributes and methods.

.. autoclass:: chatterbot.storage.StorageAdapter
:members:

Database Migrations

Various frameworks such as Django and SQL Alchemy support
functionality that allows revisions to be made to databases
programmatically. This makes it possible for updates and
revisions to structures in the database to be be applied
in consecutive version releases.

The following explains the included migration process for
each of the databases that ChatterBot comes with support for.

  • Django: Full schema migrations and data migrations will
    be included with each release.
  • SQL Alchemy: No migrations are currently provided in
    releases. If you require migrations between versions
    Alembic_ is the recommended solution for generating them.
  • MongoDB: No migrations are provided.
  • Redis: No migrations are provided.

Further Reading

.. toctree::
:maxdepth: 2

text-search
create-a-storage-adapter

.. _Alembic: https://alembic.sqlalchemy.org


Storage Mongodb (`docs/storage/mongodb.rst`)

MongoDB Storage Adapter

.. image:: /_static/MongoDB_Fores-Green.svg
:alt: MongoDB Logo
:align: center
..
Imaged used in accordance with the MongoDB Trademark Usage Guidelines
https://www.mongodb.com/legal/trademark-usage-guidelines

ChatterBot includes support for integration with MongoDB databases via its MongoDatabaseAdapter class.

Before you can use this storage adapter you will need to install pymongo_. An easy way to install it is to use the chatterbot[mongodb] extra when installing ChatterBot. For example:

.. code-block:: bash

pip install chatterbot[mongodb]

You'll also need to have a MongoDB server running. An easy way to run one locally is to use Docker:

.. code-block:: yaml
:caption: docker-compose.yml

services:
mongo:
# Use the latest stable version of the mongo image
image: mongo:8.0
# Expose the default MongoDB port
ports:
- "27017:27017"
# Persist the MongoDB data
volumes:
- ./.database/mongodb/db:/data/db

To start the MongoDB container, run:

.. code-block:: bash

docker compose up -d

.. note::

For more information on Docker and docker compose, see the Docker Compose documentation_.

Using MongoDB with SSL/TLS

For secure connections to remote MongoDB instances (such as Amazon DocumentDB, MongoDB Atlas, or production deployments), you can use SSL/TLS certificates.

Amazon DocumentDB Example

text
Amazon DocumentDB requires SSL/TLS connections with a certificate file. Here's how to configure ChatterBot:

1. Download the Amazon RDS CA certificate bundle:

.. code-block:: bash

   wget https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem

2. Configure ChatterBot to use the certificate:

.. code-block:: python

   from chatterbot import ChatBot

   bot = ChatBot(
       'MyBot',
       storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
       database_uri='mongodb://USERNAME:[email protected]:27017/?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred',
       mongodb_client_kwargs={
           'tlsCAFile': 'global-bundle.pem'  # Path to your certificate file
       }
   )

MongoDB Atlas Example
~~~~~~~~~~~~~~~~~~~~~

For MongoDB Atlas with SSL/TLS:

.. code-block:: python

   from chatterbot import ChatBot

   bot = ChatBot(
       'MyBot',
       storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
       database_uri='mongodb+srv://USERNAME:[email protected]/?retryWrites=true&w=majority',
       mongodb_client_kwargs={
           'tls': True,
           'tlsAllowInvalidCertificates': False  # Use True only for testing
       }
   )

Self-Signed Certificates
~~~~~~~~~~~~~~~~~~~~~~~~

If you're using self-signed certificates:

.. code-block:: python

   from chatterbot import ChatBot

   bot = ChatBot(
       'MyBot',
       storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
       database_uri='mongodb://localhost:27017/chatterbot-database?ssl=true',
       mongodb_client_kwargs={
           'tlsCAFile': '/path/to/ca.pem',
           'tlsCertificateKeyFile': '/path/to/client.pem',
           'tlsAllowInvalidCertificates': False
       }
   )

Additional MongoDB Client Options

The mongodb_client_kwargs parameter accepts any valid PyMongo MongoClient options, including:

  • tlsCAFile: Path to CA certificate file
  • tlsCertificateKeyFile: Path to client certificate file
  • tls: Enable/disable TLS
  • tlsAllowInvalidCertificates: Allow invalid certificates (not recommended for production)
  • serverSelectionTimeoutMS: Timeout for server selection
  • connectTimeoutMS: Connection timeout
  • socketTimeoutMS: Socket timeout
  • maxPoolSize: Maximum connection pool size
  • minPoolSize: Minimum connection pool size

For a complete list of options, see the PyMongo MongoClient documentation_.

MongoDB Adapter Class Attributes

.. autoclass:: chatterbot.storage.MongoDatabaseAdapter
:members:

.. _pymongo: https://pypi.org/project/pymongo/
.. _Docker Compose documentation: https://docs.docker.com/compose/
.. _PyMongo MongoClient documentation: https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html


Storage Redis (`docs/storage/redis.rst`)

Redis Vector Storage Adapter

.. note::

(December, 2025):
The RedisVectorStorageAdapter is new and experimental functionality introduced as a "beta" feature. Its functionality might not yet be fully stable and is subject to change in future releases.

.. meta::
:description: Redis vector storage for ChatterBot: semantic similarity search, vector embeddings, AI-powered contextual responses with HuggingFace transformers
:keywords: redis vector database, semantic search, vector embeddings, sentence transformers, AI chatbot, natural language understanding, context-aware responses, vector similarity

.. image:: /_static/Redis_Logo_Red_RGB.svg
:alt: Redis Logo
:align: center
:width: 200
..
Imaged used in accordance with the Redis Trademark Policy
https://redis.io/legal/trademark-policy/

The RedisVectorStorageAdapter enables advanced semantic similarity search for ChatterBot using Redis® as a :term:vector database.
Unlike traditional keyword-based storage adapters, this adapter uses vector embeddings and cosine similarity to understand conversational context and find semantically related responses.

Key Features:

  • Semantic Understanding: Matches responses based on meaning, not just keywords
  • Vector Embeddings: Uses HuggingFace sentence-transformers/all-mpnet-base-v2 model for state-of-the-art text encoding
  • Confidence Scoring: Returns similarity scores (0.0-1.0) based on vector distance for intelligent response ranking
  • Performance Optimized: Automatic NoOpTagger eliminates unnecessary spaCy processing overhead
  • Context-Aware Responses: Finds conversationally appropriate responses even when exact words differ

Vectors are mathematical representations of text (multi-dimensional embeddings) that capture semantic meaning.
The adapter calculates similarity between text by measuring the cosine distance between their vector representations,
allowing ChatterBot to understand that "How are you?" is similar to "How's it going?" even with different words.

For example, consider the following words:

.. code-block:: text

text
(Speaking)
            ●
           / \
          /   \
(Poetry) ●-----● (Rhyming)
          \   /
           \ /
            ●
        (Writing)

The acts of "speaking" and "writing" are both forms of communication, so they are included in the same cluster, but they are somewhat opposite to each other. Both "poetry" and "rhyming" closely related, and in some cases might possibly be used as synonyms within the context of either types of speech or types of writing.

Redis Setup

Before you use the RedisVectorStorageAdapter you will need to install
the dependencies required for Redis_ and generating vectors.
This can be done using the chatterbot[redis] extra when
installing ChatterBot. For example:

.. code-block:: bash

pip install chatterbot[redis]

You will also need to have a Redis server running, with the additional
modules installed that enable searching using vectors. And easy way to
run one locally is to use Docker:

.. code-block:: yaml
:caption: docker-compose.yml

services:
redis:
# Use the latest version of the redis-stack image
image: redis/redis-stack-server:latest
# Expose the default Redis port
ports:
- "6379:6379"
# Persist the Redis data
volumes:
- ./.database/redis/:/data

To start the Redis container, run:

.. code-block:: bash

docker compose up -d

Likewise, you can run docker compose ps to review the status of your container, and docker compose down to stop it. For more information on Docker and docker compose, see the Docker Compose documentation_.

Redis Configuration

To use the RedisVectorStorageAdapter you will need to provide the following argument when configuring your ChatterBot instance:

.. code-block:: python

from chatterbot import ChatBot

chatbot = ChatBot(
'Redis Bot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
# Optional: Override the default Redis URI
# database_uri='redis://localhost:6379/0'
)

Storage-Aware Architecture
^^^^^^^^^^^^^^^^^^^^^^^^^^

The Redis adapter automatically configures ChatterBot for optimal performance with vector-based search:

  • Automatic Tagger Selection: Uses NoOpTagger instead of PosLemmaTagger to eliminate spaCy model loading overhead
  • Semantic Vector Search: Automatically selects SemanticVectorSearch algorithm instead of text-based comparison
  • No Manual Configuration: These optimizations are applied automatically when using the Redis adapter

This "storage-aware" design means ChatterBot adapts its processing pipeline based on the storage adapter's capabilities,
ensuring maximum performance and accuracy for vector-based semantic search.

.. code-block:: python

No need to specify tagger or search algorithm - Redis adapter handles it!

chatbot = ChatBot(
'Semantic Bot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter'
)

Automatically uses:

- NoOpTagger (no spaCy overhead)

- SemanticVectorSearch (vector similarity)

- Confidence scores from cosine similarity

The Redis adapter uses semantic vector search instead of traditional pattern matching:

.. list-table:: Comparison: Semantic Vector Search vs. Text-Based Search
:widths: 30 35 35
:header-rows: 1

    • Feature
    • Traditional Text Search (SQL)
    • Semantic Vector Search (Redis)
    • Search Method
    • POS-lemma bigram matching
    • 768-dimensional vector similarity
    • Context Understanding
    • Structural patterns only
    • Deep semantic meaning
    • "How are you?" matches "How's it going?"
    • ❌ No (different lemmas)
    • ✅ Yes (similar meaning)
    • Confidence Scoring
    • Levenshtein distance
    • Cosine similarity (1 - distance/2)
    • Processing Overhead
    • Requires spaCy models
    • No spaCy needed (NoOpTagger)
    • Best For
    • Exact pattern matching
    • Conversational AI, context understanding

Example: Semantic Similarity in Action

.. code-block:: python

These inputs find similar responses despite different words:

response1 = chatbot.get_response("What's the weather like?")
response2 = chatbot.get_response("How's the climate today?")

Confidence scores help rank responses:

- Vector distance 0.1 → confidence ~0.95 (very similar)

- Vector distance 0.5 → confidence ~0.75 (somewhat similar)

Class Attributes

.. autoclass:: chatterbot.storage.RedisVectorStorageAdapter
:members:

Performance Considerations

Vector Embedding Model: By default, the Redis adapter uses sentence-transformers/all-mpnet-base-v2 from HuggingFace:

  • Dimensions: 768-dimensional embeddings
  • Model Size: ~420MB (downloaded once, cached locally)
  • Performance: ~2000 sentences/second on CPU
  • Quality: State-of-the-art semantic similarity (as of 2025)

First-Time Setup: The embedding model downloads automatically on first use:

.. code-block:: python

First initialization downloads model (~420MB)

chatbot = ChatBot('Bot', storage_adapter='chatterbot.storage.RedisVectorStorageAdapter')

Subsequent uses load from cache (fast startup)

Memory Usage: Redis vector storage requires more memory than SQL due to embedding storage:

  • Each statement: ~3KB (768 floats × 4 bytes)
  • 10,000 statements: ~30MB vector data
  • Trade-off: Higher memory for better semantic understanding

Embedding Model Configuration

.. versionadded:: 1.2.8
Support for configurable embedding models and providers.

The Redis adapter now supports custom embedding models and providers, allowing you to optimize for different use cases:

Default Configuration
^^^^^^^^^^^^^^^^^^^^^

By default, the adapter uses HuggingFace's sentence-transformers/all-mpnet-base-v2:

.. code-block:: python

chatbot = ChatBot(
'Bot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter'
)

Uses: sentence-transformers/all-mpnet-base-v2 (768-dim, balanced)

Alternative HuggingFace Models
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Choose different models based on your requirements:

Fast/Lightweight Model (for high-throughput applications):

.. code-block:: python

chatbot = ChatBot(
'FastBot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
embedding_model='all-MiniLM-L6-v2'
)

Model: all-MiniLM-L6-v2

Dimensions: 384 (vs 768 default)

Size: 80MB (vs 420MB default)

Speed: 5x faster

Quality: ~10% lower accuracy

Q&A Optimized Model (for question-answering chatbots):

.. code-block:: python

chatbot = ChatBot(
'QABot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
embedding_model='multi-qa-mpnet-base-dot-v1'
)

Model: multi-qa-mpnet-base-dot-v1

Trained specifically on Q&A datasets

Better performance on question-answer pairs

Multilingual Model (for multi-language support):

.. code-block:: python

chatbot = ChatBot(
'MultilingualBot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
embedding_model='paraphrase-multilingual-mpnet-base-v2'
)

Model: paraphrase-multilingual-mpnet-base-v2

Supports 50+ languages

Same 768 dimensions as default

Advanced Embedding Configuration
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Pass additional parameters to the embedding model:

.. code-block:: python

chatbot = ChatBot(
'CustomBot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
embedding_model='all-MiniLM-L6-v2',
embedding_kwargs={
'model_kwargs': {
'device': 'cpu', # or 'cuda' for GPU
'torch_dtype': 'float16' # Reduce memory usage
},
'encode_kwargs': {
'normalize_embeddings': True, # L2 normalization
'batch_size': 32 # Process 32 texts at once
}
}
)

Alternative Embedding Providers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

OpenAI Embeddings (cloud-based, requires API key):

.. code-block:: python

Requires: pip install langchain-openai

Set: export OPENAI_API_KEY="your-api-key"

chatbot = ChatBot(
'OpenAIBot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
embedding_provider='openai',
embedding_model='text-embedding-3-small',
embedding_kwargs={'dimensions': 1536}
)

Pros: High quality, fast API calls

Cons: Costs money per token, requires internet

Cohere Embeddings (cloud-based, requires API key):

.. code-block:: python

Requires: pip install langchain-cohere

Set: export COHERE_API_KEY="your-api-key"

chatbot = ChatBot(
'CohereBot',
storage_adapter='chatterbot.storage.RedisVectorStorageAdapter',
embedding_provider='cohere',
embedding_model='embed-english-v3.0'
)

Cons: Subscription-based, requires internet

Model Selection Guide
^^^^^^^^^^^^^^^^^^^^^

.. list-table:: Embedding Model Comparison
:widths: 25 20 20 35
:header-rows: 1

    • Use Case
    • Recommended Model
    • Dimensions
    • Trade-offs
    • General chatbot (default)
    • all-mpnet-base-v2
    • 768
    • Best balance of speed and quality
    • High-throughput / limited resources
    • all-MiniLM-L6-v2
    • 384
    • 5x faster, smaller size, slight quality loss
    • Question-answering bot
    • multi-qa-mpnet-base-dot-v1
    • 768
    • Better Q&A performance, same size as default
    • Multilingual bot
    • paraphrase-multilingual-mpnet-base-v2
    • 768
    • Supports 50+ languages, same size
    • Cloud/Production (API)
    • OpenAI or Cohere
    • 1024-1536
    • Higher quality, costs money, requires API key

Example: Complete Configuration

See examples/redis_embedding_examples.py for complete working examples of all embedding configurations.

For those looking to learn more about vector databases, vector embeddings, and semantic search in AI applications:

.. list-table:: Vector Database & AI Learning Resources
:widths: 50 50
:header-rows: 1

:sub:* Redis is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd.

.. _Redis: https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/
.. _Docker Compose documentation: https://docs.docker.com/compose/


Storage Sql (`docs/storage/sql.rst`)

SQL Storage Adapter

.. autoclass:: chatterbot.storage.SQLStorageAdapter
:members:


Storage Text Search (`docs/storage/text-search.rst`)

ChatterBot's storage adapters support text search functionality.

Text Search Example

.. literalinclude:: ../../tests/test_chatbot.py
:language: python
:pyobject: ChatterBotResponseTestCase.test_search_text_results_after_training

Bigram Text Index

Bigram pairs are used for text search

In addition, the generation of the pairs ensures that there is a smaller number
of possible matches based on the probability of finding two neighboring words
in an existing string that match the search parameter.

For searches in larger data sets, the bigrams also reduce the number of OR
comparisons that need to occur on a database level. This will always be a
reduction of n - 1 where n is the number of search words.

.. image:: ../_static/bigrams.svg
:alt: ChatterBot bigram generation process


Django Tutorial Index (`docs/django/tutorial/index.rst`)

================ Django Tutorials

These are mini tutorials designed to introduce basic parts of Django in a way that is quick and brief yet easy to understand. For a more comprehensive explanation, see the tutorial in Django's official documentation: https://docs.djangoproject.com/en/4.2/intro/tutorial01/

There are three tutorials in this collection. The first one is a basic introduction to Django, and the second one builds on the first to introduce another common library used alongside Django; Django REST framework_. The third tutorial continues by configuring the django-filter package to filter results from the API built in part 2.

Django

.. toctree::
:maxdepth: 2

django-tutorial/index
django-tutorial/part-2

Django REST Framework

.. toctree::
:maxdepth: 2

django-rest-framework-tutorial/index

.. _Django REST framework: https://www.django-rest-framework.org/

django-filter

.. toctree::
:maxdepth: 2

django-filter-tutorial/index

Writing Tests

.. toctree::
:maxdepth: 2

writing-tests

.. _Django REST framework: https://www.django-rest-framework.org/


Django Tutorial Writing Tests (`docs/django/tutorial/writing-tests.rst`)

===================================== Writing Tests for Django Applications

Writing tests helps ensure the quality and stability of your code. Creating tests from the start of a project is often easier than adding them later, and writing good tests can help establish beneficial patterns that others can copy later when adding new features.

This tutorial will show you how to write tests for Django applications, specifically for Django REST framework APIs.

Example API Test Cases

Here are a few examples of test cases for the API that we built as a part of the :ref:previous tutorials <Django Tutorials>.

A few things to note:

  • We use Django's reverse function to generate the URL for the API endpoint. This helps ensure that the tests will continue to work even if the URL changes.
  • We use Django REST framework's APITestCase class to write the test cases. This is preferred for API tests over Django's built-in TestCase classes because it provides additional features that are useful for testing APIs.
  • The status module from Django REST framework is used to check the status codes of the responses. Although not necessary, it helps keep tests more readable.

.. code-block:: python
:caption: chapters/tests.py

text
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from chapters.models import Chapter


class ChapterListApiTests(APITestCase):
    """
    Test cases for the /chapter/ endpoint.
    """

    def setUp(self):
        # Use Django's reverse function to generate the URL
        self.endpoint = reverse('chapter-list')

    def test_list_chapters(self):
        """
        A list of chapters should be returned from the API.
        """
        # Create a chapter
        Chapter.objects.create(title='Introduction', number=1)

        response = self.client.get(self.endpoint, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'count': 1,
            'next': None,
            'previous': None,
            'results': [
                {'title': 'Introduction', 'number': 1}
            ]
        })

    def test_filter_chapters_by_number(self):
        """
        The matching chapters should be returned from the API when filtering by number.
        """
        # Create chapters
        Chapter.objects.create(title='Introduction', number=1)
        Chapter.objects.create(title='Prologue', number=2)

        response = self.client.get(self.endpoint + '?number=1', format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {
            'count': 1,
            'next': None,
            'previous': None,
            'results': [
                {'title': 'Introduction', 'number': 1}
            ]
        })

    def test_create_chapter(self):
        """
        A chapter should be created when a POST request is sent to the API.
        """
        response = self.client.post(self.endpoint, {
            'title': 'Introduction', 'number': 1
        }, format='json')

        # Only one chapter should exist
        self.assertEqual(Chapter.objects.count(), 1)

        chapter = Chapter.objects.first()

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(chapter.title, 'Introduction')
        self.assertEqual(chapter.number, 1)


class ChapterDetailApiTests(APITestCase):
    """
    Test cases for the /chapter// endpoint.
    """

    def setUp(self):
        self.chapter = Chapter.objects.create(title='Introduction', number=1)
        self.endpoint = reverse('chapter-detail', args=[self.chapter.id])

    def test_update_chapter(self):
        """
        A chapter should be updated when a PATCH request is sent to the API.
        """

        response = self.client.patch(reverse('chapter-detail', args=[self.chapter.id]), {
            'title': 'Introduction', 'number': 2
        }, format='json')

        # Only one chapter should exist
        self.assertEqual(Chapter.objects.count(), 1)

        chapter = Chapter.objects.first()

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(chapter.number, 2)

    def test_delete_chapter(self):
        """
        A chapter should be deleted when a DELETE request is sent to the API.
        """
        response = self.client.delete(reverse('chapter-detail', args=[self.chapter.id]))

        # No chapters should exist
        self.assertEqual(Chapter.objects.count(), 0)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

Django Tutorial Django Filter Tutorial Index (`docs/django/tutorial/django-filter-tutorial/index.rst`)

====================== django-filter tutorial

In this section, we will be adding filtering functionality to the API built in the :ref:Django REST Framework Tutorial. To do this we'll be using the django-filter package.

For more information, django-filter has a comprehensive setup guide in its documentation <https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html>_.

  1. Install django-filter

To install django-filter, run the following command:

.. sourcecode:: sh

pip install django-filter

  1. Configure django-filter settings

Add django_filters to your INSTALLED_APPS in the settings.py file of your Django project.

.. code-block:: python
:caption: tutorial/settings.py

INSTALLED_APPS = (
# ...
'django_filters',
)

Also add the following lines to the REST_FRAMEWORK setting in the same file:

.. code-block:: python
:caption: tutorial/settings.py

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
# ...
)
}

  1. Configure filtering for the API

Define a new filterset_fields variable at the class level of the viewset you created in the previous tutorial:

.. code-block:: python
:caption: tutorial/viewsets.py

text
# ...

class ChapterViewSet(viewsets.ModelViewSet):
    queryset = Chapter.objects.all()
    serializer_class = ChapterSerializer

    # Add this line:
    filterset_fields = ('number', 'title')

# ...
  1. Test the filtering

You can now test the filtering by adding query parameters to the API URL. For example, to filter chapters by title, you can use the following URL:

.. code-block:: text

http://localhost:8000/api/chapters?title=Introduction&number=1

You'll see that only the chapter with the title "Introduction" and number "1" is returned in the response. Note that you may need to add more chapters to your database to fully see the filtering in action.

  1. Conclusion on django-filter

Now you know how to add filtering functionality to your APIs. The django-filter package has a number of additional features including the ability to create more complex and custom filters. For more information, see the django-filter documentation <https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html>_.

To wrap up these tutorials, in the :ref:next section <Writing Tests for Django Applications> we'll be covering how to write tests for the API you just built.


Django Tutorial Django Rest Framework Tutorial Index (`docs/django/tutorial/django-rest-framework-tutorial/index.rst`)

============================== Django REST Framework Tutorial

This is the second portion of ChatterBot's Django tutorial. These tutorial are intended to briefly introduce beginners to the basics of Django, Django REST Framework, and other related libraries that provide a powerful foundation of knowledge for developing Python applications. For a more comprehensive tutorial, the official documentation for Django REST Framework_ is highly recommended.

In this section, we will be adding a REST API to our Django project from the :ref:previous tutorial <Django Tutorial (Part 1)>.

.. _official documentation for Django REST Framework: https://www.django-rest-framework.org/tutorial/quickstart/

  1. Install Django REST Framework

Begin by installing Django REST Framework with the following command:

.. sourcecode:: sh

pip install djangorestframework

  1. Configure Django REST Framework settings

Next, add rest_framework to your INSTALLED_APPS in the settings.py file of your Django project.

.. code-block:: python
:caption: tutorial/settings.py

INSTALLED_APPS = (
# ...
'rest_framework',
)

Finish configuring Django REST Framework for your project by adding the following lines to your settings.py file.

.. code-block:: python
:caption: tutorial/settings.py

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}

  1. Create a Serializer

A serializer is a class that defines the fields that get converted to JSON. Create a new file called serializers.py in the chapters directory.

.. code-block:: python
:caption: chapters/serializers.py

from rest_framework import serializers
from chapters.models import Chapter

class ChapterSerializer(serializers.ModelSerializer):
class Meta:
model = Chapter
fields = (
'title',
'number',
)

  1. Create a ViewSet

A viewset is a class that provides the actions that can be performed on a resource. Create a new file called viewsets.py in the chapters directory.

.. code-block:: python
:caption: chapters/viewsets.py

from rest_framework import viewsets
from chapters.models import Chapter
from chapters.serializers import ChapterSerializer

class ChapterViewSet(viewsets.ModelViewSet):
queryset = Chapter.objects.all()
serializer_class = ChapterSerializer

  1. Add a Router

A router is a class that automatically determines the URL conf for a set of views. You can add your router to your project's existing urls.py file.

.. code-block:: python
:caption: tutorial/urls.py

from django.urls import include
from rest_framework.routers import DefaultRouter
from chapters.viewsets import ChapterViewSet

router = DefaultRouter()
router.register(r'chapters', ChapterViewSet)

urlpatterns = [
# ...
path('api/', include(router.urls)),
]

  1. Test Your API

To test your API, open a web browser and navigate to http://localhost:8000/api/chapters/. You should see a JSON response with the chapters in your database.

.. code-block:: JSON
:caption: localhost:8000/api/chapters/

text
{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "title": "Introduction",
            "number": 1
        }
    ]
}
  1. Conclusion

This concludes this mini tutorial on Django REST Framework. Now you know how to:

  • Add a REST API to your Django project
  • Create a serializer using Django REST Framework
  • Create a viewset and router to expose your API

For further learning, a good place to start would be how to use JavaScript to interact with your API from your webpages.

:ref:Up next <django-filter tutorial> in this series we'll be continuing to build off of this project by adding filtering capabilities to our API using the django-filter package.


Django Tutorial Django Tutorial Index (`docs/django/tutorial/django-tutorial/index.rst`)

======================== Django Tutorial (Part 1)

As mentioned in the previous section, this is a small tutorial designed to introduce basic parts of Django in a way that is simple and easy to understand. For a more comprehensive explanation, see the tutorial in Django's official documentation: https://docs.djangoproject.com/en/4.2/intro/tutorial01/

  1. Install Django

Begin by making sure that you have installed Django. For this tutorial we are going to be using the latest stable version of Django_, which is 4.2.

.. sourcecode:: sh

pip install "django~=4.2"

  1. Create a Django Project

Create a new Django project by running the following commands:

.. sourcecode:: sh

django-admin startproject tutorial
cd tutorial
python manage.py startapp chapters

This will create a new directory called tutorial with the following structure:

.. code-block:: sh

tutorial/
manage.py
tutorial/
init.py
settings.py
urls.py
wsgi.py
asgi.py
chapters/
init.py
migrations/
init.py
admin.py
apps.py
models.py
tests.py
views.py

These files are the basic structure of a Django project.

  1. Run the Development Server

Now we've gone through enough of the setup that you should be able to start the development server by running the following command:

.. sourcecode:: sh

python manage.py runserver 0.0.0.0:8000

You should see the following output:

.. code-block:: sh

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
February 12, 2025 - 13:03:37
Django version 4.2.19, using settings 'tutorial.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

In your web browser, go to http://localhost:8000/. You should see a "Welcome to Django" page.

.. image:: django-installed.png
:alt: ChatterBot process flow diagram
:align: center

  1. Edit the Django Project settings

Open the file tutorial/settings.py in your text editor and add the chapters app to the INSTALLED_APPS list. When done it should look like this:

.. code-block:: python
:caption: tutorial/settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

text
'chapters',

]

  1. Concluding Part 1

This concludes part 1 of this mini Django tutorial. Now you know:

  • The basics of installing a python package
  • How to create a new Django project
  • The basic structure of a Django project
  • How to start the development server

In the next part of this tutorial, we will be covering concepts including views, models, and templates.

:ref:Continue to Part 2 <Django Tutorial (Part 2)>.

.. _latest stable version of Django: https://www.djangoproject.com/download/


Django Tutorial Django Tutorial Part 2 (`docs/django/tutorial/django-tutorial/part-2.rst`)

======================== Django Tutorial (Part 2)

In the :ref:previous part <Django Tutorial (Part 1)> of this tutorial we set up our Django app. Now we're going to create a new model, and a view. If this is your first time working with these, Django's models are classes that represent database tables, and Django's views are functions that handle HTTP requests and return HTTP responses.

  1. Creating a New Model

In the chapters directory, open the file models.py. This file is where you define your models. Add the following code to the file:

.. code-block:: python
:caption: chapters/models.py

text
from django.db import models


class Chapter(models.Model):
    """
    A model representing a chapter in a digital book.
    """
    title = models.CharField(max_length=100)
    number = models.IntegerField(unique=True)

Next, run the following commands. The first will generate a migration file, code that tells Django how to create a new table in a database to correspond to this model. The second will run the migration, and create the table in the database.

.. sourcecode:: sh

text
python manage.py makemigrations
python manage.py migrate

You should see output similar to the following:

.. code-block:: sh

text
Migrations for 'chapters':
  chapters/migrations/0001_initial.py
    - Create model Chapter

Operations to perform:
  Apply all migrations: admin, auth, chapters, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying chapters.0001_initial... OK
  Applying sessions.0001_initial... OK
  1. Creating a New View

In Django, views let you define what content gets returned in response to a request. In this part of the tutorial, we're going to set up a view that renders an HTML page for the requested chapter and populate that page with the corresponding data using the model we previously created.

Start by creating a new file and folder in the chapters directory: templates/chapter.html. Add the following code to the file:

.. code-block:: html
:caption: chapters/templates/chapter.html

text
<!DOCTYPE html>
<html>
<head>
    <title>{{ chapter.title }}</title>
</head>

    <h1>{{ chapter.title }}</h1>
    This is chapter {{ chapter.number }}.

</html>

In the chapters directory, open the file chapters/views.py. This file is where you define your views. Add the following code to the file:

.. code-block:: python
:caption: chapters/views.py

text
from django.views.generic import TemplateView
from django.http import HttpResponse
from chapters.models import Chapter

class ChapterView(TemplateView):
    """
    Render an HTML page for the requested chapter.
    """

    template_name = 'chapter.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['chapter'] = Chapter.objects.get(number=kwargs['number'])

        return context

Finally, open the file tutorial/urls.py. This file is where you define the URLs for your views. Ensure the following import for ChapterView is at the top of the file, and that the path for the view is included in the urlpatterns list:

.. code-block:: python
:caption: tutorial/urls.py

text
from django.urls import path
from chapters.views import ChapterView

urlpatterns = [
    path('chapter//', ChapterView.as_view(), name='chapter'),
]
  1. Adding a Chapter

To add a chapter to the database, run the following command:

.. sourcecode:: sh

text
python manage.py shell

This will open a Python shell. Run the following commands to create a new chapter:

.. code-block:: python

text
from chapters.models import Chapter

Chapter.objects.create(title='Introduction', number=1)

Use Ctrl-D or type in exit() to exit the shell.

Now you should be able to visit http://localhost:8000/chapter/1/ in your web browser and see the chapter page you created.

  1. Concluding Part 2

This concludes part 2 of this mini Django tutorial. Now you know:

  • How to create a new model in Django
  • How to generate and run migrations
  • How to add views with html templates
  • How to add a url for your views
  • How to add data to your database using Django's shell

If you still want to learn more, Django's official documentation <https://docs.djangoproject.com/en/4.2/contents/>_ is a great place to start.

:ref:Up next <Django REST Framework Tutorial> in this series we'll be building off of the project we've begun to learn about how to add Django REST Framework to an existing Django project.


--- METRICS ---