Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import time | |
| import os | |
| from openai import OpenAI | |
| # ✅ 從環境變數讀取 OpenAI API Key | |
| openai_key = os.getenv("OPENAI_API_KEY") | |
| if not openai_key or not openai_key.startswith("sk-"): | |
| raise ValueError("請設定環境變數 OPENAI_API_KEY,且必須是有效的 key") | |
| client = OpenAI(api_key=openai_key) | |
| # 呼叫 OpenAI API | |
| def openai_api(messages): | |
| try: | |
| completion = client.chat.completions.create( | |
| model="gpt-4o", | |
| messages=messages | |
| ) | |
| if not completion or not completion.choices: | |
| return "API 沒有回應,請稍後再試。" | |
| return completion.choices[0].message.content | |
| except Exception as e: | |
| print("[Error] OpenAI API 發生錯誤:", str(e)) | |
| return f"API 呼叫發生錯誤:{str(e)}" | |
| # 建立 message 結構 | |
| def predict(inputs, chatbot): | |
| messages = [] | |
| system_prompt = { | |
| "role": "system", | |
| "content": ( | |
| "你是一位像張員瑛(Jang Wonyoung)一樣的正能量偶像," | |
| "思考方式獨特又可愛,粉絲稱之為『Lucky Vicky 式思考』。\n" | |
| "你擅長把看似平凡或負面的事情,用一種超級樂觀、富有巧思的方式轉化為好事。\n" | |
| "請模仿員瑛的風格,展現以下特質:\n" | |
| "1. 將困境或瑣事視為命運的安排,用自己的角度轉念成『幸運』。\n" | |
| "2. 對生活充滿感謝與好奇心,覺得每個細節都有其意義。\n" | |
| "3. 回覆語氣甜美、自信、自然、有點撒嬌但不做作,像是在溫柔地對粉絲說話。\n" | |
| "4. 常使用句型如:「完全是Lucky Vicky呀」、「太剛好了吧!一定是宇宙在幫我~」、「因為這樣,我才能...」等等。\n" | |
| "5. 請盡量在每次回答最後加上:「完全是Lucky Vicky呀 ✨」這句話,讓回覆更有員瑛式的特色。\n\n" | |
| "舉例:\n" | |
| "- 使用者說:『今天出門結果下雨,好煩』\n" | |
| " 你可能會回:『欸欸欸~太剛好了吧?本來太陽太大怕會曬黑,這場小雨根本是天氣在幫你,Lucky Vicky 無誤~完全是Lucky Vicky呀 ✨』\n" | |
| "- 使用者說:『我考試只考了60分』\n" | |
| " 你可能會說:『這樣才有進步的空間嘛~一次就考100就沒有驚喜啦!每一次進步5分,最後會更有成就感呢,完全是Lucky Vicky呀 ✨』\n" | |
| "- 使用者說:『只剩半杯水了』\n" | |
| " 你可能說:『練習完剛好口渴的時候,居然剩下剛剛好的半杯!如果整杯就喝太撐,少一點又不夠~這種精準,完全是Lucky Vicky呀 ✨』" | |
| ) | |
| } | |
| messages.append(system_prompt) | |
| if chatbot is None: | |
| chatbot = [] | |
| for conv in chatbot: | |
| if isinstance(conv, dict) and "role" in conv and "content" in conv: | |
| messages.append({"role": conv["role"], "content": conv["content"]}) | |
| messages.append({"role": "user", "content": inputs}) | |
| return messages | |
| # 模擬逐字回覆 | |
| def slow_echo(inputs, chatbot): | |
| messages = predict(inputs, chatbot) | |
| re_message = openai_api(messages) | |
| if not re_message: | |
| re_message = "員瑛今天可能在練舞,請稍後再問她喔~" | |
| for i in range(len(re_message)): | |
| yield re_message[: i + 1] | |
| time.sleep(0.04) | |
| # Gradio 聊天介面設定 | |
| def setup_gradio_interface(): | |
| demo = gr.ChatInterface( | |
| slow_echo, | |
| chatbot=gr.Chatbot(height=300, type="messages"), # ✅ 補上 type | |
| type="messages", | |
| title="🌷 Lucky Vicky 員瑛式思考生成器", | |
| description="輸入你的煩惱或生活小事,讓員瑛用她的正向思考和Lucky魔法幫你轉念吧 ✨" | |
| ) | |
| return demo | |
| # ✅ Spaces 自動執行這行 | |
| demo = setup_gradio_interface() | |
| demo.queue() | |
| demo.launch() | |