File size: 4,117 Bytes
496c5e9
dbb214e
f95c054
 
dbb214e
 
 
 
 
 
 
 
 
f95c054
dbb214e
 
 
f95c054
dbb214e
496c5e9
6c63c7c
 
 
f95c054
6c63c7c
 
f95c054
 
 
 
6c33fca
aeab521
99a51d3
f95c054
99a51d3
496c5e9
300f268
f95c054
a1f5293
300f268
a1f5293
 
 
71f22c9
a1f5293
 
 
 
 
 
aeab521
 
0bf1c9e
6c63c7c
a1f5293
0bf1c9e
 
 
aeab521
0bf1c9e
aeab521
6c63c7c
 
0bf1c9e
 
a1f5293
0bf1c9e
f95c054
b181909
1e645c8
6c33fca
f95c054
 
 
 
b181909
f95c054
 
 
 
 
1e645c8
f95c054
1e645c8
6c33fca
922302c
a1f5293
 
 
 
aeab521
f95c054
922302c
aeab521
922302c
 
 
 
 
0bf1c9e
6c33fca
a1f5293
 
300f268
922302c
 
 
 
a1f5293
922302c
 
a1f5293
 
 
 
922302c
 
 
 
 
b181909
 
 
922302c
b181909
70542a0
9668cb3
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
import os
import subprocess
from datetime import datetime
import gradio as gr

# 自動檢查並安裝必要的套件
def install_and_import(package):
    try:
        __import__(package)
    except ImportError:
        subprocess.check_call(["pip", "install", package])

# 安裝依賴
install_and_import("notion-client")
install_and_import("gradio")
install_and_import("groq")

from notion_client import Client
from groq import Groq

# 從環境變數中提取 Notion API Key 和資料庫 ID
NOTION_API_KEY = os.getenv("NOTION_API_KEY")
NOTION_DB_ID = os.getenv("NOTION_DB_ID")

if not NOTION_API_KEY or not NOTION_DB_ID:
    raise ValueError("請設置 NOTION_API_KEY 和 NOTION_DB_ID 環境變數!")

# 初始化 Notion 客戶端
notion = Client(auth=NOTION_API_KEY)

# 設定 Groq 的 API Key
groq_key = os.getenv("groq_key")
if not groq_key:
    raise ValueError("groq_key 環境變數未設置!")

client = Groq(api_key=groq_key)

# 定義 Chatbot 類
class SimpleChatBot:
    def __init__(self):
        self.initial_prompt = [
            {
                "role": "system",
                "content": "你是一個英文老師,會教我背單字,並用蘇格拉底問答引導我,引導時請用繁體中文 zhTW"
            }
        ]

    def get_response(self, message, chat_history):
        messages = self.initial_prompt + chat_history
        messages.append({"role": "user", "content": message})

        # 使用 groq 的 chat.completions API 生成回應
        completion = client.chat.completions.create(
            model="llama3-8b-8192",
            messages=messages,
            temperature=1,
            max_tokens=1024,
            top_p=1,
            stream=False,
        )

        # 修正:正確提取 completion 的內容
        response_content = completion.choices[0].message.content
        return response_content

chatbot = SimpleChatBot()

# 記錄聊天內容到 Notion 資料庫
def log_to_notion(user_name, user_message, bot_response):
    try:
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        notion.pages.create(
            parent={"database_id": NOTION_DB_ID},
            properties={
                "Timestamp": {"date": {"start": timestamp}},
                "Name": {"title": [{"text": {"content": user_name or "Anonymous"}}]},
                "User Input": {"rich_text": [{"text": {"content": user_message}}]},
                "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]},
            },
        )
        print("Logged to Notion successfully.")
    except Exception as e:
        print(f"Error logging to Notion: {e}")

# 定義回應邏輯
def respond(name, message, chat_history):
    chat_history = [{"role": entry["role"], "content": entry["content"]} for entry in chat_history]
    response = chatbot.get_response(message, chat_history)
    chat_history.append({"role": "user", "content": message})
    chat_history.append({"role": "assistant", "content": response})

    # 記錄到 Notion
    log_to_notion(name, message, response)

    return chat_history, ""

# 定義用於存儲用戶名字的狀態
def set_name(name):
    return name

# 建立 Gradio 界面
with gr.Blocks(title="簡單的Gradio聊天機器人") as demo:
    gr.Markdown("# 簡單的Gradio聊天機器人")
    
    # 用戶名稱輸入框
    with gr.Row():
        name_input = gr.Textbox(placeholder="輸入你的名字(僅需填寫一次)", label="你的名字", interactive=True)
        name_button = gr.Button("確認名字")
    
    # 聊天區
    chatbot_interface = gr.Chatbot(type="messages")
    with gr.Row():
        user_input = gr.Textbox(placeholder="輸入訊息...", label="你的訊息")
        send_button = gr.Button("發送")
    
    # 狀態保持,用於存儲用戶名稱
    user_name = gr.State()

    # 事件綁定
    name_button.click(set_name, inputs=[name_input], outputs=[user_name])
    send_button.click(
        respond, 
        inputs=[user_name, user_input, chatbot_interface], 
        outputs=[chatbot_interface, user_input]
    )
    
    demo.launch(share=True)