Update app.py
Browse files
app.py
CHANGED
|
@@ -26,10 +26,18 @@ from datetime import datetime
|
|
| 26 |
from typing import Optional
|
| 27 |
import traceback
|
| 28 |
|
| 29 |
-
# Set up logging
|
| 30 |
-
logging.basicConfig(
|
|
|
|
|
|
|
|
|
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# Initialize clients with error handling
|
| 34 |
try:
|
| 35 |
groq_client = Groq(api_key=os.getenv('groq_key'))
|
|
@@ -39,11 +47,24 @@ except Exception as e:
|
|
| 39 |
raise
|
| 40 |
|
| 41 |
try:
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
NOTION_DB_ID = os.getenv('NOTION_DB_ID')
|
|
|
|
| 44 |
if not NOTION_DB_ID:
|
| 45 |
-
raise ValueError("NOTION_DB_ID
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
logger.error(f"Failed to initialize Notion client: {str(e)}")
|
| 49 |
raise
|
|
@@ -58,6 +79,9 @@ def log_to_notion(name: str, user_input: str, bot_response: str) -> Optional[dic
|
|
| 58 |
Returns the created page or None if failed
|
| 59 |
"""
|
| 60 |
try:
|
|
|
|
|
|
|
|
|
|
| 61 |
taipei_tz = pytz.timezone('Asia/Taipei')
|
| 62 |
current_time = datetime.now(taipei_tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 63 |
|
|
@@ -66,6 +90,13 @@ def log_to_notion(name: str, user_input: str, bot_response: str) -> Optional[dic
|
|
| 66 |
bot_response_truncated = safe_text_truncate(bot_response)
|
| 67 |
name_truncated = safe_text_truncate(name, 100)
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
page = notion.pages.create(
|
| 70 |
parent={"database_id": NOTION_DB_ID},
|
| 71 |
properties={
|
|
@@ -83,132 +114,13 @@ def log_to_notion(name: str, user_input: str, bot_response: str) -> Optional[dic
|
|
| 83 |
}
|
| 84 |
}
|
| 85 |
)
|
| 86 |
-
|
|
|
|
| 87 |
return page
|
|
|
|
| 88 |
except Exception as e:
|
| 89 |
-
logger.error(f"Failed to log to Notion: {str(e)}
|
|
|
|
| 90 |
return None
|
| 91 |
|
| 92 |
-
|
| 93 |
-
"""Process message with error handling"""
|
| 94 |
-
try:
|
| 95 |
-
messages = [
|
| 96 |
-
{
|
| 97 |
-
"role": "system",
|
| 98 |
-
"content": "你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。\n說明數學上的可能用法時,先用中文講一遍再用B1程度的英文複述一遍\n"
|
| 99 |
-
}
|
| 100 |
-
]
|
| 101 |
-
|
| 102 |
-
for user_msg, bot_msg in history:
|
| 103 |
-
messages.append({"role": "user", "content": user_msg})
|
| 104 |
-
if bot_msg: # Only add bot message if it exists
|
| 105 |
-
messages.append({"role": "assistant", "content": bot_msg})
|
| 106 |
-
|
| 107 |
-
messages.append({"role": "user", "content": message})
|
| 108 |
-
|
| 109 |
-
completion = groq_client.chat.completions.create(
|
| 110 |
-
model="llama-3.3-70b-versatile",
|
| 111 |
-
messages=messages,
|
| 112 |
-
temperature=1,
|
| 113 |
-
max_tokens=1024,
|
| 114 |
-
top_p=1,
|
| 115 |
-
stream=True,
|
| 116 |
-
stop=None,
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
response_text = ""
|
| 120 |
-
for chunk in completion:
|
| 121 |
-
if chunk.choices and chunk.choices[0].delta:
|
| 122 |
-
delta_content = chunk.choices[0].delta.content
|
| 123 |
-
if delta_content:
|
| 124 |
-
response_text += delta_content
|
| 125 |
-
yield response_text
|
| 126 |
-
|
| 127 |
-
except Exception as e:
|
| 128 |
-
error_msg = f"Error processing message: {str(e)}"
|
| 129 |
-
logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
| 130 |
-
yield error_msg
|
| 131 |
-
|
| 132 |
-
# Create Gradio interface
|
| 133 |
-
with gr.Blocks() as demo:
|
| 134 |
-
# Add name input field at the top
|
| 135 |
-
name_input = gr.Textbox(
|
| 136 |
-
placeholder="請輸入您的姓名...",
|
| 137 |
-
label="姓名",
|
| 138 |
-
show_label=True,
|
| 139 |
-
)
|
| 140 |
-
|
| 141 |
-
chatbot = gr.Chatbot(
|
| 142 |
-
height=600,
|
| 143 |
-
show_label=False,
|
| 144 |
-
container=True,
|
| 145 |
-
)
|
| 146 |
-
|
| 147 |
-
msg = gr.Textbox(
|
| 148 |
-
placeholder="輸入您的問題...",
|
| 149 |
-
show_label=False,
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
clear = gr.Button("清除對話")
|
| 153 |
-
|
| 154 |
-
def user(user_message: str, history: list, name: str):
|
| 155 |
-
"""Handle user input with validation"""
|
| 156 |
-
try:
|
| 157 |
-
if not name.strip():
|
| 158 |
-
gr.Warning("請先輸入姓名")
|
| 159 |
-
return user_message, history
|
| 160 |
-
return "", history + [[user_message, None]]
|
| 161 |
-
except Exception as e:
|
| 162 |
-
logger.error(f"Error in user function: {str(e)}\n{traceback.format_exc()}")
|
| 163 |
-
return "", history
|
| 164 |
-
|
| 165 |
-
def bot(history: list, name: str):
|
| 166 |
-
"""Handle bot response with error handling"""
|
| 167 |
-
try:
|
| 168 |
-
if not history:
|
| 169 |
-
return history
|
| 170 |
-
|
| 171 |
-
history[-1][1] = ""
|
| 172 |
-
full_response = ""
|
| 173 |
-
|
| 174 |
-
for response in process_message(history[-1][0], history[:-1]):
|
| 175 |
-
history[-1][1] = response
|
| 176 |
-
full_response = response
|
| 177 |
-
yield history
|
| 178 |
-
|
| 179 |
-
# Log to Notion after complete response
|
| 180 |
-
if full_response:
|
| 181 |
-
notion_response = log_to_notion(
|
| 182 |
-
name=name.strip(),
|
| 183 |
-
user_input=history[-1][0],
|
| 184 |
-
bot_response=full_response
|
| 185 |
-
)
|
| 186 |
-
if not notion_response:
|
| 187 |
-
logger.warning(f"Failed to log to Notion for user: {name}")
|
| 188 |
-
|
| 189 |
-
except Exception as e:
|
| 190 |
-
error_msg = f"Error in bot response: {str(e)}"
|
| 191 |
-
logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
| 192 |
-
history[-1][1] = error_msg
|
| 193 |
-
yield history
|
| 194 |
-
|
| 195 |
-
msg.submit(
|
| 196 |
-
user,
|
| 197 |
-
inputs=[msg, chatbot, name_input],
|
| 198 |
-
outputs=[msg, chatbot],
|
| 199 |
-
queue=False
|
| 200 |
-
).then(
|
| 201 |
-
bot,
|
| 202 |
-
inputs=[chatbot, name_input],
|
| 203 |
-
outputs=[chatbot]
|
| 204 |
-
)
|
| 205 |
-
|
| 206 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
| 207 |
-
|
| 208 |
-
if __name__ == "__main__":
|
| 209 |
-
try:
|
| 210 |
-
demo.queue()
|
| 211 |
-
demo.launch()
|
| 212 |
-
except Exception as e:
|
| 213 |
-
logger.error(f"Failed to launch app: {str(e)}\n{traceback.format_exc()}")
|
| 214 |
-
raise
|
|
|
|
| 26 |
from typing import Optional
|
| 27 |
import traceback
|
| 28 |
|
| 29 |
+
# Set up logging with more detail
|
| 30 |
+
logging.basicConfig(
|
| 31 |
+
level=logging.DEBUG, # Changed to DEBUG for more detailed logs
|
| 32 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 33 |
+
)
|
| 34 |
logger = logging.getLogger(__name__)
|
| 35 |
|
| 36 |
+
# Debug: Print environment variables (will be masked in logs)
|
| 37 |
+
logger.debug(f"NOTION_API_KEY exists: {'NOTION_API_KEY' in os.environ}")
|
| 38 |
+
logger.debug(f"NOTION_DB_ID exists: {'NOTION_DB_ID' in os.environ}")
|
| 39 |
+
logger.debug(f"NOTION_DB_ID value: {os.getenv('NOTION_DB_ID')}")
|
| 40 |
+
|
| 41 |
# Initialize clients with error handling
|
| 42 |
try:
|
| 43 |
groq_client = Groq(api_key=os.getenv('groq_key'))
|
|
|
|
| 47 |
raise
|
| 48 |
|
| 49 |
try:
|
| 50 |
+
notion_api_key = os.getenv('NOTION_API_KEY')
|
| 51 |
+
if not notion_api_key:
|
| 52 |
+
raise ValueError("NOTION_API_KEY is not set in environment variables")
|
| 53 |
+
|
| 54 |
+
notion = Client(auth=notion_api_key)
|
| 55 |
NOTION_DB_ID = os.getenv('NOTION_DB_ID')
|
| 56 |
+
|
| 57 |
if not NOTION_DB_ID:
|
| 58 |
+
raise ValueError("NOTION_DB_ID is not set in environment variables")
|
| 59 |
+
|
| 60 |
+
# Test Notion connection
|
| 61 |
+
try:
|
| 62 |
+
notion.databases.retrieve(NOTION_DB_ID)
|
| 63 |
+
logger.info("Successfully connected to Notion database")
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"Failed to access Notion database: {str(e)}")
|
| 66 |
+
raise
|
| 67 |
+
|
| 68 |
except Exception as e:
|
| 69 |
logger.error(f"Failed to initialize Notion client: {str(e)}")
|
| 70 |
raise
|
|
|
|
| 79 |
Returns the created page or None if failed
|
| 80 |
"""
|
| 81 |
try:
|
| 82 |
+
logger.debug(f"Attempting to log to Notion for user: {name}")
|
| 83 |
+
logger.debug(f"Using database ID: {NOTION_DB_ID}")
|
| 84 |
+
|
| 85 |
taipei_tz = pytz.timezone('Asia/Taipei')
|
| 86 |
current_time = datetime.now(taipei_tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 87 |
|
|
|
|
| 90 |
bot_response_truncated = safe_text_truncate(bot_response)
|
| 91 |
name_truncated = safe_text_truncate(name, 100)
|
| 92 |
|
| 93 |
+
# Debug log the data being sent
|
| 94 |
+
logger.debug(f"Preparing to send data to Notion:")
|
| 95 |
+
logger.debug(f"Name: {name_truncated}")
|
| 96 |
+
logger.debug(f"Timestamp: {current_time}")
|
| 97 |
+
logger.debug(f"User Input Length: {len(user_input_truncated)}")
|
| 98 |
+
logger.debug(f"Bot Response Length: {len(bot_response_truncated)}")
|
| 99 |
+
|
| 100 |
page = notion.pages.create(
|
| 101 |
parent={"database_id": NOTION_DB_ID},
|
| 102 |
properties={
|
|
|
|
| 114 |
}
|
| 115 |
}
|
| 116 |
)
|
| 117 |
+
|
| 118 |
+
logger.info(f"Successfully logged to Notion. Page ID: {page.get('id', 'unknown')}")
|
| 119 |
return page
|
| 120 |
+
|
| 121 |
except Exception as e:
|
| 122 |
+
logger.error(f"Failed to log to Notion: {str(e)}")
|
| 123 |
+
logger.error(f"Full traceback: {traceback.format_exc()}")
|
| 124 |
return None
|
| 125 |
|
| 126 |
+
[rest of the code remains the same...]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|