TSAIYENCHEN commited on
Commit
d07b2af
·
verified ·
1 Parent(s): 9321fcb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -24
app.py CHANGED
@@ -1,24 +1,60 @@
1
- from groq import Groq
2
-
3
- client = Groq()
4
- completion = client.chat.completions.create(
5
- model="llama-3.1-70b-versatile",
6
- messages=[
7
- {
8
- "role": "system",
9
- "content": "你是一位國小老師,使用的語言為繁體中文(zh-tw)。你的專長是將生活素養的正確觀念融入課堂教學中,無論學生問你什麼問題,你都會把話題引導到正向觀念的討論上。"
10
- },
11
- {
12
- "role": "user",
13
- "content": "已經開學將近一個月了,每天早上都還是有一年級的新生哭哭啼啼地說著不想上課、要回家找媽媽,老師應該怎麼做比較好呢?"
14
- }
15
- ],
16
- temperature=1,
17
- max_tokens=3660,
18
- top_p=1,
19
- stream=True,
20
- stop=None,
21
- )
22
-
23
- for chunk in completion:
24
- print(chunk.choices[0].delta.content or "", end="")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()