File size: 1,339 Bytes
1d4a655
9fba0f2
c961de0
1d4a655
 
 
 
 
 
9fba0f2
b504c70
 
c8b8d60
1d4a655
 
9fba0f2
1d4a655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b504c70
 
1d4a655
 
 
 
 
9fba0f2
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
import os
import gradio as gr

# 確保 groq 套件可用
try:
    from groq import Groq
except ImportError:
    os.system('pip install groq')
    from groq import Groq

# 設置 GROQ_API_KEY 環境變數
os.environ["GROQ_API_KEY"] = os.getenv("groq_key")

# 初始化 Groq 客戶端
client = Groq()

# 定義 chatbot 回應的函數
def chat_with_groq(user_input):
    completion = client.chat.completions.create(
        model="llama-3.1-70b-versatile",
        messages=[
            {
                "role": "system",
                "content": "我是國文老師,專門批改國小作文"
            },
            {
                "role": "user",
                "content": user_input
            }
        ],
        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 創建 chatbot
iface = gr.Interface(
    fn=chat_with_groq,
    inputs=gr.Textbox(label="請輸入您的問題:"),  # 更新為新版 Gradio 語法
    outputs=gr.Textbox(label="回應:"),  # 更新為新版 Gradio 語法
    title="國文老師 Chatbot",
    description="這是一個專門批改國小作文的 Chatbot"
)

# 啟動應用
iface.launch()