Build a Simple OpenAI Chatbot with HTML, Flask, and Python

This guide provides a step-by-step tutorial on creating a basic chatbot using HTML for the user interface, Flask for web framework, and Python to interact with the OpenAI API. The project will involve three files:

  • index.html: Handles the user interface with input and output fields.
  • main.py: Contains the Python code to connect to the OpenAI API and generate responses.
  • app.py: Runs the Flask application that serves the HTML file and handles communication between the user interface and the Python code.

1. Project Setup and Files

  1. Create a new directory: This directory will hold all project files.
  2. Create three files: index.html, main.py, and app.py in the directory.

2. HTML File: index.html

<!DOCTYPE html>
<html>
<head>
    <title>OpenAI Chatbot</title>
</head>
<body>
    <h1>OpenAI Chatbot</h1>
    <label for='prompt'>Prompt:</label>
    <input type='text' id='prompt' name='prompt'><br><br>
    <label for='response'>Response:</label>
    <input type='text' id='response' name='response' readonly>
    <button onclick='getResponse()'>Get Response</button>
    <script>
        function getResponse() {
            var prompt = document.getElementById('prompt').value;
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/get-response?prompt=' + prompt, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById('response').value = xhr.responseText;
                }
            };
            xhr.send();
        }
    </script>
</body>
</html>

Explanation:

  • The HTML code creates a simple web page with:
    • A heading: <h1>OpenAI Chatbot</h1>
    • Two textboxes:
      • prompt: For the user to enter their question or prompt.
      • response: To display the AI's response. (Set readonly to prevent direct user input).
    • A button: Get Response that triggers the getResponse() function when clicked.
  • The getResponse() JavaScript function does the following:
    • Gets the prompt value from the prompt textbox.
    • Sends a GET request to the /get-response endpoint of the Flask application (which will be handled by the main.py file).
    • Updates the response textbox with the received response from the Flask application.

3. Python Program: main.py

import openai
from flask import Flask, request

app = Flask(__name__)

# Replace 'YOUR_API_KEY' with your actual OpenAI API key
openai.api_key = 'YOUR_API_KEY'

def generate_response(prompt):
    response = openai.Completion.create(
        engine='davinci',
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.5
    )
    return response.choices[0].text.strip()

@app.route('/get-response')
def get_response():
    prompt = request.args.get('prompt')
    response = generate_response(prompt)
    return response

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

Explanation:

  • Import necessary libraries: openai for interacting with the OpenAI API and Flask for the web framework.
  • Initialize Flask app: app = Flask(__name__)
  • Set OpenAI API Key: Replace 'YOUR_API_KEY' with your actual OpenAI API key.
  • generate_response(prompt) function:
    • Takes the user's prompt as input.
    • Sends a request to the OpenAI API (using the davinci engine by default) to generate a response.
    • Returns the generated response text after stripping any extra whitespace.
  • @app.route('/get-response'): This decorator defines the /get-response endpoint for the Flask application.
    • get_response() function:
      • Retrieves the prompt value from the request using request.args.get('prompt').
      • Calls generate_response() to get the AI's response to the prompt.
      • Returns the generated response to the HTML file (which is handled by the JavaScript code).
  • if __name__ == '__main__':: This runs the Flask application when the main.py file is executed directly.

4. Flask Application: app.py

from flask import Flask, render_template

app = Flask(__name__)

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

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

Explanation:

  • Import necessary libraries: Flask and render_template for serving the HTML file.
  • Initialize Flask app: app = Flask(__name__)
  • @app.route('/'): This decorator defines the root URL / for the Flask application.
    • index() function: Renders the index.html file and returns it to the user.
  • if __name__ == '__main__':: This runs the Flask application when the app.py file is executed directly.

5. Installation and Running

  1. Install Flask:

    pip install flask
    
  2. Install OpenAI:

    pip install openai
    
  3. Get Your OpenAI API Key: Sign up for an OpenAI account at https://beta.openai.com/ and find your API key in the API Keys section of your account settings.

  4. Run the App:

    • Open a terminal or command prompt and navigate to the directory where your files are stored.

    • Run the following command:

      python app.py
      
  5. Open the Chatbot:

    • Your chatbot will be accessible at http://localhost:5000/ in your web browser.
  6. Interact:

    • Enter a prompt in the Prompt textbox.
    • Click the Get Response button.
    • The AI's response will appear in the Response textbox.

Conclusion

You've now built a functional OpenAI chatbot! You can experiment with different prompts and see how the chatbot responds. Feel free to customize the code and user interface further. Happy chatting!

Build a Simple OpenAI Chatbot with HTML, Flask, and Python

原文地址: https://www.cveoy.top/t/topic/lCAY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录