Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,28 +7,39 @@ client = openai.OpenAI(api_key=os.environ['OPENAI_API_KEY'])
|
|
| 7 |
|
| 8 |
# 建立「男友」聊天機器人函數
|
| 9 |
def boyfriend_chatbot(user_input, history):
|
|
|
|
| 10 |
history = history or []
|
|
|
|
|
|
|
| 11 |
messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
|
| 12 |
-
|
|
|
|
| 13 |
for user_msg, bot_msg in history:
|
| 14 |
messages.append({"role": "user", "content": user_msg})
|
| 15 |
messages.append({"role": "assistant", "content": bot_msg})
|
| 16 |
|
|
|
|
| 17 |
messages.append({"role": "user", "content": user_input})
|
| 18 |
-
|
| 19 |
try:
|
|
|
|
| 20 |
completion = client.chat.completions.create(
|
| 21 |
-
model="gpt-4o-mini",
|
| 22 |
-
messages=messages,
|
| 23 |
-
temperature=0.7
|
| 24 |
)
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
except Exception as e:
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
# 建立 Gradio 介面
|
| 34 |
chat_interface = gr.ChatInterface(
|
|
|
|
| 7 |
|
| 8 |
# 建立「男友」聊天機器人函數
|
| 9 |
def boyfriend_chatbot(user_input, history):
|
| 10 |
+
# 如果 history 為 None,初始化為空清單
|
| 11 |
history = history or []
|
| 12 |
+
|
| 13 |
+
# 系統訊息:定義 ChatGPT 的角色為「溫柔、貼心的男友」
|
| 14 |
messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}]
|
| 15 |
+
|
| 16 |
+
# 將歷史訊息加入對話 context 中(交錯排列 user 和 assistant 的訊息)
|
| 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 |
+
# 加入當前使用者的輸入
|
| 22 |
messages.append({"role": "user", "content": user_input})
|
| 23 |
+
|
| 24 |
try:
|
| 25 |
+
# 呼叫 OpenAI API,使用 GPT-4o-mini 模型產生回應
|
| 26 |
completion = client.chat.completions.create(
|
| 27 |
+
model="gpt-4o-mini", # 選用輕量級 GPT 模型
|
| 28 |
+
messages=messages, # 傳入完整對話歷史
|
| 29 |
+
temperature=0.7 # 控制回應的創造力(值越高越有創意)
|
| 30 |
)
|
| 31 |
+
# 取得模型的文字回應內容,並去除多餘空白
|
| 32 |
+
response = completion.choices[0].message.content.strip()
|
| 33 |
+
|
| 34 |
except Exception as e:
|
| 35 |
+
# 若發生錯誤,顯示錯誤訊息
|
| 36 |
+
yield f"❌ 發生錯誤:{str(e)}"
|
| 37 |
+
return
|
| 38 |
|
| 39 |
+
# 將回應逐字顯示,製造打字效果
|
| 40 |
+
for i in range(1, len(response) + 1):
|
| 41 |
+
yield response[:i] # 每次顯示一個字元累加的結果
|
| 42 |
+
time.sleep(0.03) # 設定每字顯示的時間間隔(秒)
|
| 43 |
|
| 44 |
# 建立 Gradio 介面
|
| 45 |
chat_interface = gr.ChatInterface(
|