File size: 1,379 Bytes
fd42a50 aef8435 457292d fd42a50 aef8435 fd42a50 aef8435 fd42a50 aef8435 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import os
import gradio as gr
# Install the groq package if it is not installed
try:
from groq import Groq
except ImportError:
os.system('pip install groq')
from groq import Groq
# 從環境變數獲取 API 密鑰
groq_key = os.getenv('groq_key')
# 定義 Chatbot 回應函數
def chatbot_response(user_message):
client = Groq(api_key=groq_key)
completion = client.chat.completions.create(
model="llama-3.1-70b-versatile",
messages=[
{
"role": "system",
"content": "brat"
},
{
"role": "user",
"content": user_message
}
],
temperature=1,
max_tokens=1024,
top_p=1,
stream=True,
stop=None,
)
response = ""
for chunk in completion:
response += chunk.choices[0].delta.content or ""
return response
# 創建 Gradio 介面
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("Clear")
def respond(message, chat_history):
bot_message = chatbot_response(message)
chat_history.append((message, bot_message))
return chat_history, ""
msg.submit(respond, [msg, chatbot], [chatbot, msg])
clear.click(lambda: None, None, chatbot, queue=False)
# 啟動介面
demo.launch()
|