File size: 3,773 Bytes
008f597 7135063 008f597 7135063 008f597 7135063 008f597 7135063 63347cd 96e6aee 7135063 96e6aee 7135063 96e6aee 7135063 008f597 7135063 64a6601 7135063 e36321a 7135063 e36321a 96e6aee 008f597 96e6aee 008f597 96e6aee 7135063 96e6aee 64a6601 96e6aee 7135063 96e6aee 7135063 96e6aee 7135063 96e6aee e36321a 96e6aee 7135063 96e6aee 7135063 96e6aee 7135063 008f597 7135063 96e6aee 7135063 008f597 96e6aee 008f597 7135063 | 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 | 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() |