helen573 commited on
Commit
2e7cb7d
·
verified ·
1 Parent(s): 62c6500

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -71
app.py CHANGED
@@ -1,11 +1,17 @@
1
  import os
2
- import gradio as gr
3
- from datetime import datetime
4
- from notion_client import Client
5
 
6
- # Initialize Notion client with API key
7
- notion = Client(auth=os.getenv('NOTION_API_KEY'))
8
- NOTION_DB_ID = os.getenv('NOTION_DB_ID')
 
 
 
 
 
 
 
 
 
9
 
10
  # Install and import Groq
11
  try:
@@ -14,87 +20,195 @@ except ImportError:
14
  os.system('pip install groq')
15
  from groq import Groq
16
 
17
- # Initialize Groq client with API key
18
- client = Groq(api_key=os.getenv('groq_key'))
 
 
 
19
 
20
- def log_to_notion(name, user_input, bot_response):
21
- """Log conversation data to Notion."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  try:
23
- notion.pages.create(
 
 
 
 
 
 
 
 
24
  parent={"database_id": NOTION_DB_ID},
25
  properties={
26
- "Name": {"title": [{"text": {"content": name}}]},
27
- "Timestamp": {"date": {"start": datetime.utcnow().isoformat() + "Z"}},
28
- "User Input": {"rich_text": [{"text": {"content": user_input}}]},
29
- "Bot Response": {"rich_text": [{"text": {"content": bot_response}}]},
30
- },
 
 
 
 
 
 
 
 
31
  )
 
 
32
  except Exception as e:
33
- print(f"Failed to log to Notion: {e}")
34
-
35
- def process_message(message, history):
36
- """Process user message with Groq."""
37
- messages = [
38
- {
39
- "role": "system",
40
- "content": (
41
- "你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,"
42
- "你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。\n"
43
- "說明數學上的可能用法時,先用中文講一遍再用B1程度的英文複述一遍"
44
- ),
45
- }
46
- ]
47
-
48
- for user_msg, bot_msg in history:
49
- messages.append({"role": "user", "content": user_msg})
50
- messages.append({"role": "assistant", "content": bot_msg})
51
-
52
- messages.append({"role": "user", "content": message})
53
-
54
- completion = client.chat.completions.create(
55
- model="llama-3.3-70b-versatile",
56
- messages=messages,
57
- temperature=1,
58
- max_tokens=1024,
59
- top_p=1,
60
- stream=True,
61
- stop=None,
62
- )
63
 
64
- response_text = ""
65
- for chunk in completion:
66
- delta_content = chunk.choices[0].delta.content
67
- if delta_content is not None:
68
- response_text += delta_content
69
- yield response_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  # Create Gradio interface
72
  with gr.Blocks() as demo:
73
- name_input = gr.Textbox(placeholder="請輸入您的姓名", label="Name")
74
- chatbot = gr.Chatbot(height=600, show_label=False, container=True)
75
- msg = gr.Textbox(placeholder="輸入您的問題...", show_label=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  clear = gr.Button("清除對話")
77
 
78
- def user(user_message, history):
79
- return "", history + [[user_message, None]]
 
 
 
 
 
 
 
 
80
 
81
- def bot(history, name):
82
- history[-1][1] = ""
83
- user_input = history[-1][0]
84
- for response in process_message(user_input, history[:-1]):
85
- history[-1][1] = response
86
- yield history
87
 
88
- # Log to Notion after full response
89
- bot_response = history[-1][1]
90
- log_to_notion(name, user_input, bot_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
93
- bot, [chatbot, name_input], chatbot
 
 
 
 
 
 
 
94
  )
 
95
  clear.click(lambda: None, None, chatbot, queue=False)
96
 
97
- # Launch the app
98
  if __name__ == "__main__":
99
- demo.queue()
100
- demo.launch()
 
 
 
 
 
1
  import os
 
 
 
2
 
3
+ # Install required packages
4
+ try:
5
+ from notion_client import Client
6
+ except ImportError:
7
+ os.system('pip install notion-client')
8
+ from notion_client import Client
9
+
10
+ try:
11
+ import pytz
12
+ except ImportError:
13
+ os.system('pip install pytz')
14
+ import pytz
15
 
16
  # Install and import Groq
17
  try:
 
20
  os.system('pip install groq')
21
  from groq import Groq
22
 
23
+ import gradio as gr
24
+ import logging
25
+ from datetime import datetime
26
+ from typing import Optional
27
+ import traceback
28
 
29
+ # Set up logging
30
+ logging.basicConfig(level=logging.INFO)
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # Initialize clients with error handling
34
+ try:
35
+ groq_client = Groq(api_key=os.getenv('groq_key'))
36
+ logger.info("Groq client initialized successfully")
37
+ except Exception as e:
38
+ logger.error(f"Failed to initialize Groq client: {str(e)}")
39
+ raise
40
+
41
+ try:
42
+ notion = Client(auth=os.getenv('NOTION_API_KEY'))
43
+ NOTION_DB_ID = os.getenv('NOTION_DB_ID')
44
+ if not NOTION_DB_ID:
45
+ raise ValueError("NOTION_DB_ID environment variable is not set")
46
+ logger.info("Notion client initialized successfully")
47
+ except Exception as e:
48
+ logger.error(f"Failed to initialize Notion client: {str(e)}")
49
+ raise
50
+
51
+ def safe_text_truncate(text: str, max_length: int = 2000) -> str:
52
+ """Safely truncate text to avoid Notion API limits"""
53
+ return text[:max_length] if text else ""
54
+
55
+ def log_to_notion(name: str, user_input: str, bot_response: str) -> Optional[dict]:
56
+ """
57
+ Log chat interaction to Notion database with error handling
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
+
64
+ # Truncate long texts to avoid Notion API limits
65
+ user_input_truncated = safe_text_truncate(user_input)
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={
72
+ "Name": {
73
+ "title": [{"text": {"content": name_truncated}}]
74
+ },
75
+ "Timestamp": {
76
+ "rich_text": [{"text": {"content": current_time}}]
77
+ },
78
+ "User Input": {
79
+ "rich_text": [{"text": {"content": user_input_truncated}}]
80
+ },
81
+ "Bot Response": {
82
+ "rich_text": [{"text": {"content": bot_response_truncated}}]
83
+ }
84
+ }
85
  )
86
+ logger.info(f"Successfully logged to Notion for user: {name}")
87
+ return page
88
  except Exception as e:
89
+ logger.error(f"Failed to log to Notion: {str(e)}\n{traceback.format_exc()}")
90
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ def process_message(message: str, history: list):
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