Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,24 +1,60 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
)
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
# 嘗試安裝並導入 groq
|
4 |
+
try:
|
5 |
+
from groq import Groq
|
6 |
+
except ImportError:
|
7 |
+
os.system('pip install groq') # 嘗試安裝 groq
|
8 |
+
from groq import Groq
|
9 |
+
|
10 |
+
import gradio as gr
|
11 |
+
|
12 |
+
# 從環境變數中取得 API key
|
13 |
+
groq_key = os.getenv('groq_key')
|
14 |
+
|
15 |
+
# 創建 Groq 客戶端
|
16 |
+
client = Groq(api_key=groq_key)
|
17 |
+
|
18 |
+
# 定義與 Groq 的聊天功能
|
19 |
+
def chat_with_groq(message, chat_history):
|
20 |
+
# 將先前的對話記錄加到 messages 中
|
21 |
+
messages = [{"role": "system", "content": "你是一位國小老師,使用的語言為繁體中文(zh-tw)。你的專長是將生活素養的正確觀念融入課堂教學中,無論學生問你什麼問題,你都會把話題引導到正向觀念的討論上。"}]
|
22 |
+
for user_msg, bot_msg in chat_history:
|
23 |
+
messages.append({"role": "user", "content": user_msg})
|
24 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
25 |
+
|
26 |
+
messages.append({"role": "user", "content": message})
|
27 |
+
|
28 |
+
# 呼叫 groq API 生成回應
|
29 |
+
completion = client.chat.completions.create(
|
30 |
+
model="llama-3.1-70b-versatile", # 使用 groq 的模型
|
31 |
+
messages=messages,
|
32 |
+
temperature=1,
|
33 |
+
max_tokens=3660,
|
34 |
+
top_p=1,
|
35 |
+
stream=False,
|
36 |
+
stop=None,
|
37 |
+
)
|
38 |
+
|
39 |
+
# 獲取模型回應
|
40 |
+
response = completion['choices'][0]['message']['content']
|
41 |
+
|
42 |
+
# 更新聊天記錄
|
43 |
+
chat_history.append((message, response))
|
44 |
+
|
45 |
+
return chat_history, chat_history
|
46 |
+
|
47 |
+
# 建立 Gradio 的聊天機器人介面
|
48 |
+
with gr.Blocks() as demo:
|
49 |
+
chatbot = gr.Chatbot() # 聊天機器人介面
|
50 |
+
user_input = gr.Textbox(placeholder="輸入你的問題", label="輸入")
|
51 |
+
send_button = gr.Button("發送") # 發送按鈕
|
52 |
+
clear_button = gr.Button("清除對話") # 清除聊天紀錄按鈕
|
53 |
+
chat_history = gr.State([]) # 儲存聊天紀錄的狀態
|
54 |
+
|
55 |
+
# 設定按鈕點擊後的動作:呼叫 `chat_with_groq`,將結果顯示在 `chatbot` 中
|
56 |
+
send_button.click(chat_with_groq, inputs=[user_input, chat_history], outputs=[chatbot, chat_history])
|
57 |
+
clear_button.click(lambda: None, None, chatbot, queue=False) # 清除聊天內容
|
58 |
+
|
59 |
+
# 啟動 Gradio 介面
|
60 |
+
demo.launch()
|