File size: 4,151 Bytes
26b84ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import gradio as gr
from groq import Groq

class GroqChatbot:
    def __init__(self, api_key, model="mixtral-8x7b-32768"):
        """
        初始化 Groq AI 聊天機器人
        
        :param api_key: Groq API 金鑰
        :param model: 要使用的模型,預設為 mixtral-8x7b-32768
        """
        self.client = Groq(api_key=api_key)
        self.model = model
        self.conversation_history = []

    def generate_response(self, user_message):
        """
        使用 Groq AI 產生回覆
        
        :param user_message: 使用者輸入的訊息
        :return: AI 的回覆
        """
        try:
            # 準備對話歷史記錄
            messages = [
                {"role": "system", "content": "你是一個樂於助人的 AI 助理。請用繁體中文回答問題。"}
            ]
            
            # 新增先前的對話歷史
            for past_user, past_ai in self.conversation_history:
                messages.append({"role": "user", "content": past_user})
                messages.append({"role": "assistant", "content": past_ai})
            
            # 新增目前使用者訊息
            messages.append({"role": "user", "content": user_message})
            
            # 呼叫 Groq API
            chat_completion = self.client.chat.completions.create(
                messages=messages,
                model=self.model
            )
            
            # 取得回覆
            response = chat_completion.choices[0].message.content
            return response
        
        except Exception as e:
            return f"發生錯誤:{str(e)}"

    def chat_interface(self, user_message):
        """
        主要聊天介面方法
        
        :param user_message: 使用者輸入的訊息
        :return: AI 回覆和對話歷史
        """
        # 產生回覆
        response = self.generate_response(user_message)
        
        # 更新對話歷史
        self.conversation_history.append((user_message, response))
        
        # 準備歷史顯示
        history_text = ""
        for i, (question, answer) in enumerate(self.conversation_history):
            history_text += f"問題 {i+1}{question}\n"
            history_text += f"回覆 {i+1}{answer}\n\n"
        
        return response, history_text

def create_gradio_interface(api_key):
    """
    建立 Gradio 聊天介面
    
    :param api_key: Groq API 金鑰
    :return: Gradio 介面
    """
    # 初始化聊天機器人
    chatbot = GroqChatbot(api_key)
    
    # 示範問題
    examples = [
        "什麼是人工智能?", 
        "請解釋量子運算的基本原理",
        "能分享一個有趣的科技創新故事嗎?"
    ]
    
    # 建立 Gradio 介面
    with gr.Blocks() as demo:
        gr.Markdown("# 🤖 Groq AI 智能助理 🌐")
        gr.Markdown("使用 Groq AI 技術的智慧對話助手")
        
        with gr.Row():
            with gr.Column(scale=3):
                input_text = gr.Textbox(label="請在此輸入您的問題...")
                submit_btn = gr.Button("傳送")
            
            with gr.Column(scale=1):
                gr.Markdown("### 快速範例")
                example_buttons = [gr.Button(ex) for ex in examples]
        
        output_text = gr.Textbox(label="AI 回覆")
        history_text = gr.Textbox(label="對話紀錄")
        
        # 傳送按鈕邏輯
        submit_btn.click(
            fn=chatbot.chat_interface, 
            inputs=input_text, 
            outputs=[output_text, history_text]
        )
        
        # 範例按鈕邏輯
        for btn, ex in zip(example_buttons, examples):
            btn.click(
                fn=chatbot.chat_interface, 
                inputs=gr.State(ex), 
                outputs=[output_text, history_text]
            )
    
    return demo

# 使用方法
if __name__ == "__main__":
    # 請更換為您的 Groq API 金鑰
    GROQ_API_KEY = "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"
    
    # 啟動 Gradio 介面
    demo = create_gradio_interface(GROQ_API_KEY)
    demo.launch()