skip to Main Content

I’m trying to use a Python script that calls the OpenAI API to get a response from ChatGPT as it currently stands the Python script works and displays the conversation in the terminal but the assignment requires it to be displayed on my HTML webpage. Is there a way to send the output of the Python script to the HTML page while also sending inputs from the HTML page back to the Python script which then calls the API? This is what I got so far.

Python:

import openai

openai.api_key = "apikey"

def chat_with_gpt(prompt):
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
        )

    return response.choices[0].message.content.strip()

if __name__ == "__main__":
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["quit", "exit", "bye"]:
            break

        response = chat_with_gpt(user_input)
        print("Chatbot: ", response)

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Chatbot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #fff; /* Set the background color */
        }

        #chatbot-content {
            text-align: center;
            width: 300px;
        }

        #chat-area {
            width: 100%;
            height: 200px;
            padding: 10px;
            border: 1px solid #333;
            background-color: #f0f0f0;
            margin-bottom: 10px;
            overflow-y: scroll;
        }

        #user-input {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            margin-bottom: 10px;
        }

        #send-btn {
            padding: 10px 20px;
            background-color: #007bff; /* Bootstrap's Primary Color */
            color: #fff;
            text-decoration: none;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>

    <div id="chatbot-content">
        <h1>Text Chatbot</h1>

        <!-- Chat Area -->
        <div id="chat-area"></div>

        <!-- User Input -->
        <input type="text" id="user-input" placeholder="Type your message here">

        <!-- Send Button -->
        <button id="send-btn">Send</button>
    </div>

    <script>
        function displayMessage(message) {
            // Get the chat area
            const chatArea = document.getElementById("chat-area");

            // Create a new message element
            const messageElement = document.createElement("div");
            messageElement.textContent = message;

            // Append the message element to the chat area
            chatArea.appendChild(messageElement);

            // Scroll to the bottom of the chat area to show the latest message
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        function getBotReply(userInput) {
            // Convert user input to lowercase for case-insensitive matching
            const lowerCaseInput = userInput.toLowerCase();

            // Define responses based on keywords
            if (lowerCaseInput.includes("hi") || lowerCaseInput.includes("hello")) {
                return "Hello!";
            } else if (lowerCaseInput.includes("how are you")) {
                return "I'm doing well, thank you!";
            } else {
                return "I'm here to chat! Ask me anything.";
            }
        }

        document.getElementById("send-btn").addEventListener("click", function () {
            // Get the user's input
            const userInput = document.getElementById("user-input").value;

            // Display the user's message in the chat area
            displayMessage("You: " + userInput);

            // Get the bot's reply based on user input
            const botReply = getBotReply(userInput);
            displayMessage("Bot: " + botReply);

            // Clear the user input
            document.getElementById("user-input").value = "";
        });
    </script>

</body>
</html>

I’ve got the website up and running on a Google Cloud VM currently but outside of it displaying the HTML code it doesn’t seem to do anything with the Python script.

2

Answers


  1. To integrate your Python script with your HTML page, you can use a web framework called Flask. Flask will allow you to create a web server in Python that can handle requests from your HTML page.

    1. Install flask: pip install flask
    2. Modify your script to create a Flask application to handle requests from the HTML. Add this to your code under the def chat_with_gpt function (below return):
        @app.route('/chat', methods=['POST'])
        def chat():
            user_input = request.json['message']
            response = chat_with_gpt(user_input)
            return jsonify({"reply": response})
    
    1. Make these changes within the tag of your HTML file:

       
           async function getBotReply(userInput) {
               const response = await fetch('/chat', {
                   method: 'POST',
                   headers: {
                       'Content-Type': 'application/json'
                   },
                   body: JSON.stringify({ message: userInput })
               });
               const data = await response.json();
               return data.reply;
           }
      
           document.getElementById("send-btn").addEventListener("click", async function () {
               // Get the user's input
               const userInput = document.getElementById("user-input").value;
      
               // Display the user's message in the chat area
               displayMessage("You: " + userInput);
      
               // Get the bot's reply using the Flask server
               const botReply = await getBotReply(userInput);
               displayMessage("Bot: " + botReply);
      
               // Clear the user input field
               document.getElementById("user-input").value = "";
           });
      
           function displayMessage(message) {
               // Existing function to display messages
               ...
           }
       
       
    2. Run Your Flask App: It will start a local web server. You can then open your HTML file in a browser and it should be able to communicate with your Python backend.

    Login or Signup to reply.
  2. Maybe, I think python-to-json is also a good choice. You can use js or php to recall python code and get the current json response which is added by python code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search