File size: 3,434 Bytes
75961ec 7a863aa 6324f8e e67cf59 c83dfee 75961ec 6324f8e 7a863aa 2e7cb7d 6324f8e ba56c82 6324f8e 7a863aa 6324f8e 7a863aa 6324f8e 7a863aa 6324f8e 7a863aa 6324f8e 7a863aa 6324f8e 7a863aa 6324f8e ba56c82 7a863aa 6324f8e 7a863aa 6324f8e 7a863aa 6324f8e 7a863aa f56c317 6324f8e 7a863aa ba56c82 cf92c10 |
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 |
import os
import gradio as gr
from datetime import datetime
# Install and import required packages
try:
from notion_client import Client
except ImportError:
os.system('pip install notion-client')
from notion_client import Client
try:
from groq import Groq
except ImportError:
os.system('pip install groq')
from groq import Groq
# Initialize Groq client with API key
client = Groq(api_key=os.getenv('groq_key'))
# Initialize Notion client
notion = Client(auth=os.getenv("NOTION_API_KEY"))
NOTION_DB_ID = os.getenv("NOTION_DB_ID")
def log_to_notion(name, user_input, bot_response):
"""Logs the conversation to Notion."""
try:
notion.pages.create(
parent={"database_id": NOTION_DB_ID},
properties={
"Name": {"title": [{"text": {"content": name}}]},
"Timestamp": {"date": {"start": datetime.now().isoformat() }},
"User Input": {"rich_text": [{"text": {"content": user_input}}]},
"Bot Response": {"rich_text": [{"text": {"content": bot_response}}]},
},
)
except Exception as e:
print(f"Failed to log to Notion: {e}")
def process_message(message, history):
"""Processes the user message and returns the bot response."""
messages = [
{
"role": "system",
"content": "你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。\n說明數學上的可能用法時,先用中文講一遍再用B1程度的英文複述一遍\n"
}
]
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
messages.append({"role": "user", "content": message})
completion = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
temperature=1,
max_tokens=1024,
top_p=1,
stream=True,
stop=None,
)
response_text = ""
for chunk in completion:
delta_content = chunk.choices[0].delta.content
if delta_content is not None:
response_text += delta_content
yield response_text
# Create Gradio interface
with gr.Blocks() as demo:
with gr.Row():
name_input = gr.Textbox(placeholder="輸入您的名字...", label="Name")
msg = gr.Textbox(placeholder="輸入您的問題...", label="User Input")
chatbot = gr.Chatbot(height=600, show_label=False, container=True)
clear = gr.Button("清除對話")
def user(name, user_message, history):
return "", history + [[user_message, None]], name
def bot(name, history):
history[-1][1] = ""
for response in process_message(history[-1][0], history[:-1]):
history[-1][1] = response
yield history
# Log the conversation to Notion
if name.strip():
log_to_notion(name, history[-1][0], history[-1][1])
msg.submit(user, [name_input, msg, chatbot], [msg, chatbot, name_input], queue=False).then(
bot, [name_input, chatbot], chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
# Launch the app
if __name__ == "__main__":
demo.queue()
demo.launch()
|