Building a Simple OpenAI Chatbot with Flask and HTML

This tutorial will guide you through creating a basic OpenAI chatbot using Flask for backend logic and HTML for the user interface. You'll learn how to integrate OpenAI's API, structure your project files, and deploy your chatbot for interactive conversations.

Project Structure and Files

  1. index.html: Contains the HTML code for the user interface.
  2. main.py: Handles the core logic for interacting with the OpenAI API.
  3. app.py: Runs the Flask application and sets up the route for handling requests from the HTML file.

1. 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'><br><br>
	<label for='answer'>Answer:</label>
	<input type='text' id='answer'><br><br>
	<button onclick='getResponse()'>Get Response</button>
	<script>
		function getResponse() {
			let prompt = document.getElementById('prompt').value;
			fetch('/get_response', {
			  method: 'POST',
			  headers: {
			    'Content-Type': 'application/json'
			  },
			  body: JSON.stringify({prompt: prompt})
			})
			.then(response => response.json())
			.then(data => {
				document.getElementById('answer').value = data.response;
			});
		}
	</script>
</body>
</html>

2. Python Program: main.py

import openai
import os

openai.api_key = 'YOUR_API_KEY'

def get_response(prompt):
    completions = openai.Completion.create(
        engine='davinci',
        prompt=prompt,
        max_tokens=60,
        n=1,
        stop=None,
        temperature=0.5,
    )

    message = completions.choices[0].text
    return message.strip()

if __name__ == '__main__':
    from flask import Flask, request, jsonify

    app = Flask(__name__)

    @app.route('/get_response', methods=['POST'])
    def get_response_route():
        data = request.get_json()
        prompt = data['prompt']
        response = get_response(prompt)
        return jsonify({'response': response})

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

3. Flask Application: app.py

from main import app

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

Instructions for Installing Flask and OpenAI

  1. Install Flask:

    • Open a command prompt/terminal window.
    • Run the command pip install flask
  2. Install OpenAI:

    • Open a command prompt/terminal window.
    • Run the command pip install openai
  3. Store the Files:

    • Store index.html and app.py in the same directory/folder.
    • Store main.py in the same directory as the other files.
  4. Start the Flask Application:

    • Open the command prompt/terminal window and navigate to the directory/folder where the files are stored.
    • Run the command python app.py to start the Flask application.
  5. Access the Chatbot:

    • Open a web browser and navigate to http://localhost:5000 to access the HTML file and use the OpenAI chatbot.

Explanation

  • index.html:

    • The HTML code provides the basic structure and elements for the user interface: a textbox for entering prompts, a textbox to display the response, and a button to trigger the interaction.
    • The getResponse() function sends a POST request to the /get_response route in the Flask application, passing the user's prompt as a JSON payload.
    • The script fetches the response from the Flask application, parses it as JSON, and updates the answer textbox with the chatbot's response.
  • main.py:

    • This Python program contains the core logic for interacting with the OpenAI API.
    • The get_response() function takes a user prompt as input and sends it to the OpenAI API using the openai.Completion.create() method.
    • The function returns the generated response from the OpenAI model.
  • app.py:

    • This file runs the Flask application, which acts as the server for the chatbot.
    • The get_response_route() function handles POST requests to the /get_response route, retrieves the prompt from the request, calls the get_response() function, and returns the response as JSON to the HTML file.

Remember to replace 'YOUR_API_KEY' in main.py with your actual OpenAI API key. Now you have a working OpenAI chatbot powered by Flask and HTML! You can further customize the interface and functionality as needed.

Build a Simple OpenAI Chatbot with Flask and HTML

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

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