Building a Simple Chatbot with Flask

Introduction

Chatbots are everywhere these days! From customer service assistants to fun conversational tools, they’ve become an integral part of our digital lives. Ever wondered how to build one yourself? In this guide, we’ll walk through creating a very simple web-based chatbot using Flask, a lightweight Python web framework. It’s a perfect starting point for beginners to understand the basics of web development and simple conversational AI.

What is a Chatbot?
A chatbot is a computer program designed to simulate human conversation through text or voice interactions. It allows users to communicate with digital devices as if they were talking to a real person. Our chatbot will interact using text.

Why Flask?
Flask is a “micro” web framework for Python. This means it’s minimalistic and doesn’t come with many built-in tools or libraries. While this might sound like a limitation, it actually makes Flask incredibly flexible and easy to get started with, especially for smaller projects like our simple chatbot. It allows you to build web applications with minimal code.

By the end of this tutorial, you’ll have a basic chatbot running in your web browser that can respond to a few pre-defined questions.

What You’ll Need

Before we start coding, make sure you have the following installed on your computer:

  • Python 3: This is the programming language we’ll use. You can download it from the official Python website (python.org).
    • Simple Explanation: Python is a popular, easy-to-read programming language that’s great for beginners and powerful enough for complex applications.
  • pip: This is Python’s package installer. It usually comes bundled with Python installations. We’ll use it to install Flask.
    • Simple Explanation: Think of pip as an “app store” for Python. It lets you download and install additional tools and libraries that other people have created.
  • A Text Editor or IDE: Something like Visual Studio Code, Sublime Text, or Atom will be perfect for writing your code.
  • A Web Browser: To view and interact with your chatbot!

Setting Up Your Project

Let’s get our workspace ready.

1. Create a Project Folder

First, create a new folder on your computer where all your chatbot’s files will live. You can name it something like my_chatbot.

mkdir my_chatbot
cd my_chatbot

2. Set Up a Virtual Environment

It’s good practice to use a virtual environment for every Python project. This creates an isolated space for your project’s Python packages, preventing conflicts with other projects or your system’s global Python installation.

  • Simple Explanation: Imagine you have different toy sets, and each set needs specific batteries. A virtual environment is like having separate battery boxes for each toy set, so their batteries don’t get mixed up. This keeps your projects tidy and prevents version conflicts.

To create and activate a virtual environment:

On macOS/Linux:

python3 -m venv venv
source venv/bin/activate

On Windows:

python -m venv venv
.\venv\Scripts\activate

You’ll know it’s activated when you see (venv) at the beginning of your terminal prompt.

3. Install Flask

Now that your virtual environment is active, let’s install Flask.

pip install Flask

The Core Flask Application (app.py)

Every Flask application starts with a main Python file, usually named app.py or main.py. This file will contain all the logic for our web server.

1. Your First Flask App (Optional but Recommended)

Let’s create a super basic Flask app to ensure everything is set up correctly. Create a file named app.py inside your my_chatbot folder and add the following code:

from flask import Flask

app = Flask(__name__) # Creates a Flask application instance

@app.route('/') # Defines the route for the homepage (the root URL, e.g., /)
def hello_world():
    return 'Hello, Chatbot!'

if __name__ == '__main__':
    # Runs the Flask development server. debug=True allows for automatic reloading on code changes.
    app.run(debug=True)

Run this app:

Make sure your virtual environment is still active, then run:

python app.py

Open your web browser and go to http://127.0.0.1:5000/. You should see “Hello, Chatbot!”. This confirms Flask is working! Press Ctrl+C (or Cmd+C) in your terminal to stop the server.

Designing Our Chatbot Interaction

Our chatbot will work like this:

  1. The user visits the web page and sees a chat interface with an input box.
  2. The user types a message and clicks a “Send” button.
  3. The web application (our Flask app) receives the message.
  4. Based on the message, our simple chatbot logic generates a response.
  5. The response, along with the user’s message, is displayed on the web page.

Building the Chatbot Logic

Now, let’s modify our app.py to include the chatbot’s brain and handle user interactions.

1. app.py – The Brains of Our Chatbot

We’ll need to import a few more things from Flask:
* request: To handle incoming user data (like messages from a form).
* Simple Explanation: When you submit a form on a website, request helps our Flask app grab the information you sent.
* render_template: To display our HTML web pages.
* Simple Explanation: This function tells Flask to take an HTML file and send it to the user’s browser, possibly filling it with dynamic data from our Python code.

Our app.py will have two main parts:
* One route (/) to display the initial chat interface.
* Another route (/chat) to process user input and generate a response.

First, let’s define a simple function that will act as our chatbot’s brain. It takes a user message and returns a predefined response.

from flask import Flask, request, render_template

app = Flask(__name__)

def get_chatbot_response(user_message):
    user_message = user_message.lower() # Convert to lowercase for easier matching

    if "hello" in user_message or "hi" in user_message:
        return "Hello there! How can I help you today?"
    elif "how are you" in user_message:
        return "I'm a computer program, so I don't have feelings, but thanks for asking!"
    elif "name" in user_message:
        return "I don't have a name, I'm just a simple chatbot."
    elif "bye" in user_message or "goodbye" in user_message:
        return "Goodbye! Have a great day!"
    else:
        return "I'm sorry, I don't understand that. Can you rephrase?"

chat_history = []

@app.route('/')
def index():
    # This route handles GET requests to the root URL (when you first visit the page)
    # Renders the index.html template and passes the current chat history to it
    return render_template('index.html', chat_history=chat_history)

@app.route('/chat', methods=['POST'])
def chat():
    # This route handles POST requests (when the user submits a message)
    user_message = request.form['user_message'] # Get the message from the form input named 'user_message'
    bot_response = get_chatbot_response(user_message)

    # Add both the user's message and the bot's response to our chat history
    chat_history.append({'sender': 'user', 'message': user_message})
    chat_history.append({'sender': 'bot', 'message': bot_response})

    # Render the index page again, now with the updated chat history
    return render_template('index.html', chat_history=chat_history)

if __name__ == '__main__':
    app.run(debug=True)

Explanation of new concepts:

  • @app.route('/', methods=['POST']): This is a decorator that associates a URL path (/ or /chat in our case) with the Python function directly below it. The methods=['POST'] part specifies that this route should only respond to HTTP POST requests.
    • Simple Explanation: Think of routes as specific addresses on your website. When you type http://127.0.0.1:5000/ into your browser, it’s a GET request. When you click a “Submit” button on a form, it often sends a POST request.
  • request.form['user_message']: When a user submits a form, the data is sent to the server. request.form is a dictionary-like object that holds this data. We access the value of the input field that had the name="user_message" attribute.

Creating the Web Interface (templates/index.html)

Flask needs to know how to display the chat interface. For this, we use HTML templates. Create a new folder named templates inside your my_chatbot folder. Inside templates, create a file called index.html.

Your project structure should now look like this:

my_chatbot/
├── venv/
├── app.py
└── templates/
    └── index.html

Now, paste the following HTML code into templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Flask Chatbot</title>
    <style>
        /* Basic CSS to make our chatbot look a bit nicer */
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; }
        .chat-container { max-width: 600px; margin: 0 auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .message { margin-bottom: 10px; padding: 8px 12px; border-radius: 5px; }
        .user-message { background-color: #e0f7fa; text-align: right; } /* Light blue for user */
        .bot-message { background-color: #e8f5e9; text-align: left; }  /* Light green for bot */
        .chat-input { display: flex; margin-top: 20px; }
        .chat-input input[type="text"] { flex-grow: 1; padding: 10px; border: 1px solid #ddd; border-radius: 5px 0 0 5px; }
        .chat-input button { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 0 5px 5px 0; cursor: pointer; }
        .chat-input button:hover { background-color: #0056b3; }
        #chat-box { max-height: 400px; overflow-y: auto; border: 1px solid #eee; padding: 10px; border-radius: 5px; background-color: #fcfcfc; }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>My Simple Chatbot</h1>
        <div id="chat-box">
            <!-- This is where our chat messages will appear -->
            {% for message in chat_history %}
                {% if message.sender == 'user' %}
                    <div class="message user-message">You: {{ message.message }}</div>
                {% else %}
                    <div class="message bot-message">Chatbot: {{ message.message }}</div>
                {% endif %}
            {% endfor %}
        </div>
        <!-- This is the form for sending new messages -->
        <form action="/chat" method="post" class="chat-input">
            <input type="text" name="user_message" placeholder="Type your message..." required>
            <button type="submit">Send</button>
        </form>
    </div>
</body>
</html>

Explanation of HTML and Jinja2:

  • <!DOCTYPE html> to </html>: This is standard HTML structure for any web page.
  • <style> tags: Contains basic CSS (Cascading Style Sheets) to make our chatbot look a little nicer.
    • Simple Explanation: CSS is like the interior designer for your webpage. It tells the browser how elements should look (colors, colors, fonts, layout, etc.).
  • <form action="/chat" method="post">: This is our input form. When you click “Send”, the text in the input box will be sent to the /chat route in our app.py using a POST request. The name="user_message" attribute is crucial because that’s how Flask identifies the data (request.form['user_message']).
  • {% for message in chat_history %}: This is a Jinja2 template tag. Jinja2 is the templating engine Flask uses. It allows us to embed Python-like logic directly into our HTML. Here, it loops through the chat_history list that we passed from app.py.
  • {% if message.sender == 'user' %} and {% else %}: These are also Jinja2 tags for conditional logic. They check who sent the message (user or bot) to display it differently (e.g., with different background colors).
  • {{ message.message }}: This is a Jinja2 expression. It prints the actual content of the message from the message object in our loop.

Running Your Chatbot

You’re all set! Make sure your virtual environment is active in your terminal, then run your Flask application:

python app.py

Open your web browser and navigate to http://127.0.0.1:5000/.

You should now see your simple chatbot interface! Try typing “hello”, “how are you”, or “what is your name” to see its responses.

Next Steps for Your Chatbot

This is just the beginning! Here are some ideas to make your chatbot more advanced:

  • More Complex Logic: Instead of simple if/else statements, you could use a dictionary of keywords and responses, or even regular expressions for pattern matching.
  • Natural Language Processing (NLP): Integrate libraries like NLTK or spaCy to understand user intent, extract entities (like names or dates), and generate more contextually relevant responses.
  • Persistent Chat History: Currently, the chat history resets every time you refresh the page or restart the server. You could store it in a file, a simple database (like SQLite), or browser session storage.
  • Better User Interface: Enhance the front-end with more advanced CSS, JavaScript for dynamic updates (without full page reloads), or a dedicated front-end framework like React or Vue.js.
  • External APIs: Connect your chatbot to external services, like a weather API, a news API, or even a generative AI model (like OpenAI’s GPT).
  • Deployment: Learn how to deploy your Flask app to a cloud platform like Heroku, Vercel, or AWS so others can access it.

Conclusion

Congratulations! You’ve successfully built a basic web-based chatbot using Flask, Python, and HTML. You’ve learned about setting up a Flask project, handling web requests, using HTML templates, and implementing simple conversational logic. This project lays a strong foundation for exploring more complex web development and AI concepts. Keep experimenting and happy coding!

Comments

Leave a Reply