Create a Simple ChatGPT-4 Chatbot

Building your own chatbot using OpenAI's powerful GPT-4 is now easier than ever. In this guide, we will demonstrate how you can create a simple chatbot using Python for the backend (Flask) and a basic HTML interface for the frontend. By the end of this tutorial, you will have a functional chatbot capable of answering a wide range of questions.

Step 1: Set Up the Backend with Python and Flask

First, we need to set up the backend using Python's Flask framework to handle HTTP requests and communicate with the OpenAI GPT-4 API. Here is the code to set up your Flask server:

from flask import Flask, request, jsonify
import openai

app = Flask(__name__)

# Set up your OpenAI API key
openai.api_key = 'your-api-key-here'

@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    prompt = data.get('prompt')

    response = openai.Completion.create(
        engine="gpt-4",
        prompt=prompt,
        max_tokens=150,
        n=1,
        stop=None,
        temperature=0.7
    )
    return jsonify({'response': response.choices[0].text.strip()})

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

In the Python code above, we create a Flask application that listens for POST requests at the /chat endpoint. The request contains a prompt (user input), which is sent to OpenAI’s GPT-4 API. The response is then returned as a JSON object.

Step 2: Setting Up the Frontend (HTML)

Next, we will build the frontend using basic HTML, which will allow users to interact with the chatbot. This HTML page will send user inputs (prompts) to the backend, and then display the chatbot's response on the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple ChatGPT-4 Chatbot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            background-color: #f4f4f9;
            color: #333;
        }
        h1 {
            text-align: center;
            color: #4CAF50;
            margin-top: 20px;
        }
        .chat-container {
            width: 400px;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin: 20px auto;
        }
        .chat-container textarea {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .chat-container button {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .chat-container button:hover {
            background-color: #45a049;
        }
        .response {
            margin-top: 20px;
            padding: 10px;
            background-color: #f4f4f9;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>ChatGPT-4 Chatbot</h1>
        <textarea id="prompt" rows="4" placeholder="Ask me anything..."></textarea>
        <button onclick="sendPrompt()">Send</button>
        <div id="response" class="response"></div>
    </div>

    <script>
        async function sendPrompt() {
            const prompt = document.getElementById('prompt').value;
            const responseElement = document.getElementById('response');

            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ prompt })
            });

            const data = await response.json();
            responseElement.textContent = data.response;
        }
    </script>
</body>
</html>

This HTML file contains a text area for user input and a button to submit the prompt. Once the user clicks "Send," the input is sent to the Flask backend, which processes the request and sends back a response from GPT-4. The chatbot's response is then displayed below the input field.

Step 3: Running Your Chatbot

To run your chatbot, follow these steps:

Once everything is set up, you will be able to chat with the GPT-4 model directly from your browser!

Conclusion

You've just created a simple chatbot using GPT-4, Flask, and basic HTML. You can expand this chatbot further by adding more features, such as chat history, user authentication, or integrating it into a more sophisticated web app. The possibilities are endless when it comes to enhancing the chatbot's functionality.