Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,60 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
try:
|
| 3 |
from groq import Groq
|
| 4 |
except ImportError:
|
| 5 |
os.system('pip install groq')
|
| 6 |
from groq import Groq
|
| 7 |
-
import gradio as gr
|
| 8 |
|
| 9 |
# 設定 API key
|
| 10 |
groq_key = os.getenv("groq_key")
|
| 11 |
if not groq_key:
|
| 12 |
raise ValueError("請設定環境變數 'groq_key',包含您的 API 金鑰")
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
client = Groq(api_key=groq_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# 定義 Chatbot 的回應邏輯
|
| 17 |
-
def chat_with_groq(history):
|
| 18 |
"""
|
| 19 |
-
與 Groq 聊天機器人互動,根據 Gradio 的 Chatbot 結構處理歷史記錄
|
|
|
|
| 20 |
:param history: List of tuples (user_input, bot_response)
|
| 21 |
:return: Updated history with new bot response
|
| 22 |
"""
|
| 23 |
-
# 提取最新的用戶輸入
|
| 24 |
user_message = history[-1][0] if history else "你好!"
|
| 25 |
|
| 26 |
-
# 初始化對話,帶有 role: system 的設定
|
| 27 |
messages = [
|
| 28 |
{
|
| 29 |
"role": "system",
|
|
@@ -31,15 +62,12 @@ def chat_with_groq(history):
|
|
| 31 |
}
|
| 32 |
]
|
| 33 |
|
| 34 |
-
|
| 35 |
-
for user_msg, bot_msg in history[:-1]: # 忽略最後一條,因為它是新的輸入
|
| 36 |
messages.append({"role": "user", "content": user_msg})
|
| 37 |
messages.append({"role": "assistant", "content": bot_msg})
|
| 38 |
-
|
| 39 |
-
# 添加最新的用戶訊息
|
| 40 |
messages.append({"role": "user", "content": user_message})
|
| 41 |
|
| 42 |
-
# 呼叫 Groq API 生成回應
|
| 43 |
try:
|
| 44 |
completion = client.chat.completions.create(
|
| 45 |
model="llama3-8b-8192",
|
|
@@ -47,21 +75,25 @@ def chat_with_groq(history):
|
|
| 47 |
temperature=1,
|
| 48 |
max_tokens=1024,
|
| 49 |
top_p=1,
|
| 50 |
-
stream=False,
|
| 51 |
stop=None,
|
| 52 |
)
|
| 53 |
-
# 提取 AI 回應
|
| 54 |
response = completion.choices[0].message.content.strip()
|
| 55 |
except Exception as e:
|
| 56 |
response = f"抱歉,發生了一個錯誤:{str(e)}"
|
| 57 |
-
|
| 58 |
-
#
|
|
|
|
|
|
|
|
|
|
| 59 |
history[-1][1] = response
|
| 60 |
return history
|
| 61 |
|
| 62 |
# 建立 Gradio 介面
|
| 63 |
with gr.Blocks() as demo:
|
| 64 |
gr.Markdown("## 🎨 AI 美術老師 Chatbot")
|
|
|
|
|
|
|
| 65 |
chatbot = gr.Chatbot()
|
| 66 |
with gr.Row():
|
| 67 |
msg = gr.Textbox(
|
|
@@ -77,7 +109,7 @@ with gr.Blocks() as demo:
|
|
| 77 |
return "", chat_history
|
| 78 |
|
| 79 |
msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 80 |
-
chat_with_groq, chatbot, chatbot
|
| 81 |
)
|
| 82 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 83 |
|
|
|
|
| 1 |
import os
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from notion_client import Client
|
| 5 |
+
|
| 6 |
try:
|
| 7 |
from groq import Groq
|
| 8 |
except ImportError:
|
| 9 |
os.system('pip install groq')
|
| 10 |
from groq import Groq
|
|
|
|
| 11 |
|
| 12 |
# 設定 API key
|
| 13 |
groq_key = os.getenv("groq_key")
|
| 14 |
if not groq_key:
|
| 15 |
raise ValueError("請設定環境變數 'groq_key',包含您的 API 金鑰")
|
| 16 |
|
| 17 |
+
notion_api_key = os.getenv("NOTION_API_KEY")
|
| 18 |
+
notion_db_id = os.getenv("NOTION_DB_ID")
|
| 19 |
+
|
| 20 |
+
if not notion_api_key or not notion_db_id:
|
| 21 |
+
raise ValueError("請設定環境變數 'NOTION_API_KEY' 和 'NOTION_DB_ID',以連結 Notion 資料庫")
|
| 22 |
+
|
| 23 |
client = Groq(api_key=groq_key)
|
| 24 |
+
notion = Client(auth=notion_api_key)
|
| 25 |
+
|
| 26 |
+
# 定義函數,將對話記錄寫入 Notion
|
| 27 |
+
def log_to_notion(name, timestamp, user_input, bot_response):
|
| 28 |
+
"""
|
| 29 |
+
將聊天記錄寫入 Notion 資料庫
|
| 30 |
+
:param name: 用戶名稱
|
| 31 |
+
:param timestamp: 時間戳
|
| 32 |
+
:param user_input: 用戶輸入
|
| 33 |
+
:param bot_response: 機器人回應
|
| 34 |
+
"""
|
| 35 |
+
try:
|
| 36 |
+
notion.pages.create(
|
| 37 |
+
parent={"database_id": notion_db_id},
|
| 38 |
+
properties={
|
| 39 |
+
"Name": {"title": [{"text": {"content": name}}]},
|
| 40 |
+
"Timestamp": {"date": {"start": timestamp}},
|
| 41 |
+
"User Input": {"rich_text": [{"text": {"content": user_input}}]},
|
| 42 |
+
"Bot Response": {"rich_text": [{"text": {"content": bot_response}}]},
|
| 43 |
+
},
|
| 44 |
+
)
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Failed to log to Notion: {str(e)}")
|
| 47 |
|
| 48 |
# 定義 Chatbot 的回應邏輯
|
| 49 |
+
def chat_with_groq(name, history):
|
| 50 |
"""
|
| 51 |
+
與 Groq 聊天機器人互動,根據 Gradio 的 Chatbot 結構處理歷史記錄,並記錄到 Notion
|
| 52 |
+
:param name: 用戶名稱
|
| 53 |
:param history: List of tuples (user_input, bot_response)
|
| 54 |
:return: Updated history with new bot response
|
| 55 |
"""
|
|
|
|
| 56 |
user_message = history[-1][0] if history else "你好!"
|
| 57 |
|
|
|
|
| 58 |
messages = [
|
| 59 |
{
|
| 60 |
"role": "system",
|
|
|
|
| 62 |
}
|
| 63 |
]
|
| 64 |
|
| 65 |
+
for user_msg, bot_msg in history[:-1]:
|
|
|
|
| 66 |
messages.append({"role": "user", "content": user_msg})
|
| 67 |
messages.append({"role": "assistant", "content": bot_msg})
|
| 68 |
+
|
|
|
|
| 69 |
messages.append({"role": "user", "content": user_message})
|
| 70 |
|
|
|
|
| 71 |
try:
|
| 72 |
completion = client.chat.completions.create(
|
| 73 |
model="llama3-8b-8192",
|
|
|
|
| 75 |
temperature=1,
|
| 76 |
max_tokens=1024,
|
| 77 |
top_p=1,
|
| 78 |
+
stream=False,
|
| 79 |
stop=None,
|
| 80 |
)
|
|
|
|
| 81 |
response = completion.choices[0].message.content.strip()
|
| 82 |
except Exception as e:
|
| 83 |
response = f"抱歉,發生了一個錯誤:{str(e)}"
|
| 84 |
+
|
| 85 |
+
# 記錄到 Notion 資料庫
|
| 86 |
+
timestamp = datetime.now().isoformat()
|
| 87 |
+
log_to_notion(name, timestamp, user_message, response)
|
| 88 |
+
|
| 89 |
history[-1][1] = response
|
| 90 |
return history
|
| 91 |
|
| 92 |
# 建立 Gradio 介面
|
| 93 |
with gr.Blocks() as demo:
|
| 94 |
gr.Markdown("## 🎨 AI 美術老師 Chatbot")
|
| 95 |
+
with gr.Row():
|
| 96 |
+
name_input = gr.Textbox(label="Name", placeholder="請輸入您的名字...")
|
| 97 |
chatbot = gr.Chatbot()
|
| 98 |
with gr.Row():
|
| 99 |
msg = gr.Textbox(
|
|
|
|
| 109 |
return "", chat_history
|
| 110 |
|
| 111 |
msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 112 |
+
lambda history: chat_with_groq(name_input.value, history), chatbot, chatbot
|
| 113 |
)
|
| 114 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 115 |
|