CasperDylan commited on
Commit
8e45093
·
verified ·
1 Parent(s): 5067cdb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -13
app.py CHANGED
@@ -1,13 +1,14 @@
1
  import os
2
- import subprocess
3
- import sys
4
  import gradio as gr
5
-
6
- # 安裝 groq 套件
7
- subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'groq'])
8
-
9
  from groq import Groq
10
 
 
 
 
 
 
 
 
11
  # 從環境變數中獲取 Groq API 密鑰
12
  groq_key = os.getenv("groq_key")
13
  if not groq_key:
@@ -16,7 +17,8 @@ if not groq_key:
16
  # 初始化 Groq 客戶端
17
  client = Groq(api_key=groq_key)
18
 
19
- def chatbot_response(user_message):
 
20
  messages = [
21
  {
22
  "role": "system",
@@ -39,19 +41,18 @@ def chatbot_response(user_message):
39
  )
40
 
41
  response_message = completion.choices[0].message['content']
42
- return response_message
 
43
 
44
- # 建立 Gradio 界面
45
  with gr.Blocks() as demo:
46
  chatbot = gr.Chatbot()
47
  user_input = gr.Textbox(placeholder="輸入訊息...")
48
- send_button = gr.Button("發送")
49
 
50
  def user_message_handler(user_message, history):
51
- bot_response = chatbot_response(user_message)
52
- history.append((user_message, bot_response))
53
  return history, ""
54
 
55
- send_button.click(user_message_handler, [user_input, chatbot], [chatbot, user_input])
56
 
57
  demo.launch()
 
1
  import os
 
 
2
  import gradio as gr
 
 
 
 
3
  from groq import Groq
4
 
5
+ # Install the groq package if it is not installed
6
+ try:
7
+ from groq import Groq
8
+ except ImportError:
9
+ os.system('pip install groq')
10
+ from groq import Groq
11
+
12
  # 從環境變數中獲取 Groq API 密鑰
13
  groq_key = os.getenv("groq_key")
14
  if not groq_key:
 
17
  # 初始化 Groq 客戶端
18
  client = Groq(api_key=groq_key)
19
 
20
+ def chatbot_response(history):
21
+ user_message = history[-1]["content"]
22
  messages = [
23
  {
24
  "role": "system",
 
41
  )
42
 
43
  response_message = completion.choices[0].message['content']
44
+ history.append({"role": "assistant", "content": response_message})
45
+ return history
46
 
 
47
  with gr.Blocks() as demo:
48
  chatbot = gr.Chatbot()
49
  user_input = gr.Textbox(placeholder="輸入訊息...")
 
50
 
51
  def user_message_handler(user_message, history):
52
+ history.append({"role": "user", "content": user_message})
53
+ history = chatbot_response(history)
54
  return history, ""
55
 
56
+ user_input.submit(user_message_handler, [user_input, chatbot], [chatbot, user_input])
57
 
58
  demo.launch()