math_e / app.py
helen573's picture
Update app.py
c83dfee verified
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()