Spaces:
Sleeping
Sleeping
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) | |