Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,35 +1,36 @@
|
|
| 1 |
-
import
|
| 2 |
import openai
|
|
|
|
| 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 |
-
|
|
|
|
| 1 |
+
import os
|
| 2 |
import openai
|
| 3 |
+
from flask import Flask, request, jsonify
|
| 4 |
|
| 5 |
+
app = Flask(__name__)
|
| 6 |
+
|
| 7 |
+
# β
Get the API key from environment variables
|
| 8 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
|
| 10 |
+
if not openai.api_key:
|
| 11 |
+
raise ValueError("β OPENAI_API_KEY is not set. Go to Hugging Face > Settings > Variables and Secrets and add it there.")
|
| 12 |
+
|
| 13 |
+
@app.route("/chat", methods=["POST"])
|
| 14 |
+
def chat():
|
| 15 |
+
try:
|
| 16 |
+
data = request.json
|
| 17 |
+
user_message = data.get("message", "")
|
| 18 |
+
|
| 19 |
+
if not user_message:
|
| 20 |
+
return jsonify({"error": "Message is required"}), 400
|
| 21 |
+
|
| 22 |
+
# Example: call the ChatGPT model
|
| 23 |
+
response = openai.ChatCompletion.create(
|
| 24 |
+
model="gpt-3.5-turbo", # or gpt-4 if available
|
| 25 |
+
messages=[{"role": "user", "content": user_message}],
|
| 26 |
+
temperature=0.7
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
reply = response.choices[0].message["content"]
|
| 30 |
+
return jsonify({"reply": reply})
|
| 31 |
+
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return jsonify({"error": str(e)}), 500
|
| 34 |
+
|
| 35 |
+
if __name__ == "__main__":
|
| 36 |
+
app.run(host="0.0.0.0", port=7860)
|