EduTechTeam commited on
Commit
ded59e5
·
verified ·
1 Parent(s): c847717

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -45
app.py CHANGED
@@ -1,60 +1,43 @@
1
  import openai
2
  import gradio as gr
3
  import os
4
- from dotenv import load_dotenv
 
5
 
6
- # 載入環境變數
7
- load_dotenv()
8
- openai.api_key = os.getenv("OPENAI_API_KEY")
9
- if openai.api_key is None:
10
- raise ValueError("請設定環境變數 OPENAI_API_KEY,確保 API Key 可用")
11
 
12
- # 聊天機器人主邏輯
13
  def boyfriend_chatbot(user_input, history):
14
  history = history or []
15
- log_messages = []
16
-
17
- # 確保 history 是 list of 2-tuples
18
- if not all(isinstance(pair, (list, tuple)) and len(pair) == 2 for pair in history):
19
- log = "[❌ Error] 歷史紀錄格式錯誤,已重置"
20
- history = []
21
- else:
22
- log = "[✅ 收到訊息]"
23
-
24
  messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
25
-
26
  for user_msg, bot_msg in history:
27
  messages.append({"role": "user", "content": user_msg})
28
  messages.append({"role": "assistant", "content": bot_msg})
29
-
30
- messages.append({"role": "user", "content": user_input})
31
 
 
 
32
  try:
33
- response = openai.ChatCompletion.create(
34
- model="gpt-4o",
35
- messages=messages
 
36
  )
37
- reply = response.choices[0].message.content
38
- history.append((user_input, reply))
39
- log += f"\n[✅ Success] 回應完成,共 {len(messages)} 則訊息。"
40
  except Exception as e:
41
- reply = "抱歉,發生錯誤,我先抱抱你 😢"
42
- log += f"\n[❌ API Error] {str(e)}"
43
-
44
- return reply, history, log
45
-
46
- # Gradio UI
47
- with gr.Blocks(title="貼心男友聊天機器人") as demo:
48
- gr.Markdown("# 💕 貼心男友聊天機器人 💕")
49
- chatbot = gr.Chatbot()
50
- msg = gr.Textbox(label="輸入你的訊息", placeholder="說點什麼吧...")
51
- log_output = gr.Textbox(label="狀態日誌", interactive=False)
52
- clear = gr.Button("🧹 清除對話")
53
-
54
- def respond(user_input, chat_history):
55
- return boyfriend_chatbot(user_input, chat_history)
56
-
57
- msg.submit(respond, inputs=[msg, chatbot], outputs=[chatbot, chatbot, log_output])
58
- clear.click(lambda: ([], "", ""), outputs=[chatbot, msg, log_output])
59
-
60
- demo.launch(share=True)
 
1
  import openai
2
  import gradio as gr
3
  import os
4
+ import time
5
+ from google.colab import userdata
6
 
7
+ client = openai.OpenAI(api_key=userdata.get('OPENAI_API_KEY'))
 
 
 
 
8
 
9
+ # 建立「男友」聊天機器人函數
10
  def boyfriend_chatbot(user_input, history):
11
  history = history or []
 
 
 
 
 
 
 
 
 
12
  messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
13
+
14
  for user_msg, bot_msg in history:
15
  messages.append({"role": "user", "content": user_msg})
16
  messages.append({"role": "assistant", "content": bot_msg})
 
 
17
 
18
+ messages.append({"role": "user", "content": user_input})
19
+
20
  try:
21
+ completion = client.chat.completions.create(
22
+ model="gpt-4o-mini",
23
+ messages=messages,
24
+ temperature=0.7
25
  )
26
+ response = completion.choices[0].message.content
 
 
27
  except Exception as e:
28
+ response = f" 發生錯誤:{str(e)}"
29
+
30
+ for i in range(len(response)):
31
+ yield response[: i + 1]
32
+ time.sleep(0.05)
33
+
34
+ # 建立 Gradio 介面
35
+ chat_interface = gr.ChatInterface(
36
+ boyfriend_chatbot,
37
+ chatbot=gr.Chatbot(type="messages"),
38
+ type="messages",
39
+ title="💕 貼心男友聊天機器人 💕"
40
+ )
41
+
42
+ # 啟動介面
43
+ chat_interface.launch(share=True)