Using ChatGPT 4.0 to create a basic Python web application

In another blog post, I created a command-line based Python 3 chatbot. This screenshot is an example of how the chatbot looked like with the request-response design:

However, I wanted to create a web-based interface for this. I was relatively new to Python to I decided to leverage AI to fasttrack the development process.

So started first with Microsoft Copilot Pro (embedded into Microsoft Teams). Sadly, it was a no-go. Not only did it not allow me to upload my code as a file attachment, apparently pasting it exceeded the 2000 character limit.

I opted to use ChatGPT 4.0 instead.

My Prompts to ChatGPT

I submitted two prompts to ChatGPT, the first one included an attachment of my code in app.py:

Prompt #1

Background:

  • I will attach some code written in Python 3.
  • This code is a chatbot, so it accepts input from the user and returns a response.
  • The process repeats itself until the user types "exit".
  • This code runs on the command line.

(attach app.py file)

Prompt #2

Request:

  • I want to create a web-based version of this Python code.
  • So the result should be a single web page where a user can type in his text in an HTML input field, press SUBMIT and then a response is returned.
  • Previous responses should remain on the screen.
  • Provide all files required to make this work.
  • Provide instructions on how to deploy it so that it listens on an HTTP port.

The Result

I have to admit, given the 10 minutes it took get this working end-to-end, I was impressed. I had to open up Flask default port of 5000 from the cloud console as well as the internal Linux firewall, but I was good to go as you can see.

The Complete ChatGPT Response

To create a web-based version of the chatbot, we can use Flask, a lightweight web framework for Python. We will set up an HTML front end to interact with the user and a Flask back end to handle the API requests and responses.

Here are the files and instructions required to make this work:

1. app.py (Flask back end)

from flask import Flask, request, render_template, jsonify
import openai

app = Flask(__name__)
openai.api_key = '<your-openai-api-key-here>'

# Load the book data from the TXT file
with open("mydata.txt") as file:
    product_data = file.read()

# Initialize the context with interaction rules and product data
context = []

# Define the chatbot's interaction rules here
rules = """
Your name is Ahmed and you are an AI clone of the real Ahmed Aboulnaga. 
The way you look on video and the sound of your voice are both somewhat creepy and artificial. 
When responding, be more informal than formal. 
The data consists of two chapters from a book titled "DevSecOps on Oracle Cloud". 
You are the author of the chapters and your name is Ahmed. 
These chapters all revolve around the topic of Terraform and Oracle Cloud Infrastructure, also referred to as OCI. 
Each chapter is comprised of multiple sections. 
The book will be published sometime in 2024. 
When asked about the content of the data, mimic someone with a personality that is honest, but can be sarcastic at times. 
In the responses, keep the answers brief but engaging. 
"""

context.append({'role': 'system', 'content': f"""{rules} {product_data}"""})

def fetch_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature,
    )
    return response.choices[0].message["content"]

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/chat', methods=['POST'])
def chat():
    user_message = request.form['message']
    context.append({'role': 'user', 'content': user_message})
    response = fetch_messages(context, temperature=0.7)
    context.append({'role': 'assistant', 'content': response})
    return jsonify(response=response)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

2. templates/index.html (HTML front end)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatbot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
        }
        .container {
            width: 50%;
            margin: auto;
            margin-top: 50px;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .chat-box {
            border: 1px solid #ccc;
            padding: 10px;
            height: 300px;
            overflow-y: scroll;
            margin-bottom: 10px;
        }
        .message {
            margin: 10px 0;
        }
        .message.user {
            text-align: right;
        }
        .message.assistant {
            text-align: left;
        }
        form {
            display: flex;
        }
        input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }
        button {
            padding: 10px;
            border: none;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-box" id="chat-box"></div>
        <form id="chat-form">
            <input type="text" id="message" placeholder="Type a message" required>
            <button type="submit">Submit</button>
        </form>
    </div>
    <script>
        document.getElementById('chat-form').addEventListener('submit', async function(event) {
            event.preventDefault();
            const message = document.getElementById('message').value;
            document.getElementById('message').value = '';
            const chatBox = document.getElementById('chat-box');
            
            // Append user message to chat box
            const userMessageDiv = document.createElement('div');
            userMessageDiv.className = 'message user';
            userMessageDiv.textContent = message;
            chatBox.appendChild(userMessageDiv);
            
            // Scroll to bottom of chat box
            chatBox.scrollTop = chatBox.scrollHeight;

            const response = await fetch('/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ message })
            });
            const data = await response.json();
            
            // Append assistant message to chat box
            const assistantMessageDiv = document.createElement('div');
            assistantMessageDiv.className = 'message assistant';
            assistantMessageDiv.textContent = data.response;
            chatBox.appendChild(assistantMessageDiv);

            // Scroll to bottom of chat box
            chatBox.scrollTop = chatBox.scrollHeight;
        });
    </script>
</body>
</html>

3. mydata.txt

Ensure this file is in the same directory as app.py and contains your product data.

Deployment Instructions

  1. Access the Web Page:
    Open a web browser and navigate to http://localhost:5000. You should see the chat interface where you can interact with the chatbot.

Run the Flask Application:

python app.py

This will start the Flask server and listen on port 5000.

Install Dependencies:
Ensure you have Flask and OpenAI installed:

pip install flask openai

Summary

This setup involves:

  • A back-end app.py script using Flask to handle API calls and maintain the conversation context.
  • An index.html file that provides a user interface for interacting with the chatbot.
  • A mydata.txt file containing product data used by the chatbot.

The provided code will create a simple yet functional web-based chatbot. You can further customize the HTML/CSS and extend the Flask back end as needed.

Issues with the ChatGPT Response

The only problem with the response above is that the 3 instructions under the Deployment Instructions subsection were in reverse order.

Other than that, it worked like a charm.