water64 commited on
Commit
96e6aee
·
verified ·
1 Parent(s): 008f597

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -41
app.py CHANGED
@@ -1,61 +1,86 @@
1
  import os
2
- import gradio as gr
3
  try:
4
  from groq import Groq
5
  except ImportError:
6
  os.system('pip install groq')
7
  from groq import Groq
 
 
 
 
 
 
8
 
9
- # Initialize Groq client
10
- client = Groq(api_key=os.getenv("groq_key"))
11
 
12
- # Chat history to store conversation
13
- chat_history = []
 
 
 
 
 
 
 
14
 
15
- def chat(message, history):
16
  messages = [
17
  {
18
- "role": "system",
19
  "content": "你是一個美術老師,請用繁體中文稱讚學生的問題,問什麼問題都會引導到藝術"
20
  }
21
  ]
 
 
 
 
 
22
 
23
- # Add chat history
24
- for human, assistant in history:
25
- messages.append({"role": "user", "content": human})
26
- messages.append({"role": "assistant", "content": assistant})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # Add current message
29
- messages.append({"role": "user", "content": message})
30
-
31
- # Get response from Groq
32
- completion = client.chat.completions.create(
33
- model="llama3-8b-8192",
34
- messages=messages,
35
- temperature=1,
36
- max_tokens=1024,
37
- top_p=1,
38
- stream=True,
39
- stop=None
40
- )
 
 
 
 
 
 
 
41
 
42
- # Build response text from stream
43
- response = ""
44
- for chunk in completion:
45
- if chunk.choices[0].delta.content is not None:
46
- response += chunk.choices[0].delta.content
47
- yield response
48
-
49
- # Create Gradio interface
50
- demo = gr.ChatInterface(
51
- fn=chat,
52
- title="藝術老師聊天機器人",
53
- description="我是一位熱愛藝術的老師,讓我們來聊聊藝術吧!",
54
- examples=["你好", "我想學畫畫", "什麼是藝術"],
55
- retry_btn=None,
56
- undo_btn=None,
57
- clear_btn="清除對話",
58
- )
59
 
 
60
  if __name__ == "__main__":
61
  demo.launch()
 
1
  import os
 
2
  try:
3
  from groq import Groq
4
  except ImportError:
5
  os.system('pip install groq')
6
  from groq import Groq
7
+ import gradio as gr
8
+
9
+ # 設定 API key
10
+ groq_key = os.getenv("groq_key")
11
+ if not groq_key:
12
+ raise ValueError("請設定環境變數 'groq_key',包含您的 API 金鑰")
13
 
14
+ client = Groq(api_key=groq_key)
 
15
 
16
+ # 定義 Chatbot 的回應邏輯
17
+ def chat_with_groq(history):
18
+ """
19
+ 與 Groq 聊天機器人互動,根據 Gradio 的 Chatbot 結構處理歷史記錄。
20
+ :param history: List of tuples (user_input, bot_response)
21
+ :return: Updated history with new bot response
22
+ """
23
+ # 提取最新的用戶輸入
24
+ user_message = history[-1][0] if history else "你好!"
25
 
26
+ # 初始化對話,帶有 role: system 的設定
27
  messages = [
28
  {
29
+ "role": "system",
30
  "content": "你是一個美術老師,請用繁體中文稱讚學生的問題,問什麼問題都會引導到藝術"
31
  }
32
  ]
33
+
34
+ # 添加歷史記錄作為上下文
35
+ for user_msg, bot_msg in history[:-1]: # 忽略最後一條,因為它是新的輸入
36
+ messages.append({"role": "user", "content": user_msg})
37
+ messages.append({"role": "assistant", "content": bot_msg})
38
 
39
+ # 添加最新的用戶訊息
40
+ messages.append({"role": "user", "content": user_message})
41
+
42
+ # 呼叫 Groq API 生成回應
43
+ try:
44
+ completion = client.chat.completions.create(
45
+ model="llama3-8b-8192",
46
+ messages=messages,
47
+ temperature=1,
48
+ max_tokens=1024,
49
+ top_p=1,
50
+ stream=False, # Gradio 不支援流式輸出,設為 False
51
+ stop=None,
52
+ )
53
+ # 提取 AI 回應
54
+ response = completion.choices[0].message.content.strip()
55
+ except Exception as e:
56
+ response = f"抱歉,發生了一個錯誤:{str(e)}"
57
 
58
+ # 將新回應加入歷史記錄
59
+ history[-1][1] = response
60
+ return history
61
+
62
+ # 建立 Gradio 介面
63
+ with gr.Blocks() as demo:
64
+ gr.Markdown("## 🎨 AI 美術老師 Chatbot")
65
+ chatbot = gr.Chatbot()
66
+ with gr.Row():
67
+ msg = gr.Textbox(
68
+ show_label=False,
69
+ placeholder="請輸入您的問題...",
70
+ )
71
+ clear = gr.Button("清除對話")
72
+
73
+ # 定義互動邏輯
74
+ def user_input(user_message, chat_history):
75
+ chat_history = chat_history or []
76
+ chat_history.append((user_message, None)) # 暫時加入用戶輸入,等待回應
77
+ return "", chat_history
78
 
79
+ msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
80
+ chat_with_groq, chatbot, chatbot
81
+ )
82
+ clear.click(lambda: None, None, chatbot, queue=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # 啟動應用程式
85
  if __name__ == "__main__":
86
  demo.launch()