EduTechTeam commited on
Commit
bf4e6ef
·
verified ·
1 Parent(s): 519d7a7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -0
app.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 確保 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
+ messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
16
+
17
+ for user_msg, bot_msg in history:
18
+ messages.append({"role": "user", "content": user_msg})
19
+ messages.append({"role": "assistant", "content": bot_msg})
20
+
21
+ messages.append({"role": "user", "content": user_input})
22
+
23
+ response = openai.ChatCompletion.create(
24
+ model="gpt-4o",
25
+ messages=messages
26
+ )
27
+
28
+ return response.choices[0].message.content
29
+
30
+
31
+ # 建立 Gradio 介面
32
+ chat_interface = gr.ChatInterface(
33
+ fn=boyfriend_chatbot,
34
+ title="💕 貼心男友聊天機器人 💕"
35
+ )
36
+
37
+ # 啟動介面
38
+ chat_interface.launch(share=True)