EduTechTeam commited on
Commit
535ef75
·
verified ·
1 Parent(s): 9dac091

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -17
app.py CHANGED
@@ -1,16 +1,22 @@
1
  import openai
2
  import gradio as gr
3
  import os
 
4
 
5
- # 從環境變數讀取 OpenAI API 金鑰
6
- openai.api_key = os.getenv("OPENAI_API_KEY")
7
 
 
 
8
  if openai.api_key is None:
9
  raise ValueError("請設定環境變數 OPENAI_API_KEY,確保 API Key 可用")
10
 
11
- # 建立男友聊天機器人函數
12
  def boyfriend_chatbot(user_input, history):
13
  history = history or []
 
 
 
14
  messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
15
 
16
  for user_msg, bot_msg in history:
@@ -19,21 +25,34 @@ def boyfriend_chatbot(user_input, history):
19
 
20
  messages.append({"role": "user", "content": user_input})
21
 
22
- response = openai.ChatCompletion.create(
23
- model="gpt-4o",
24
- messages=messages
25
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- reply = response.choices[0].message.content
28
- history.append((user_input, reply))
29
- return reply, history
30
 
31
- # 建立 Gradio Chat 介面
32
- chat_interface = gr.ChatInterface(
33
- fn=boyfriend_chatbot,
34
- title="💕 貼心男友聊天機器人 💕",
35
- theme="soft"
36
- )
37
 
38
  # 啟動介面
39
- chat_interface.launch(share=True)
 
1
  import openai
2
  import gradio as gr
3
  import os
4
+ from dotenv import load_dotenv
5
 
6
+ # 載入 .env 環境變數(如果你有放 .env 檔案)
7
+ load_dotenv()
8
 
9
+ # 設定 API Key
10
+ openai.api_key = os.getenv("OPENAI_API_KEY")
11
  if openai.api_key is None:
12
  raise ValueError("請設定環境變數 OPENAI_API_KEY,確保 API Key 可用")
13
 
14
+ # 建立男友聊天機器人函數,加入 log 訊息
15
  def boyfriend_chatbot(user_input, history):
16
  history = history or []
17
+ log_messages = []
18
+
19
+ # 系統角色說明
20
  messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
21
 
22
  for user_msg, bot_msg in history:
 
25
 
26
  messages.append({"role": "user", "content": user_input})
27
 
28
+ try:
29
+ response = openai.ChatCompletion.create(
30
+ model="gpt-4o",
31
+ messages=messages
32
+ )
33
+ reply = response.choices[0].message.content
34
+ history.append((user_input, reply))
35
+ log = f"[✅ Success] 回應完成,共 {len(messages)} 則對話。"
36
+ except Exception as e:
37
+ reply = "抱歉,出現了一些錯誤 😢"
38
+ log = f"[❌ Error] {str(e)}"
39
+
40
+ return reply, history, log
41
+
42
+
43
+ # 使用 Gradio Blocks 來加上 log 顯示
44
+ with gr.Blocks(title="貼心男友聊天機器人") as demo:
45
+ gr.Markdown("# 💕 貼心男友聊天機器人 💕")
46
+ chatbot = gr.Chatbot()
47
+ msg = gr.Textbox(label="輸入你的訊息")
48
+ log_output = gr.Textbox(label="狀態日誌", interactive=False)
49
+ clear = gr.Button("清除對話")
50
 
51
+ def respond(user_input, history):
52
+ return boyfriend_chatbot(user_input, history)
 
53
 
54
+ msg.submit(respond, inputs=[msg, chatbot], outputs=[chatbot, chatbot, log_output])
55
+ clear.click(lambda: ([], "", ""), outputs=[chatbot, msg, log_output])
 
 
 
 
56
 
57
  # 啟動介面
58
+ demo.launch(share=True)