Build a Question Answering Website with OpenAI API and Python
We will be using Python programming language and OpenAI API to create a website that can ask questions and provide answers. Here are the steps:
- Install OpenAI API: First, create an account on OpenAI website and obtain the API key. Then, install the OpenAI package using pip command:
pip install openai
- Create a Python file: Create a Python file named
app.pyand import the required libraries:
import openai
from flask import Flask, request, jsonify
- Create a web server: Create a web server using Flask:
app = Flask(__name__)
@app.route('/ask', methods=['POST'])
def ask():
# code to ask question and get answer
- Ask question and get answer: Use the OpenAI API to ask questions and get answers:
openai.api_key = 'YOUR_API_KEY'
def ask_question(question):
response = openai.Completion.create(
engine='davinci',
prompt=f'Q: {question}
A:',
temperature=0.5,
max_tokens=1024,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
return response.choices[0].text.strip()
- Process POST request: Process the POST request and return the answer:
@app.route('/ask', methods=['POST'])
def ask():
data = request.get_json()
question = data['question']
answer = ask_question(question)
response = {
'answer': answer
}
return jsonify(response)
- Create HTML file: Create an HTML file named
index.htmlthat contains the form to ask the question
<!DOCTYPE html>
<html>
<head>
<title>Ask Question</title>
</head>
<body>
<form>
<label for="question">Question:</label>
<input type="text" id="question" name="question"><br><br>
<input type="button" onclick="ask_question()" value="Ask">
</form>
<div id="answer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function ask_question() {
var question = $('#question').val();
$.ajax({
url: '/ask',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'question': question}),
success: function(data) {
$('#answer').html(data.answer);
}
});
}
</script>
</body>
</html>
- Run the web server: Run the web server using the following command:
python app.py
Now, open the website in the browser using the URL http://localhost5000/. Enter a question in the form and click on the "Ask" button. The answer will be displayed below the form.
原文地址: https://www.cveoy.top/t/topic/lBO1 著作权归作者所有。请勿转载和采集!