Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -36,11 +36,11 @@ def save_user(data):
|
|
| 36 |
with open(USER_FILE, "w") as f:
|
| 37 |
json.dump(data, f)
|
| 38 |
|
| 39 |
-
#
|
| 40 |
def get_client():
|
| 41 |
api_key = os.getenv("OPENAI_API_KEY")
|
| 42 |
if not api_key or api_key.strip() == "":
|
| 43 |
-
raise ValueError("OpenAI API key missing. Please
|
| 44 |
return OpenAI(api_key=api_key)
|
| 45 |
|
| 46 |
# Helpline numbers
|
|
@@ -71,6 +71,8 @@ def chat():
|
|
| 71 |
try:
|
| 72 |
data = request.get_json()
|
| 73 |
message = data.get("message", "").strip()
|
|
|
|
|
|
|
| 74 |
mode = data.get("mode", "emotional_support")
|
| 75 |
user_ip = request.remote_addr
|
| 76 |
|
|
@@ -107,7 +109,7 @@ def chat():
|
|
| 107 |
)}
|
| 108 |
] + history
|
| 109 |
|
| 110 |
-
#
|
| 111 |
client = get_client()
|
| 112 |
response = client.chat.completions.create(
|
| 113 |
model="gpt-4o-mini",
|
|
@@ -121,10 +123,16 @@ def chat():
|
|
| 121 |
|
| 122 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
print(f"❌ Chat error: {e}")
|
| 126 |
return jsonify({
|
| 127 |
-
"reply": "Something went wrong.
|
| 128 |
"emotion": "neutral"
|
| 129 |
}), 500
|
| 130 |
|
|
|
|
| 36 |
with open(USER_FILE, "w") as f:
|
| 37 |
json.dump(data, f)
|
| 38 |
|
| 39 |
+
# Safe OpenAI client initialization
|
| 40 |
def get_client():
|
| 41 |
api_key = os.getenv("OPENAI_API_KEY")
|
| 42 |
if not api_key or api_key.strip() == "":
|
| 43 |
+
raise ValueError("OpenAI API key is missing or empty. Please set OPENAI_API_KEY in Hugging Face Secrets.")
|
| 44 |
return OpenAI(api_key=api_key)
|
| 45 |
|
| 46 |
# Helpline numbers
|
|
|
|
| 71 |
try:
|
| 72 |
data = request.get_json()
|
| 73 |
message = data.get("message", "").strip()
|
| 74 |
+
if not message:
|
| 75 |
+
return jsonify({"reply": "Please enter a message.", "emotion": "neutral"}), 400
|
| 76 |
mode = data.get("mode", "emotional_support")
|
| 77 |
user_ip = request.remote_addr
|
| 78 |
|
|
|
|
| 109 |
)}
|
| 110 |
] + history
|
| 111 |
|
| 112 |
+
# Create client and make API call
|
| 113 |
client = get_client()
|
| 114 |
response = client.chat.completions.create(
|
| 115 |
model="gpt-4o-mini",
|
|
|
|
| 123 |
|
| 124 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 125 |
|
| 126 |
+
except ValueError as e:
|
| 127 |
+
print(f"❌ API Key Error: {e}")
|
| 128 |
+
return jsonify({
|
| 129 |
+
"reply": "API key is missing or invalid. Please check your Hugging Face Secrets.",
|
| 130 |
+
"emotion": "neutral"
|
| 131 |
+
}), 500
|
| 132 |
except Exception as e:
|
| 133 |
print(f"❌ Chat error: {e}")
|
| 134 |
return jsonify({
|
| 135 |
+
"reply": "Something went wrong (e.g., API quota exceeded or network issue). Try again later.",
|
| 136 |
"emotion": "neutral"
|
| 137 |
}), 500
|
| 138 |
|