Build a Functional AI Chatbot with HTML, OpenAI, and Python
To create a functional program that connects HTML, OpenAI, and Python, follow the steps below:
-
Install Flask and OpenAI:
-
Flask: Flask is a micro web framework written in Python. It is used to create web applications quickly and easily. To install Flask, use the following command in your command prompt or terminal:
pip install Flask -
OpenAI: OpenAI is an artificial intelligence research laboratory consisting of the for-profit corporation OpenAI LP and its parent company, the non-profit OpenAI Inc. To install OpenAI, use the following command:
pip install openai
-
-
Create an HTML file:
-
Create a new file named 'index.html' in your preferred text editor.
-
Add the following code to create a textbox for prompt and a textbox for answer:
<form method='POST' action='/'> <label for='prompt'>Enter your prompt:</label> <input type='text' id='prompt' name='prompt'><br> <label for='answer'>Answer:</label> <input type='text' id='answer' name='answer'><br> <input type='submit' value='Submit'> </form>
-
-
Create a Python program:
-
Create a new file named 'main.py' in your preferred text editor.
-
Add the following code to import the necessary libraries and create a function to generate the response using OpenAI:
import openai import os from flask import Flask, request, render_template app = Flask(__name__) # Set up OpenAI API key openai.api_key = os.environ['OPENAI_API_KEY'] # Function to generate the response using OpenAI def generate_response(prompt): response = openai.Completion.create( engine='davinci', prompt=prompt, temperature=0.5, max_tokens=1024, n=1, stop=None, timeout=10, frequency_penalty=0, presence_penalty=0 ) return response.choices[0].text.strip() # Route for index page @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': prompt = request.form['prompt'] answer = generate_response(prompt) return render_template('index.html', prompt=prompt, answer=answer) else: return render_template('index.html')
-
-
Create a Flask application:
-
Create a new file named 'app.py' in your preferred text editor.
-
Add the following code to run the Flask application:
from main import app if __name__ == '__main__': app.run(debug=True)
-
-
Store all files:
- Create a directory named 'templates'.
- Store the 'index.html' file in the 'templates' directory.
- Store the 'main.py' and 'app.py' files in the same directory as the 'templates' directory.
-
Run the program:
-
Open your command prompt or terminal and navigate to the directory where the files are stored.
-
Run the following command to start the Flask application:
python app.py
-
-
Use the program:
- Open your web browser and go to http://localhost:5000/.
- Enter a prompt in the textbox provided and click the Submit button.
- The answer generated by OpenAI will be displayed in the answer textbox.
原文地址: https://www.cveoy.top/t/topic/lCAN 著作权归作者所有。请勿转载和采集!