import os from datetime import datetime try: from groq import Groq from notion_client import Client except ImportError: os.system('pip install groq notion-client') from groq import Groq from notion_client import Client import gradio as gr # 設定 API keys groq_key = os.getenv("groq_key") notion_key = os.getenv("NOTION_API_KEY") notion_db_id = os.getenv("NOTION_DB_ID") if not groq_key: raise ValueError("請設定環境變數 'groq_key'") if not notion_key or not notion_db_id: raise ValueError("請設定 NOTION_API_KEY 和 NOTION_DB_ID") groq_client = Groq(api_key=groq_key) notion_client = Client(auth=notion_key) def log_to_notion(name, user_input, bot_response): """記錄對話到 Notion database""" try: notion_client.pages.create( parent={"database_id": notion_db_id}, properties={ "Name": {"title": [{"text": {"content": name}}]}, "Timestamp": {"date": {"start": datetime.utcnow().isoformat()}}, "User Input": {"rich_text": [{"text": {"content": user_input}}]}, "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]} } ) except Exception as e: print(f"Notion logging error: {str(e)}") def chat_with_groq(history, name): """ 與 Groq 聊天機器人互動,並記錄到 Notion """ user_message = history[-1][0] if history else "你好!" messages = [ { "role": "system", "content": "你是一個美術老師,請用繁體中文稱讚學生的問題,問什麼問題都會引導到藝術" } ] for user_msg, bot_msg in history[:-1]: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": bot_msg}) messages.append({"role": "user", "content": user_message}) try: completion = groq_client.chat.completions.create( model="llama3-8b-8192", messages=messages, temperature=1, max_tokens=1024, top_p=1, stream=False, stop=None, ) response = completion.choices[0].message.content.strip() # 記錄到 Notion log_to_notion(name, user_message, response) except Exception as e: response = f"抱歉,發生了一個錯誤:{str(e)}" history[-1][1] = response return history # 建立 Gradio 介面 with gr.Blocks() as demo: gr.Markdown("## 🎨 AI 美術老師 Chatbot") # 新增使用者名稱輸入 name_input = gr.Textbox( label="您的名字", placeholder="請輸入您的名字...", value="" ) chatbot = gr.Chatbot() with gr.Row(): msg = gr.Textbox( show_label=False, placeholder="請輸入您的問題...", ) clear = gr.Button("清除對話") def user_input(user_message, chat_history, name): if not name.strip(): return user_message, chat_history, "請先輸入您的名字" chat_history = chat_history or [] chat_history.append((user_message, None)) return "", chat_history, "" # 新增錯誤訊息顯示 error_message = gr.Textbox(label="提示訊息", interactive=False) msg.submit( user_input, [msg, chatbot, name_input], [msg, chatbot, error_message], queue=False ).then( chat_with_groq, [chatbot, name_input], chatbot ) def clear_chat(): return None, "" clear.click(clear_chat, None, [chatbot, error_message], queue=False) # 啟動應用程式 if __name__ == "__main__": demo.launch()