Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,54 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
|
| 6 |
-
if max_number <= 0:
|
| 7 |
-
return "請輸入一個正整數"
|
| 8 |
-
return random.randint(1, max_number)
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
# 啟動介面
|
| 21 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
from groq import Groq
|
| 4 |
|
| 5 |
+
# 安裝 groq 套件
|
| 6 |
+
os.system('pip install groq')
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# 從環境變數獲取 API 密鑰
|
| 9 |
+
groq_key = os.getenv('groq_key')
|
| 10 |
+
|
| 11 |
+
# 定義 Chatbot 回應函數
|
| 12 |
+
def chatbot_response(user_message):
|
| 13 |
+
client = Groq(api_key=groq_key)
|
| 14 |
+
completion = client.chat.completions.create(
|
| 15 |
+
model="llama-3.1-70b-versatile",
|
| 16 |
+
messages=[
|
| 17 |
+
{
|
| 18 |
+
"role": "system",
|
| 19 |
+
"content": "brat"
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"role": "user",
|
| 23 |
+
"content": user_message
|
| 24 |
+
}
|
| 25 |
+
],
|
| 26 |
+
temperature=1,
|
| 27 |
+
max_tokens=1024,
|
| 28 |
+
top_p=1,
|
| 29 |
+
stream=True,
|
| 30 |
+
stop=None,
|
| 31 |
+
)
|
| 32 |
|
| 33 |
+
response = ""
|
| 34 |
+
for chunk in completion:
|
| 35 |
+
response += chunk.choices[0].delta.content or ""
|
| 36 |
|
| 37 |
+
return response
|
| 38 |
+
|
| 39 |
+
# 創建 Gradio 介面
|
| 40 |
+
with gr.Blocks() as demo:
|
| 41 |
+
chatbot = gr.Chatbot()
|
| 42 |
+
msg = gr.Textbox()
|
| 43 |
+
clear = gr.Button("Clear")
|
| 44 |
+
|
| 45 |
+
def respond(message, chat_history):
|
| 46 |
+
bot_message = chatbot_response(message)
|
| 47 |
+
chat_history.append((message, bot_message))
|
| 48 |
+
return chat_history, ""
|
| 49 |
+
|
| 50 |
+
msg.submit(respond, [msg, chatbot], [chatbot, msg])
|
| 51 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 52 |
|
| 53 |
# 啟動介面
|
| 54 |
demo.launch()
|