-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
39 lines (31 loc) · 1.04 KB
/
app.py
File metadata and controls
39 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from flask import Flask, request, jsonify
from openai import OpenAI
import os
from dotenv import load_dotenv
from flask_cors import CORS
import traceback
# Load environment variables
load_dotenv()
app = Flask(__name__)
CORS(app) # Allows frontend to communicate with backend
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
@app.route("/generate-haiku", methods=["POST"])
def generate_haiku():
try:
# Get prompt from request
data = request.json
prompt = data.get("prompt", "Write a haiku about nature")
# Call OpenAI API
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
haiku = response.choices[0].message.content
return jsonify({"haiku": haiku})
except Exception as e:
print(f"ERROR: {e}")
print(traceback.format_exc())
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=8000)