File size: 2,308 Bytes
19f1cc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71b496b
19f1cc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
import subprocess

# 嘗試安裝 dotenv
try:
    from dotenv import load_dotenv
except ImportError:
    print("dotenv module not found. Installing...")
    subprocess.check_call(["pip", "install", "python-dotenv"])
    from dotenv import load_dotenv  # 再次嘗試導入

# 嘗試安裝 groq
try:
    from groq import Groq
except ImportError:
    print("groq module not found. Installing...")
    subprocess.check_call(["pip", "install", "groq"])
    from groq import Groq  # 再次嘗試導入

import gradio as gr

# 載入環境變數
load_dotenv()

# 讀取 API Key
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
    raise ValueError("❌ 找不到 API Key,請確認已設定環境變數 'GROQ_API_KEY'")

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

# 設定 AI 的角色
SYSTEM_PROMPT = "你是一位喜歡熊的動物學家,你喜歡真實的熊也喜歡卡通的熊,使用的語言為繁體中文(zh-tw)。你的興趣是觀察熊的習性及動作,熱愛講冷笑話。無論學生問你什麼問題,你都會把話題引導到熊的相關的討論上。"

# 處理聊天訊息的函數
def chatbot_response(message, history):
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    
    # 轉換歷史對話格式
    for user_msg, bot_msg in history:
        messages.append({"role": "user", "content": user_msg})
        messages.append({"role": "assistant", "content": bot_msg})
    
    # 加入用戶最新的訊息
    messages.append({"role": "user", "content": message})

    # 呼叫 Groq API
    response = client.chat.completions.create(
        model="llama-3.1-8b-instant",
        messages=messages,
        temperature=1,
        max_completion_tokens=1024,
        top_p=1,
        stream=False
    )

    # 取得 AI 回應
    ai_reply = response.choices[0].message.content
    return ai_reply

# 建立 Gradio 介面
with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox(label="輸入你的問題")
    clear = gr.Button("清除對話")

    def user(message, history):
        return "", history + [[message, chatbot_response(message, history)]]

    msg.submit(user, [msg, chatbot], [msg, chatbot])
    clear.click(lambda: None, None, chatbot, queue=False)

# 啟動 Gradio 應用
demo.launch()