以下是代码:
pip install flask openai
接下来,创建一个名为
app.py 的文件,并将以下代码复制粘贴到文件中:
from flask import Flask, render_template, request
import openai_secret_manager
import openai
import os
# Use dotenv to read the environment variables from the .env file
from dotenv import load_dotenv
load_dotenv()
# Initialize the Flask application
app = Flask(__name__)
# Configure the OpenAI API client
assert "OPENAI_API_KEY" in os.environ, "Environment variable 'OPENAI_API_KEY' not found."
secrets = openai_secret_manager.get_secret("openai")
openai.api_key = secrets["api_key"]
# Define a route for the root page of the website
@
app.route("/")
def home():
return render_template("index.html")
# Define a route for the API endpoint
@
app.route("/api/generate", methods=["POST"])
def generate_text():
# Get the input text from the POST request
input_text = request.form["input_text"]
# Call the OpenAI API to generate text
model_engine = "text-davinci-002"
prompt = input_text.strip()
response = openai.Completion.create(
engine=model_engine,
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
generated_text = response.choices[0].text.strip()
# Return the generated text as a JSON response
return {"generated_text": generated_text}
if __name__ == "__main__":
app.run(debug=True)
在您的项目中创建一个名为 templates 的目录,并在该目录中创建一个名为 index.html 的 HTML 文件,并将以下代码复制到该文件中:
<!DOCTYPE html>
<html>
<head>
<title>OpenAI API Demo</title>
</head>
<body>
<h1>OpenAI API Demo</h1>
<form id="generate-form">
<label for="input-text">Input Text:</label><br>
<textarea id="input-text" name="input_text" rows="5" cols="50"></textarea><br>
<button type="submit">Generate Text</button>
</form>
<div id="generated-text"></div>
<script src="
https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Listen for form submit event
$("#generate-form").submit(function(event) {
event.preventDefault();
// Get input text from form
var inputText = $("#input-text").val();
// Send input text to server via AJAX POST request
$.post("/api/generate", { input_text: inputText }, function(data) {
// Update the generated text in the HTML
$("#generated-text").text(data.generated_text);
});
});
</script>
</body>
</html>
在命令行中运行以下命令以启动应用程序:
export FLASK_APP=
app.pyflask run