hchsuk's picture
Update app.py
6bfa25f verified
Raw History Blame Contribute Delete
4.14 kB
import os
import gradio as gr
import datetime # 用於獲取當前時間
# 安裝和導入 Groq 套件
try:
from groq import Groq
except ImportError:
os.system('pip install groq')
from groq import Groq
# 安裝和導入 Notion 套件
try:
from notion_client import Client
except ImportError:
os.system('pip install notion-client')
from notion_client import Client
# 取得 API Keys 和 Database ID
GROQ_API_KEY = os.getenv('groq_key')
NOTION_API_KEY = os.getenv('notion_key')
NOTION_DB_ID = os.getenv('notion_db_id')
# 確認 API Key 是否存在
if not GROQ_API_KEY:
raise ValueError("請確認已在系統環境變數中設置 'groq_key' 的值,這是您的 Groq API 金鑰。")
if not NOTION_API_KEY or not NOTION_DB_ID:
raise ValueError("請確認已在系統環境變數中設置 'notion_key' 和 'notion_db_id' 的值,這是您的 Notion API 金鑰和資料庫 ID。")
# 初始化 Groq 和 Notion 客戶端
client = Groq(api_key=GROQ_API_KEY)
notion = Client(auth=NOTION_API_KEY)
# 定義 Gradio 中的 chatbot 函數
def chatbot_response(user_name, user_message, chat_history):
""" 使用 Groq API 生成回應,並更新聊天記錄,同時將對話記錄儲存到 Notion。"""
try:
messages = [
{"role": "system", "content": "你是一位Chief Learning Officer 學習長, 使用的語言為繁體中文(zh-tw). 你的興趣是熟悉各種學習理論, talent management, successor planning, assessment tool, 熱愛用inspiring 的風格, 講冷笑話. 無論學生同事問你什麼問題, 你都會把話題引導到人資人才培訓能力發展相關的討論上. 回答不超過200字."}
]
# 添加歷史對話到 messages 中
for message in chat_history:
role = "user" if message[0] == "user" else "assistant"
messages.append({"role": role, "content": message[1]})
# 加入使用者的新訊息
messages.append({"role": "user", "content": user_message})
# 請求 Groq API 生成回應
completion = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
temperature=1,
max_tokens=1024,
top_p=1,
stream=False, # 不使用流式回應以簡化處理
stop=None,
)
# 獲取 Groq 的回應
bot_response = completion.choices[0].message.content # 修正這裡的訪問方式
# 更新聊天記錄
chat_history.append(("user", user_message))
chat_history.append(("assistant", bot_response))
# 紀錄到 Notion 表格
try:
notion.pages.create(
parent={"database_id": NOTION_DB_ID},
properties={
"Name": {"title": [{"text": {"content": user_name}}]},
"Timestamp": {"date": {"start": datetime.datetime.now().isoformat()}},
"User Input": {"rich_text": [{"text": {"content": user_message}}]},
"Bot Response": {"rich_text": [{"text": {"content": bot_response}}]}
}
)
except Exception as notion_error:
print(f"無法儲存到 Notion: {str(notion_error)}")
return chat_history
except Exception as e:
error_message = f"發生錯誤: {str(e)}"
chat_history.append(("assistant", error_message))
return chat_history
# 創建 Gradio 介面
with gr.Blocks() as demo:
gr.Markdown("# 🤖 Chief Learning Officer Chatbot")
name_input = gr.Textbox(placeholder="請輸入您的名字...", label="姓名") # 新增用戶名稱的輸入框
chatbot = gr.Chatbot()
message = gr.Textbox(placeholder="請輸入您的訊息...", label="輸入訊息")
submit_button = gr.Button("發送")
chat_history = gr.State([]) # 儲存聊天記錄
# 當點擊「發送」按鈕時,更新對話框
submit_button.click(fn=chatbot_response, inputs=[name_input, message, chat_history], outputs=chatbot)
# 啟動應用程式
if __name__ == "__main__":
demo.launch()