AI was supposed to win people over by now — it hasn’t
Back to Tutorials
aiTutorialbeginner

AI was supposed to win people over by now — it hasn’t

August 19, 20266 views6 min read

Learn to build a simple AI chatbot using Python and Hugging Face Transformers, understanding both the technical implementation and consumer concerns around AI adoption.

Introduction

In today's digital world, AI is everywhere – from the recommendations on your streaming service to the chatbots helping you with customer support. However, as the news article from TechCrunch points out, many consumers are becoming more cautious about AI technology, even as it becomes harder to avoid. This tutorial will teach you how to build a simple AI-powered chatbot using Python and the Hugging Face Transformers library. This hands-on project will help you understand how AI works in practical applications while also exploring the ethical considerations that are making consumers wary.

Prerequisites

Before starting this tutorial, you'll need:

  • A computer with Python 3.7 or higher installed
  • Basic understanding of Python programming concepts
  • Internet connection for downloading packages
  • Optional: A text editor or IDE (like VS Code or PyCharm)

Step-by-step instructions

Step 1: Set up your Python environment

Why this step is important

Before we can start working with AI, we need to create a clean environment where our code will run without conflicts. This ensures that all the packages we install will work properly together.

  1. Open your terminal or command prompt
  2. Create a new directory for our project: mkdir ai_chatbot_tutorial
  3. Navigate to the directory: cd ai_chatbot_tutorial
  4. Create a virtual environment: python -m venv chatbot_env
  5. Activate the virtual environment:
    • On Windows: chatbot_env\Scripts\activate
    • On macOS/Linux: source chatbot_env/bin/activate

Step 2: Install required packages

Why this step is important

We need specific libraries to work with AI models. The Transformers library from Hugging Face provides easy access to state-of-the-art language models, while the Flask library will help us create a simple web interface to test our chatbot.

  1. Install the required packages using pip:
    pip install transformers torch flask
  2. Verify installation by checking if packages are properly installed:
    pip list

Step 3: Create the basic chatbot structure

Why this step is important

Now we'll build the core functionality of our chatbot. This involves loading a pre-trained language model that can understand and respond to text inputs. We'll start with a simple model to keep things beginner-friendly.

  1. Create a new Python file called chatbot.py
  2. Open the file and add the following code:
    from transformers import pipeline, Conversation
    
    # Load a pre-trained conversational model
    chatbot = pipeline("conversational", model="microsoft/DialoGPT-medium")
    
    def get_response(user_input):
        # Create a conversation object
        conversation = Conversation(user_input)
        
        # Generate a response
        chatbot(conversation)
        
        # Return the last response
        return conversation.generated_responses[-1]
    
    # Test the chatbot
    if __name__ == "__main__":
        print("Chatbot initialized! Type 'quit' to exit.")
        while True:
            user_input = input("You: ")
            if user_input.lower() == 'quit':
                break
            response = get_response(user_input)
            print(f"Bot: {response}")

Step 4: Run and test your chatbot

Why this step is important

Testing your chatbot helps you understand how it works and identify any issues. This is where you'll see firsthand how AI models process language and generate responses.

  1. Save your chatbot.py file
  2. Run the chatbot: python chatbot.py
  3. Try asking simple questions like "Hello" or "What is AI?"
  4. Notice how the bot responds based on its training data

Step 5: Add a web interface

Why this step is important

Most people interact with AI through web interfaces rather than command-line tools. Adding a web interface will help you understand how AI systems are deployed in real applications and how they might be perceived by users.

  1. Modify your chatbot.py file to include a Flask web interface:
    from flask import Flask, render_template, request, jsonify
    from transformers import pipeline, Conversation
    
    app = Flask(__name__)
    chatbot = pipeline("conversational", model="microsoft/DialoGPT-medium")
    
    @app.route('/')
    def home():
        return render_template('index.html')
    
    @app.route('/chat', methods=['POST'])
    def chat():
        user_input = request.json['message']
        conversation = Conversation(user_input)
        chatbot(conversation)
        response = conversation.generated_responses[-1]
        return jsonify({'response': response})
    
    if __name__ == "__main__":
        app.run(debug=True)
  2. Create a new folder called templates in your project directory
  3. Create an index.html file in the templates folder with:
    <!DOCTYPE html>
    <html>
    <head>
        <title>AI Chatbot</title>
    </head>
    <body>
        <h1>AI Chatbot</h1>
        <div id="chatbox"></div>
        <input type="text" id="userInput" placeholder="Type your message...">
        <button onclick="sendMessage()">Send</button>
        
        <script>
            function sendMessage() {
                const input = document.getElementById('userInput');
                const message = input.value;
                
                if (message) {
                    // Display user message
                    displayMessage('You: ' + message, 'user');
                    
                    // Send to backend
                    fetch('/chat', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({message: message})
                    })
                    .then(response => response.json())
                    .then(data => {
                        displayMessage('Bot: ' + data.response, 'bot');
                    });
                    
                    input.value = '';
                }
            }
            
            function displayMessage(message, sender) {
                const chatbox = document.getElementById('chatbox');
                const messageElement = document.createElement('div');
                messageElement.textContent = message;
                messageElement.className = sender;
                chatbox.appendChild(messageElement);
                chatbox.scrollTop = chatbox.scrollHeight;
            }
            
            // Allow Enter key to send message
            document.getElementById('userInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });
        </script>
    </body>
    </html>

Step 6: Run the web-based chatbot

Why this step is important

Running the web version gives you a better understanding of how AI systems are actually used by people in real-world applications. This is where the consumer concerns mentioned in the TechCrunch article start to become apparent – users interact with AI systems through interfaces they may not fully understand.

  1. Save all files and run: python chatbot.py
  2. Open your web browser and go to http://127.0.0.1:5000
  3. Test the chatbot through the web interface
  4. Notice how the conversation flows and how responses are generated

Step 7: Reflect on AI adoption concerns

Why this step is important

As you've built and tested your AI chatbot, consider the concerns mentioned in the TechCrunch article. What aspects of AI interaction make you feel wary? Understanding these concerns is crucial for developing AI systems that people trust and accept.

  1. Think about what makes AI systems like yours seem trustworthy or untrustworthy
  2. Consider how your chatbot might behave in real-world scenarios
  3. Reflect on the balance between AI capabilities and user concerns about privacy, transparency, and control

Summary

In this tutorial, you've learned how to build a simple AI chatbot using Python and the Hugging Face Transformers library. You've created both a command-line version and a web-based interface, giving you hands-on experience with how AI systems work. By understanding how AI models process language and generate responses, you can better appreciate why consumers might be wary of AI adoption. The journey from simple code to a functional chatbot mirrors the broader challenge that Silicon Valley faces – creating AI systems that are not only powerful but also accepted and trusted by users.

Remember that as AI becomes more integrated into our daily lives, the focus is shifting from just making technology work to making technology work well for people. Your understanding of both the technical and human aspects of AI is crucial for building systems that will be embraced rather than feared.

Related Articles