Build a Simple Q&A Website with OpenAI, HTML, and Python
To create a website that uses OpenAI to ask and answer questions, we'll need the following tools:
- HTML/CSS for the website layout and design
- Python for the backend code that interacts with OpenAI
- OpenAI API key for accessing the OpenAI GPT-3 language model
- Flask web framework for creating the web application
- Apache web server for hosting the website
File Structure:
- 'index.html' - Contains the website's HTML and CSS code.
- 'app.py' - Contains the backend Flask code.
- 'requirements.txt' - Lists all Python dependencies needed for our application.
Installation:
- Install Python and pip on your computer.
- Create a new directory for your project and navigate to it in the terminal.
- Install Flask and the OpenAI Python package using pip:
pip install Flask openai
- Create 'app.py' and paste the following code:
from flask import Flask, render_template, request
import openai
openai.api_key = 'YOUR_API_KEY'
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ask', methods=['POST'])
def ask():
question = request.form['question']
answer = openai.Completion.create(
engine='text-davinci-002',
prompt=f'Q: {question}
A:',
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
).choices[0].text.strip()
return render_template('index.html', question=question, answer=answer)
if __name__ == '__main__':
app.run()
- Create 'index.html' and paste the following code:
<!DOCTYPE html>
<html>
<head>
<title>OpenAI Q&A</title>
</head>
<body>
<h1>OpenAI Q&A</h1>
<form method='POST' action='/ask'>
<input type='text' name='question' placeholder='Ask your question...'>
<button type='submit'>Ask</button>
</form>
{% if question %}
<h2>Your question:</h2>
<p>{{ question }}</p>
<h2>Answer:</h2>
<p>{{ answer }}</p>
{% endif %}
</body>
</html>
- Save 'requirements.txt' with the following contents:
Flask==2.0.2
openai==0.10.0
- Run the following command in the terminal to start the Flask app:
export FLASK_APP=app.py
flask run
- Open your web browser and navigate to http://localhost:5000 to view the website. You should now be able to ask a question and get a response from OpenAI.
Note: Replace 'YOUR_API_KEY' with your actual OpenAI API key in 'app.py'. You can get an API key by signing up for OpenAI at https://beta.openai.com/signup/.
Congratulations, you have just created a simple Q&A website using OpenAI and Flask!
原文地址: https://www.cveoy.top/t/topic/lBPX 著作权归作者所有。请勿转载和采集!