ngwakomadikwe commited on
Commit
64b4650
Β·
verified Β·
1 Parent(s): 88e0b7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -33
app.py CHANGED
@@ -1,35 +1,36 @@
1
- import gradio as gr
2
  import openai
 
3
 
4
- # Paste your OpenAI key here
5
- openai.api_key = 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
6
-
7
-
8
- def chat_with_ai(message, history):
9
- history = history or []
10
- conversation = [{"role": "system", "content": "You are a friendly, helpful student buddy and tutor. Keep explanations clear and engaging, as if you are a supportive classmate."}]
11
-
12
- for user, bot in history:
13
- conversation.append({"role": "user", "content": user})
14
- conversation.append({"role": "assistant", "content": bot})
15
- conversation.append({"role": "user", "content": message})
16
-
17
- response = openai.ChatCompletion.create(
18
- model="gpt-4o-mini", # Fast & affordable
19
- messages=conversation
20
- )
21
-
22
- bot_reply = response["choices"][0]["message"]["content"]
23
- history.append((message, bot_reply))
24
- return history, history
25
-
26
- with gr.Blocks() as demo:
27
- gr.Markdown("# πŸŽ“ SmartMate AI\nAsk me anything about your courses!")
28
- chatbot = gr.Chatbot()
29
- state = gr.State()
30
- with gr.Row():
31
- msg = gr.Textbox(placeholder="Type your question here...")
32
- submit = gr.Button("Send")
33
- submit.click(chat_with_ai, inputs=[msg, state], outputs=[chatbot, state])
34
-
35
- demo.launch()
 
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)