Spaces:
Sleeping
Sleeping
| import openai | |
| import gradio as gr | |
| import os | |
| import time | |
| # 設定 API 金鑰(從環境變數讀取) | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| if not openai.api_key: | |
| raise ValueError("❌ 請設定環境變數 OPENAI_API_KEY") | |
| # 聊天機器人函數 | |
| def boyfriend_chatbot(user_input, history): | |
| history = history or [] | |
| messages = [{ | |
| "role": "system", | |
| "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。" | |
| }] | |
| # 正確處理 history(List[Dict]) | |
| for msg in history: | |
| if msg.get("role") in ["user", "assistant"]: | |
| messages.append({"role": msg["role"], "content": msg["content"]}) | |
| messages.append({"role": "user", "content": user_input}) | |
| try: | |
| completion = openai.ChatCompletion.create( | |
| model="gpt-4", | |
| messages=messages, | |
| temperature=0.7 | |
| ) | |
| response = completion.choices[0].message["content"].strip() | |
| except Exception as e: | |
| return f"❌ 發生錯誤(API 呼叫失敗):{str(e)}" | |
| # 逐字動畫輸出 | |
| try: | |
| for i in range(1, len(response) + 1): | |
| yield response[:i] | |
| time.sleep(0.03) | |
| except Exception as e: | |
| yield f"⚠️ 顯示訊息時發生錯誤:{str(e)}" | |
| # Gradio 介面 | |
| chat_interface = gr.ChatInterface( | |
| fn=boyfriend_chatbot, | |
| chatbot=gr.Chatbot(type="messages"), | |
| type="messages", | |
| title="💕 貼心男友聊天機器人 💕", | |
| theme=gr.themes.Soft() | |
| ) | |
| # 啟動介面 | |
| chat_interface.launch() | |