Search⌘ K
AI Features

Building an AI-Powered Chatbot

Explore how to develop AI-powered chatbots in Python that interpret and solve a variety of math problems using logic adapters. Learn to handle natural language input, evaluate dynamic queries, and build conversational bots with ChatterBot to move beyond rigid rule-based designs.

In the previous lesson, we built a simple chatbot that followed predefined rules to give us the current time in various cities. It was like teaching a toddler to answer specific questions: “What time is it in Tokyo?” led to an accurate response, but ask it something slightly different, like “What’s the time in Paris?” (a city we didn’t add), and it would get confused. That gave us a taste of rule-based chatbots. It was rigid, predictable, and great for straightforward tasks. But now, it’s time to take a step forward.

What if you wanted a chatbot to help with something more dynamic, like math? We could build another rule-based bot for specific calculations like “What’s 2 + 2?” But how many rules would we need to cover all possible math problems? It would be like writing separate instructions for every grain of sand on a beach—not practical. If you tried to write a rule-based bot for all possible basic arithmetic questions up to 100, you’d need to cover over 40,000 unique combinations! This doesn’t even account for variations in how questions might be phrased in natural language, ‘‘What’s the sum of 15 and 20?’’ vs. ‘‘Add 15 and 20 for me.’’

That’s where logic adapters come in. Think of them as built-in “cheat sheets’’ that give our chatbot advanced skills without requiring us to program every possible scenario. To demonstrate, we’ll use a chatbot that can act as a math-savvy assistant: the AI Calculator.

Why are we doing this?

If the World Clock bot was a bicycle—steady, reliable, but limited in speed—then the AI Calculator is a sleek motorbike. Not only is it faster, but it also easily handles the curves of dynamic input, giving you a smooth ride through complex queries. With the AI Calculator, you’ll learn about:

  • The working of logic adapters: These are like preinstalled tools that make the bot capable of advanced tasks.

  • Handling natural language input: The AI Calculator can interpret math questions in plain English instead of rigid rules.

  • Evaluating dynamic queries: It doesn’t need specific instructions for every input—it understands general patterns, thanks to its math skills.

Think of the chatbot as a friendly assistant who can take a conversational question like, “What is 25 divided by 5?” and instantly respond with “5”. You can ask it a variety of math questions, such as:

  • “What is 50 minus 20?” The bot will recognize “minus” as a subtraction operation, subtract 20 from 50, and give you the answer: 30.

  • “What is 10 times 15?” The bot identifies “times” as multiplication, computes the result (150), and responds conversationally.

  • “What is 100 divided by 25?” It interprets “divided by” as division, calculates the quotient (4.0), and gives you the answer.

Here’s the best part: the AI Calculator uses a logic adapter to dynamically process and evaluate math expressions. You don’t have to teach it every possible question—it’s smart enough to recognize patterns and solve a wide range of math problems as long as they fall within its capabilities.

But like any assistant, it has limitations. It might not know how to respond if you ask something too complex, such as “What is 2 raised to the power of 56?” Still, it’s a quick and efficient problem solver for everyday math questions that makes learning fun and interactive. It’s conversational, intelligent, and ready to help—perfect for exploring the next level of chatbot functionality.

Fun fact: The earliest computers, like the ENIAC in the 1940s, were designed primarily to perform complex mathematical calculations for tasks like artillery trajectory plotting. So, using AI to solve math problems is a nod to the very origins of computing!

How to create an AI chatbot

Let’s upgrade our chatbot-building skills using ChatterBot, a powerful library for conversational AI creation. We can add advanced features like mathematical evaluation without getting bogged down in technical complexities with just a few lines of code.

In our AI Calculator, the MathematicalEvaluationThe MathematicalEvaluation logic adapter parses input to determine whether the user is asking a question that requires math to be done. If so, the equation is extracted from the input and returned with the evaluated result. logic adapter acts as the brain for solving math problems. It takes user queries, interprets phrases like “plus,” “times,” or “divided by,” translates them into mathematical operations, and computes the results. It’s like having a prebuilt engine that knows how to handle numbers, operations, and equations, freeing you to focus on building the chatbot’s interface and personality.

Here’s why we’re using ChatterBot:

  1. It demonstrates how to build functional chatbots with minimal setup.

  2. It’s beginner-friendly while offering a glimpse into advanced capabilities.

  3. It supports logic adapters like MathematicalEvaluation, which powers our calculator.

Note: Although ChatterBot isn’t actively maintained, it’s still a great tool for learning chatbot basics and exploring core concepts. Plus, you won’t have to worry about the complicated setup or dependencies—at Educative, we handle everything for you. Your focus? Learning and building awesome projects.

from chatterbot import ChatBot

# naming the ChatBot calculator
# using mathematical evaluation logic
# the calculator AI will not learn with the user input
Bot = ChatBot(name = 'Calculator',
                read_only = True,                  
                logic_adapters = ["chatterbot.logic.MathematicalEvaluation"],                 
                storage_adapter = "chatterbot.storage.SQLStorageAdapter")
    

# clear the screen and start the calculator
print('\033c')
print("Hello, I am a calculator. How may I help you?")
while (True):
    # take the input from the user
    user_input = input("me: ")
    
    # check if the user has typed quit to exit the prgram   
    if user_input.lower() == 'quit':
        print("Exiting")
        break

    # otherwise, evaluate the user input
    # print invalid input if the AI is unable to comprehend the input
    try:
        response = Bot.get_response(user_input)
        print("Calculator:", response)
    except:
        print("Calculator: Please enter valid input.")
AI chatbot

In the above code:

  • Line 1: Import the ChatBot class from the chatterbot library. This is the foundation of the chatbot. The ChatBot class provides the framework for creating and configuring the bot, including setting its name, logic, and storage.

  • Lines 6–9: Initialize the chatbot with the name Calculator, using the MathematicalEvaluation logic adapter for math operations and the SQLStorageAdapter for storage. The bot is set to read_only to maintain a consistent behavior.

  • Lines 13–14: Clear the terminal and greet the user with an introductory message.

  • Lines 15–17: Start an infinite loop to accept user input continuously until explicitly exited.

  • Lines 20–21: Check if the user types "quit". If so, terminate the loop and print an exit message.

  • Lines 26–28: Pass the user input to the bot’s get_response method to process and calculate the answer, then display the result. The MathematicalEvaluation logic adapter interprets math queries, performs calculations, and returns the result.

  • Lines 29–30: Handle invalid input gracefully by prompting the user to try again.

We can see that the MathematicalEvaluation adapter is the core logic that powers the AI Calculator. It’s the brain behind the chatbot’s ability to dynamically process and solve mathematical queries. Unlike simple rule-based systems, this adapter uses natural language parsing and dynamic computation to interpret user input, extract mathematical expressions, and compute accurate results. Let’s dive into the code and explore how this adapter transforms user queries into intelligent responses.

Python 3.10.4
from chatterbot.logic import LogicAdapter
from chatterbot.conversation import Statement
from chatterbot import languages
class MathematicalEvaluation(LogicAdapter):
"""
The MathematicalEvaluation logic adapter parses input to determine
whether the user is asking a question that requires math to be done.
If so, the equation is extracted from the input and returned with
the evaluated result.
For example:
User: 'What is three plus five?'
Bot: 'Three plus five equals eight'
:kwargs:
* *language* (``object``) --
The language is set to ``chatterbot.languages.ENG`` for English by default.
"""
def __init__(self, chatbot, **kwargs):
"""
Initialize the adapter with the chatbot and optional keyword arguments.
Default language is set to English (ENG), and a cache is used for optimization.
"""
super().__init__(chatbot, **kwargs)
# Set the language for processing (default is English)
self.language = kwargs.get('language', languages.ENG)
# Cache for storing previously processed results for quick lookup
self.cache = {}
def can_process(self, statement):
"""
Determines if the adapter can handle the given input.
- Calls `process()` to evaluate the statement.
- Stores the result in the cache for reuse.
- Returns True only if the confidence score is 1 (fully confident).
"""
response = self.process(statement) # Process the input statement
self.cache[statement.text] = response # Store the result in the cache
return response.confidence == 1 # Return True if the adapter is confident
def process(self, statement, additional_response_selection_parameters=None):
"""
Processes the input statement to:
- Extract a mathematical expression.
- Solve the expression and return the result.
- Handle errors if the expression cannot be evaluated.
"""
from mathparse import mathparse # Import mathparse for parsing and evaluating expressions
input_text = statement.text # Get the user input as text
# Check if the result for this input is already cached
if input_text in self.cache:
cached_result = self.cache[input_text]
self.cache = {} # Clear the cache for a fresh start
return cached_result
# Extract mathematical expression from the input text
expression = mathparse.extract_expression(input_text, language=self.language.ISO_639.upper())
# Create a response statement with the extracted expression
response = Statement(text=expression)
try:
# Evaluate the mathematical expression and format the response
response.text = '{} = {}'.format(
response.text, # Original expression
mathparse.parse(expression, language=self.language.ISO_639.upper()) # Computed result
)
# Set confidence to 1 (high) if evaluation is successful
response.confidence = 1
except mathparse.PostfixTokenEvaluationException:
# If evaluation fails, set confidence to 0 (low)
response.confidence = 0
return response # Return the response statement

We can see the code and conclude that the adapter enables AI functionality by employing dynamic parsing, decision-making, and contextual understanding. It uses the mathparse library to extract mathematical expressions from natural language input. This is a step beyond rule-based systems because the adapter doesn’t need explicit instructions for every scenario—it generalizes from patterns in the input.

One of the biggest challenges in traditional AI was understanding natural language. For instance, a chatbot needs to recognize that “What’s 5 over 2?” and “What is 5 divided by 2?” mean the same thing—something humans take for granted!