Spaces:
Build error
Build error
| import openai | |
| import gradio as gr | |
| import os | |
| import time | |
| client = openai.OpenAI(api_key=os.environ['OPENAI_API_KEY']) | |
| # 建立「男友」聊天機器人函數 | |
| def boyfriend_chatbot(user_input, history): | |
| history = history or [] | |
| # 加入系統提示,設定角色 | |
| messages = [{ | |
| "role": "system", | |
| "content": "你是一個溫柔、貼心的男友,總是關心對方的感受,給予支持和鼓勵,用輕鬆、暖心的語氣回應。" | |
| }] | |
| # history 是一串角色訊息(dict),可直接 append | |
| for msg in history: | |
| if msg.get("role") in ["user", "assistant"]: | |
| messages.append(msg) | |
| # 加入當前使用者訊息 | |
| messages.append({"role": "user", "content": user_input}) | |
| try: | |
| completion = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=messages, | |
| temperature=0.7 | |
| ) | |
| response = completion.choices[0].message.content.strip() | |
| except Exception as e: | |
| yield f"❌ 發生錯誤(API 回應失敗):{str(e)}" | |
| return | |
| 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( | |
| boyfriend_chatbot, | |
| chatbot=gr.Chatbot(type="messages"), | |
| type="messages", | |
| title="💕 貼心男友聊天機器人 💕" | |
| ) | |
| # 啟動介面 | |
| chat_interface.launch(share=True) | |