Spaces:
Build error
Build error
| import openai | |
| import gradio as gr | |
| import os | |
| # 從環境變數讀取 OpenAI API 金鑰 | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| # 確保 API Key 存在 | |
| if openai.api_key is None: | |
| raise ValueError("請設定環境變數 OPENAI_API_KEY,確保 API Key 可用") | |
| # 建立「男友」聊天機器人函數 | |
| def boyfriend_chatbot(user_input, history): | |
| history = history or [] | |
| messages = [{"role": "system", "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。"}] | |
| for user_msg, bot_msg in history: | |
| messages.append({"role": "user", "content": user_msg}) | |
| messages.append({"role": "assistant", "content": bot_msg}) | |
| messages.append({"role": "user", "content": user_input}) | |
| response = openai.ChatCompletion.create( | |
| model="gpt-4o", | |
| messages=messages | |
| ) | |
| return response.choices[0].message.content | |
| # 建立 Gradio 介面 | |
| chat_interface = gr.ChatInterface( | |
| fn=boyfriend_chatbot, | |
| title="💕 貼心男友聊天機器人 💕" | |
| ) | |
| # 啟動介面 | |
| chat_interface.launch(share=True) |