Howarddddd commited on
Commit
ea6efec
·
verified ·
1 Parent(s): 9ecd1e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -50
app.py CHANGED
@@ -1,64 +1,94 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
41
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
1
  import gradio as gr
2
+ import time
3
+ import os
4
+ from openai import OpenAI
5
 
6
+ # ✅ 從環境變數讀取 OpenAI API Key
7
+ openai_key = os.getenv("OPENAI_API_KEY")
8
+ if not openai_key or not openai_key.startswith("sk-"):
9
+ raise ValueError("請設定環境變數 OPENAI_API_KEY,且必須是有效的 key")
10
 
11
+ client = OpenAI(api_key=openai_key)
12
 
13
+ # 呼叫 OpenAI API
14
+ def openai_api(messages):
15
+ try:
16
+ completion = client.chat.completions.create(
17
+ model="gpt-4o",
18
+ messages=messages
19
+ )
20
+ if not completion or not completion.choices:
21
+ return "API 沒有回應,請稍後再試。"
22
+ return completion.choices[0].message.content
23
+ except Exception as e:
24
+ print("[Error] OpenAI API 發生錯誤:", str(e))
25
+ return f"API 呼叫發生錯誤:{str(e)}"
26
 
27
+ # 建立 message 結構
28
+ def predict(inputs, chatbot):
29
+ messages = []
 
 
30
 
31
+ system_prompt = {
32
+ "role": "system",
33
+ "content": (
34
+ "你是一位像張員瑛(Jang Wonyoung)一樣的正能量偶像,"
35
+ "思考方式獨特又可愛,粉絲稱之為『Lucky Vicky 式思考』。\n"
36
+ "你擅長把看似平凡或負面的事情,用一種超級樂觀、富有巧思的方式轉化為好事。\n"
37
+ "請模仿員瑛的風格,展現以下特質:\n"
38
+ "1. 將困境或瑣事視為命運的安排,用自己的角度轉念成『幸運』。\n"
39
+ "2. 對生活充滿感謝與好奇心,覺得每個細節都有其意義。\n"
40
+ "3. 回覆語氣甜美、自信、自然、有點撒嬌但不做作,像是在溫柔地對粉絲說話。\n"
41
+ "4. 常使用句型如:「完全是Lucky Vicky呀」、「太剛好了吧!一定是宇宙在幫我~」、「因為這樣,我才能...」等等。\n"
42
+ "5. 請盡量在每次回答最後加上:「完全是Lucky Vicky呀 ✨」這句話,讓回覆更有員瑛式的特色。\n\n"
43
+ "舉例:\n"
44
+ "- 使用者說:『今天出門結果下雨,好煩』\n"
45
+ " 你可能會回:『欸欸欸~太剛好了吧?本來太陽太大怕會曬黑,這場小雨根本是天氣在幫你,Lucky Vicky 無誤~完全是Lucky Vicky呀 ✨』\n"
46
+ "- 使用者說:『我考試只考了60分』\n"
47
+ " 你可能會說:『這樣才有進步的空間嘛~一次就考100就沒有驚喜啦!每一次進步5分,最後會更有成就感呢,完全是Lucky Vicky呀 ✨』\n"
48
+ "- 使用者說:『只剩半杯水了』\n"
49
+ " 你可能說:『練習完剛好口渴的時候,居然剩下剛剛好的半杯!如果整杯就喝太撐,少一點又不夠~這種精準,完全是Lucky Vicky呀 ✨』"
50
+ )
51
+ }
52
 
53
+ messages.append(system_prompt)
54
 
55
+ if chatbot is None:
56
+ chatbot = []
 
 
 
 
 
 
57
 
58
+ for conv in chatbot:
59
+ if isinstance(conv, dict) and "role" in conv and "content" in conv:
60
+ messages.append({"role": conv["role"], "content": conv["content"]})
61
 
62
+ messages.append({"role": "user", "content": inputs})
63
+ return messages
64
 
65
+ # 模擬逐字回覆
66
+ def slow_echo(inputs, chatbot):
67
+ messages = predict(inputs, chatbot)
68
+ re_message = openai_api(messages)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ if not re_message:
71
+ re_message = "員瑛今天可能在練舞,請稍後再問她喔~"
72
 
73
+ for i in range(len(re_message)):
74
+ yield re_message[: i + 1]
75
+ time.sleep(0.04)
76
+
77
+ # Gradio 聊天介面設定
78
+ def setup_gradio_interface():
79
+ demo = gr.ChatInterface(
80
+ slow_echo,
81
+ chatbot=gr.Chatbot(height=500),
82
+ type="messages",
83
+ flagging_options=["療癒", "太可愛", "不太懂", "其他"],
84
+ title="🌷 Lucky Vicky 員瑛式思考生成器",
85
+ description="輸入你的煩惱或生活小事,讓員瑛用她的正向思考和Lucky魔法幫你轉念吧 ✨"
86
+ )
87
+ return demo
88
+
89
+ # 啟動主程式
90
  if __name__ == "__main__":
91
+ demo = setup_gradio_interface()
92
+ port = 7865
93
+ demo.queue()
94
+ demo.launch(server_name="0.0.0.0", server_port=port)