peterchuang commited on
Commit
e47afcc
·
verified ·
1 Parent(s): f704d7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py CHANGED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from groq import Groq
4
+ from gradio import ChatMessage
5
+
6
+ # 從環境變數中獲取 API 密鑰
7
+ api_key = os.getenv("groq_key")
8
+
9
+ # 初始化 groq 客戶端
10
+ client = Groq(api_key)
11
+
12
+ # 定義回應函數
13
+ def respond(message, chat_history):
14
+ # 構建聊天記錄
15
+ messages = [{"role": "system", "content": "你是一個友善的 AI 助手,請幫助使用者解答問題。"}]
16
+ for entry in chat_history:
17
+ messages.append({"role": "user", "content": entry['content']} if entry['role'] == 'user' else {"role": "assistant", "content": entry['content']})
18
+
19
+ # 添加當前用戶消息
20
+ messages.append({"role": "user", "content": message})
21
+
22
+ # 獲取回應
23
+ completion = client.chat.completions.create(
24
+ model="llama-3.1-70b-versatile",
25
+ messages=messages,
26
+ temperature=1,
27
+ max_tokens=1024,
28
+ top_p=1,
29
+ stream=True,
30
+ stop=None,
31
+ )
32
+
33
+ reply = ""
34
+ for chunk in completion:
35
+ reply += chunk.choices[0].delta.content or ""
36
+
37
+ # 添加當前回應到聊天記錄
38
+ chat_history.append(ChatMessage(role="user", content=message))
39
+ chat_history.append(ChatMessage(role="assistant", content=reply))
40
+ return chat_history
41
+
42
+ # 創建 Gradio Chatbot 界面
43
+ with gr.Blocks() as demo:
44
+ chatbot = gr.Chatbot(type='messages')
45
+ msg = gr.Textbox(label="輸入訊息")
46
+ clear = gr.Button("清除聊天")
47
+
48
+ def user(user_message, history):
49
+ return "", history + [ChatMessage(role="user", content=user_message)]
50
+
51
+ def bot(history):
52
+ user_message = history[-1]['content']
53
+ history = respond(user_message, history[:-1])
54
+ return history
55
+
56
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
57
+ bot, chatbot, chatbot
58
+ )
59
+ clear.click(lambda: [], None, chatbot, queue=False)
60
+
61
+ demo.launch()