Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,40 +7,41 @@ client = openai.OpenAI(api_key=os.environ['OPENAI_API_KEY'])
|
|
| 7 |
|
| 8 |
# 建立「男友」聊天機器人函數
|
| 9 |
def boyfriend_chatbot(user_input, history):
|
| 10 |
-
# 如果 history 為 None,初始化為空清單
|
| 11 |
history = history or []
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
| 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",
|
| 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"❌
|
| 37 |
return
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
|
|
|
| 44 |
# 建立 Gradio 介面
|
| 45 |
chat_interface = gr.ChatInterface(
|
| 46 |
boyfriend_chatbot,
|
|
|
|
| 7 |
|
| 8 |
# 建立「男友」聊天機器人函數
|
| 9 |
def boyfriend_chatbot(user_input, history):
|
|
|
|
| 10 |
history = history or []
|
| 11 |
|
| 12 |
+
messages = [{
|
| 13 |
+
"role": "system",
|
| 14 |
+
"content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"
|
| 15 |
+
}]
|
| 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 |
try:
|
|
|
|
| 24 |
completion = client.chat.completions.create(
|
| 25 |
+
model="gpt-4o-mini",
|
| 26 |
+
messages=messages,
|
| 27 |
+
temperature=0.7
|
| 28 |
)
|
|
|
|
| 29 |
response = completion.choices[0].message.content.strip()
|
|
|
|
| 30 |
except Exception as e:
|
| 31 |
+
# 第一層:無法取得 API 回應
|
| 32 |
+
yield f"❌ 發生錯誤(API 回應失敗):{str(e)}"
|
| 33 |
return
|
| 34 |
|
| 35 |
+
try:
|
| 36 |
+
# 第二層:回應逐字輸出時出錯(如斷線、非字串等)
|
| 37 |
+
for i in range(1, len(response) + 1):
|
| 38 |
+
yield response[:i]
|
| 39 |
+
time.sleep(0.03)
|
| 40 |
+
except Exception as e:
|
| 41 |
+
# 顯示錯誤並終止
|
| 42 |
+
yield f"⚠️ 顯示訊息時發生錯誤:{str(e)}"
|
| 43 |
|
| 44 |
+
|
| 45 |
# 建立 Gradio 介面
|
| 46 |
chat_interface = gr.ChatInterface(
|
| 47 |
boyfriend_chatbot,
|