ngwakomadikwe commited on
Commit
9c74f73
·
verified ·
1 Parent(s): 2b7e761

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -11
app.py CHANGED
@@ -1,36 +1,53 @@
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)
 
1
  import os
2
+ from openai import OpenAI
3
+ from flask import Flask, request, jsonify, render_template
4
 
5
  app = Flask(__name__)
6
 
7
  # ✅ Get the API key from environment variables
8
+ api_key = os.getenv("OPENAI_API_KEY")
9
 
10
+ if not api_key:
11
+ print("WARNING: OPENAI_API_KEY is not set. Chat functionality will not work.")
12
+ client = None
13
+ else:
14
+ client = OpenAI(api_key=api_key)
15
+
16
+ @app.route("/")
17
+ def home():
18
+ """Serve the chat web interface"""
19
+ return render_template('index.html')
20
 
21
  @app.route("/chat", methods=["POST"])
22
  def chat():
23
  try:
24
+ if not client:
25
+ return jsonify({"error": "OpenAI API key not configured"}), 500
26
+
27
  data = request.json
28
  user_message = data.get("message", "")
29
 
30
  if not user_message:
31
  return jsonify({"error": "Message is required"}), 400
32
 
33
+ # Use the new OpenAI client
34
+ response = client.chat.completions.create(
35
+ model="gpt-3.5-turbo",
36
  messages=[{"role": "user", "content": user_message}],
37
+ temperature=0.7,
38
+ max_tokens=1000
39
  )
40
 
41
+ reply = response.choices[0].message.content
42
  return jsonify({"reply": reply})
43
 
44
  except Exception as e:
45
  return jsonify({"error": str(e)}), 500
46
 
47
+ @app.route("/health")
48
+ def health():
49
+ """Health check endpoint"""
50
+ return jsonify({"status": "healthy", "service": "SmartMate"})
51
+
52
  if __name__ == "__main__":
53
+ app.run(host="0.0.0.0", port=7860)